hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
84cde4baa224ab3fe2e99d515afc885c05240f09 | 1,953 | /*
* Copyright (c) 2022 Huawei Technologies Co.,Ltd.
*
* openGauss is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
package org.opengauss.mppdbide.view.ui;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.BrowserFunction;
/**
*
* Title: class
*
* Description: The Class DBAssistantFunctionProcessSelection2.
*
* @since 3.0.0
*/
public class DBAssistantFunctionProcessSelection2 extends BrowserFunction {
/**
* Instantiates a new DB assistant function process selection 2.
*
* @param browser the browser
* @param name the name
*/
public DBAssistantFunctionProcessSelection2(Browser browser, String name) {
super(browser, name);
}
/**
* Function.
*
* @param arguments the arguments
* @return the object
*/
@Override
public Object function(Object[] arguments) {
String query = arguments[0].toString();
if (DBAssistantWindow.getViewer() != null && DBAssistantWindow.getViewer().getControl().isVisible()) {
int offset = DBAssistantWindow.getViewer().getTextWidget().getCaretOffset();
StringBuilder txt = new StringBuilder(DBAssistantWindow.getViewer().getTextWidget().getText());
txt.insert(offset, query);
DBAssistantWindow.getViewer().getDocument().set(txt.toString());
DBAssistantWindow.getViewer().getTextWidget().setCaretOffset(offset + query.length());
}
return super.function(arguments);
}
}
| 31 | 110 | 0.676395 |
ef630dc2c498bf7271491fa80fa62066be587ec0 | 62 | package naef.mvo;
public enum PortMode {
VLAN,
IP
}
| 7.75 | 22 | 0.612903 |
8fadc3572fbcc10dc7b6731997f6885620228103 | 1,829 | package frontEnd.Skeleton.AoTools.AttributeVisualization;
import javafx.scene.Node;
/**
* This interface serves as a way to visualize all attribute types of the
* project. If any attribute types are added a new method is required here.
*
* @author Miguel Anderson
*
*/
public interface AttributeVisualization {
/**
* The string of the format of the rest of the methods in this interface
*
* @return
*/
public String getMethodNameFormat();
/**
* The viewer or editor for image attributes, will show the image to the
* user.
*
* @return
*/
public Node getIMAGE();
/**
* The viewer or editor for Double attributes, will show the numeric value
* to the user.
*
* @return
*/
public Node getDOUBLE();
/**
* The viewer or editor for component attributes, will show the name of the
* preset and the image to the user.
*
* @return
*/
public Node getCOMPONENT();
/**
* The viewer or editor for position attributes, will show the x and y value
* to the user.
*
* @return
*/
public Node getPOSITION();
/**
* The viewer or editor for Integer attributes, will show the numeric value
* to the user.
*
* @return
*/
public Node getINTEGER();
/**
* The viewer or editor for Boolean attributes, will show the value to the
* user.
*
* @return
*/
public Node getBOOLEAN();
/**
* The viewer or editor for Stringlist attributes, will show the string
* value to the user. The options for this attribute is a list of strings.
* They can be dyanimic or static (decided by an XML)
*
* @return
*/
public Node getSTRINGLIST();
/**
* The viewer or editor for Editable string attributes, will show the value
* to the user. This can be a name, or things decided by the user
*
* @return
*/
public Node getEDITABLESTRING();
}
| 20.784091 | 77 | 0.671405 |
ab78314442dd531498799581280ce635a7a775ba | 62,797 | /* The following code was generated by JFlex 1.4.1 on 3/24/13 12:59 AM */
/*
* 03/24/2013
*
* VisualBasicTokenMaker.java - Scanner for Visual Basic
*
* This library is distributed under a modified BSD license. See the included
* RSyntaxTextArea.License.txt file for details.
*/
package org.fife.ui.rsyntaxtextarea.modes;
import java.io.*;
import javax.swing.text.Segment;
import org.fife.ui.rsyntaxtextarea.*;
/**
* Scanner for Visual Basic.
*
* This implementation was created using
* <a href="http://www.jflex.de/">JFlex</a> 1.4.1; however, the generated file
* was modified for performance. Memory allocation needs to be almost
* completely removed to be competitive with the handwritten lexers (subclasses
* of <code>AbstractTokenMaker</code>, so this class has been modified so that
* Strings are never allocated (via yytext()), and the scanner never has to
* worry about refilling its buffer (needlessly copying chars around).
* We can achieve this because RText always scans exactly 1 line of tokens at a
* time, and hands the scanner this line as an array of characters (a Segment
* really). Since tokens contain pointers to char arrays instead of Strings
* holding their contents, there is no need for allocating new memory for
* Strings.<p>
*
* The actual algorithm generated for scanning has, of course, not been
* modified.<p>
*
* If you wish to regenerate this file yourself, keep in mind the following:
* <ul>
* <li>The generated VisualBasicTokenMaker.java</code> file will contain two
* definitions of both <code>zzRefill</code> and <code>yyreset</code>.
* You should hand-delete the second of each definition (the ones
* generated by the lexer), as these generated methods modify the input
* buffer, which we'll never have to do.</li>
* <li>You should also change the declaration/definition of zzBuffer to NOT
* be initialized. This is a needless memory allocation for us since we
* will be pointing the array somewhere else anyway.</li>
* <li>You should NOT call <code>yylex()</code> on the generated scanner
* directly; rather, you should use <code>getTokenList</code> as you would
* with any other <code>TokenMaker</code> instance.</li>
* </ul>
*
* @author Robert Futrell
* @version 1.0
*/
public class VisualBasicTokenMaker extends AbstractJFlexTokenMaker {
/** This character denotes the end of file */
public static final int YYEOF = -1;
/** lexical states */
public static final int EOL_COMMENT = 1;
public static final int YYINITIAL = 0;
/**
* Translates characters to character classes
*/
private static final String ZZ_CMAP_PACKED =
"\11\0\1\11\1\10\1\0\1\11\1\5\22\0\1\64\1\37\1\12"+
"\1\6\1\1\1\37\1\16\1\13\2\36\1\41\1\27\1\37\1\27"+
"\1\30\1\44\1\3\11\3\1\47\1\37\1\42\1\40\1\43\1\37"+
"\1\6\1\35\1\54\1\4\1\15\1\26\1\34\1\57\1\25\1\21"+
"\1\60\1\63\1\22\1\61\1\52\1\53\1\46\1\1\1\14\1\24"+
"\1\31\1\17\1\56\1\50\1\62\1\55\1\1\1\37\1\7\1\37"+
"\1\45\1\2\1\0\1\35\1\54\1\4\1\51\1\26\1\33\1\57"+
"\1\65\1\20\1\60\1\63\1\22\1\61\1\52\1\53\1\46\1\1"+
"\1\32\1\23\1\31\1\17\1\56\1\66\1\62\1\55\1\1\3\5"+
"\1\37\uff81\0";
/**
* Translates characters to character classes
*/
private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED);
/**
* Translates DFA states to action switch labels.
*/
private static final int [] ZZ_ACTION = zzUnpackAction();
private static final String ZZ_ACTION_PACKED_0 =
"\2\0\1\1\1\2\1\3\2\2\1\4\1\5\1\6"+
"\1\7\1\10\2\2\1\4\6\2\1\4\4\2\1\11"+
"\1\4\13\2\1\12\1\13\6\12\1\14\1\3\2\14"+
"\1\15\13\2\1\16\5\2\1\17\1\0\3\2\3\17"+
"\47\2\1\17\14\2\1\12\2\0\3\12\2\0\1\15"+
"\1\0\1\15\1\14\24\2\1\17\7\2\1\20\24\2"+
"\1\17\2\2\1\17\11\2\1\17\13\2\1\17\12\2"+
"\1\17\3\2\1\17\2\2\1\12\2\0\3\12\2\0"+
"\2\2\1\21\14\2\1\20\1\14\16\2\1\22\17\2"+
"\1\17\17\2\1\12\1\0\2\12\1\23\1\0\52\2"+
"\1\0\1\12\1\0\1\2\1\24\21\2\1\17\6\2"+
"\1\17\14\2\1\0\10\2\1\0\3\2\1\0\2\2"+
"\6\0\1\17";
private static int [] zzUnpackAction() {
int [] result = new int[417];
int offset = 0;
offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result);
return result;
}
private static int zzUnpackAction(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
do result[j++] = value; while (--count > 0);
}
return j;
}
/**
* Translates a state to a row index in the transition table
*/
private static final int [] ZZ_ROWMAP = zzUnpackRowMap();
private static final String ZZ_ROWMAP_PACKED_0 =
"\0\0\0\67\0\156\0\245\0\334\0\u0113\0\u014a\0\u0181"+
"\0\u014a\0\u01b8\0\u01ef\0\u014a\0\u0226\0\u025d\0\u0294\0\u02cb"+
"\0\u0302\0\u0339\0\u0370\0\u03a7\0\u03de\0\u0415\0\u044c\0\u0483"+
"\0\u04ba\0\u04f1\0\u014a\0\u014a\0\u0528\0\u055f\0\u0596\0\u05cd"+
"\0\u0604\0\u063b\0\u0672\0\u06a9\0\u06e0\0\u0717\0\u074e\0\u0785"+
"\0\u014a\0\u07bc\0\u07f3\0\u082a\0\u0861\0\u0898\0\u08cf\0\u0906"+
"\0\u0906\0\u093d\0\u0974\0\u09ab\0\u09e2\0\u0a19\0\u0a50\0\u0a87"+
"\0\u0abe\0\u0af5\0\u0b2c\0\u0b63\0\u0b9a\0\u0bd1\0\u0c08\0\u014a"+
"\0\u0c3f\0\u0c76\0\u0cad\0\u0ce4\0\u0d1b\0\u0d52\0\u0d89\0\u0dc0"+
"\0\u0df7\0\u0e2e\0\u0e65\0\245\0\u0e9c\0\u0ed3\0\u0f0a\0\u0f41"+
"\0\u0f78\0\u0faf\0\u0fe6\0\u101d\0\u1054\0\u108b\0\u10c2\0\u10f9"+
"\0\u1130\0\u1167\0\u119e\0\u11d5\0\u120c\0\u1243\0\u127a\0\u12b1"+
"\0\u12e8\0\u131f\0\u1356\0\u138d\0\u13c4\0\u13fb\0\u1432\0\u1469"+
"\0\u14a0\0\u14d7\0\u150e\0\u1545\0\u157c\0\u15b3\0\u15ea\0\u1621"+
"\0\u1658\0\u168f\0\u16c6\0\u16fd\0\u1734\0\u176b\0\u17a2\0\u17d9"+
"\0\u1810\0\u1847\0\u187e\0\u18b5\0\u18ec\0\u1923\0\u195a\0\u1991"+
"\0\u19c8\0\u19ff\0\u1a36\0\u1a6d\0\u1aa4\0\u1adb\0\u1b12\0\u1b49"+
"\0\u1b80\0\u1bb7\0\u1bee\0\u0906\0\u1c25\0\u1c5c\0\u1c93\0\u1cca"+
"\0\u1d01\0\u1d38\0\u1d6f\0\u1da6\0\u1ddd\0\u1e14\0\u1e4b\0\u1e82"+
"\0\u1eb9\0\u1ef0\0\u1f27\0\u1f5e\0\u1f95\0\u1fcc\0\u2003\0\u203a"+
"\0\u2071\0\u20a8\0\u20df\0\u2116\0\u214d\0\u2184\0\u21bb\0\u21f2"+
"\0\u2229\0\u2260\0\u2297\0\u22ce\0\u2305\0\u233c\0\u2373\0\u23aa"+
"\0\u23e1\0\u2418\0\u244f\0\u2486\0\u24bd\0\u24f4\0\u252b\0\u2562"+
"\0\u2599\0\u25d0\0\u2607\0\u263e\0\u2675\0\u26ac\0\u26e3\0\u271a"+
"\0\u2751\0\u2788\0\u27bf\0\u27f6\0\u282d\0\u2864\0\u289b\0\u28d2"+
"\0\u2909\0\u2940\0\u2977\0\u29ae\0\u29e5\0\u2a1c\0\u2a53\0\u2a8a"+
"\0\u2ac1\0\u2af8\0\u2b2f\0\u2b66\0\u2b9d\0\u2bd4\0\u2c0b\0\u2c42"+
"\0\u2c79\0\u2cb0\0\u2ce7\0\u2d1e\0\u2d55\0\u2d8c\0\u2dc3\0\u2dfa"+
"\0\u2e31\0\u2e68\0\u2e9f\0\u2ed6\0\u2f0d\0\u2f44\0\u2f7b\0\u2fb2"+
"\0\u2fe9\0\u3020\0\u3057\0\u308e\0\u30c5\0\u30fc\0\u3133\0\u316a"+
"\0\u31a1\0\u31d8\0\u320f\0\245\0\u3246\0\u327d\0\u32b4\0\u32eb"+
"\0\u3322\0\u3359\0\u3390\0\u33c7\0\u33fe\0\u3435\0\u346c\0\u34a3"+
"\0\u0906\0\u34da\0\u3511\0\u3548\0\u357f\0\u35b6\0\u35ed\0\u3624"+
"\0\u365b\0\u3692\0\u36c9\0\u3700\0\u3737\0\u376e\0\u37a5\0\u37dc"+
"\0\245\0\u3813\0\u384a\0\u3881\0\u38b8\0\u38ef\0\u3926\0\u395d"+
"\0\u3994\0\u39cb\0\u3a02\0\u3a39\0\u3a70\0\u3aa7\0\u3ade\0\u3b15"+
"\0\u3b4c\0\u3b83\0\u3bba\0\u3bf1\0\u3c28\0\u3c5f\0\u3c96\0\u3ccd"+
"\0\u3d04\0\u3d3b\0\u3d72\0\u3da9\0\u3de0\0\u3e17\0\u3e4e\0\u3e85"+
"\0\u3ebc\0\u3ef3\0\u3f2a\0\u3f61\0\u3f98\0\u3fcf\0\u4006\0\u403d"+
"\0\u4074\0\u40ab\0\u40e2\0\u4119\0\u4150\0\u4187\0\u41be\0\u41f5"+
"\0\u422c\0\u4263\0\u429a\0\u42d1\0\u4308\0\u433f\0\u4376\0\u43ad"+
"\0\u43e4\0\u441b\0\u4452\0\u4489\0\u44c0\0\u44f7\0\u452e\0\u4565"+
"\0\u459c\0\u45d3\0\u460a\0\u4641\0\u4678\0\u46af\0\u46e6\0\u471d"+
"\0\u4754\0\u478b\0\u47c2\0\u47f9\0\u4830\0\u4867\0\u489e\0\u48d5"+
"\0\u490c\0\u4943\0\u3f98\0\u497a\0\245\0\u49b1\0\u49e8\0\u2788"+
"\0\u4a1f\0\u4a56\0\u4a8d\0\u4ac4\0\u4afb\0\u4b32\0\u4b69\0\u4ba0"+
"\0\u4bd7\0\u4c0e\0\u4c45\0\u4c7c\0\u4cb3\0\u4cea\0\u2dfa\0\u4d21"+
"\0\u4d58\0\u4d8f\0\u4dc6\0\u4dfd\0\u4e34\0\u4e6b\0\u4ea2\0\u4ed9"+
"\0\u4f10\0\u4f47\0\u4f7e\0\u4fb5\0\u4fec\0\u5023\0\u505a\0\u5091"+
"\0\u50c8\0\u50ff\0\u5136\0\u516d\0\u51a4\0\u51db\0\u5212\0\u5249"+
"\0\u5280\0\u52b7\0\u52ee\0\u5325\0\u535c\0\u5393\0\u53ca\0\u5401"+
"\0\u5438\0\u546f\0\u54a6\0\u54dd\0\u5514\0\u554b\0\u5582\0\u55b9"+
"\0\u014a";
private static int [] zzUnpackRowMap() {
int [] result = new int[417];
int offset = 0;
offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result);
return result;
}
private static int zzUnpackRowMap(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int high = packed.charAt(i++) << 16;
result[j++] = high | packed.charAt(i++);
}
return j;
}
/**
* The transition table of the DFA
*/
private static final int [] ZZ_TRANS = zzUnpackTrans();
private static final String ZZ_TRANS_PACKED_0 =
"\1\3\2\4\1\5\1\6\1\7\1\3\1\10\1\11"+
"\1\12\1\13\1\14\1\15\1\16\1\17\1\20\2\21"+
"\1\22\2\23\1\24\1\25\1\26\1\27\1\30\1\15"+
"\2\31\1\32\1\33\1\7\1\34\1\26\1\35\1\36"+
"\2\26\1\37\1\7\1\40\1\16\1\41\1\42\1\43"+
"\1\4\1\44\1\45\1\4\1\46\1\47\1\4\1\12"+
"\1\24\1\40\10\50\1\51\14\50\1\52\5\50\1\53"+
"\1\54\13\50\1\55\14\50\1\56\1\57\5\3\1\0"+
"\2\3\4\0\2\3\1\0\10\3\2\0\5\3\10\0"+
"\1\3\1\0\14\3\1\0\3\3\4\4\1\0\2\3"+
"\4\0\2\4\1\0\10\4\2\0\5\4\10\0\1\4"+
"\1\0\14\4\1\0\2\4\3\60\1\5\1\60\1\0"+
"\2\60\4\0\3\61\1\62\1\60\1\61\2\60\1\61"+
"\1\60\1\63\1\0\1\64\3\60\1\61\1\60\10\0"+
"\1\60\1\0\14\60\1\0\2\60\1\3\3\4\1\65"+
"\1\0\2\3\4\0\1\4\1\66\1\0\1\67\2\70"+
"\1\71\2\72\1\73\1\4\2\0\1\74\3\4\1\75"+
"\10\0\1\4\1\0\1\4\1\66\1\4\1\76\1\77"+
"\7\4\1\0\1\73\1\4\67\0\5\3\1\0\2\3"+
"\4\0\2\3\1\0\10\3\2\0\5\3\2\0\1\34"+
"\5\0\1\3\1\0\14\3\1\0\2\3\11\0\1\12"+
"\52\0\1\12\2\0\12\13\1\100\54\13\1\3\4\4"+
"\1\0\2\3\4\0\2\4\1\0\7\4\1\101\2\0"+
"\4\4\1\102\10\0\1\4\1\0\14\4\1\0\2\4"+
"\1\3\4\4\1\0\2\3\4\0\2\4\1\0\1\4"+
"\2\103\4\4\1\104\2\0\4\4\1\105\10\0\1\4"+
"\1\0\3\4\1\106\10\4\1\0\2\4\25\0\1\107"+
"\12\0\1\34\24\0\1\107\1\0\1\3\4\4\1\0"+
"\2\3\4\0\2\4\1\0\1\4\2\110\1\111\2\112"+
"\2\4\2\0\5\4\10\0\1\4\1\0\14\4\1\0"+
"\2\4\1\3\4\4\1\0\2\3\4\0\2\4\1\0"+
"\4\4\2\113\2\4\2\0\2\4\2\114\1\4\10\0"+
"\1\4\1\0\2\4\1\115\6\4\1\116\2\4\1\0"+
"\2\4\1\3\4\4\1\0\2\3\4\0\2\4\1\0"+
"\1\4\2\117\4\4\1\120\2\0\5\4\10\0\1\4"+
"\1\0\3\4\1\121\10\4\1\0\2\4\1\3\4\4"+
"\1\0\2\3\4\0\2\4\1\0\1\122\2\123\3\4"+
"\1\124\1\125\2\0\1\126\4\4\10\0\1\4\1\0"+
"\4\4\1\127\1\130\6\4\1\0\1\124\1\4\1\3"+
"\4\4\1\0\2\3\4\0\2\4\1\0\10\4\2\0"+
"\4\4\1\131\10\0\1\4\1\0\14\4\1\0\2\4"+
"\1\3\4\4\1\0\2\3\4\0\1\132\1\4\1\0"+
"\3\4\1\133\4\4\2\0\1\4\1\132\2\4\1\134"+
"\10\0\1\4\1\0\2\4\1\135\3\4\1\136\3\4"+
"\1\137\1\4\1\0\2\4\40\0\1\34\31\0\1\64"+
"\63\0\1\3\4\4\1\0\2\3\4\0\1\140\1\4"+
"\1\0\6\4\1\141\1\4\2\0\1\4\1\140\3\4"+
"\10\0\1\4\1\0\3\4\1\114\1\4\1\142\6\4"+
"\1\0\1\141\1\4\1\3\4\4\1\0\2\3\4\0"+
"\1\143\1\4\1\0\1\144\2\145\5\4\2\0\1\4"+
"\1\143\2\4\1\146\10\0\1\4\1\0\3\4\1\147"+
"\10\4\1\0\2\4\1\3\4\4\1\0\2\3\4\0"+
"\1\4\1\150\1\0\3\4\1\151\2\114\2\4\2\0"+
"\5\4\10\0\1\4\1\0\1\4\1\150\1\152\11\4"+
"\1\0\2\4\42\0\1\26\67\0\1\26\23\0\1\3"+
"\4\4\1\0\2\3\4\0\1\153\1\4\1\0\1\154"+
"\7\4\2\0\1\4\1\153\2\4\1\155\10\0\1\4"+
"\1\0\14\4\1\0\2\4\1\3\4\4\1\0\2\3"+
"\4\0\1\156\1\4\1\0\1\4\2\157\3\4\1\160"+
"\1\161\2\0\1\4\1\156\3\4\10\0\1\4\1\0"+
"\14\4\1\0\1\160\1\4\1\3\4\4\1\0\2\3"+
"\4\0\2\4\1\0\7\4\1\162\2\0\4\4\1\163"+
"\10\0\1\4\1\0\3\4\1\164\10\4\1\0\2\4"+
"\1\3\4\4\1\0\2\3\4\0\1\165\1\4\1\0"+
"\1\120\7\4\2\0\1\4\1\165\2\114\1\4\10\0"+
"\1\166\1\0\2\4\1\114\1\4\1\167\1\4\1\170"+
"\5\4\1\0\2\4\1\3\4\4\1\0\2\3\4\0"+
"\2\4\1\0\10\4\2\0\5\4\10\0\1\4\1\0"+
"\3\4\1\171\1\4\1\172\6\4\1\0\2\4\1\3"+
"\4\4\1\0\2\3\4\0\2\4\1\0\10\4\2\0"+
"\4\4\1\173\10\0\1\4\1\0\14\4\1\0\2\4"+
"\1\3\4\4\1\0\2\3\4\0\2\4\1\0\3\4"+
"\1\174\3\4\1\175\2\0\5\4\10\0\1\4\1\0"+
"\3\4\1\176\10\4\1\0\2\4\1\3\4\4\1\0"+
"\2\3\4\0\2\4\1\0\1\177\6\4\1\114\2\0"+
"\5\4\10\0\1\4\1\0\3\4\1\200\1\4\1\201"+
"\6\4\1\0\2\4\1\3\4\4\1\0\2\3\4\0"+
"\2\4\1\0\10\4\2\0\5\4\10\0\1\4\1\0"+
"\3\4\1\147\10\4\1\0\2\4\10\50\1\0\22\50"+
"\1\0\31\50\2\0\10\50\1\0\20\50\1\202\1\50"+
"\1\0\31\50\22\0\2\203\7\0\1\204\35\0\10\50"+
"\1\0\7\50\2\205\7\50\1\206\1\50\1\0\31\50"+
"\2\0\10\50\1\0\22\50\1\0\14\50\1\207\14\50"+
"\1\0\1\210\31\0\1\211\105\0\1\210\15\0\1\210"+
"\5\60\1\0\2\60\4\0\2\60\1\0\10\60\2\0"+
"\5\60\10\0\1\60\1\0\14\60\1\0\7\60\1\0"+
"\2\60\4\0\2\60\1\0\1\60\5\61\2\60\2\0"+
"\5\60\10\0\1\60\1\0\14\60\1\0\5\60\1\212"+
"\1\60\1\0\2\60\4\0\2\60\1\0\10\60\1\213"+
"\1\0\5\60\10\0\1\60\1\0\14\60\1\0\5\60"+
"\1\64\1\60\1\0\2\60\4\0\3\214\1\215\1\60"+
"\1\214\2\60\1\214\1\60\1\63\2\0\3\60\1\214"+
"\1\60\10\0\1\60\1\0\14\60\1\0\2\60\1\3"+
"\4\4\1\0\2\3\4\0\2\4\1\0\6\4\1\216"+
"\1\4\2\0\5\4\10\0\1\4\1\0\14\4\1\0"+
"\1\216\1\4\1\3\4\4\1\0\2\3\4\0\2\4"+
"\1\0\7\4\1\217\2\0\4\4\1\220\10\0\1\4"+
"\1\0\4\4\1\221\7\4\1\0\2\4\1\3\4\4"+
"\1\0\2\3\4\0\2\4\1\0\1\4\2\70\1\222"+
"\2\223\2\4\2\0\5\4\10\0\1\4\1\0\14\4"+
"\1\0\2\4\1\3\4\4\1\0\2\3\4\0\2\4"+
"\1\0\10\4\2\0\5\4\10\0\1\4\1\0\2\4"+
"\1\120\11\4\1\0\2\4\1\3\4\4\1\0\2\3"+
"\4\0\2\4\1\0\10\4\2\0\4\4\1\224\10\0"+
"\1\4\1\0\2\4\1\225\11\4\1\0\2\4\1\3"+
"\4\4\1\0\2\3\4\0\2\4\1\0\6\4\1\226"+
"\1\4\2\0\1\147\4\4\10\0\1\4\1\0\2\4"+
"\1\225\1\4\1\227\7\4\1\0\1\226\1\4\1\3"+
"\4\4\1\0\2\3\4\0\2\4\1\0\10\4\2\0"+
"\4\4\1\230\10\0\1\4\1\0\14\4\1\0\2\4"+
"\1\3\4\4\1\0\2\3\4\0\2\4\1\0\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1\4\1\0\10\4\2\0\1\4\1\341\3\4\10\0"+
"\1\4\1\0\14\4\1\0\2\4\1\3\4\4\1\0"+
"\2\3\4\0\2\4\1\0\10\4\2\0\5\4\10\0"+
"\1\4\1\0\3\4\1\342\10\4\1\0\2\4\1\3"+
"\4\4\1\0\2\3\4\0\2\4\1\0\10\4\2\0"+
"\1\343\4\4\10\0\1\4\1\0\14\4\1\0\2\4"+
"\1\3\4\4\1\0\2\3\4\0\2\4\1\0\4\4"+
"\2\344\2\4\2\0\1\345\4\4\10\0\1\4\1\0"+
"\14\4\1\0\2\4\1\3\4\4\1\0\2\3\4\0"+
"\2\4\1\0\4\4\2\346\2\4\2\0\5\4\10\0"+
"\1\4\1\0\14\4\1\0\2\4\1\3\4\4\1\0"+
"\2\3\4\0\1\4\1\347\1\0\10\4\2\0\5\4"+
"\10\0\1\4\1\0\1\4\1\347\12\4\1\0\2\4"+
"\1\3\3\4\1\350\1\0\2\3\4\0\2\4\1\0"+
"\10\4\2\0\5\4\10\0\1\4\1\0\4\4\1\351"+
"\7\4\1\0\2\4\10\50\1\0\20\50\1\352\1\50"+
"\1\0\31\50\24\0\1\353\112\0\1\354\20\0\10\50"+
"\1\0\11\50\1\355\10\50\1\0\31\50\2\0\10\50"+
"\1\0\22\50\1\0\12\50\1\356\16\50\2\0\10\50"+
"\1\0\22\50\1\0\14\50\1\357\14\50\1\0\1\360"+
"\50\0\1\360\15\0\1\360\31\0\1\361\35\0\3\60"+
"\1\212\1\60\1\0\2\60\4\0\3\214\1\215\1\60"+
"\1\214\2\60\1\214\2\60\2\0\3\60\1\214\1\60"+
"\10\0\1\60\1\0\14\60\1\0\2\60\3\0\1\212"+
"\63\0\5\60\1\0\2\60\4\0\2\60\1\0\1\60"+
"\5\214\2\60\2\0\5\60\10\0\1\60\1\0\14\60"+
"\1\0\2\60\1\3\4\4\1\0\2\3\4\0\2\4"+
"\1\0\10\4\2\0\4\4\1\147\10\0\1\4\1\0"+
"\14\4\1\0\2\4\1\3\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4\1\0\2\4\1\3\4\4\1\0\2\3\4\0"+
"\2\4\1\0\10\4\2\0\1\u012e\4\4\10\0\1\4"+
"\1\0\14\4\1\0\2\4\1\3\4\4\1\0\2\3"+
"\4\0\2\4\1\0\1\u012f\7\4\2\0\5\4\10\0"+
"\1\4\1\0\14\4\1\0\2\4\1\3\4\4\1\0"+
"\2\3\4\0\2\4\1\0\3\4\1\u0130\4\4\2\0"+
"\5\4\10\0\1\4\1\0\14\4\1\0\2\4\1\3"+
"\4\4\1\0\2\3\4\0\2\4\1\0\10\4\2\0"+
"\4\4\1\274\10\0\1\4\1\0\14\4\1\0\2\4"+
"\10\50\1\0\22\50\1\0\12\50\1\u0131\16\50\30\0"+
"\1\354\107\0\1\u0132\17\0\10\50\1\0\15\50\1\356"+
"\4\50\1\0\31\50\2\0\10\50\1\0\22\50\1\0"+
"\13\50\1\u0133\15\50\2\0\10\50\1\0\17\50\1\u0134"+
"\2\50\1\0\31\50\32\0\1\u0135\104\0\1\u0136\20\0"+
"\1\3\4\4\1\0\2\3\4\0\2\4\1\0\4\4"+
"\2\114\2\4\2\0\5\4\10\0\1\4\1\0\14\4"+
"\1\0\2\4\1\3\4\4\1\0\2\3\4\0\1\120"+
"\1\4\1\0\10\4\2\0\1\4\1\120\3\4\10\0"+
"\1\4\1\0\14\4\1\0\2\4\1\3\4\4\1\0"+
"\2\3\4\0\2\4\1\0\1\4\2\u0137\5\4\2\0"+
"\5\4\10\0\1\4\1\0\14\4\1\0\2\4\1\3"+
"\4\4\1\0\2\3\4\0\2\4\1\0\10\4\2\0"+
"\5\4\10\0\1\4\1\0\11\4\1\232\2\4\1\0"+
"\2\4\1\3\4\4\1\0\2\3\4\0\1\u0138\1\4"+
"\1\0\10\4\2\0\1\4\1\u0138\3\4\10\0\1\4"+
"\1\0\14\4\1\0\2\4\1\3\4\4\1\0\2\3"+
"\4\0\2\4\1\0\10\4\2\0\5\4\10\0\1\4"+
"\1\0\3\4\1\u0139\10\4\1\0\2\4\1\3\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10\4\2\0\5\4\10\0\1\4\1\0\11\4"+
"\1\u015d\2\4\1\0\2\4\1\3\4\4\1\0\2\3"+
"\4\0\2\4\1\0\1\4\2\u015e\5\4\2\0\5\4"+
"\10\0\1\4\1\0\3\4\1\u015f\10\4\1\0\2\4"+
"\1\3\4\4\1\0\2\3\4\0\2\4\1\0\3\4"+
"\1\u0160\4\4\2\0\5\4\10\0\1\4\1\0\14\4"+
"\1\0\2\4\1\3\4\4\1\0\2\3\4\0\2\4"+
"\1\0\10\4\2\0\4\4\1\224\10\0\1\4\1\0"+
"\14\4\1\0\2\4\10\50\1\0\12\50\2\356\6\50"+
"\1\0\13\50\1\u0133\15\50\46\0\1\u0161\22\0\10\50"+
"\1\0\22\50\1\0\10\50\1\u0162\20\50\2\0\1\50"+
"\4\u0134\1\50\1\u0134\1\50\1\0\2\50\20\u0134\1\u0135"+
"\6\u0134\2\50\1\u0134\1\50\16\u0134\1\50\2\u0135\1\0"+
"\1\u0135\1\u0163\2\u0135\1\0\1\u0163\4\0\1\u0163\2\u0135"+
"\1\u0163\10\u0135\2\u0163\5\u0135\4\u0163\2\0\1\u0135\1\0"+
"\1\u0135\1\u0163\14\u0135\1\0\2\u0135\23\0\2\354\22\0"+
"\1\u0132\17\0\1\3\4\4\1\0\2\3\4\0\2\4"+
"\1\0\10\4\2\0\5\4\10\0\1\4\1\0\2\4"+
"\1\u0164\11\4\1\0\2\4\1\3\4\4\1\0\2\3"+
"\4\0\2\4\1\0\10\4\2\0\5\4\10\0\1\4"+
"\1\0\2\4\1\u0165\11\4\1\0\2\4\1\3\4\4"+
"\1\0\2\3\4\0\2\4\1\0\10\4\2\0\5\4"+
"\10\0\1\4\1\0\2\4\1\u014c\11\4\1\0\2\4"+
"\1\3\4\4\1\0\2\3\4\0\2\4\1\0\7\4"+
"\1\u0166\2\0\5\4\10\0\1\4\1\0\14\4\1\0"+
"\2\4\1\3\4\4\1\0\2\3\4\0\2\4\1\0"+
"\7\4\1\u0167\2\0\5\4\10\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1\0\2\4\31\0\1\u019c\63\0\1\u019d\121\0\1\u019e"+
"\33\0\1\u019f\112\0\1\u01a0\45\0\1\u01a1\35\0";
private static int [] zzUnpackTrans() {
int [] result = new int[22000];
int offset = 0;
offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result);
return result;
}
private static int zzUnpackTrans(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
value--;
do result[j++] = value; while (--count > 0);
}
return j;
}
/* error codes */
private static final int ZZ_UNKNOWN_ERROR = 0;
private static final int ZZ_NO_MATCH = 1;
private static final int ZZ_PUSHBACK_2BIG = 2;
/* error messages for the codes above */
private static final String ZZ_ERROR_MSG[] = {
"Unkown internal scanner error",
"Error: could not match input",
"Error: pushback value was too large"
};
/**
* ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code>
*/
private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute();
private static final String ZZ_ATTRIBUTE_PACKED_0 =
"\2\0\4\1\1\11\1\1\1\11\2\1\1\11\16\1"+
"\2\11\14\1\1\11\26\1\1\11\6\1\1\0\73\1"+
"\2\0\3\1\2\0\1\1\1\0\137\1\2\0\3\1"+
"\2\0\100\1\1\0\3\1\1\0\52\1\1\0\1\1"+
"\1\0\47\1\1\0\10\1\1\0\3\1\1\0\2\1"+
"\6\0\1\11";
private static int [] zzUnpackAttribute() {
int [] result = new int[417];
int offset = 0;
offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result);
return result;
}
private static int zzUnpackAttribute(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
do result[j++] = value; while (--count > 0);
}
return j;
}
/** the input device */
private java.io.Reader zzReader;
/** the current state of the DFA */
private int zzState;
/** the current lexical state */
private int zzLexicalState = YYINITIAL;
/** this buffer contains the current text to be matched and is
the source of the yytext() string */
private char zzBuffer[];
/** the textposition at the last accepting state */
private int zzMarkedPos;
/** the current text position in the buffer */
private int zzCurrentPos;
/** startRead marks the beginning of the yytext() string in the buffer */
private int zzStartRead;
/** endRead marks the last character in the buffer, that has been read
from input */
private int zzEndRead;
/** zzAtEOF == true <=> the scanner is at the EOF */
private boolean zzAtEOF;
/* user code: */
/**
* Constructor. This must be here because JFlex does not generate a
* no-parameter constructor.
*/
public VisualBasicTokenMaker() {
}
/**
* Adds the token specified to the current linked list of tokens.
*
* @param tokenType The token's type.
* @see #addToken(int, int, int)
*/
private void addHyperlinkToken(int start, int end, int tokenType) {
int so = start + offsetShift;
addToken(zzBuffer, start,end, tokenType, so, true);
}
/**
* Adds the token specified to the current linked list of tokens.
*
* @param tokenType The token's type.
*/
private void addToken(int tokenType) {
addToken(zzStartRead, zzMarkedPos-1, tokenType);
}
/**
* Adds the token specified to the current linked list of tokens.
*
* @param tokenType The token's type.
* @see #addHyperlinkToken(int, int, int)
*/
private void addToken(int start, int end, int tokenType) {
int so = start + offsetShift;
addToken(zzBuffer, start,end, tokenType, so, false);
}
/**
* Adds the token specified to the current linked list of tokens.
*
* @param array The character array.
* @param start The starting offset in the array.
* @param end The ending offset in the array.
* @param tokenType The token's type.
* @param startOffset The offset in the document at which this token
* occurs.
* @param hyperlink Whether this token is a hyperlink.
*/
public void addToken(char[] array, int start, int end, int tokenType,
int startOffset, boolean hyperlink) {
super.addToken(array, start,end, tokenType, startOffset, hyperlink);
zzStartRead = zzMarkedPos;
}
/**
* Returns the text to place at the beginning and end of a
* line to "comment" it in a this programming language.
*
* @return The start and end strings to add to a line to "comment"
* it out.
*/
public String[] getLineCommentStartAndEnd() {
return new String[] { "'", null };
}
/**
* Returns the first token in the linked list of tokens generated
* from <code>text</code>. This method must be implemented by
* subclasses so they can correctly implement syntax highlighting.
*
* @param text The text from which to get tokens.
* @param initialTokenType The token type we should start with.
* @param startOffset The offset into the document at which
* <code>text</code> starts.
* @return The first <code>Token</code> in a linked list representing
* the syntax highlighted text.
*/
public Token getTokenList(Segment text, int initialTokenType, int startOffset) {
resetTokenList();
this.offsetShift = -text.offset + startOffset;
// Start off in the proper state.
int state = YYINITIAL;
s = text;
try {
yyreset(zzReader);
yybegin(state);
return yylex();
} catch (IOException ioe) {
ioe.printStackTrace();
return new Token();
}
}
/**
* Refills the input buffer.
*
* @return <code>true</code> if EOF was reached, otherwise
* <code>false</code>.
*/
private boolean zzRefill() {
return zzCurrentPos>=s.offset+s.count;
}
/**
* Resets the scanner to read from a new input stream.
* Does not close the old reader.
*
* All internal variables are reset, the old input stream
* <b>cannot</b> be reused (internal buffer is discarded and lost).
* Lexical state is set to <tt>YY_INITIAL</tt>.
*
* @param reader the new input stream
*/
public final void yyreset(java.io.Reader reader) {
// 's' has been updated.
zzBuffer = s.array;
/*
* We replaced the line below with the two below it because zzRefill
* no longer "refills" the buffer (since the way we do it, it's always
* "full" the first time through, since it points to the segment's
* array). So, we assign zzEndRead here.
*/
//zzStartRead = zzEndRead = s.offset;
zzStartRead = s.offset;
zzEndRead = zzStartRead + s.count - 1;
zzCurrentPos = zzMarkedPos = s.offset;
zzLexicalState = YYINITIAL;
zzReader = reader;
zzAtEOF = false;
}
/**
* Creates a new scanner
* There is also a java.io.InputStream version of this constructor.
*
* @param in the java.io.Reader to read input from.
*/
public VisualBasicTokenMaker(java.io.Reader in) {
this.zzReader = in;
}
/**
* Creates a new scanner.
* There is also java.io.Reader version of this constructor.
*
* @param in the java.io.Inputstream to read input from.
*/
public VisualBasicTokenMaker(java.io.InputStream in) {
this(new java.io.InputStreamReader(in));
}
/**
* Unpacks the compressed character translation table.
*
* @param packed the packed character translation table
* @return the unpacked character translation table
*/
private static char [] zzUnpackCMap(String packed) {
char [] map = new char[0x10000];
int i = 0; /* index in packed string */
int j = 0; /* index in unpacked array */
while (i < 184) {
int count = packed.charAt(i++);
char value = packed.charAt(i++);
do map[j++] = value; while (--count > 0);
}
return map;
}
/**
* Closes the input stream.
*/
public final void yyclose() throws java.io.IOException {
zzAtEOF = true; /* indicate end of file */
zzEndRead = zzStartRead; /* invalidate buffer */
if (zzReader != null)
zzReader.close();
}
/**
* Returns the current lexical state.
*/
public final int yystate() {
return zzLexicalState;
}
/**
* Enters a new lexical state
*
* @param newState the new lexical state
*/
public final void yybegin(int newState) {
zzLexicalState = newState;
}
/**
* Returns the text matched by the current regular expression.
*/
public final String yytext() {
return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead );
}
/**
* Returns the character at position <tt>pos</tt> from the
* matched text.
*
* It is equivalent to yytext().charAt(pos), but faster
*
* @param pos the position of the character to fetch.
* A value from 0 to yylength()-1.
*
* @return the character at position pos
*/
public final char yycharat(int pos) {
return zzBuffer[zzStartRead+pos];
}
/**
* Returns the length of the matched text region.
*/
public final int yylength() {
return zzMarkedPos-zzStartRead;
}
/**
* Reports an error that occured while scanning.
*
* In a wellformed scanner (no or only correct usage of
* yypushback(int) and a match-all fallback rule) this method
* will only be called with things that "Can't Possibly Happen".
* If this method is called, something is seriously wrong
* (e.g. a JFlex bug producing a faulty scanner etc.).
*
* Usual syntax/scanner level error handling should be done
* in error fallback rules.
*
* @param errorCode the code of the errormessage to display
*/
private void zzScanError(int errorCode) {
String message;
try {
message = ZZ_ERROR_MSG[errorCode];
}
catch (ArrayIndexOutOfBoundsException e) {
message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
}
throw new Error(message);
}
/**
* Pushes the specified amount of characters back into the input stream.
*
* They will be read again by then next call of the scanning method
*
* @param number the number of characters to be read again.
* This number must not be greater than yylength()!
*/
public void yypushback(int number) {
if ( number > yylength() )
zzScanError(ZZ_PUSHBACK_2BIG);
zzMarkedPos -= number;
}
/**
* Resumes scanning until the next regular expression is matched,
* the end of input is encountered or an I/O-Error occurs.
*
* @return the next token
* @exception java.io.IOException if any I/O-Error occurs
*/
public org.fife.ui.rsyntaxtextarea.Token yylex() throws java.io.IOException {
int zzInput;
int zzAction;
// cached fields:
int zzCurrentPosL;
int zzMarkedPosL;
int zzEndReadL = zzEndRead;
char [] zzBufferL = zzBuffer;
char [] zzCMapL = ZZ_CMAP;
int [] zzTransL = ZZ_TRANS;
int [] zzRowMapL = ZZ_ROWMAP;
int [] zzAttrL = ZZ_ATTRIBUTE;
while (true) {
zzMarkedPosL = zzMarkedPos;
zzAction = -1;
zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL;
zzState = zzLexicalState;
zzForAction: {
while (true) {
if (zzCurrentPosL < zzEndReadL)
zzInput = zzBufferL[zzCurrentPosL++];
else if (zzAtEOF) {
zzInput = YYEOF;
break zzForAction;
}
else {
// store back cached positions
zzCurrentPos = zzCurrentPosL;
zzMarkedPos = zzMarkedPosL;
boolean eof = zzRefill();
// get translated positions and possibly new buffer
zzCurrentPosL = zzCurrentPos;
zzMarkedPosL = zzMarkedPos;
zzBufferL = zzBuffer;
zzEndReadL = zzEndRead;
if (eof) {
zzInput = YYEOF;
break zzForAction;
}
else {
zzInput = zzBufferL[zzCurrentPosL++];
}
}
int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ];
if (zzNext == -1) break zzForAction;
zzState = zzNext;
int zzAttributes = zzAttrL[zzState];
if ( (zzAttributes & 1) == 1 ) {
zzAction = zzState;
zzMarkedPosL = zzCurrentPosL;
if ( (zzAttributes & 8) == 8 ) break zzForAction;
}
}
}
// store back cached position
zzMarkedPos = zzMarkedPosL;
switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) {
case 5:
{ addNullToken(); return firstToken;
}
case 21: break;
case 6:
{ addToken(Token.WHITESPACE);
}
case 22: break;
case 16:
{ addToken(Token.LITERAL_NUMBER_HEXADECIMAL);
}
case 23: break;
case 13:
{ addToken(Token.LITERAL_NUMBER_FLOAT);
}
case 24: break;
case 15:
{ addToken(Token.RESERVED_WORD);
}
case 25: break;
case 9:
{ addToken(Token.SEPARATOR);
}
case 26: break;
case 2:
{ addToken(Token.IDENTIFIER);
}
case 27: break;
case 11:
{ addToken(start,zzStartRead-1, Token.COMMENT_EOL); addNullToken(); return firstToken;
}
case 28: break;
case 7:
{ addToken(Token.ERROR_STRING_DOUBLE); addNullToken(); return firstToken;
}
case 29: break;
case 1:
{ addToken(Token.ERROR_IDENTIFIER);
}
case 30: break;
case 17:
{ addToken(Token.DATA_TYPE);
}
case 31: break;
case 18:
{ addToken(Token.LITERAL_BOOLEAN);
}
case 32: break;
case 14:
{ addToken(Token.LITERAL_STRING_DOUBLE_QUOTE);
}
case 33: break;
case 19:
{ int temp=zzStartRead; addToken(start,zzStartRead-1, Token.COMMENT_EOL); addHyperlinkToken(temp,zzMarkedPos-1, Token.COMMENT_EOL); start = zzMarkedPos;
}
case 34: break;
case 20:
{ addToken(Token.RESERVED_WORD_2);
}
case 35: break;
case 12:
{ addToken(Token.ERROR_NUMBER_FORMAT);
}
case 36: break;
case 8:
{ start = zzMarkedPos-1; yybegin(EOL_COMMENT);
}
case 37: break;
case 3:
{ addToken(Token.LITERAL_NUMBER_DECIMAL_INT);
}
case 38: break;
case 4:
{ addToken(Token.OPERATOR);
}
case 39: break;
case 10:
{
}
case 40: break;
default:
if (zzInput == YYEOF && zzStartRead == zzCurrentPos) {
zzAtEOF = true;
switch (zzLexicalState) {
case EOL_COMMENT: {
addToken(start,zzStartRead-1, Token.COMMENT_EOL); addNullToken(); return firstToken;
}
case 418: break;
case YYINITIAL: {
addNullToken(); return firstToken;
}
case 419: break;
default:
return null;
}
}
else {
zzScanError(ZZ_NO_MATCH);
}
}
}
}
}
| 38.76358 | 163 | 0.504212 |
ecf2249db678e6c86730732b435f42dfa432de95 | 657 | package com.louisblogs.louismall.member.config;
import com.louisblogs.louismall.member.interceptor.LoginUserInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author :luqi
* @description:TODO
* @date :2021/7/1 9:04
*/
@Configuration
public class MemberWebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//拦截哪个拦截器的所有请求
registry.addInterceptor(new LoginUserInterceptor()).addPathPatterns("/**");
}
}
| 26.28 | 77 | 0.806697 |
c9344915abc2af128642c0349cb6de861f929602 | 4,599 | package org.jgroups.protocols.mklinger;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Objects;
import java.util.function.Supplier;
import org.jgroups.Global;
import org.jgroups.stack.IpAddress;
public class HostAddress extends IpAddress {
public HostAddress() {
}
public HostAddress(final IpAddress ipAddress) {
super(ipAddress.getIpAddress(), ipAddress.getPort());
}
public HostAddress(final InetAddress i, final int p) {
super(i, p);
}
public HostAddress(final InetSocketAddress sock_addr) {
super(sock_addr);
}
/** e.g. 192.168.1.5:7800 or localhost/127.0.0.1:8080 */
public HostAddress(final String addr_port) throws Exception {
final int lastColonIdx = addr_port.lastIndexOf(':');
String withoutPort;
if(lastColonIdx == -1) {
withoutPort = addr_port;
} else {
withoutPort = addr_port.substring(0, lastColonIdx);
port = Integer.valueOf(addr_port.substring(lastColonIdx+1));
}
String hostName;
String ip;
final int firstSlashIdx = withoutPort.indexOf('/');
if (firstSlashIdx == -1) {
hostName = null;
ip = withoutPort;
} else {
hostName = withoutPort.substring(0, firstSlashIdx);
if (hostName.isEmpty()) {
hostName = null;
}
ip = withoutPort.substring(firstSlashIdx + 1);
}
final byte[] ipBytes = InetAddresses.ipStringToBytes(ip);
if (ipBytes == null) {
ip_addr = InetAddress.getByName(ip);
} else {
ip_addr = InetAddress.getByAddress(hostName, ipBytes);
}
}
@Override
public Supplier<? extends IpAddress> create() {
return HostAddress::new;
}
@Override
public HostAddress copy() {
return new HostAddress(ip_addr, port);
}
@Override
public String printIpAddress() {
return Objects.toString(ip_addr, "<null>") + ":" + port;
}
@Override
public String toString() {
return printIpAddress();
}
@Override
public void writeTo(final DataOutput out) throws Exception {
writeHostName(out);
writeIp(out);
writePort(out);
}
private void writeHostName(final DataOutput out) throws IOException {
final String hostName = getHostName();
if (hostName == null) {
out.writeInt(0);
} else {
out.writeInt(hostName.length());
out.writeChars(hostName);
}
}
public String getHostName() {
final String s = ip_addr.toString();
final int idx = s.indexOf('/');
if (idx > 0) {
return s.substring(0, idx);
} else {
return null;
}
}
private void writeIp(final DataOutput out) throws IOException {
if(ip_addr != null) {
final byte[] address=ip_addr.getAddress(); // 4 bytes (IPv4) or 16 bytes (IPv6)
out.writeByte(address.length); // 1 byte
out.write(address, 0, address.length);
if(ip_addr instanceof Inet6Address) {
out.writeInt(((Inet6Address)ip_addr).getScopeId());
}
}
else {
out.writeByte(0);
}
}
private void writePort(final DataOutput out) throws IOException {
out.writeShort(port);
}
@Override
public void readFrom(final DataInput in) throws Exception {
readHostNameAndIp(in);
readPort(in);
}
private void readHostNameAndIp(final DataInput in) throws IOException {
final String hostName = doReadHostName(in);
final int len=in.readByte();
if(len > 0 && (len != Global.IPV4_SIZE && len != Global.IPV6_SIZE)) {
throw new IOException("length has to be " + Global.IPV4_SIZE + " or " + Global.IPV6_SIZE + " bytes (was " +
len + " bytes)");
}
final byte[] a = new byte[len]; // 4 bytes (IPv4) or 16 bytes (IPv6)
in.readFully(a);
if(len == Global.IPV6_SIZE) {
final int scope_id=in.readInt();
this.ip_addr=Inet6Address.getByAddress(hostName, a, scope_id);
}
else {
this.ip_addr=InetAddress.getByAddress(hostName, a);
}
}
private String doReadHostName(final DataInput in) throws IOException {
final int len = in.readInt();
if (len == 0) {
return null;
}
final char[] buf = new char[len];
for (int i = 0; i < buf.length; i++) {
buf[i] = in.readChar();
}
return new String(buf);
}
private void readPort(final DataInput in) throws IOException {
// changed from readShort(): we need the full 65535, with a short we'd only get up to 32K !
port=in.readUnsignedShort();
}
@Override
public int serializedSize() {
// length (1 bytes) + 4 bytes for port
int tmp_size=Global.BYTE_SIZE+ Global.SHORT_SIZE;
if(ip_addr != null) {
// 4 bytes for IPv4, 20 for IPv6 (16 + 4 for scope-id)
tmp_size+=(ip_addr instanceof Inet4Address)? 4 : 20;
}
return tmp_size;
}
}
| 25.131148 | 110 | 0.688411 |
4d7066b9c654aea5e197442b70d5ca9fcfe19e64 | 1,931 | package com.gtc.tradinggateway.service.gdax;
import com.appunite.websocket.rx.object.messages.RxObjectEventConnected;
import com.fasterxml.jackson.databind.JsonNode;
import com.gtc.tradinggateway.config.GdaxConfig;
import com.gtc.tradinggateway.meta.TradingCurrency;
import com.gtc.tradinggateway.service.BaseWsClient;
import com.gtc.tradinggateway.service.CreateOrder;
import com.gtc.tradinggateway.service.dto.OrderCreatedDto;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.Map;
import java.util.Optional;
import static com.gtc.tradinggateway.config.Const.Clients.GDAX;
/**
* Created by Valentyn Berezin on 16.01.18.
*/
@Service
public class GdaxWsService extends BaseWsClient implements CreateOrder {
private final GdaxConfig cfg;
private final GdaxEncryptionService signer;
public GdaxWsService(GdaxConfig cfg, GdaxEncryptionService signer) {
super(cfg.getMapper());
this.cfg = cfg;
this.signer = signer;
}
@Override
public Optional<OrderCreatedDto> create(String tryToAssignId, TradingCurrency from, TradingCurrency to,
BigDecimal amount, BigDecimal price) {
return Optional.empty();
}
@Override
protected String getWs() {
return cfg.getWsBase();
}
@Override
protected void onConnected(RxObjectEventConnected conn) {
// NOP
}
@Override
protected void parseEventDto(JsonNode node) {
// NOP
}
@Override
protected void parseArray(JsonNode node) {
// NOP
}
@Override
protected void login() {}
@Override
protected boolean handledAsLogin(JsonNode node) {
return false;
}
@Override
protected Map<String, String> headers() {
return signer.signingHeaders("", "", "");
}
@Override
public String name() {
return GDAX;
}
}
| 25.077922 | 107 | 0.690316 |
7f5ef5b138c6fb6cc17185e5aa079c3d7080e34f | 2,536 | package com.campcode.maanav.digimate.activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatSeekBar;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import com.campcode.maanav.digimate.R;
import com.campcode.maanav.digimate.helper.OtsuThresholder;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.googlecode.leptonica.android.GrayQuant;
import com.googlecode.leptonica.android.Pix;
public class BinarizationActivity extends AppCompatActivity implements View.OnClickListener, SeekBar.OnSeekBarChangeListener {
public static Bitmap umbralization;
private Pix pix;
private ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_binarization);
img = (ImageView) findViewById(R.id.croppedImage);
FloatingActionButton mFab = (FloatingActionButton) findViewById(R.id.nextStep);
mFab.setOnClickListener(this);
pix = com.googlecode.leptonica.android.ReadFile.readBitmap(CropActivity.croppedImage);
OtsuThresholder otsuThresholder = new OtsuThresholder();
int threshold = otsuThresholder.doThreshold(pix.getData());
/* Increasing value of threshold is better */
threshold += 20;
umbralization = com.googlecode.leptonica.android.WriteFile.writeBitmap
(GrayQuant.pixThresholdToBinary(pix, threshold));
img.setImageBitmap(umbralization);
AppCompatSeekBar seekBar = (AppCompatSeekBar) findViewById(R.id.umbralization);
seekBar.setProgress((50 * threshold) / 254);
seekBar.setOnSeekBarChangeListener(this);
}
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
umbralization = com.googlecode.leptonica.android.WriteFile.writeBitmap(
GrayQuant.pixThresholdToBinary(pix, ((254 * seekBar.getProgress()) / 50)));
img.setImageBitmap(umbralization);
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.nextStep) {
startActivity(new Intent(BinarizationActivity.this, RecognizerActivity.class));
}
}
}
| 37.850746 | 126 | 0.736199 |
65d0ca31867a585de862ee6d9bd8927188b4a0cd | 1,236 | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.quickstarts.ejbTimer;
import javax.ejb.Schedule;
import javax.ejb.Singleton;
/**
* Demonstrates how to use the EJB's @Schedule.
*
* @author <a href="mailto:ozizka@redhat.com">Ondrej Zizka</a>
*/
@Singleton
public class ScheduleExample {
@Schedule(second="*/2", minute="*",hour="*", persistent=false)
public void doWork(){
System.out.println( "Hi from the EJB timer example!" );
}
} | 34.333333 | 75 | 0.723301 |
ad0459442d3fe94a880c3e3c8dc4e10479d44e62 | 1,707 | package com.github.jinsen47.baidu;
import java.util.Scanner;
/**
* Created by Jinsen on 16/9/20.
* ss请cc来家里钓鱼,鱼塘可划分为n*m的格子,每个格子有不同的概率钓上鱼,cc一直在坐标(x,y)的格子钓鱼,而ss每分钟随机钓一个格子。问t分钟后他们谁至少钓到一条鱼的概率大?为多少?
* 第一行五个整数n,m,x,y,t(1≤n,m,t≤1000,1≤x≤n,1≤y≤m);
* 接下来为一个n*m的矩阵,每行m个一位小数,共n行,第i行第j个数代表坐标为(i,j)的格子钓到鱼的概率为p(0≤p≤1)
*
* 输出两行。第一行为概率大的人的名字(cc/ss/equal),第二行为这个概率(保留2位小数)
*/
public class Fish {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
int n = in.nextInt();
int m = in.nextInt();
int x = in.nextInt();
int y = in.nextInt();
int t = in.nextInt();
float[][] matrix = new float[n][m];
float pSS = 0.0f;
in.nextLine();
for (int i = 0; i < n; i++) {
String[] line = in.nextLine().split(" ");
for (int j = 0; j < m; j++) {
matrix[i][j] = Float.valueOf(line[j]);
pSS += matrix[i][j];
}
}
pSS /= m*n;
float pCC = matrix[x - 1][y - 1];
String nPSS = String.format("%.2f", 1 - (float)Math.pow(1-pSS, t));
String nPCC = String.format("%.2f", 1 - (float)Math.pow(1-pCC, t));
if (Float.valueOf(nPSS) > Float.valueOf(nPCC)) {
System.out.println("ss");
System.out.println(nPSS);
} else if (nPSS.equals(nPCC)) {
System.out.println("equal");
System.out.println(nPSS);
} else {
System.out.println("cc");
System.out.println(nPSS);
}
}
}
}
| 33.470588 | 97 | 0.485062 |
17682da603e635baf924fa8f232b4de603a45acc | 3,360 | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2020 DBeaver Corp and others
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.cloudbeaver.service.sql;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.model.*;
import org.jkiss.dbeaver.model.exec.DBCExecutionContext;
import org.jkiss.dbeaver.model.sql.SQLSyntaxManager;
import org.jkiss.dbeaver.model.sql.completion.SQLCompletionContext;
import org.jkiss.dbeaver.model.sql.completion.SQLCompletionProposalBase;
import org.jkiss.dbeaver.model.sql.completion.SQLCompletionRequest;
import java.util.Map;
/**
* Web SQL dialect.
*/
public class WebSQLCompletionContext implements SQLCompletionContext {
private static final Log log = Log.getLog(WebSQLCompletionContext.class);
private final WebSQLContextInfo sqlContext;
public WebSQLCompletionContext(WebSQLContextInfo context) {
this.sqlContext = context;
}
@Override
public DBPDataSource getDataSource() {
return sqlContext.getProcessor().getConnection().getDataSource();
}
@Override
public DBCExecutionContext getExecutionContext() {
return DBUtils.getDefaultContext(
sqlContext.getProcessor().getConnection().getDataSource(),
false);
}
@Override
public SQLSyntaxManager getSyntaxManager() {
return sqlContext.getProcessor().getSyntaxManager();
}
@Override
public boolean isUseFQNames() {
return false;
}
@Override
public boolean isReplaceWords() {
return false;
}
@Override
public boolean isShowServerHelp() {
return false;
}
@Override
public boolean isUseShortNames() {
return false;
}
@Override
public int getInsertCase() {
return PROPOSAL_CASE_DEFAULT;
}
@Override
public boolean isSearchProcedures() {
return false;
}
@Override
public boolean isSearchInsideNames() {
return false;
}
@Override
public boolean isSortAlphabetically() {
return false;
}
@Override
public boolean isSearchGlobally() {
return false;
}
@Override
public boolean isHideDuplicates() {
return false;
}
@Override
public SQLCompletionProposalBase createProposal(@NotNull SQLCompletionRequest request, @NotNull String displayString, @NotNull String replacementString, int cursorPosition, @Nullable DBPImage image, @NotNull DBPKeywordType proposalType, @Nullable String description, @Nullable DBPNamedObject object, @NotNull Map<String, Object> params) {
return new SQLCompletionProposalBase(this, request.getWordDetector(), displayString, replacementString, cursorPosition, image, proposalType, description, object, params);
}
}
| 28.965517 | 342 | 0.716964 |
fee3812324e62751fe1014aa32853258a330cddf | 7,218 | /*
* 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 SVGPath2TextTest;
import static SVGPath2TextTest.AddViewport.setViewBoxPageSize;
import static SVGPath2TextTest.ExtraktLettersFromPath.getUri;
import java.awt.GridLayout;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URI;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import org.apache.batik.bridge.BridgeContext;
import org.apache.batik.bridge.DocumentLoader;
import org.apache.batik.bridge.GVTBuilder;
import org.apache.batik.bridge.UserAgent;
import org.apache.batik.bridge.UserAgentAdapter;
import org.apache.batik.dom.svg.SAXSVGDocumentFactory;
import org.apache.batik.dom.svg.SVGOMPathElement;
import org.apache.batik.dom.svg.SVGOMSVGElement;
import org.apache.batik.gvt.GraphicsNode;
import org.apache.batik.svggen.SVGGraphics2D;
import org.apache.batik.svggen.SVGGraphics2DIOException;
import org.apache.batik.swing.JSVGCanvas;
import org.apache.batik.util.XMLResourceDescriptor;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.svg.SVGDocument;
public class RemoveAllRedPathes {
// see also http://mt4j.googlecode.com/svn-history/r320/trunk/src/org/mt4j/util/xml/svg/SVGLoader.java
private static String svgNS;
private static JFrame jFrame;
private static SVGDocument doc;
private static BridgeContext ctx;
private static GVTBuilder builder;
private static SVGOMSVGElement myRootSVGElement;
private static UserAgent userAgent;
private static DocumentLoader loader;
private static GraphicsNode rootGN;
private static GraphicsNode gnElement;
private static GraphicsNode gntxtElem;
private static NodeList nlPath;
private static String uri;
/**
* @param args
*/
public static void main(String[] args) throws IOException {
// Create a new JSVGCanvas.
JSVGCanvas canvas;
canvas = new JSVGCanvas();
// A frame for the canvas to live in
jFrame = new JFrame("uri");
jFrame.setSize(800, 800);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setLayout(new GridLayout());
jFrame.getContentPane().add(canvas);
jFrame.setVisible(true);
String name = ExtraktLettersFromPath.getUri().substring(6, ExtraktLettersFromPath.getUri().indexOf(".svg"))
+ "_path_text.svg";
// (ExtraktLettersFromPath.getUri()).toURL().toString();
///////////////////////////////////////////////////////////////////////////
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);
String uri = new File(name).toURI().toString(); // the URI of your SVG document
doc = (SVGDocument) f.createDocument(uri);
userAgent = new UserAgentAdapter();
loader = new DocumentLoader(userAgent);
ctx = new BridgeContext(userAgent, loader);
ctx.setDynamicState(BridgeContext.DYNAMIC);
builder = new GVTBuilder();
rootGN = builder.build(ctx, doc);
myRootSVGElement = (SVGOMSVGElement) doc.getDocumentElement();
///////////////////////////////////////////////////////////////////////////
svgNS = myRootSVGElement.SVG_NAMESPACE_URI;
// Make the text look nice.
// svgRoot.setAttributeNS(null, "text-rendering", "geometricPrecision");
// Remove the xml-stylesheet PI.
for (Node n = myRootSVGElement.getPreviousSibling();
n != null;
n = n.getPreviousSibling()) {
if (n.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
doc.removeChild(n);
break;
}
}
// Remove the Batik sample mark 'use' element.
for (Node n = myRootSVGElement.getLastChild();
n != null;
n = n.getPreviousSibling()) {
if (n.getNodeType() == Node.ELEMENT_NODE
&& n.getLocalName().equals("use")) {
myRootSVGElement.removeChild(n);
break;
}
}
// Display the document.
canvas.setDocumentState(JSVGCanvas.ALWAYS_DYNAMIC);
canvas.setDocument(doc);
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(RemoveAllRedPathes.class.getName()).log(Level.SEVERE, null, ex);
}
nlPath = myRootSVGElement.getElementsByTagName("path");
for (int i = nlPath.getLength() - 1; i >= 0; i--) {
SVGOMPathElement nlElem = (SVGOMPathElement) nlPath.item(i);
System.out.print("Inspecting: "+ nlElem.getAttributeNS(null, "id"));
String attrFill = nlElem.getAttributeNS(null, "fill");
String attrStyle = nlElem.getAttributeNS(null, "style");
if ( attrFill.equals( ExtraktLettersFromPath.getStrColor4Done()[0]) ||
attrStyle.equals( ExtraktLettersFromPath.getStrColor4Done()[1] )) {
nlElem.getParentNode().removeChild(nlElem);
System.out.println("\t...deleted");
}
else {
System.out.println();
}
}
saveSVG();
System.exit(0);
}
private static void saveSVG() {
setViewBoxPageSize(myRootSVGElement, rootGN, doc);
OutputStream os = null;
String strOutPutFile = ExtraktLettersFromPath.getUri().substring(6
, ExtraktLettersFromPath.getUri().indexOf(".svg")) + "_text.svg";
try {
os = new FileOutputStream(strOutPutFile);
// ("C:\\Users\\Martin\\Programming\\git\\SVG2Text_Netbeans\\Daten\\test.svg");
Writer w = new OutputStreamWriter(os, "UTF-8");
SVGGraphics2D svgGenerator = new SVGGraphics2D(doc);
svgGenerator.stream(myRootSVGElement, w);
w.close();
os.close();
svgGenerator.dispose();
} catch (FileNotFoundException ex) {
Logger.getLogger(ExtraktLettersFromPath.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(ExtraktLettersFromPath.class.getName()).log(Level.SEVERE, null, ex);
} catch (SVGGraphics2DIOException ex) {
Logger.getLogger(ExtraktLettersFromPath.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ExtraktLettersFromPath.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
os.close();
} catch (IOException ex) {
Logger.getLogger(ExtraktLettersFromPath.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
| 40.324022 | 115 | 0.634802 |
ee56b3cec4b3b6c7e01d1e9dbc19f4b94f3a9184 | 5,419 | package org.firstinspires.ftc.teamcode.test;
import android.graphics.Bitmap;
import android.graphics.Color;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
//import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
//import org.firstinspires.ftc.teamcode.framework.abstractopmodes.AbstractAuton;
//import org.firstinspires.ftc.teamcode.framework.userhardware.DoubleTelemetry;
import org.firstinspires.ftc.teamcode.hardware.image.ImageViewer;
import org.firstinspires.ftc.teamcode.hardware.vuforia.VuforiaImpl;
import java.util.ArrayList;
import java.util.Collections;
//@TeleOp(name = "VisionTest", group = "Test")
//@Disabled
@TeleOp(name = "VisionTest Draw Lines", group = "Sensor")
public class VisionTest extends LinearOpMode {
VuforiaImpl vuforia;
ImageViewer imageViewer;
int currentRow = -1;
@Override
public void runOpMode( ) {
vuforia = new VuforiaImpl(hardwareMap, false, true);
imageViewer = new ImageViewer(vuforia.getRotation());
// Wait for the game to start (driver presses PLAY)
waitForStart();
while ( opModeIsActive()) {
Bitmap bitmap = vuforia.getImage();
ArrayList<Integer> rows = new ArrayList<>();
for(int r = 0; r < bitmap.getHeight(); r+=16) {
int y = 0;
for(int c = 0; c < bitmap.getWidth(); c+=16) {
int pixel = bitmap.getPixel(c, r);
y += (Color.red(pixel) + Color.green(pixel) / 2) - Color.blue(pixel);
}
rows.add(y);
}
//telemetry.addDataDB(DoubleTelemetry.LogMode.INFO, rows);
rows = filterArray(rows, 5);
//telemetry.addDataDB(DoubleTelemetry.LogMode.INFO, rows);
if(currentRow == -1) currentRow = bitmap.getHeight() / 2;
ArrayList<Integer> pixels = new ArrayList<>();
for(int p = 0; p < bitmap.getWidth(); p++) {
int pixel = bitmap.getPixel(p, currentRow);
bitmap.setPixel(p, currentRow, Color.rgb(0, 0, 0));
pixels.add(Color.red(pixel) + Color.green(pixel) + Color.blue(pixel));
}
positionFromPixels(pixels);
for(int p = 0; p < bitmap.getHeight(); p++) {
// white
bitmap.setPixel((bitmap.getWidth() / 5) * 1, p, Color.rgb(254, 254, 254));
// green
bitmap.setPixel((bitmap.getWidth() / 5) * 2, p, Color.rgb(16 , 242, 91));
// red
bitmap.setPixel((bitmap.getWidth() / 5) * 3, p, Color.rgb(255, 0, 0));
// blue
bitmap.setPixel((bitmap.getWidth() / 5) * 4, p, Color.rgb(0, 0, 255));
}
/*int above = 0, below = 0;
for(int r = 0; r < rows.size(); r++) {
if(rows.get(r) == -1) continue;
for(int c = 0; c < bitmap.getWidth(); c++) {
bitmap.setPixel(c, r * 8, Color.rgb(254, 254, 254));
}
if(r * 8 < currentRow) {
above++;
} else {
below++;
}
}*/
//currentRow += (below - above) * 5;
imageViewer.setImage(bitmap);
} // end of runOpMode
}
// draw circle example
// https://stackoverflow.com/questions/9007977/draw-circle-using-pixels-applied-in-an-image-with-for-loop
public void positionFromPixels(ArrayList<Integer> pixels) {
int numPixels = pixels.size();
//telemetry.addData( "Unfiltered: " , pixels);
pixels = filterArray(pixels, 5);
//telemetry.addData( "Filtered: " , pixels);
int left = 0, center = 0, right = 0;
for(int p = 0; p < numPixels; p++) {
if(pixels.get(p) == -1) pixels.set(p, 255);
pixels.set(p, 255 - pixels.get(p));
if(pixels.get(p) == 0) continue;
if(p > (numPixels / 4.0) && p < (numPixels / 5.0) * 2) {
left++;
} else if(p > (numPixels / 5.0) * 2 && p < (numPixels / 5) * 3) {
center++;
} else if(p > (numPixels / 5) * 3 && p < (numPixels / 4) * 3){
right++;
}
}
telemetry.addData( "Left: " + left + " Center: " + center + " Right: " + right, " ");
if(left > center && left > right) {
telemetry.addData( "Left", " ");
} else if(center > right) {
telemetry.addData( "Center", "");
} else {
telemetry.addData( "Right","");
}
telemetry.update();
}
public ArrayList<Integer> filterArray(ArrayList<Integer> pixels, int level) {
int numPixels = pixels.size();
ArrayList<Integer> sortedPixels = (ArrayList<Integer>) pixels.clone();
Collections.sort(sortedPixels);
for(int p = 0; p < numPixels; p++) {
int total = 0;
total += pixels.get(p);
if(p != 0) total += pixels.get(p - 1);
if(p != pixels.size() - 1) total += pixels.get(p + 1);
pixels.set(p, total / 3);
}
int cutoff = sortedPixels.get(numPixels / level);
for(int p = 0; p < numPixels; p++) {
if(pixels.get(p) > cutoff) {
pixels.set(p, -1);
}
}
return pixels;
}
}
| 32.644578 | 109 | 0.53091 |
67d66a7073071d164e7864cea6a61719e2d52b84 | 237 | package creational.builder;
public interface Builder {
public String getName();
void buildComponent1(String component1);
void buildComponent2(String component2);
void buildComponent3(String component3);
Product getProduct();
} | 26.333333 | 42 | 0.78903 |
80001b7155c993f76d53ce9ae748815158671f86 | 10,028 | package net.minecraft.server;
import java.util.List;
import java.util.UUID;
import javax.annotation.Nullable;
public abstract class EntityProjectile extends Entity implements IProjectile {
private int blockX;
private int blockY;
private int blockZ;
private Block inBlockId;
protected boolean inGround;
public int shake;
public EntityLiving shooter;
public String shooterName;
private int au;
private int av;
public Entity d;
private int aw;
public EntityProjectile(World world) {
super(world);
this.blockX = -1;
this.blockY = -1;
this.blockZ = -1;
this.setSize(0.25F, 0.25F);
}
public EntityProjectile(World world, double d0, double d1, double d2) {
this(world);
this.setPosition(d0, d1, d2);
}
public EntityProjectile(World world, EntityLiving entityliving) {
this(world, entityliving.locX, entityliving.locY + (double) entityliving.getHeadHeight() - 0.10000000149011612D, entityliving.locZ);
this.shooter = entityliving;
}
protected void i() {}
public void a(Entity entity, float f, float f1, float f2, float f3, float f4) {
float f5 = -MathHelper.sin(f1 * 0.017453292F) * MathHelper.cos(f * 0.017453292F);
float f6 = -MathHelper.sin((f + f2) * 0.017453292F);
float f7 = MathHelper.cos(f1 * 0.017453292F) * MathHelper.cos(f * 0.017453292F);
this.shoot((double) f5, (double) f6, (double) f7, f3, f4);
this.motX += entity.motX;
this.motZ += entity.motZ;
if (!entity.onGround) {
this.motY += entity.motY;
}
}
public void shoot(double d0, double d1, double d2, float f, float f1) {
float f2 = MathHelper.sqrt(d0 * d0 + d1 * d1 + d2 * d2);
d0 /= (double) f2;
d1 /= (double) f2;
d2 /= (double) f2;
d0 += this.random.nextGaussian() * 0.007499999832361937D * (double) f1;
d1 += this.random.nextGaussian() * 0.007499999832361937D * (double) f1;
d2 += this.random.nextGaussian() * 0.007499999832361937D * (double) f1;
d0 *= (double) f;
d1 *= (double) f;
d2 *= (double) f;
this.motX = d0;
this.motY = d1;
this.motZ = d2;
float f3 = MathHelper.sqrt(d0 * d0 + d2 * d2);
this.yaw = (float) (MathHelper.c(d0, d2) * 57.2957763671875D);
this.pitch = (float) (MathHelper.c(d1, (double) f3) * 57.2957763671875D);
this.lastYaw = this.yaw;
this.lastPitch = this.pitch;
this.au = 0;
}
public void B_() {
this.M = this.locX;
this.N = this.locY;
this.O = this.locZ;
super.B_();
if (this.shake > 0) {
--this.shake;
}
if (this.inGround) {
if (this.world.getType(new BlockPosition(this.blockX, this.blockY, this.blockZ)).getBlock() == this.inBlockId) {
++this.au;
if (this.au == 1200) {
this.die();
}
return;
}
this.inGround = false;
this.motX *= (double) (this.random.nextFloat() * 0.2F);
this.motY *= (double) (this.random.nextFloat() * 0.2F);
this.motZ *= (double) (this.random.nextFloat() * 0.2F);
this.au = 0;
this.av = 0;
} else {
++this.av;
}
Vec3D vec3d = new Vec3D(this.locX, this.locY, this.locZ);
Vec3D vec3d1 = new Vec3D(this.locX + this.motX, this.locY + this.motY, this.locZ + this.motZ);
MovingObjectPosition movingobjectposition = this.world.rayTrace(vec3d, vec3d1);
vec3d = new Vec3D(this.locX, this.locY, this.locZ);
vec3d1 = new Vec3D(this.locX + this.motX, this.locY + this.motY, this.locZ + this.motZ);
if (movingobjectposition != null) {
vec3d1 = new Vec3D(movingobjectposition.pos.x, movingobjectposition.pos.y, movingobjectposition.pos.z);
}
Entity entity = null;
List list = this.world.getEntities(this, this.getBoundingBox().b(this.motX, this.motY, this.motZ).g(1.0D));
double d0 = 0.0D;
boolean flag = false;
for (int i = 0; i < list.size(); ++i) {
Entity entity1 = (Entity) list.get(i);
if (entity1.isInteractable()) {
if (entity1 == this.d) {
flag = true;
} else if (this.shooter != null && this.ticksLived < 2 && this.d == null) {
this.d = entity1;
flag = true;
} else {
flag = false;
AxisAlignedBB axisalignedbb = entity1.getBoundingBox().g(0.30000001192092896D);
MovingObjectPosition movingobjectposition1 = axisalignedbb.b(vec3d, vec3d1);
if (movingobjectposition1 != null) {
double d1 = vec3d.distanceSquared(movingobjectposition1.pos);
if (d1 < d0 || d0 == 0.0D) {
entity = entity1;
d0 = d1;
}
}
}
}
}
if (this.d != null) {
if (flag) {
this.aw = 2;
} else if (this.aw-- <= 0) {
this.d = null;
}
}
if (entity != null) {
movingobjectposition = new MovingObjectPosition(entity);
}
if (movingobjectposition != null) {
if (movingobjectposition.type == MovingObjectPosition.EnumMovingObjectType.BLOCK && this.world.getType(movingobjectposition.a()).getBlock() == Blocks.PORTAL) {
this.e(movingobjectposition.a());
} else {
this.a(movingobjectposition);
}
}
this.locX += this.motX;
this.locY += this.motY;
this.locZ += this.motZ;
float f = MathHelper.sqrt(this.motX * this.motX + this.motZ * this.motZ);
this.yaw = (float) (MathHelper.c(this.motX, this.motZ) * 57.2957763671875D);
for (this.pitch = (float) (MathHelper.c(this.motY, (double) f) * 57.2957763671875D); this.pitch - this.lastPitch < -180.0F; this.lastPitch -= 360.0F) {
;
}
while (this.pitch - this.lastPitch >= 180.0F) {
this.lastPitch += 360.0F;
}
while (this.yaw - this.lastYaw < -180.0F) {
this.lastYaw -= 360.0F;
}
while (this.yaw - this.lastYaw >= 180.0F) {
this.lastYaw += 360.0F;
}
this.pitch = this.lastPitch + (this.pitch - this.lastPitch) * 0.2F;
this.yaw = this.lastYaw + (this.yaw - this.lastYaw) * 0.2F;
float f1 = 0.99F;
float f2 = this.j();
if (this.isInWater()) {
for (int j = 0; j < 4; ++j) {
float f3 = 0.25F;
this.world.addParticle(EnumParticle.WATER_BUBBLE, this.locX - this.motX * 0.25D, this.locY - this.motY * 0.25D, this.locZ - this.motZ * 0.25D, this.motX, this.motY, this.motZ, new int[0]);
}
f1 = 0.8F;
}
this.motX *= (double) f1;
this.motY *= (double) f1;
this.motZ *= (double) f1;
if (!this.isNoGravity()) {
this.motY -= (double) f2;
}
this.setPosition(this.locX, this.locY, this.locZ);
}
protected float j() {
return 0.03F;
}
protected abstract void a(MovingObjectPosition movingobjectposition);
public static void a(DataConverterManager dataconvertermanager, String s) {}
public void b(NBTTagCompound nbttagcompound) {
nbttagcompound.setInt("xTile", this.blockX);
nbttagcompound.setInt("yTile", this.blockY);
nbttagcompound.setInt("zTile", this.blockZ);
MinecraftKey minecraftkey = (MinecraftKey) Block.REGISTRY.b(this.inBlockId);
nbttagcompound.setString("inTile", minecraftkey == null ? "" : minecraftkey.toString());
nbttagcompound.setByte("shake", (byte) this.shake);
nbttagcompound.setByte("inGround", (byte) (this.inGround ? 1 : 0));
if ((this.shooterName == null || this.shooterName.isEmpty()) && this.shooter instanceof EntityHuman) {
this.shooterName = this.shooter.getName();
}
nbttagcompound.setString("ownerName", this.shooterName == null ? "" : this.shooterName);
}
public void a(NBTTagCompound nbttagcompound) {
this.blockX = nbttagcompound.getInt("xTile");
this.blockY = nbttagcompound.getInt("yTile");
this.blockZ = nbttagcompound.getInt("zTile");
if (nbttagcompound.hasKeyOfType("inTile", 8)) {
this.inBlockId = Block.getByName(nbttagcompound.getString("inTile"));
} else {
this.inBlockId = Block.getById(nbttagcompound.getByte("inTile") & 255);
}
this.shake = nbttagcompound.getByte("shake") & 255;
this.inGround = nbttagcompound.getByte("inGround") == 1;
this.shooter = null;
this.shooterName = nbttagcompound.getString("ownerName");
if (this.shooterName != null && this.shooterName.isEmpty()) {
this.shooterName = null;
}
this.shooter = this.getShooter();
}
@Nullable
public EntityLiving getShooter() {
if (this.shooter == null && this.shooterName != null && !this.shooterName.isEmpty()) {
this.shooter = this.world.a(this.shooterName);
if (this.shooter == null && this.world instanceof WorldServer) {
try {
Entity entity = ((WorldServer) this.world).getEntity(UUID.fromString(this.shooterName));
if (entity instanceof EntityLiving) {
this.shooter = (EntityLiving) entity;
}
} catch (Throwable throwable) {
this.shooter = null;
}
}
}
return this.shooter;
}
}
| 35.434629 | 204 | 0.550459 |
8ffb7872b2bb1df05ff6e8f9fe6539477435a244 | 791 | package com.szh.offer1;
/**
* 在一个递增数组中,找两个和为s的数
* @author kexun
*
*/
public class Day29 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Day29 d = new Day29();
int[] array = {
1,2,4,7,11,15
};
d.findSumEqS(array, 15);
}
/**
* 维护两个指针 头和尾
* 和大于s的时候,尾指针向前移一位,小于s的时候,头指针向前移一位
* @param array
* @param s
*/
public void findSumEqS(int[] array, int s) {
int length = array.length;
int indexFirst = 0;
int indexLast = length - 1;
while (indexFirst < indexLast) {
int sum = array[indexFirst] + array[indexLast];
if (sum > s) {
indexLast--;
} else if (sum < s) {
indexFirst++;
} else {
System.out.println(array[indexFirst]);
System.out.println(array[indexLast]);
break;
}
}
}
}
| 16.479167 | 50 | 0.594185 |
4d229f9e9a297dc1557ff366a7354c336d838a81 | 1,089 | /* Initializes the Unix words.txt dictionary as a hashmap for constant time access */
import java.io.*;
import java.util.*;
public class Dictionary {
private final String FILENAME = "dictionary.ser";
HashMap<String,Boolean> dictionary = new HashMap<String,Boolean>();
public Dictionary() {
try {
System.out.print( "Initializing Dictionary..." );
FileInputStream fis = new FileInputStream(FILENAME);
ObjectInputStream ois = new ObjectInputStream(fis);
dictionary = (HashMap) ois.readObject();
ois.close();
fis.close();
System.out.println( " Done." );
/*
while( in.hasNext() ) {
dictionary.put( in.next(), true );
}
System.out.println( dictionary );
*/
} catch (Exception e ) {
e.printStackTrace();
}
}
public boolean contains( String word ) {
return dictionary.containsKey( word );
}
public static void main( String[] args ) {
Dictionary dict = new Dictionary( );
System.out.println( dict.contains( "dog" ) + " AND " + dict.contains( "blASH" ) );
}
} | 24.75 | 86 | 0.62259 |
54c637af2cb4ed98477a8c4c581bf930c9fb87e4 | 595 | package com.sri.ai.util.explanation.logging.core.handler;
import java.io.IOException;
/**
* A handler producing files in the format required by Squirrel (http://www.ai.sri.com/~braz/detaillogging.html)
* @author braz
*
*/
public class SquirrelFileExplanationHandler extends FileExplanationHandler {
public SquirrelFileExplanationHandler(String filename) throws IOException {
super(filename);
setNestingStringBlock("*");
setNestingPostfix(" ");
}
@Override
public String toString() {
return "Squirrel file explanation handler for " + getFilename();
}
}
| 25.869565 | 113 | 0.729412 |
3e85cdc8ac7fee1f29551514c27d8bf1c60fa4e6 | 2,555 | /**
Copyright 2015 Osiris Project Team
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.fhc25.percepcion.osiris.mapviewer.model.location;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
* Map feature represented by a Geometry type including a dictionary of
* properties and a list of relations. Domain object
*/
public class Feature implements Serializable {
private Map<String, String> properties;
private List<Map<String, String>> propertiesRelations;
private String id;
private Geometry geometry;
/**
* Gets the properties related with this Feature
*
* @return properties dictionary
*/
public Map<String, String> getProperties() {
return properties;
}
/**
* Sets the properties for this Feature
*
* @param properties
*/
public void setProperties(Map<String, String> properties) {
this.properties = properties;
}
/**
* Gets the properties relations of this Feature
*
* @return relations
*/
public List<Map<String, String>> getPropertiesRelations() {
return propertiesRelations;
}
/**
* Sets the properties relations of this Feature
*
* @param propertiesRelations
*/
public void setPropertiesRelations(
List<Map<String, String>> propertiesRelations) {
this.propertiesRelations = propertiesRelations;
}
/**
* Gets the ID of the Feature
*
* @return id
*/
public String getId() {
return id;
}
/**
* Sets the ID of the Feature
*
* @param id
*/
public void setId(String id) {
this.id = id;
}
/**
* Gets the geometry of the Feature
*
* @return geometry
*/
public Geometry getGeometry() {
return geometry;
}
/**
* Sets the geometry of the Feature
*
* @param geometry
*/
public void setGeometry(Geometry geometry) {
this.geometry = geometry;
}
}
| 23.440367 | 75 | 0.640313 |
48407792e3d80144b795cd88ec2be545eae30648 | 556 | package com.morph.game.shooting.entities.powerups;
import com.morph.engine.entities.EntityRectangle;
import com.morph.engine.graphics.Color;
import com.morph.engine.graphics.Shader;
import com.morph.engine.graphics.Texture;
import com.morph.game.shooting.entities.components.powerups.SpeedBoost;
public class SpeedBoostEntity extends EntityRectangle {
public SpeedBoostEntity(float x, float y, Shader<?> shader) {
super(x, y, 3, 3, new Color(1, 1, 1), shader, new Texture("textures/lightningSpeed.png"), true);
addComponent(new SpeedBoost(2));
}
}
| 37.066667 | 98 | 0.784173 |
409c4456c73a240fb568109a0faddcff9cb018e9 | 4,807 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.tinkerpop.gremlin.process.traversal.step.map;
import org.apache.tinkerpop.gremlin.process.computer.KeyValue;
import org.apache.tinkerpop.gremlin.process.computer.MapReduce;
import org.apache.tinkerpop.gremlin.process.computer.traversal.TraversalVertexProgram;
import org.apache.tinkerpop.gremlin.process.computer.util.StaticMapReduce;
import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
import org.apache.tinkerpop.gremlin.process.traversal.Traverser;
import org.apache.tinkerpop.gremlin.process.traversal.step.MapReducer;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.ReducingBarrierStep;
import org.apache.tinkerpop.gremlin.process.traversal.traverser.TraverserRequirement;
import org.apache.tinkerpop.gremlin.process.traversal.traverser.util.TraverserSet;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.util.function.ConstantSupplier;
import java.io.Serializable;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.Set;
import java.util.function.BiFunction;
/**
* @author Marko A. Rodriguez (http://markorodriguez.com)
*/
public final class CountGlobalStep<S> extends ReducingBarrierStep<S, Long> implements MapReducer {
private static final Set<TraverserRequirement> REQUIREMENTS = EnumSet.of(TraverserRequirement.BULK);
public CountGlobalStep(final Traversal.Admin traversal) {
super(traversal);
this.setSeedSupplier(new ConstantSupplier<>(0L));
this.setBiFunction(CountBiFunction.<S>instance());
}
@Override
public Set<TraverserRequirement> getRequirements() {
return REQUIREMENTS;
}
@Override
public MapReduce<MapReduce.NullObject, Long, MapReduce.NullObject, Long, Long> getMapReduce() {
return CountGlobalMapReduce.instance();
}
///////////
private static class CountBiFunction<S> implements BiFunction<Long, Traverser<S>, Long>, Serializable {
private static final CountBiFunction INSTANCE = new CountBiFunction();
private CountBiFunction() {
}
@Override
public Long apply(final Long mutatingSeed, final Traverser<S> traverser) {
return mutatingSeed + traverser.bulk();
}
public final static <S> CountBiFunction<S> instance() {
return INSTANCE;
}
}
///////////
private static class CountGlobalMapReduce extends StaticMapReduce<MapReduce.NullObject, Long, MapReduce.NullObject, Long, Long> {
private static CountGlobalMapReduce INSTANCE = new CountGlobalMapReduce();
private CountGlobalMapReduce() {
}
@Override
public boolean doStage(final MapReduce.Stage stage) {
return true;
}
@Override
public void map(final Vertex vertex, final MapEmitter<NullObject, Long> emitter) {
vertex.<TraverserSet<?>>property(TraversalVertexProgram.HALTED_TRAVERSERS).ifPresent(traverserSet -> traverserSet.forEach(traverser -> emitter.emit(traverser.bulk())));
}
@Override
public void combine(final NullObject key, final Iterator<Long> values, final ReduceEmitter<NullObject, Long> emitter) {
this.reduce(key, values, emitter);
}
@Override
public void reduce(final NullObject key, final Iterator<Long> values, final ReduceEmitter<NullObject, Long> emitter) {
long count = 0l;
while (values.hasNext()) {
count = count + values.next();
}
emitter.emit(count);
}
@Override
public String getMemoryKey() {
return REDUCING;
}
@Override
public Long generateFinalResult(final Iterator<KeyValue<NullObject, Long>> keyValues) {
return keyValues.hasNext() ? keyValues.next().getValue() : 0L;
}
public static final CountGlobalMapReduce instance() {
return INSTANCE;
}
}
}
| 35.607407 | 180 | 0.707094 |
bbaec49847a85a2e1c96d3885886d39451cab470 | 6,155 | package fr.anatom3000.gwwhit.command;
import com.mojang.brigadier.arguments.StringArgumentType;
import fr.anatom3000.gwwhit.GWWHIT;
import fr.anatom3000.gwwhit.Python;
import fr.anatom3000.gwwhit.block.entity.InfectedMassBlockEntity;
import fr.anatom3000.gwwhit.block.entity.RandomisingBlockEntity;
import fr.anatom3000.gwwhit.config.ConfigManager;
import fr.anatom3000.gwwhit.mixin.access.GameRendererAccess;
import net.fabricmc.fabric.api.client.command.v1.ClientCommandManager;
import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource;
import net.fabricmc.fabric.api.command.v1.CommandRegistrationCallback;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.render.GameRenderer;
import net.minecraft.command.argument.IdentifierArgumentType;
import net.minecraft.command.argument.ItemStackArgument;
import net.minecraft.command.argument.ItemStackArgumentType;
import net.minecraft.item.ItemStack;
import net.minecraft.server.command.CommandManager;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.LiteralText;
import net.minecraft.util.Identifier;
public class Commands {
private Commands() {
}
public static void registerClient() {
if (ConfigManager.getActiveConfig().misc.debugMode)
ClientCommandManager.DISPATCHER.register(ClientCommandManager.literal("gwwhitclient")
.then(ClientCommandManager.literal("set_shader")
.then(ClientCommandManager.argument("name", IdentifierArgumentType.identifier())
.executes(context -> {
Identifier id = context.getArgument("name", Identifier.class);
((GameRendererAccess)MinecraftClient.getInstance().gameRenderer).callLoadShader(id);
return 1;
})
)
));
}
public static void register() {
CommandRegistrationCallback.EVENT.register((dispatcher, dedicated) -> dispatcher.register(CommandManager.literal(GWWHIT.MOD_ID)
.requires(source -> source.hasPermissionLevel(2))
.then(CommandManager.literal("config")
.then(CommandManager.literal("reload")
.executes(context -> {
ConfigManager.reloadLocalConfig();
for (ServerPlayerEntity player : context.getSource().getMinecraftServer().getPlayerManager().getPlayerList()) {
ServerPlayNetworking.send(player, GWWHIT.CONFIG_SYNC_ID, ConfigManager.toPacketByteBuf());
}
return 1;
})
)
)
.then(CommandManager.literal("debug")
.then(CommandManager.literal("remove_destructive_blocks")
.executes(context -> {
int ticks = context.getSource().getMinecraftServer().getTicks();
InfectedMassBlockEntity.removeTick = ticks;
RandomisingBlockEntity.removeTick = ticks;
return 1;
})
)
)
.then(CommandManager.literal("python")
.requires(source -> ConfigManager.getActiveConfig().misc.scripting)
.then(CommandManager.literal("execute")
.then(CommandManager.argument("script", new ScriptArgumentType())
.executes(context -> {
try {
Python.execute(ScriptArgumentType.getScript(context, "script"));
return 1;
} catch (RuntimeException e) {
context.getSource().sendError(new LiteralText(createErrorMessage(e, 0)));
return 0;
}
})
)
)
)
.then(CommandManager.literal("fillinv")
.then(CommandManager.argument("item", ItemStackArgumentType.itemStack())
.executes(context -> {
ItemStackArgument item = ItemStackArgumentType.getItemStackArgument(context, "item");
ItemStack stack = item.createStack(item.getItem().getMaxCount(), false);
ServerPlayerEntity player = context.getSource().getPlayer();
if (player == null) return 0;
for (int i = 0; i < player.getInventory().size(); i++) {
player.getInventory().setStack(i, stack.copy());
}
for (int i = 0; i < player.getEnderChestInventory().size(); i++) {
player.getEnderChestInventory().setStack(i, stack.copy());
}
return 1;
})
)
)
));
}
private static String createErrorMessage(Throwable e, int indentation) {
StringBuilder sb = new StringBuilder();
sb.append(" ".repeat(indentation));
sb.append(e.getMessage());
sb.append('\n');
for (Throwable t : e.getSuppressed()) sb.append(createErrorMessage(t, indentation + 1));
return sb.toString();
}
}
| 52.606838 | 147 | 0.516653 |
e066ac329731f93d7178ee7f60b0a214c307d81f | 256 | package org.ldk.enums;
/**
* An enum representing the available verbosity levels of the logger.
*/
public enum Level {
LDKLevel_Trace,
LDKLevel_Debug,
LDKLevel_Info,
LDKLevel_Warn,
LDKLevel_Error,
; static native void init();
static { init(); }
} | 18.285714 | 69 | 0.730469 |
39bf9b136a39b3cb6621dea530358c9f6389917f | 3,353 | package com.prometrx.myinstagramclone.UserLoginSignup;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.prometrx.myinstagramclone.MainActivity;
import com.prometrx.myinstagramclone.R;
public class LoginActivity extends AppCompatActivity {
private EditText loginEmailEditText,loginPasswordEditText;
private TextView signupTextView;
private Button loginButton;
private FirebaseAuth firebaseAuth;
private FirebaseUser fuser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
init();
loginButton();
signupTextViewClick();
fuser = FirebaseAuth.getInstance().getCurrentUser();
if(fuser != null) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
private void init() {
loginButton = findViewById(R.id.loginButton);
signupTextView = findViewById(R.id.notMemberSignUpTextView);
loginEmailEditText = findViewById(R.id.loginEmailEditText);
loginPasswordEditText = findViewById(R.id.loginPasswordEditText);
firebaseAuth =FirebaseAuth.getInstance();
}
private void loginButton() {
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(loginEmailEditText.getText().toString().equals("") || loginPasswordEditText.getText().toString().equals("")){
}else{
firebaseAuth.signInWithEmailAndPassword(loginEmailEditText.getText().toString(), loginPasswordEditText.getText().toString()).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
@Override
public void onSuccess(AuthResult authResult) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(LoginActivity.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
private void signupTextViewClick() {
signupTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this, SignUpActivity.class);
startActivity(intent);
}
});
}
} | 33.868687 | 203 | 0.641217 |
12b0249ac0d7e583a843b5fcb28cfb47f735cd74 | 5,348 | /*
* Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved.
*/
package com.sap.hybris.sapcpioaaorderintegration.sourcing.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sap.retail.oaa.commerce.services.sourcing.SourcingService;
import com.sap.retail.oaa.commerce.services.sourcing.exception.SourcingException;
import com.sap.retail.oaa.model.model.ScheduleLineModel;
import de.hybris.platform.core.enums.OrderStatus;
import de.hybris.platform.core.model.order.AbstractOrderEntryModel;
import de.hybris.platform.core.model.order.AbstractOrderModel;
import de.hybris.platform.core.model.order.OrderModel;
import de.hybris.platform.ordersplitting.WarehouseService;
import de.hybris.platform.servicelayer.model.ModelService;
import de.hybris.platform.site.BaseSiteService;
import de.hybris.platform.store.services.BaseStoreService;
import de.hybris.platform.warehousing.data.sourcing.SourcingResult;
import de.hybris.platform.warehousing.data.sourcing.SourcingResults;
import de.hybris.platform.warehousing.sourcing.impl.DefaultSourcingService;
/**
* Service for Sourcing and Reservation to COS
*/
public class SapOaaSourcingService extends DefaultSourcingService{
private static final Logger LOGGER = LoggerFactory.getLogger(SapOaaSourcingService.class);
private BaseStoreService baseStoreService;
private WarehouseService warehouseService;
private SourcingService oaaSourcingService;
private BaseSiteService baseSiteService;
private ModelService modelService;
@Override
public SourcingResults sourceOrder(AbstractOrderModel abstractOrderModel) {
OrderModel order = (OrderModel) abstractOrderModel;
if (order.getSapCosSystemUsed() != null && order.getSapCosSystemUsed()) {
doSourcingAndReservation(order);
}
final SourcingResults results = new SourcingResults();
final Set<SourcingResult> sourcingResults = new HashSet<SourcingResult>();
constructSourcingResult(order, sourcingResults);
results.setResults(sourcingResults);
results.setComplete(true);
return results;
}
protected void doSourcingAndReservation(final OrderModel order) {
try
{
order.setIsCosOrderAcknowledgedByBackend(Boolean.FALSE);
baseSiteService.setCurrentBaseSite(order.getSite(), false);
oaaSourcingService.callRestService(order, false, true);
LOGGER.info("Reservation to Backend successful");
}
catch (final SourcingException e)
{
order.setStatus(OrderStatus.SUSPENDED);
getModelService().save(order);
LOGGER.error("Error when executing Sourcing and reservation",e);
throw new SourcingException(e);
}
}
protected void constructSourcingResult(final OrderModel order, final Set<SourcingResult> sourcingResults)
{
final List<AbstractOrderEntryModel> abstractOrderEntryModels = new ArrayList<AbstractOrderEntryModel>();
final SourcingResult result = new SourcingResult();
final Map<AbstractOrderEntryModel, Long> allocation = new HashMap<AbstractOrderEntryModel, Long>();
for (final AbstractOrderEntryModel abstractOrderEntryModel : order.getEntries())
{
long allocationQuantity = 0l;
final List<ScheduleLineModel> list = abstractOrderEntryModel.getScheduleLines();
for (final ScheduleLineModel scheduleLineModel : list)
{
allocationQuantity = (long) (allocationQuantity + scheduleLineModel.getConfirmedQuantity());
}
allocation.put(abstractOrderEntryModel, allocationQuantity);
if (null != abstractOrderEntryModel.getProduct() && null != abstractOrderEntryModel.getSapSource()) {
LOGGER.info("Product : '{}' sourced from : '{}' Quantity : '{}'",
abstractOrderEntryModel.getProduct().getCode(),
abstractOrderEntryModel.getSapSource().getName(), allocationQuantity);
}
abstractOrderEntryModels.add(abstractOrderEntryModel);
}
result.setAllocation(allocation);
if (!warehouseService.getWarehouses(abstractOrderEntryModels).isEmpty())
{
result.setWarehouse(warehouseService.getWarehouses(abstractOrderEntryModels).get(0));
}
else if (!warehouseService.getDefWarehouse().isEmpty())
{
result.setWarehouse(warehouseService.getDefWarehouse().get(0));
}
else
{
LOGGER.warn("Could not find the virtual warehouse");
}
sourcingResults.add(result);
}
public BaseStoreService getBaseStoreService() {
return baseStoreService;
}
public void setBaseStoreService(BaseStoreService baseStoreService) {
this.baseStoreService = baseStoreService;
}
public WarehouseService getWarehouseService() {
return warehouseService;
}
public void setWarehouseService(WarehouseService warehouseService) {
this.warehouseService = warehouseService;
}
public SourcingService getOaaSourcingService() {
return oaaSourcingService;
}
public void setOaaSourcingService(SourcingService sourcingService) {
this.oaaSourcingService = sourcingService;
}
public BaseSiteService getBaseSiteService() {
return baseSiteService;
}
public void setBaseSiteService(BaseSiteService baseSiteService) {
this.baseSiteService = baseSiteService;
}
public ModelService getModelService() {
return modelService;
}
public void setModelService(ModelService modelService) {
this.modelService = modelService;
}
}
| 31.833333 | 106 | 0.792633 |
80c5fc95e081f94752658f54423f4465042fdc0f | 11,039 |
package ca.bcit.geekkit;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.LayoutManager2;
import java.awt.Rectangle;
import java.util.Hashtable;
/**
* The <code>GraphPaperLayout</code> class is a layout manager that lays out a container's components in a rectangular
* grid, similar to GridLayout. Unlike GridLayout, however, components can take up multiple rows and/or columns. The
* layout manager acts as a sheet of graph paper. When a component is added to the layout manager, the location and
* relative size of the component are simply supplied by the constraints as a Rectangle.
* <p>
* <code><pre>
* import java.awt.*;
* import java.applet.Applet;
* public class ButtonGrid extends Applet {
* public void init() {
* setLayout(new GraphPaperLayout(new Dimension(5,5)));
* // Add a 1x1 Rect at (0,0)
* add(new Button("1"), new Rectangle(0,0,1,1));
* // Add a 2x1 Rect at (2,0)
* add(new Button("2"), new Rectangle(2,0,2,1));
* // Add a 1x2 Rect at (1,1)
* add(new Button("3"), new Rectangle(1,1,1,2));
* // Add a 2x2 Rect at (3,2)
* add(new Button("4"), new Rectangle(3,2,2,2));
* // Add a 1x1 Rect at (0,4)
* add(new Button("5"), new Rectangle(0,4,1,1));
* // Add a 1x2 Rect at (2,3)
* add(new Button("6"), new Rectangle(2,3,1,2));
* }
* }
* </pre></code>
*
* @author Michael Martak
*/
public class GraphPaperLayout
implements LayoutManager2
{
int hgap; //horizontal gap
int vgap; //vertical gap
Dimension gridSize; //grid size in logical units (n x m)
Hashtable compTable; //constraints (Rectangles)
/**
* Creates a graph paper layout with a default of a 1 x 1 graph, with no vertical or horizontal padding.
*/
public GraphPaperLayout()
{
this( new Dimension( 1, 1 ) );
}
/**
* Creates a graph paper layout with the given grid size, with no vertical or horizontal padding.
*/
public GraphPaperLayout( final Dimension gridSize )
{
this( gridSize, 0, 0 );
}
/**
* Creates a graph paper layout with the given grid size and padding.
*
* @param gridSize size of the graph paper in logical units (n x m)
* @param hgap horizontal padding
* @param vgap vertical padding
*/
public GraphPaperLayout( final Dimension gridSize, final int hgap, final int vgap )
{
if ( gridSize.width <= 0 || gridSize.height <= 0 )
{
throw new IllegalArgumentException( "dimensions must be greater than zero" );
}
this.gridSize = new Dimension( gridSize );
this.hgap = hgap;
this.vgap = vgap;
this.compTable = new Hashtable();
}
/**
* @return the size of the graph paper in logical units (n x m)
*/
public Dimension getGridSize()
{
return new Dimension( this.gridSize );
}
/**
* Set the size of the graph paper in logical units (n x m)
*/
public void setGridSize( final Dimension d )
{
this.setGridSize( d.width, d.height );
}
/**
* Set the size of the graph paper in logical units (n x m)
*/
public void setGridSize( final int width, final int height )
{
this.gridSize = new Dimension( width, height );
}
public void setConstraints( final Component comp, final Rectangle constraints )
{
this.compTable.put( comp, new Rectangle( constraints ) );
}
/**
* Adds the specified component with the specified name to the layout. This does nothing in GraphPaperLayout, since
* constraints are required.
*/
public void addLayoutComponent( final String name, final Component comp )
{
}
/**
* Removes the specified component from the layout.
*
* @param comp the component to be removed
*/
public void removeLayoutComponent( final Component comp )
{
this.compTable.remove( comp );
}
/**
* Calculates the preferred size dimensions for the specified panel given the components in the specified parent
* container.
*
* @param parent the component to be laid out
* @see #minimumLayoutSize
*/
public Dimension preferredLayoutSize( final Container parent )
{
return this.getLayoutSize( parent, true );
}
/**
* Calculates the minimum size dimensions for the specified panel given the components in the specified parent
* container.
*
* @param parent the component to be laid out
* @see #preferredLayoutSize
*/
public Dimension minimumLayoutSize( final Container parent )
{
return this.getLayoutSize( parent, false );
}
/**
* Algorithm for calculating layout size (minimum or preferred).
* <p>
* The width of a graph paper layout is the largest cell width (calculated in <code>getLargestCellSize()</code>
* times the number of columns, plus the horizontal padding times the number of columns plus one, plus the left and
* right insets of the target container.
* <p>
* The height of a graph paper layout is the largest cell height (calculated in <code>getLargestCellSize()</code>
* times the number of rows, plus the vertical padding times the number of rows plus one, plus the top and bottom
* insets of the target container.
*
* @param parent the container in which to do the layout.
* @param isPreferred true for calculating preferred size, false for calculating minimum size.
* @return the dimensions to lay out the subcomponents of the specified container.
* @see java.awt.GraphPaperLayout#getLargestCellSize
*/
protected Dimension getLayoutSize( final Container parent, final boolean isPreferred )
{
Dimension largestSize = this.getLargestCellSize( parent, isPreferred );
Insets insets = parent.getInsets();
largestSize.width =
largestSize.width * this.gridSize.width + this.hgap * ( this.gridSize.width + 1 ) + insets.left + insets.right;
largestSize.height =
largestSize.height * this.gridSize.height + this.vgap * ( this.gridSize.height + 1 ) + insets.top + insets.bottom;
return largestSize;
}
/**
* Algorithm for calculating the largest minimum or preferred cell size.
* <p>
* Largest cell size is calculated by getting the applicable size of each component and keeping the maximum value,
* dividing the component's width by the number of columns it is specified to occupy and dividing the component's
* height by the number of rows it is specified to occupy.
*
* @param parent the container in which to do the layout.
* @param isPreferred true for calculating preferred size, false for calculating minimum size.
* @return the largest cell size required.
*/
protected Dimension getLargestCellSize( final Container parent, final boolean isPreferred )
{
int ncomponents = parent.getComponentCount();
Dimension maxCellSize = new Dimension( 0, 0 );
for ( int i = 0; i < ncomponents; i++ )
{
Component c = parent.getComponent( i );
Rectangle rect = (Rectangle) this.compTable.get( c );
if ( c != null && rect != null )
{
Dimension componentSize;
if ( isPreferred )
{
componentSize = c.getPreferredSize();
}
else
{
componentSize = c.getMinimumSize();
}
// Note: rect dimensions are already asserted to be > 0 when the
// component is added with constraints
maxCellSize.width = Math.max( maxCellSize.width, componentSize.width / rect.width );
maxCellSize.height = Math.max( maxCellSize.height, componentSize.height / rect.height );
}
}
return maxCellSize;
}
/**
* Lays out the container in the specified container.
*
* @param parent the component which needs to be laid out
*/
public void layoutContainer( final Container parent )
{
synchronized ( parent.getTreeLock() )
{
Insets insets = parent.getInsets();
int ncomponents = parent.getComponentCount();
if ( ncomponents == 0 )
{
return;
}
// Total parent dimensions
Dimension size = parent.getSize();
int totalW = size.width - ( insets.left + insets.right );
int totalH = size.height - ( insets.top + insets.bottom );
// Cell dimensions, including padding
int totalCellW = totalW / this.gridSize.width;
int totalCellH = totalH / this.gridSize.height;
// Cell dimensions, without padding
int cellW = ( totalW - ( this.gridSize.width + 1 ) * this.hgap ) / this.gridSize.width;
int cellH = ( totalH - ( this.gridSize.height + 1 ) * this.vgap ) / this.gridSize.height;
for ( int i = 0; i < ncomponents; i++ )
{
Component c = parent.getComponent( i );
Rectangle rect = (Rectangle) this.compTable.get( c );
if ( rect != null )
{
int x = insets.left + totalCellW * rect.x + this.hgap;
int y = insets.top + totalCellH * rect.y + this.vgap;
int w = cellW * rect.width - this.hgap;
int h = cellH * rect.height - this.vgap;
c.setBounds( x, y, w, h );
}
}
}
}
// LayoutManager2 /////////////////////////////////////////////////////////
/**
* Adds the specified component to the layout, using the specified constraint object.
*
* @param comp the component to be added
* @param constraints where/how the component is added to the layout.
*/
public void addLayoutComponent( final Component comp, final Object constraints )
{
if ( constraints instanceof Rectangle )
{
Rectangle rect = (Rectangle) constraints;
if ( rect.width <= 0 || rect.height <= 0 )
{
throw new IllegalArgumentException(
"cannot add to layout: rectangle must have positive width and height" );
}
if ( rect.x < 0 || rect.y < 0 )
{
throw new IllegalArgumentException( "cannot add to layout: rectangle x and y must be >= 0" );
}
this.setConstraints( comp, rect );
}
else if ( constraints != null )
{
throw new IllegalArgumentException( "cannot add to layout: constraint must be a Rectangle" );
}
}
/**
* Returns the maximum size of this component.
*
* @see java.awt.Component#getMinimumSize()
* @see java.awt.Component#getPreferredSize()
* @see LayoutManager
*/
public Dimension maximumLayoutSize( final Container target )
{
return new Dimension( Integer.MAX_VALUE, Integer.MAX_VALUE );
}
/**
* Returns the alignment along the x axis. This specifies how the component would like to be aligned relative to
* other components. The value should be a number between 0 and 1 where 0 represents alignment along the origin, 1
* is aligned the furthest away from the origin, 0.5 is centered, etc.
*/
public float getLayoutAlignmentX( final Container target )
{
return 0.5f;
}
/**
* Returns the alignment along the y axis. This specifies how the component would like to be aligned relative to
* other components. The value should be a number between 0 and 1 where 0 represents alignment along the origin, 1
* is aligned the furthest away from the origin, 0.5 is centered, etc.
*/
public float getLayoutAlignmentY( final Container target )
{
return 0.5f;
}
/**
* Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.
*/
public void invalidateLayout( final Container target )
{
// Do nothing
}
}
| 32.467647 | 118 | 0.684573 |
27ac3cd4041e501fff5e0c7cbd859341ebf34506 | 4,020 | package ru.stm.rpc.kafkaredis.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import javax.validation.constraints.NotEmpty;
import java.util.Map;
/**
* Configuration for KafkaRedis RPC
*/
@Data
@ConfigurationProperties("stm.rpc.kafkaredis")
@Component
public class KafkaRedisRpcProperties {
public static final String REDIS_NODE_MODE_SENTINEL = "Sentinel";
private final static int DEFAULT_RPC_TIMEOUT = 30000;
private Map<String, KafkaRedisRpcItem> namespace;
@Data
public static class KafkaRedisRpcItem {
private long responseWarnThreshold = 200_000;
// with 40_000_000 chars ~ 80 MB + JSON encoded payload
private long responseRefuseThreshold = 40_000_000;
private int printLength = 3000;
private RedisConfiguration redis;
private KafkaRedisProducer producer;
private KafkaRedisConsumer consumer;
private int loggingThreshold = 50000;
}
/**
* Configuration Redis for Consumer & Producer
*/
@Data
public static class RedisConfiguration {
// For Standalone mode
private String host;
private int port;
// For Redis Sentinel (HA) mode
private String nodes;
private String nodeMode = REDIS_NODE_MODE_SENTINEL;
private String clusterName = "mycluster";
}
/**
* Configuration Kafka for Producer
*/
@Data
public static class KafkaProducerConfiguration {
@NotEmpty
private String bootstrapServers;
}
/**
* Configuration Kafka for Consumer
*/
@Data
public static class KafkaConsumerConfiguration {
@NotEmpty
private String bootstrapServers;
private boolean enableUniqConsumerGroupByApplicationId = true;
private String groupId = "RPC";
}
/**
* Configuration for RPC Producer
*/
@Data
public static class KafkaRedisProducer {
@NotEmpty
private long timeout = DEFAULT_RPC_TIMEOUT;
// two minutes timeout for system operation such as delete GC or poll batch
@NotEmpty
private long internalDeleteOperationTimeout = 30;
// polling interval if we have not previous poll
private long pollingOperationTimeout = 5;
@NotEmpty
private long redisPolling = 15;
private long redisIdlePolling = redisPolling * 2;
@NotEmpty
private long statsInterval = 1000;
@NotEmpty
private long cleanerFinalizerInterval = 10;
@NotEmpty
private boolean showCurrentStats = false;
@NotEmpty
private boolean showAllStats = false;
private KafkaProducerConfiguration kafka;
private long finalizerStaleSec = 40;
/**
* threadshold errors in statsInterval
*/
private int timeoutFailedThreshold = 5;
private int purgeThreshold = 500;
/**
* The maximum size of a request in bytes.
* This setting will limit the number of record batches the producer will send in a single request to avoid sending huge requests.
* This is also effectively a cap on the maximum record batch size. Note that the server has its own cap on record batch size
* which may be different from this.
*/
private Integer maxRequestSize = null;
}
/**
* Configuration for RPC Consumer
*/
@Data
public static class KafkaRedisConsumer {
// disable consumer
private boolean disable = false;
private long statsInterval = 2000;
private int executionTimeout = DEFAULT_RPC_TIMEOUT;
private boolean showCurrentStats = false;
private long redisTtl = (long) (DEFAULT_RPC_TIMEOUT * 1.5);
private KafkaConsumerConfiguration kafka;
private long retryTimes = 3;
private long retryBackoff = 3000;
}
}
| 26.979866 | 138 | 0.662438 |
daeb1dfdf96891a140c1d21ff6e8863b823424eb | 1,141 | package com.onaple.itemizer.commands.manager;
import com.onaple.itemizer.data.beans.ItemBean;
import com.onaple.itemizer.utils.managers.ItemLoreManager;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.spec.CommandExecutor;
import org.spongepowered.api.text.Text;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class LoreManagerCommand implements CommandExecutor {
@Override
@SuppressWarnings("unchecked")
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
Optional<ItemBean> item= args.getOne("id");
List<Text> lore = args.<List>getOne("lore").orElse(new ArrayList<>());
if(item.isPresent()){
ItemLoreManager itemLoreManager = ItemLoreManager.of(item.get(),lore);
itemLoreManager.apply();
return CommandResult.success();
}
return CommandResult.empty();
}
}
| 36.806452 | 98 | 0.751096 |
cf5eb523394f394a63d70267dc3bccd3ade839b6 | 5,175 | /*
Good read:
http://www.cs.yale.edu/homes/aspnes/pinewiki/SuffixArrays.html
Generally speaking, suffix arrays are used to do multiple queries
efficiently on one piece of data rather than to do one operation
then move on to another piece of text.
Some things suffix trees are great for are:
1) Searching if a substring occurs in the text
2) Finding all occurrences of a substring in the larger text
3) Longest repeated substring
4) Most frequently occurring substrings
5) Longest duplicate substrings
6)
*/
public class SuffixArrayNaive {
class Suffix implements Comparable <Suffix> {
// Starting position of suffix in text
final int index, len;
final char [] text;
public Suffix(char [] text, int index) {
// if (text.length() >= index) throw new IllegalArgumentException();
this.len = text.length - index;
this.index = index;
this.text = text;
}
// Compare the two suffixes inspired by Robert Sedgewick and Kevin Wayne
@Override public int compareTo(Suffix other) {
if (this == other) return 0;
int min_len = Math.min(len, other.len);
for (int i = 0; i < min_len; i++) {
if (text[index+i] < other.text[other.index+i]) return -1;
if (text[index+i] > other.text[other.index+i]) return +1;
}
return len - other.len;
}
@Override public String toString() {
return new String(text, index, len);
}
}
int len;
char[] text;
// Contains all the suffixes of the SuffixArray
Suffix[] suffixes;
// Contains Longest Common Prefix (LCP) count between adjacent suffixes.
// LCP[i] = longestCommonPrefixLength( suffixes[i], suffixes[i+1] ). Also, LCP[len-1] = 0
int LCP [];
public SuffixArrayNaive(String text) {
this(text == null ? null : text.toCharArray());
}
// O(n^2log(n)) construction. O(nlog(n)) for sorting, but
// each suffix takes O(n) comparison time
// Look into:
// http://www.geeksforgeeks.org/suffix-array-set-2-a-nlognlogn-algorithm/
public SuffixArrayNaive(char[] text) {
if (text == null) throw new IllegalArgumentException();
this.text = text;
len = text.length;
suffixes = new Suffix[len];
for (int i = 0; i < len; i++)
suffixes[i] = new Suffix(text, i);
java.util.Arrays.sort(suffixes);
kasai();
// System.out.println(Arrays.toString(suffixes));
}
// Constructs the LCP (longest common prefix) array in linear time
// http://www.mi.fu-berlin.de/wiki/pub/ABI/RnaSeqP4/suffix-array.pdf
private void kasai() {
LCP = new int[len];
// Compute inverse index values
int [] inv = new int[len];
for (int i = 0; i < len; i++)
inv[suffixes[i].index] = i;
int lcp_len = 0;
for (int i = 0; i < len; i++) {
if (inv[i] > 0) {
// Get the index of where the suffix below is
int k = suffixes[inv[i] - 1].index;
// Compute lcp length. For most loops this is O(1)
while( (i + lcp_len < len) && (k + lcp_len < len) &&
text[i+lcp_len] == text[k+lcp_len] )
lcp_len++;
LCP[inv[i]-1] = lcp_len;
if (lcp_len > 0) lcp_len--;
}
}
}
public int[] getSuffixPositions() {
int [] ar = new int[len];
for (int i = 0; i < len; i++)
ar[i] = suffixes[i].index;
return ar;
}
// Runs on O(mlog(n)) where m is the length of the substring
// and n is the length of the text.
// NOTE: This is the naive implementation. There exists an
// implementation which runs in O(m + log(n)) time
public boolean contains(String substr) {
if (substr == null) return false;
String suffix_str;
int lo = 0, hi = len - 1;
int substr_len = substr.length();
while( lo <= hi ) {
int mid = (lo + hi) / 2;
Suffix suffix = suffixes[mid];
// Extract part of the suffix we need to compare
if (suffix.len <= substr_len) suffix_str = suffix.toString();
else suffix_str = new String(text, suffix.index, substr_len);
int cmp = suffix_str.compareTo(substr);
// Found a match
if ( cmp == 0 ) {
// To find the first occurrence linear scan down
// or keep doing binary search
return true;
// Substring is found above
} else if (cmp < 0) {
lo = mid + 1;
// Substring is found below
} else {
hi = mid - 1;
}
}
return false;
}
// Finds the LRS (Longest Repeated Substring) that occurs in a string
// Traditionally we are only interested in sub strings that appear at
// least twice, so this method returns null if this is the case.
public String lrs() {
int max_len = 0;
Suffix suffix = null;
for (int i = 0; i < len; i++) {
if (LCP[i] > max_len) {
max_len = LCP[i];
suffix = suffixes[i];
}
}
return suffix == null ? null : suffix.toString().substring(0, max_len);
}
@Override public String toString() {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < len; i++) {
Suffix suf = suffixes[i];
sb.append(new String(text, suf.index, suf.len) + "\n");
}
return sb.toString();
}
}
| 26.675258 | 91 | 0.606184 |
28db93bb9f04a0ab289b3fdfcdd0cf09dc74315c | 1,171 | package edu.ccsu.cs417.decorator;
import edu.ccsu.cs417.composite.CPU;
import edu.ccsu.cs417.composite.ComputerComponent;
import edu.ccsu.cs417.composite.ComputerComposite;
import edu.ccsu.cs417.composite.GraphicsCard;
import edu.ccsu.cs417.composite.Motherboard;
import edu.ccsu.cs417.composite.RAMChip;
/**
* Demonstration of decorator pattern
*/
public class Main {
public static void main(String[] args){
// Construct part-whole hierarchy
ComputerComposite graphicsCard = new GraphicsCard();
graphicsCard.add(new CPU());
graphicsCard.add(new RAMChip());
ComputerComposite motherboard = new Motherboard();
// Add decorator for price to be adjusted based on market
motherboard.add(new MarketPriceAdjusterDecorator(graphicsCard));
motherboard.add(new CPU());
motherboard.add(new CPU());
// 10% discount on these all motherboard RAMChips
motherboard.add(new SaleDecorator(.9,new RAMChip()));
ComputerComponent chip =new RAMChip();
chip = new SaleDecorator(.9, chip);
// Extra 50% off for this chip, so add a decorator on the decorator
chip = new SaleDecorator(.5, chip);
motherboard.add(chip);
}
}
| 34.441176 | 71 | 0.736977 |
fa0cba5b7894048f8e7e9c203cefef6c4903c03a | 162 | package com.baeldung.cglib.mixin;
public class Class1 implements Interface1 {
@Override
public String first() {
return "first behaviour";
}
} | 20.25 | 43 | 0.679012 |
64f717a52e411eac106402a19901f153c5e62db0 | 7,168 | package com.hjcenry.util.enumutil;
import com.hjcenry.log.KtucpLog;
import com.hjcenry.util.Assert;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* 从0开始的可索引枚举接口定义,实现此接口的枚举各个元素的index可以不连续,但此接口的实现类多为稀疏数组结构,保持index连续可以节省空间
*
* @author guowei
* @since 2010-6-7
*/
public interface IndexedEnum {
static final Logger logger = KtucpLog.logger;
/**
* 获取该枚举的索引值
*
* @return 返回>=0的索引值
*/
public abstract int getIndex();
public static class IndexedEnumUtil {
/**
* 索引警戒上限,发现超过此值的索引可能存在较大的空间浪费
*/
private static final int WORNNING_MAX_INDEX = 1000;
/**
* 检测枚举索引
* <p>
* 仅在起服时候用
*
* @return 如果未定义,返回false。
*/
public static <T extends Enum<T>> boolean checkIndex(List<T> allIndexedEnums, int index) {
return checkIndex(allIndexedEnums, index, true);
}
/**
* 检测枚举索引
* <p>
* 仅在起服时候用
*
* @return 如果未定义,返回false。
*/
public static <T extends Enum<T>> boolean checkIndex(List<T> allIndexedEnums, int index, boolean printErrLog) {
try {
if (EnumUtil.valueOf(allIndexedEnums, index, printErrLog) == null) {
return false;
}
} catch (Exception e) {
return false;
}
return true;
}
/**
* 将枚举中的元素放到一个List中,每个元素在list中的下表即为他的index,如果有不连续的index,则空缺的index用null填充
*
* @param enums
* @param <E>
* @return
*/
public static <E extends IndexedEnum> List<Integer> toIndexIntList(E[] enums) {
int maxIndex = Integer.MIN_VALUE;
int curIdx = 0;
// 找到最大index,此值+1就是结果list的size
for (E enm : enums) {
curIdx = enm.getIndex();
// 索引不能为负
Assert.isTrue(curIdx >= 0, String.format("枚举索引不能为负 index: %1$d type: %2$s ", curIdx, enums.getClass()
.getComponentType().getName()));
if (curIdx > maxIndex) {
maxIndex = curIdx;
}
}
if (maxIndex >= WORNNING_MAX_INDEX && logger.isWarnEnabled()) {
logger.warn(String.format("警告:枚举类%s中有索引超过%d的索引,如果有很多索引空缺,可能会造成空间浪费", enums.getClass().getSimpleName(), WORNNING_MAX_INDEX));
}
List<Integer> instances = new ArrayList<>(maxIndex + 1);
// 先全用null填充
for (int i = 0; i < maxIndex + 1; i++) {
instances.add(null);
}
for (E enm : enums) {
curIdx = enm.getIndex();
// 索引必须唯一
Assert.isTrue(instances.get(curIdx) == null, String.format("枚举中有重复的index type=%s,index=%s "
, enums.getClass().getComponentType().getName(), curIdx));
instances.set(curIdx, enm.getIndex());
}
return instances;
}
/**
* 将枚举中的元素放到一个List中,每个元素在list中的下表即为他的index,如果有不连续的index,则空缺的index用null填充
*
* @param <E>
* @param enums
* @return
*/
public static <E extends IndexedEnum> List<E> toIndexes(E[] enums) {
int maxIndex = Integer.MIN_VALUE;
int curIdx = 0;
// 找到最大index,此值+1就是结果list的size
for (E enm : enums) {
curIdx = enm.getIndex();
// 索引不能为负
Assert.isTrue(curIdx >= 0, String.format("枚举索引不能为负 index: %1$d type: %2$s ", curIdx, enums.getClass()
.getComponentType().getName()));
if (curIdx > maxIndex) {
maxIndex = curIdx;
}
}
if (maxIndex >= WORNNING_MAX_INDEX) {
logger.warn(String.format("警告:枚举类%s中有索引超过%d的索引,如果有很多索引空缺,可能会造成空间浪费", enums.getClass().getSimpleName(), WORNNING_MAX_INDEX));
}
List<E> instances = new ArrayList<E>(maxIndex + 1);
// 先全用null填充
for (int i = 0; i < maxIndex + 1; i++) {
instances.add(null);
}
for (E enm : enums) {
curIdx = enm.getIndex();
// 索引必须唯一
Assert.isTrue(instances.get(curIdx) == null, String.format("枚举中有重复的index type=%s,index=%s "
, enums.getClass().getComponentType().getName(), curIdx));
instances.set(curIdx, enm);
}
return instances;
}
/**
* 将枚举中的元素放到一个List中,每个元素在list中的下表即为他的index,如果有不连续的index,则空缺的index用null填充
*
* @param <E>
* @param enums
* @return
*/
public static <E extends IndexedEnum> List<E> toReverseIndexes(E[] enums) {
int maxIndex = Integer.MIN_VALUE;
int curIdx = 0;
// 找到最大index,此值+1就是结果list的size
for (E enm : enums) {
curIdx = enm.getIndex();
// 索引不能为负
Assert.isTrue(curIdx >= 0, String.format("枚举索引不能为负 index: %1$d type: %2$s ", curIdx, enums.getClass()
.getComponentType().getName()));
if (curIdx > maxIndex) {
maxIndex = curIdx;
}
}
if (maxIndex >= WORNNING_MAX_INDEX) {
logger.warn(String.format("警告:枚举类%s中有索引超过%d的索引,如果有很多索引空缺,可能会造成空间浪费", enums.getClass().getSimpleName(), WORNNING_MAX_INDEX));
}
List<E> instances = new ArrayList<E>(maxIndex + 1);
// 先全用null填充
for (int i = 0; i < maxIndex + 1; i++) {
instances.add(null);
}
int reverseIndex;
for (E enm : enums) {
curIdx = enm.getIndex();
reverseIndex = maxIndex - curIdx;
// 索引必须唯一
Assert.isTrue(instances.get(reverseIndex) == null, "枚举中有重复的index type= "
+ enums.getClass().getComponentType().getName());
instances.set(reverseIndex, enm);
}
return instances;
}
public static <E extends IndexedEnum> HashMap<Integer, E> toIndexMap(E[] enums) {
HashMap<Integer, E> map = new HashMap<>();
for (E enm : enums) {
map.put(enm.getIndex(), enm);
}
return map;
}
/**
* 打印枚举所有index
*
* @param allIndexedEnums
* @param <E>
* @return
*/
public static <E extends IndexedEnum> String printEnumIndexes(List<E> allIndexedEnums) {
StringBuilder stringBuilder = new StringBuilder();
for (E e : allIndexedEnums) {
if (e == null) {
continue;
}
stringBuilder.append(e.getIndex() + " ");
}
return stringBuilder.length() > 0 ? stringBuilder.substring(0, stringBuilder.length() - 1) : stringBuilder.toString();
}
}
} | 34.796117 | 140 | 0.502232 |
18860da1f1d417210fe6d7bc83c99b004792546c | 55 | package os.microsoft.System32;
public class mkdir {
}
| 11 | 30 | 0.763636 |
78b7e53d6a71b728f742bc8d9dd0b0e0bc2008ec | 5,042 | package org.cfpa;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.options.GameOptions;
import net.minecraft.client.resource.language.LanguageDefinition;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
@Environment(EnvType.CLIENT)
public class I18nUpdateMod implements ClientModInitializer {
public static final String MOD_ID = "i18nupdatemod";
public static final Logger LOGGER = LogManager.getLogger(MOD_ID);
public final static Path CACHE_DIR = Paths.get(System.getProperty("user.home"), "." + MOD_ID, "1.16.5");
public final static Path RESOURCE_FOLDER = Paths.get(MinecraftClient.getInstance().runDirectory.getPath(), "resourcepacks");
public final static Path LOCAL_LANGUAGE_PACK = RESOURCE_FOLDER.resolve("Minecraft-Mod-Language-Modpack-1-16.zip");
public final static Path LANGUAGE_PACK = CACHE_DIR.resolve("Minecraft-Mod-Language-Modpack-1-16.zip");
public final static Path LANGUAGE_MD5 = CACHE_DIR.resolve("1.16.md5");
public final static String LINK = "http://downloader1.meitangdehulu.com:22943/Minecraft-Mod-Language-Modpack-1-16.zip";
public final static String MD5 = "http://downloader1.meitangdehulu.com:22943/1.16.md5";
public static String MD5String = "";
public I18nUpdateMod(){
LOGGER.info("Constructing mod...");
}
@Override
public void onInitializeClient() {
//mc.getLanguageManager().setLanguage(new LanguageDefinition("zh_cn","中文(简体)","China",false));
// 检查主资源包目录是否存在
if (!Files.isDirectory(CACHE_DIR)) {
try {
Files.createDirectories(CACHE_DIR);
} catch (IOException e) {
e.printStackTrace();
return;
}
}
//检查游戏下资源包目录
if (!Files.isDirectory(RESOURCE_FOLDER)) {
try {
Files.createDirectories(RESOURCE_FOLDER);
} catch (IOException e) {
e.printStackTrace();
return;
}
}
//尝试加载MD5文件
try {
FileUtils.copyURLToFile(new URL(MD5), LANGUAGE_MD5.toFile());
} catch (IOException e) {
e.printStackTrace();
LOGGER.error("Download MD5 failed.");
return;
}
try {
StringBuilder stringBuffer = new StringBuilder();
List<String> lines = Files.readAllLines(LANGUAGE_MD5);
for (String line : lines) {
stringBuffer.append(line);
MD5String = stringBuffer.toString();
}
} catch (IOException e) {
e.printStackTrace();
return;
}
MinecraftClient mc = MinecraftClient.getInstance();
if (Files.exists(LANGUAGE_PACK)) {
String md5;
try {
InputStream is = Files.newInputStream(LANGUAGE_PACK);
md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(is).toUpperCase();
} catch (IOException e) {
e.printStackTrace();
LOGGER.error("Error when compute md5.");
return;
}
try {
if (!md5.equals(MD5String)) {
FileUtils.copyURLToFile(new URL(LINK), LANGUAGE_PACK.toFile());
if(Files.exists(LOCAL_LANGUAGE_PACK)){
Files.delete(LOCAL_LANGUAGE_PACK);
}
Files.copy(LANGUAGE_PACK, LOCAL_LANGUAGE_PACK);
}
} catch (MalformedURLException e) {
LOGGER.error("Download Langpack failed.");
e.printStackTrace();
return;
} catch (IOException e) {
LOGGER.error("Error when copy file.");
e.printStackTrace();
return;
}
//Util.setResourcesRepository(mc);
} else {
try {
FileUtils.copyURLToFile(new URL(LINK), LANGUAGE_PACK.toFile());
Files.copy(LANGUAGE_PACK, LOCAL_LANGUAGE_PACK);
} catch (IOException e) {
LOGGER.error("Download Langpack failed.");
e.printStackTrace();
return;
}
try {
//Util.setResourcesRepository(mc);
//Minecraft.getInstance().getResourcePackRepository().addPackFinder(new LanguagePackFinder());
} catch (Exception e) {
e.printStackTrace();
return;
}
}
if(!Files.exists(LOCAL_LANGUAGE_PACK)){
try {
Files.copy(LANGUAGE_PACK, LOCAL_LANGUAGE_PACK);
//InputStream is1 = Files.newInputStream(LOCAL_LANGUAGE_PACK);
//InputStream is2 = Files.newInputStream(LANGUAGE_PACK);
//String md51 = org.apache.commons.codec.digest.DigestUtils.md5Hex(is1).toUpperCase();
//String md52 = org.apache.commons.codec.digest.DigestUtils.md5Hex(is2).toUpperCase();
//if (!md51.equals(md52)){
//Files.delete(LOCAL_LANGUAGE_PACK);
//Files.copy(LANGUAGE_PACK, LOCAL_LANGUAGE_PACK);
//}
} catch (IOException e) {
e.printStackTrace();
LOGGER.error("Error when copy file.");
return;
}
try {
//Util.setResourcesRepository(mc);
//Minecraft.getInstance().getResourcePackRepository().addPackFinder(new LanguagePackFinder());
} catch (Exception e) {
e.printStackTrace();
return;
}
}
//Util.setResourcesRepository(mc);
}
}
| 31.31677 | 125 | 0.714796 |
5753fe8c9233d195d2c4faf5c6862e854b90c6f5 | 48,983 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is autogenerated by:
// mojo/public/tools/bindings/mojom_bindings_generator.py
// For:
// third_party/blink/public/mojom/mediastream/media_stream.mojom
//
package org.chromium.blink.mojom;
import org.chromium.mojo.bindings.DeserializationException;
class MediaStreamDispatcherHost_Internal {
public static final org.chromium.mojo.bindings.Interface.Manager<MediaStreamDispatcherHost, MediaStreamDispatcherHost.Proxy> MANAGER =
new org.chromium.mojo.bindings.Interface.Manager<MediaStreamDispatcherHost, MediaStreamDispatcherHost.Proxy>() {
@Override
public String getName() {
return "blink.mojom.MediaStreamDispatcherHost";
}
@Override
public int getVersion() {
return 0;
}
@Override
public Proxy buildProxy(org.chromium.mojo.system.Core core,
org.chromium.mojo.bindings.MessageReceiverWithResponder messageReceiver) {
return new Proxy(core, messageReceiver);
}
@Override
public Stub buildStub(org.chromium.mojo.system.Core core, MediaStreamDispatcherHost impl) {
return new Stub(core, impl);
}
@Override
public MediaStreamDispatcherHost[] buildArray(int size) {
return new MediaStreamDispatcherHost[size];
}
};
private static final int GENERATE_STREAM_ORDINAL = 0;
private static final int CANCEL_REQUEST_ORDINAL = 1;
private static final int STOP_STREAM_DEVICE_ORDINAL = 2;
private static final int OPEN_DEVICE_ORDINAL = 3;
private static final int CLOSE_DEVICE_ORDINAL = 4;
private static final int SET_CAPTURING_LINK_SECURED_ORDINAL = 5;
private static final int ON_STREAM_STARTED_ORDINAL = 6;
static final class Proxy extends org.chromium.mojo.bindings.Interface.AbstractProxy implements MediaStreamDispatcherHost.Proxy {
Proxy(org.chromium.mojo.system.Core core,
org.chromium.mojo.bindings.MessageReceiverWithResponder messageReceiver) {
super(core, messageReceiver);
}
@Override
public void generateStream(
int requestId, StreamControls controls, boolean userGesture,
GenerateStreamResponse callback) {
MediaStreamDispatcherHostGenerateStreamParams _message = new MediaStreamDispatcherHostGenerateStreamParams();
_message.requestId = requestId;
_message.controls = controls;
_message.userGesture = userGesture;
getProxyHandler().getMessageReceiver().acceptWithResponder(
_message.serializeWithHeader(
getProxyHandler().getCore(),
new org.chromium.mojo.bindings.MessageHeader(
GENERATE_STREAM_ORDINAL,
org.chromium.mojo.bindings.MessageHeader.MESSAGE_EXPECTS_RESPONSE_FLAG,
0)),
new MediaStreamDispatcherHostGenerateStreamResponseParamsForwardToCallback(callback));
}
@Override
public void cancelRequest(
int requestId) {
MediaStreamDispatcherHostCancelRequestParams _message = new MediaStreamDispatcherHostCancelRequestParams();
_message.requestId = requestId;
getProxyHandler().getMessageReceiver().accept(
_message.serializeWithHeader(
getProxyHandler().getCore(),
new org.chromium.mojo.bindings.MessageHeader(CANCEL_REQUEST_ORDINAL)));
}
@Override
public void stopStreamDevice(
String deviceId, int sessionId) {
MediaStreamDispatcherHostStopStreamDeviceParams _message = new MediaStreamDispatcherHostStopStreamDeviceParams();
_message.deviceId = deviceId;
_message.sessionId = sessionId;
getProxyHandler().getMessageReceiver().accept(
_message.serializeWithHeader(
getProxyHandler().getCore(),
new org.chromium.mojo.bindings.MessageHeader(STOP_STREAM_DEVICE_ORDINAL)));
}
@Override
public void openDevice(
int requestId, String deviceId, int type,
OpenDeviceResponse callback) {
MediaStreamDispatcherHostOpenDeviceParams _message = new MediaStreamDispatcherHostOpenDeviceParams();
_message.requestId = requestId;
_message.deviceId = deviceId;
_message.type = type;
getProxyHandler().getMessageReceiver().acceptWithResponder(
_message.serializeWithHeader(
getProxyHandler().getCore(),
new org.chromium.mojo.bindings.MessageHeader(
OPEN_DEVICE_ORDINAL,
org.chromium.mojo.bindings.MessageHeader.MESSAGE_EXPECTS_RESPONSE_FLAG,
0)),
new MediaStreamDispatcherHostOpenDeviceResponseParamsForwardToCallback(callback));
}
@Override
public void closeDevice(
String label) {
MediaStreamDispatcherHostCloseDeviceParams _message = new MediaStreamDispatcherHostCloseDeviceParams();
_message.label = label;
getProxyHandler().getMessageReceiver().accept(
_message.serializeWithHeader(
getProxyHandler().getCore(),
new org.chromium.mojo.bindings.MessageHeader(CLOSE_DEVICE_ORDINAL)));
}
@Override
public void setCapturingLinkSecured(
int sessionId, int type, boolean isSecure) {
MediaStreamDispatcherHostSetCapturingLinkSecuredParams _message = new MediaStreamDispatcherHostSetCapturingLinkSecuredParams();
_message.sessionId = sessionId;
_message.type = type;
_message.isSecure = isSecure;
getProxyHandler().getMessageReceiver().accept(
_message.serializeWithHeader(
getProxyHandler().getCore(),
new org.chromium.mojo.bindings.MessageHeader(SET_CAPTURING_LINK_SECURED_ORDINAL)));
}
@Override
public void onStreamStarted(
String label) {
MediaStreamDispatcherHostOnStreamStartedParams _message = new MediaStreamDispatcherHostOnStreamStartedParams();
_message.label = label;
getProxyHandler().getMessageReceiver().accept(
_message.serializeWithHeader(
getProxyHandler().getCore(),
new org.chromium.mojo.bindings.MessageHeader(ON_STREAM_STARTED_ORDINAL)));
}
}
static final class Stub extends org.chromium.mojo.bindings.Interface.Stub<MediaStreamDispatcherHost> {
Stub(org.chromium.mojo.system.Core core, MediaStreamDispatcherHost impl) {
super(core, impl);
}
@Override
public boolean accept(org.chromium.mojo.bindings.Message message) {
try {
org.chromium.mojo.bindings.ServiceMessage messageWithHeader =
message.asServiceMessage();
org.chromium.mojo.bindings.MessageHeader header = messageWithHeader.getHeader();
if (!header.validateHeader(org.chromium.mojo.bindings.MessageHeader.NO_FLAG)) {
return false;
}
switch(header.getType()) {
case org.chromium.mojo.bindings.interfacecontrol.InterfaceControlMessagesConstants.RUN_OR_CLOSE_PIPE_MESSAGE_ID:
return org.chromium.mojo.bindings.InterfaceControlMessagesHelper.handleRunOrClosePipe(
MediaStreamDispatcherHost_Internal.MANAGER, messageWithHeader);
case CANCEL_REQUEST_ORDINAL: {
MediaStreamDispatcherHostCancelRequestParams data =
MediaStreamDispatcherHostCancelRequestParams.deserialize(messageWithHeader.getPayload());
getImpl().cancelRequest(data.requestId);
return true;
}
case STOP_STREAM_DEVICE_ORDINAL: {
MediaStreamDispatcherHostStopStreamDeviceParams data =
MediaStreamDispatcherHostStopStreamDeviceParams.deserialize(messageWithHeader.getPayload());
getImpl().stopStreamDevice(data.deviceId, data.sessionId);
return true;
}
case CLOSE_DEVICE_ORDINAL: {
MediaStreamDispatcherHostCloseDeviceParams data =
MediaStreamDispatcherHostCloseDeviceParams.deserialize(messageWithHeader.getPayload());
getImpl().closeDevice(data.label);
return true;
}
case SET_CAPTURING_LINK_SECURED_ORDINAL: {
MediaStreamDispatcherHostSetCapturingLinkSecuredParams data =
MediaStreamDispatcherHostSetCapturingLinkSecuredParams.deserialize(messageWithHeader.getPayload());
getImpl().setCapturingLinkSecured(data.sessionId, data.type, data.isSecure);
return true;
}
case ON_STREAM_STARTED_ORDINAL: {
MediaStreamDispatcherHostOnStreamStartedParams data =
MediaStreamDispatcherHostOnStreamStartedParams.deserialize(messageWithHeader.getPayload());
getImpl().onStreamStarted(data.label);
return true;
}
default:
return false;
}
} catch (org.chromium.mojo.bindings.DeserializationException e) {
System.err.println(e.toString());
return false;
}
}
@Override
public boolean acceptWithResponder(org.chromium.mojo.bindings.Message message, org.chromium.mojo.bindings.MessageReceiver receiver) {
try {
org.chromium.mojo.bindings.ServiceMessage messageWithHeader =
message.asServiceMessage();
org.chromium.mojo.bindings.MessageHeader header = messageWithHeader.getHeader();
if (!header.validateHeader(org.chromium.mojo.bindings.MessageHeader.MESSAGE_EXPECTS_RESPONSE_FLAG)) {
return false;
}
switch(header.getType()) {
case org.chromium.mojo.bindings.interfacecontrol.InterfaceControlMessagesConstants.RUN_MESSAGE_ID:
return org.chromium.mojo.bindings.InterfaceControlMessagesHelper.handleRun(
getCore(), MediaStreamDispatcherHost_Internal.MANAGER, messageWithHeader, receiver);
case GENERATE_STREAM_ORDINAL: {
MediaStreamDispatcherHostGenerateStreamParams data =
MediaStreamDispatcherHostGenerateStreamParams.deserialize(messageWithHeader.getPayload());
getImpl().generateStream(data.requestId, data.controls, data.userGesture, new MediaStreamDispatcherHostGenerateStreamResponseParamsProxyToResponder(getCore(), receiver, header.getRequestId()));
return true;
}
case OPEN_DEVICE_ORDINAL: {
MediaStreamDispatcherHostOpenDeviceParams data =
MediaStreamDispatcherHostOpenDeviceParams.deserialize(messageWithHeader.getPayload());
getImpl().openDevice(data.requestId, data.deviceId, data.type, new MediaStreamDispatcherHostOpenDeviceResponseParamsProxyToResponder(getCore(), receiver, header.getRequestId()));
return true;
}
default:
return false;
}
} catch (org.chromium.mojo.bindings.DeserializationException e) {
System.err.println(e.toString());
return false;
}
}
}
static final class MediaStreamDispatcherHostGenerateStreamParams extends org.chromium.mojo.bindings.Struct {
private static final int STRUCT_SIZE = 24;
private static final org.chromium.mojo.bindings.DataHeader[] VERSION_ARRAY = new org.chromium.mojo.bindings.DataHeader[] {new org.chromium.mojo.bindings.DataHeader(24, 0)};
private static final org.chromium.mojo.bindings.DataHeader DEFAULT_STRUCT_INFO = VERSION_ARRAY[0];
public int requestId;
public StreamControls controls;
public boolean userGesture;
private MediaStreamDispatcherHostGenerateStreamParams(int version) {
super(STRUCT_SIZE, version);
}
public MediaStreamDispatcherHostGenerateStreamParams() {
this(0);
}
public static MediaStreamDispatcherHostGenerateStreamParams deserialize(org.chromium.mojo.bindings.Message message) {
return decode(new org.chromium.mojo.bindings.Decoder(message));
}
/**
* Similar to the method above, but deserializes from a |ByteBuffer| instance.
*
* @throws org.chromium.mojo.bindings.DeserializationException on deserialization failure.
*/
public static MediaStreamDispatcherHostGenerateStreamParams deserialize(java.nio.ByteBuffer data) {
return deserialize(new org.chromium.mojo.bindings.Message(
data, new java.util.ArrayList<org.chromium.mojo.system.Handle>()));
}
@SuppressWarnings("unchecked")
public static MediaStreamDispatcherHostGenerateStreamParams decode(org.chromium.mojo.bindings.Decoder decoder0) {
if (decoder0 == null) {
return null;
}
decoder0.increaseStackDepth();
MediaStreamDispatcherHostGenerateStreamParams result;
try {
org.chromium.mojo.bindings.DataHeader mainDataHeader = decoder0.readAndValidateDataHeader(VERSION_ARRAY);
final int elementsOrVersion = mainDataHeader.elementsOrVersion;
result = new MediaStreamDispatcherHostGenerateStreamParams(elementsOrVersion);
{
result.requestId = decoder0.readInt(8);
}
{
result.userGesture = decoder0.readBoolean(12, 0);
}
{
org.chromium.mojo.bindings.Decoder decoder1 = decoder0.readPointer(16, false);
result.controls = StreamControls.decode(decoder1);
}
} finally {
decoder0.decreaseStackDepth();
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected final void encode(org.chromium.mojo.bindings.Encoder encoder) {
org.chromium.mojo.bindings.Encoder encoder0 = encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO);
encoder0.encode(this.requestId, 8);
encoder0.encode(this.userGesture, 12, 0);
encoder0.encode(this.controls, 16, false);
}
}
static final class MediaStreamDispatcherHostGenerateStreamResponseParams extends org.chromium.mojo.bindings.Struct {
private static final int STRUCT_SIZE = 40;
private static final org.chromium.mojo.bindings.DataHeader[] VERSION_ARRAY = new org.chromium.mojo.bindings.DataHeader[] {new org.chromium.mojo.bindings.DataHeader(40, 0)};
private static final org.chromium.mojo.bindings.DataHeader DEFAULT_STRUCT_INFO = VERSION_ARRAY[0];
public int result;
public String label;
public MediaStreamDevice[] audioDevices;
public MediaStreamDevice[] videoDevices;
private MediaStreamDispatcherHostGenerateStreamResponseParams(int version) {
super(STRUCT_SIZE, version);
}
public MediaStreamDispatcherHostGenerateStreamResponseParams() {
this(0);
}
public static MediaStreamDispatcherHostGenerateStreamResponseParams deserialize(org.chromium.mojo.bindings.Message message) {
return decode(new org.chromium.mojo.bindings.Decoder(message));
}
/**
* Similar to the method above, but deserializes from a |ByteBuffer| instance.
*
* @throws org.chromium.mojo.bindings.DeserializationException on deserialization failure.
*/
public static MediaStreamDispatcherHostGenerateStreamResponseParams deserialize(java.nio.ByteBuffer data) {
return deserialize(new org.chromium.mojo.bindings.Message(
data, new java.util.ArrayList<org.chromium.mojo.system.Handle>()));
}
@SuppressWarnings("unchecked")
public static MediaStreamDispatcherHostGenerateStreamResponseParams decode(org.chromium.mojo.bindings.Decoder decoder0) {
if (decoder0 == null) {
return null;
}
decoder0.increaseStackDepth();
MediaStreamDispatcherHostGenerateStreamResponseParams result;
try {
org.chromium.mojo.bindings.DataHeader mainDataHeader = decoder0.readAndValidateDataHeader(VERSION_ARRAY);
final int elementsOrVersion = mainDataHeader.elementsOrVersion;
result = new MediaStreamDispatcherHostGenerateStreamResponseParams(elementsOrVersion);
{
result.result = decoder0.readInt(8);
MediaStreamRequestResult.validate(result.result);
}
{
result.label = decoder0.readString(16, false);
}
{
org.chromium.mojo.bindings.Decoder decoder1 = decoder0.readPointer(24, false);
{
org.chromium.mojo.bindings.DataHeader si1 = decoder1.readDataHeaderForPointerArray(org.chromium.mojo.bindings.BindingsHelper.UNSPECIFIED_ARRAY_LENGTH);
result.audioDevices = new MediaStreamDevice[si1.elementsOrVersion];
for (int i1 = 0; i1 < si1.elementsOrVersion; ++i1) {
org.chromium.mojo.bindings.Decoder decoder2 = decoder1.readPointer(org.chromium.mojo.bindings.DataHeader.HEADER_SIZE + org.chromium.mojo.bindings.BindingsHelper.POINTER_SIZE * i1, false);
result.audioDevices[i1] = MediaStreamDevice.decode(decoder2);
}
}
}
{
org.chromium.mojo.bindings.Decoder decoder1 = decoder0.readPointer(32, false);
{
org.chromium.mojo.bindings.DataHeader si1 = decoder1.readDataHeaderForPointerArray(org.chromium.mojo.bindings.BindingsHelper.UNSPECIFIED_ARRAY_LENGTH);
result.videoDevices = new MediaStreamDevice[si1.elementsOrVersion];
for (int i1 = 0; i1 < si1.elementsOrVersion; ++i1) {
org.chromium.mojo.bindings.Decoder decoder2 = decoder1.readPointer(org.chromium.mojo.bindings.DataHeader.HEADER_SIZE + org.chromium.mojo.bindings.BindingsHelper.POINTER_SIZE * i1, false);
result.videoDevices[i1] = MediaStreamDevice.decode(decoder2);
}
}
}
} finally {
decoder0.decreaseStackDepth();
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected final void encode(org.chromium.mojo.bindings.Encoder encoder) {
org.chromium.mojo.bindings.Encoder encoder0 = encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO);
encoder0.encode(this.result, 8);
encoder0.encode(this.label, 16, false);
if (this.audioDevices == null) {
encoder0.encodeNullPointer(24, false);
} else {
org.chromium.mojo.bindings.Encoder encoder1 = encoder0.encodePointerArray(this.audioDevices.length, 24, org.chromium.mojo.bindings.BindingsHelper.UNSPECIFIED_ARRAY_LENGTH);
for (int i0 = 0; i0 < this.audioDevices.length; ++i0) {
encoder1.encode(this.audioDevices[i0], org.chromium.mojo.bindings.DataHeader.HEADER_SIZE + org.chromium.mojo.bindings.BindingsHelper.POINTER_SIZE * i0, false);
}
}
if (this.videoDevices == null) {
encoder0.encodeNullPointer(32, false);
} else {
org.chromium.mojo.bindings.Encoder encoder1 = encoder0.encodePointerArray(this.videoDevices.length, 32, org.chromium.mojo.bindings.BindingsHelper.UNSPECIFIED_ARRAY_LENGTH);
for (int i0 = 0; i0 < this.videoDevices.length; ++i0) {
encoder1.encode(this.videoDevices[i0], org.chromium.mojo.bindings.DataHeader.HEADER_SIZE + org.chromium.mojo.bindings.BindingsHelper.POINTER_SIZE * i0, false);
}
}
}
}
static class MediaStreamDispatcherHostGenerateStreamResponseParamsForwardToCallback extends org.chromium.mojo.bindings.SideEffectFreeCloseable
implements org.chromium.mojo.bindings.MessageReceiver {
private final MediaStreamDispatcherHost.GenerateStreamResponse mCallback;
MediaStreamDispatcherHostGenerateStreamResponseParamsForwardToCallback(MediaStreamDispatcherHost.GenerateStreamResponse callback) {
this.mCallback = callback;
}
@Override
public boolean accept(org.chromium.mojo.bindings.Message message) {
try {
org.chromium.mojo.bindings.ServiceMessage messageWithHeader =
message.asServiceMessage();
org.chromium.mojo.bindings.MessageHeader header = messageWithHeader.getHeader();
if (!header.validateHeader(GENERATE_STREAM_ORDINAL,
org.chromium.mojo.bindings.MessageHeader.MESSAGE_IS_RESPONSE_FLAG)) {
return false;
}
MediaStreamDispatcherHostGenerateStreamResponseParams response = MediaStreamDispatcherHostGenerateStreamResponseParams.deserialize(messageWithHeader.getPayload());
mCallback.call(response.result, response.label, response.audioDevices, response.videoDevices);
return true;
} catch (org.chromium.mojo.bindings.DeserializationException e) {
return false;
}
}
}
static class MediaStreamDispatcherHostGenerateStreamResponseParamsProxyToResponder implements MediaStreamDispatcherHost.GenerateStreamResponse {
private final org.chromium.mojo.system.Core mCore;
private final org.chromium.mojo.bindings.MessageReceiver mMessageReceiver;
private final long mRequestId;
MediaStreamDispatcherHostGenerateStreamResponseParamsProxyToResponder(
org.chromium.mojo.system.Core core,
org.chromium.mojo.bindings.MessageReceiver messageReceiver,
long requestId) {
mCore = core;
mMessageReceiver = messageReceiver;
mRequestId = requestId;
}
@Override
public void call(Integer result, String label, MediaStreamDevice[] audioDevices, MediaStreamDevice[] videoDevices) {
MediaStreamDispatcherHostGenerateStreamResponseParams _response = new MediaStreamDispatcherHostGenerateStreamResponseParams();
_response.result = result;
_response.label = label;
_response.audioDevices = audioDevices;
_response.videoDevices = videoDevices;
org.chromium.mojo.bindings.ServiceMessage _message =
_response.serializeWithHeader(
mCore,
new org.chromium.mojo.bindings.MessageHeader(
GENERATE_STREAM_ORDINAL,
org.chromium.mojo.bindings.MessageHeader.MESSAGE_IS_RESPONSE_FLAG,
mRequestId));
mMessageReceiver.accept(_message);
}
}
static final class MediaStreamDispatcherHostCancelRequestParams extends org.chromium.mojo.bindings.Struct {
private static final int STRUCT_SIZE = 16;
private static final org.chromium.mojo.bindings.DataHeader[] VERSION_ARRAY = new org.chromium.mojo.bindings.DataHeader[] {new org.chromium.mojo.bindings.DataHeader(16, 0)};
private static final org.chromium.mojo.bindings.DataHeader DEFAULT_STRUCT_INFO = VERSION_ARRAY[0];
public int requestId;
private MediaStreamDispatcherHostCancelRequestParams(int version) {
super(STRUCT_SIZE, version);
}
public MediaStreamDispatcherHostCancelRequestParams() {
this(0);
}
public static MediaStreamDispatcherHostCancelRequestParams deserialize(org.chromium.mojo.bindings.Message message) {
return decode(new org.chromium.mojo.bindings.Decoder(message));
}
/**
* Similar to the method above, but deserializes from a |ByteBuffer| instance.
*
* @throws org.chromium.mojo.bindings.DeserializationException on deserialization failure.
*/
public static MediaStreamDispatcherHostCancelRequestParams deserialize(java.nio.ByteBuffer data) {
return deserialize(new org.chromium.mojo.bindings.Message(
data, new java.util.ArrayList<org.chromium.mojo.system.Handle>()));
}
@SuppressWarnings("unchecked")
public static MediaStreamDispatcherHostCancelRequestParams decode(org.chromium.mojo.bindings.Decoder decoder0) {
if (decoder0 == null) {
return null;
}
decoder0.increaseStackDepth();
MediaStreamDispatcherHostCancelRequestParams result;
try {
org.chromium.mojo.bindings.DataHeader mainDataHeader = decoder0.readAndValidateDataHeader(VERSION_ARRAY);
final int elementsOrVersion = mainDataHeader.elementsOrVersion;
result = new MediaStreamDispatcherHostCancelRequestParams(elementsOrVersion);
{
result.requestId = decoder0.readInt(8);
}
} finally {
decoder0.decreaseStackDepth();
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected final void encode(org.chromium.mojo.bindings.Encoder encoder) {
org.chromium.mojo.bindings.Encoder encoder0 = encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO);
encoder0.encode(this.requestId, 8);
}
}
static final class MediaStreamDispatcherHostStopStreamDeviceParams extends org.chromium.mojo.bindings.Struct {
private static final int STRUCT_SIZE = 24;
private static final org.chromium.mojo.bindings.DataHeader[] VERSION_ARRAY = new org.chromium.mojo.bindings.DataHeader[] {new org.chromium.mojo.bindings.DataHeader(24, 0)};
private static final org.chromium.mojo.bindings.DataHeader DEFAULT_STRUCT_INFO = VERSION_ARRAY[0];
public String deviceId;
public int sessionId;
private MediaStreamDispatcherHostStopStreamDeviceParams(int version) {
super(STRUCT_SIZE, version);
}
public MediaStreamDispatcherHostStopStreamDeviceParams() {
this(0);
}
public static MediaStreamDispatcherHostStopStreamDeviceParams deserialize(org.chromium.mojo.bindings.Message message) {
return decode(new org.chromium.mojo.bindings.Decoder(message));
}
/**
* Similar to the method above, but deserializes from a |ByteBuffer| instance.
*
* @throws org.chromium.mojo.bindings.DeserializationException on deserialization failure.
*/
public static MediaStreamDispatcherHostStopStreamDeviceParams deserialize(java.nio.ByteBuffer data) {
return deserialize(new org.chromium.mojo.bindings.Message(
data, new java.util.ArrayList<org.chromium.mojo.system.Handle>()));
}
@SuppressWarnings("unchecked")
public static MediaStreamDispatcherHostStopStreamDeviceParams decode(org.chromium.mojo.bindings.Decoder decoder0) {
if (decoder0 == null) {
return null;
}
decoder0.increaseStackDepth();
MediaStreamDispatcherHostStopStreamDeviceParams result;
try {
org.chromium.mojo.bindings.DataHeader mainDataHeader = decoder0.readAndValidateDataHeader(VERSION_ARRAY);
final int elementsOrVersion = mainDataHeader.elementsOrVersion;
result = new MediaStreamDispatcherHostStopStreamDeviceParams(elementsOrVersion);
{
result.deviceId = decoder0.readString(8, false);
}
{
result.sessionId = decoder0.readInt(16);
}
} finally {
decoder0.decreaseStackDepth();
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected final void encode(org.chromium.mojo.bindings.Encoder encoder) {
org.chromium.mojo.bindings.Encoder encoder0 = encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO);
encoder0.encode(this.deviceId, 8, false);
encoder0.encode(this.sessionId, 16);
}
}
static final class MediaStreamDispatcherHostOpenDeviceParams extends org.chromium.mojo.bindings.Struct {
private static final int STRUCT_SIZE = 24;
private static final org.chromium.mojo.bindings.DataHeader[] VERSION_ARRAY = new org.chromium.mojo.bindings.DataHeader[] {new org.chromium.mojo.bindings.DataHeader(24, 0)};
private static final org.chromium.mojo.bindings.DataHeader DEFAULT_STRUCT_INFO = VERSION_ARRAY[0];
public int requestId;
public String deviceId;
public int type;
private MediaStreamDispatcherHostOpenDeviceParams(int version) {
super(STRUCT_SIZE, version);
}
public MediaStreamDispatcherHostOpenDeviceParams() {
this(0);
}
public static MediaStreamDispatcherHostOpenDeviceParams deserialize(org.chromium.mojo.bindings.Message message) {
return decode(new org.chromium.mojo.bindings.Decoder(message));
}
/**
* Similar to the method above, but deserializes from a |ByteBuffer| instance.
*
* @throws org.chromium.mojo.bindings.DeserializationException on deserialization failure.
*/
public static MediaStreamDispatcherHostOpenDeviceParams deserialize(java.nio.ByteBuffer data) {
return deserialize(new org.chromium.mojo.bindings.Message(
data, new java.util.ArrayList<org.chromium.mojo.system.Handle>()));
}
@SuppressWarnings("unchecked")
public static MediaStreamDispatcherHostOpenDeviceParams decode(org.chromium.mojo.bindings.Decoder decoder0) {
if (decoder0 == null) {
return null;
}
decoder0.increaseStackDepth();
MediaStreamDispatcherHostOpenDeviceParams result;
try {
org.chromium.mojo.bindings.DataHeader mainDataHeader = decoder0.readAndValidateDataHeader(VERSION_ARRAY);
final int elementsOrVersion = mainDataHeader.elementsOrVersion;
result = new MediaStreamDispatcherHostOpenDeviceParams(elementsOrVersion);
{
result.requestId = decoder0.readInt(8);
}
{
result.type = decoder0.readInt(12);
MediaStreamType.validate(result.type);
}
{
result.deviceId = decoder0.readString(16, false);
}
} finally {
decoder0.decreaseStackDepth();
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected final void encode(org.chromium.mojo.bindings.Encoder encoder) {
org.chromium.mojo.bindings.Encoder encoder0 = encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO);
encoder0.encode(this.requestId, 8);
encoder0.encode(this.type, 12);
encoder0.encode(this.deviceId, 16, false);
}
}
static final class MediaStreamDispatcherHostOpenDeviceResponseParams extends org.chromium.mojo.bindings.Struct {
private static final int STRUCT_SIZE = 32;
private static final org.chromium.mojo.bindings.DataHeader[] VERSION_ARRAY = new org.chromium.mojo.bindings.DataHeader[] {new org.chromium.mojo.bindings.DataHeader(32, 0)};
private static final org.chromium.mojo.bindings.DataHeader DEFAULT_STRUCT_INFO = VERSION_ARRAY[0];
public boolean success;
public String label;
public MediaStreamDevice device;
private MediaStreamDispatcherHostOpenDeviceResponseParams(int version) {
super(STRUCT_SIZE, version);
}
public MediaStreamDispatcherHostOpenDeviceResponseParams() {
this(0);
}
public static MediaStreamDispatcherHostOpenDeviceResponseParams deserialize(org.chromium.mojo.bindings.Message message) {
return decode(new org.chromium.mojo.bindings.Decoder(message));
}
/**
* Similar to the method above, but deserializes from a |ByteBuffer| instance.
*
* @throws org.chromium.mojo.bindings.DeserializationException on deserialization failure.
*/
public static MediaStreamDispatcherHostOpenDeviceResponseParams deserialize(java.nio.ByteBuffer data) {
return deserialize(new org.chromium.mojo.bindings.Message(
data, new java.util.ArrayList<org.chromium.mojo.system.Handle>()));
}
@SuppressWarnings("unchecked")
public static MediaStreamDispatcherHostOpenDeviceResponseParams decode(org.chromium.mojo.bindings.Decoder decoder0) {
if (decoder0 == null) {
return null;
}
decoder0.increaseStackDepth();
MediaStreamDispatcherHostOpenDeviceResponseParams result;
try {
org.chromium.mojo.bindings.DataHeader mainDataHeader = decoder0.readAndValidateDataHeader(VERSION_ARRAY);
final int elementsOrVersion = mainDataHeader.elementsOrVersion;
result = new MediaStreamDispatcherHostOpenDeviceResponseParams(elementsOrVersion);
{
result.success = decoder0.readBoolean(8, 0);
}
{
result.label = decoder0.readString(16, false);
}
{
org.chromium.mojo.bindings.Decoder decoder1 = decoder0.readPointer(24, false);
result.device = MediaStreamDevice.decode(decoder1);
}
} finally {
decoder0.decreaseStackDepth();
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected final void encode(org.chromium.mojo.bindings.Encoder encoder) {
org.chromium.mojo.bindings.Encoder encoder0 = encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO);
encoder0.encode(this.success, 8, 0);
encoder0.encode(this.label, 16, false);
encoder0.encode(this.device, 24, false);
}
}
static class MediaStreamDispatcherHostOpenDeviceResponseParamsForwardToCallback extends org.chromium.mojo.bindings.SideEffectFreeCloseable
implements org.chromium.mojo.bindings.MessageReceiver {
private final MediaStreamDispatcherHost.OpenDeviceResponse mCallback;
MediaStreamDispatcherHostOpenDeviceResponseParamsForwardToCallback(MediaStreamDispatcherHost.OpenDeviceResponse callback) {
this.mCallback = callback;
}
@Override
public boolean accept(org.chromium.mojo.bindings.Message message) {
try {
org.chromium.mojo.bindings.ServiceMessage messageWithHeader =
message.asServiceMessage();
org.chromium.mojo.bindings.MessageHeader header = messageWithHeader.getHeader();
if (!header.validateHeader(OPEN_DEVICE_ORDINAL,
org.chromium.mojo.bindings.MessageHeader.MESSAGE_IS_RESPONSE_FLAG)) {
return false;
}
MediaStreamDispatcherHostOpenDeviceResponseParams response = MediaStreamDispatcherHostOpenDeviceResponseParams.deserialize(messageWithHeader.getPayload());
mCallback.call(response.success, response.label, response.device);
return true;
} catch (org.chromium.mojo.bindings.DeserializationException e) {
return false;
}
}
}
static class MediaStreamDispatcherHostOpenDeviceResponseParamsProxyToResponder implements MediaStreamDispatcherHost.OpenDeviceResponse {
private final org.chromium.mojo.system.Core mCore;
private final org.chromium.mojo.bindings.MessageReceiver mMessageReceiver;
private final long mRequestId;
MediaStreamDispatcherHostOpenDeviceResponseParamsProxyToResponder(
org.chromium.mojo.system.Core core,
org.chromium.mojo.bindings.MessageReceiver messageReceiver,
long requestId) {
mCore = core;
mMessageReceiver = messageReceiver;
mRequestId = requestId;
}
@Override
public void call(Boolean success, String label, MediaStreamDevice device) {
MediaStreamDispatcherHostOpenDeviceResponseParams _response = new MediaStreamDispatcherHostOpenDeviceResponseParams();
_response.success = success;
_response.label = label;
_response.device = device;
org.chromium.mojo.bindings.ServiceMessage _message =
_response.serializeWithHeader(
mCore,
new org.chromium.mojo.bindings.MessageHeader(
OPEN_DEVICE_ORDINAL,
org.chromium.mojo.bindings.MessageHeader.MESSAGE_IS_RESPONSE_FLAG,
mRequestId));
mMessageReceiver.accept(_message);
}
}
static final class MediaStreamDispatcherHostCloseDeviceParams extends org.chromium.mojo.bindings.Struct {
private static final int STRUCT_SIZE = 16;
private static final org.chromium.mojo.bindings.DataHeader[] VERSION_ARRAY = new org.chromium.mojo.bindings.DataHeader[] {new org.chromium.mojo.bindings.DataHeader(16, 0)};
private static final org.chromium.mojo.bindings.DataHeader DEFAULT_STRUCT_INFO = VERSION_ARRAY[0];
public String label;
private MediaStreamDispatcherHostCloseDeviceParams(int version) {
super(STRUCT_SIZE, version);
}
public MediaStreamDispatcherHostCloseDeviceParams() {
this(0);
}
public static MediaStreamDispatcherHostCloseDeviceParams deserialize(org.chromium.mojo.bindings.Message message) {
return decode(new org.chromium.mojo.bindings.Decoder(message));
}
/**
* Similar to the method above, but deserializes from a |ByteBuffer| instance.
*
* @throws org.chromium.mojo.bindings.DeserializationException on deserialization failure.
*/
public static MediaStreamDispatcherHostCloseDeviceParams deserialize(java.nio.ByteBuffer data) {
return deserialize(new org.chromium.mojo.bindings.Message(
data, new java.util.ArrayList<org.chromium.mojo.system.Handle>()));
}
@SuppressWarnings("unchecked")
public static MediaStreamDispatcherHostCloseDeviceParams decode(org.chromium.mojo.bindings.Decoder decoder0) {
if (decoder0 == null) {
return null;
}
decoder0.increaseStackDepth();
MediaStreamDispatcherHostCloseDeviceParams result;
try {
org.chromium.mojo.bindings.DataHeader mainDataHeader = decoder0.readAndValidateDataHeader(VERSION_ARRAY);
final int elementsOrVersion = mainDataHeader.elementsOrVersion;
result = new MediaStreamDispatcherHostCloseDeviceParams(elementsOrVersion);
{
result.label = decoder0.readString(8, false);
}
} finally {
decoder0.decreaseStackDepth();
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected final void encode(org.chromium.mojo.bindings.Encoder encoder) {
org.chromium.mojo.bindings.Encoder encoder0 = encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO);
encoder0.encode(this.label, 8, false);
}
}
static final class MediaStreamDispatcherHostSetCapturingLinkSecuredParams extends org.chromium.mojo.bindings.Struct {
private static final int STRUCT_SIZE = 24;
private static final org.chromium.mojo.bindings.DataHeader[] VERSION_ARRAY = new org.chromium.mojo.bindings.DataHeader[] {new org.chromium.mojo.bindings.DataHeader(24, 0)};
private static final org.chromium.mojo.bindings.DataHeader DEFAULT_STRUCT_INFO = VERSION_ARRAY[0];
public int sessionId;
public int type;
public boolean isSecure;
private MediaStreamDispatcherHostSetCapturingLinkSecuredParams(int version) {
super(STRUCT_SIZE, version);
}
public MediaStreamDispatcherHostSetCapturingLinkSecuredParams() {
this(0);
}
public static MediaStreamDispatcherHostSetCapturingLinkSecuredParams deserialize(org.chromium.mojo.bindings.Message message) {
return decode(new org.chromium.mojo.bindings.Decoder(message));
}
/**
* Similar to the method above, but deserializes from a |ByteBuffer| instance.
*
* @throws org.chromium.mojo.bindings.DeserializationException on deserialization failure.
*/
public static MediaStreamDispatcherHostSetCapturingLinkSecuredParams deserialize(java.nio.ByteBuffer data) {
return deserialize(new org.chromium.mojo.bindings.Message(
data, new java.util.ArrayList<org.chromium.mojo.system.Handle>()));
}
@SuppressWarnings("unchecked")
public static MediaStreamDispatcherHostSetCapturingLinkSecuredParams decode(org.chromium.mojo.bindings.Decoder decoder0) {
if (decoder0 == null) {
return null;
}
decoder0.increaseStackDepth();
MediaStreamDispatcherHostSetCapturingLinkSecuredParams result;
try {
org.chromium.mojo.bindings.DataHeader mainDataHeader = decoder0.readAndValidateDataHeader(VERSION_ARRAY);
final int elementsOrVersion = mainDataHeader.elementsOrVersion;
result = new MediaStreamDispatcherHostSetCapturingLinkSecuredParams(elementsOrVersion);
{
result.sessionId = decoder0.readInt(8);
}
{
result.type = decoder0.readInt(12);
MediaStreamType.validate(result.type);
}
{
result.isSecure = decoder0.readBoolean(16, 0);
}
} finally {
decoder0.decreaseStackDepth();
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected final void encode(org.chromium.mojo.bindings.Encoder encoder) {
org.chromium.mojo.bindings.Encoder encoder0 = encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO);
encoder0.encode(this.sessionId, 8);
encoder0.encode(this.type, 12);
encoder0.encode(this.isSecure, 16, 0);
}
}
static final class MediaStreamDispatcherHostOnStreamStartedParams extends org.chromium.mojo.bindings.Struct {
private static final int STRUCT_SIZE = 16;
private static final org.chromium.mojo.bindings.DataHeader[] VERSION_ARRAY = new org.chromium.mojo.bindings.DataHeader[] {new org.chromium.mojo.bindings.DataHeader(16, 0)};
private static final org.chromium.mojo.bindings.DataHeader DEFAULT_STRUCT_INFO = VERSION_ARRAY[0];
public String label;
private MediaStreamDispatcherHostOnStreamStartedParams(int version) {
super(STRUCT_SIZE, version);
}
public MediaStreamDispatcherHostOnStreamStartedParams() {
this(0);
}
public static MediaStreamDispatcherHostOnStreamStartedParams deserialize(org.chromium.mojo.bindings.Message message) {
return decode(new org.chromium.mojo.bindings.Decoder(message));
}
/**
* Similar to the method above, but deserializes from a |ByteBuffer| instance.
*
* @throws org.chromium.mojo.bindings.DeserializationException on deserialization failure.
*/
public static MediaStreamDispatcherHostOnStreamStartedParams deserialize(java.nio.ByteBuffer data) {
return deserialize(new org.chromium.mojo.bindings.Message(
data, new java.util.ArrayList<org.chromium.mojo.system.Handle>()));
}
@SuppressWarnings("unchecked")
public static MediaStreamDispatcherHostOnStreamStartedParams decode(org.chromium.mojo.bindings.Decoder decoder0) {
if (decoder0 == null) {
return null;
}
decoder0.increaseStackDepth();
MediaStreamDispatcherHostOnStreamStartedParams result;
try {
org.chromium.mojo.bindings.DataHeader mainDataHeader = decoder0.readAndValidateDataHeader(VERSION_ARRAY);
final int elementsOrVersion = mainDataHeader.elementsOrVersion;
result = new MediaStreamDispatcherHostOnStreamStartedParams(elementsOrVersion);
{
result.label = decoder0.readString(8, false);
}
} finally {
decoder0.decreaseStackDepth();
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected final void encode(org.chromium.mojo.bindings.Encoder encoder) {
org.chromium.mojo.bindings.Encoder encoder0 = encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO);
encoder0.encode(this.label, 8, false);
}
}
}
| 40.548841 | 217 | 0.620889 |
025e6846293b1fc29c6caa42d8b13468dddbd91e | 1,665 | /*
* Project jmxprofiler.
*
* Created by Maxim Morozov on 2017.04.23 22:20.
*
* Copyright (c) 2017 Maxim Morozov. All rights reserved.
*/
package ru.ixtal.jmxprofiler.jmx.core.mbean;
import ru.ixtal.jmxprofiler.jmx.core.mbean.filters.JMXMBeanFilter;
import javax.management.AttributeList;
import javax.management.JMException;
import java.io.IOException;
import java.time.Instant;
public final class JMXMBeanSnapshot {
private final Instant timestamp;
private final String name;
private final AttributeList attributes;
public JMXMBeanSnapshot(final JMXMBeanAttributes attributes) throws IOException, JMException {
this.timestamp = Instant.now();
this.name = attributes.name();
this.attributes = attributes.values();
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
} else if ((o == null) || (o.getClass() != this.getClass())) {
return false;
}
final JMXMBeanSnapshot that = (JMXMBeanSnapshot) o;
return new JMXMBeanComparator(this.attributes).compareTo(that.attributes);
}
@Override
public String toString() {
final StringBuilder s = new StringBuilder();
attributes.forEach((attribute) -> {
if (s.length() > 0) {
s.append(", ");
}
s.append(attribute);
});
return timestamp + " " + name + ": " + s;
}
public void traverse(final JMXMBeanVisitor visitor, final JMXMBeanFilter filter) throws Exception {
new JMXMBeanTraverser(visitor, filter, timestamp, name, attributes).traverse();
}
}
| 28.220339 | 103 | 0.643243 |
a93125342f702028bf065653273289b5496e6bc3 | 3,260 | package no.mnemonic.act.platform.service.ti.helpers;
import no.mnemonic.act.platform.api.exceptions.InvalidArgumentException;
import no.mnemonic.act.platform.dao.cassandra.FactManager;
import no.mnemonic.act.platform.dao.cassandra.entity.FactTypeEntity;
import java.util.UUID;
import static no.mnemonic.act.platform.service.ti.ThreatIntelligenceServiceImpl.GLOBAL_NAMESPACE;
public class FactTypeResolver {
static final UUID RETRACTION_FACT_TYPE_ID = UUID.nameUUIDFromBytes("SystemRetractionFactType".getBytes());
static final String RETRACTION_FACT_TYPE_NAME = "Retraction";
private final FactManager factManager;
public FactTypeResolver(FactManager factManager) {
this.factManager = factManager;
}
/**
* Tries to resolve a FactTypeEntity.
* <p>
* If the provided 'type' parameter is a String representing a UUID the FactType will be fetched by UUID, otherwise
* it will be fetched by name. An InvalidArgumentException is thrown if the FactType cannot be resolved.
*
* @param type Type UUID or type name
* @return Resolved FactTypeEntity
* @throws InvalidArgumentException If FactType cannot be resolved
*/
public FactTypeEntity resolveFactType(String type) throws InvalidArgumentException {
FactTypeEntity typeEntity;
try {
typeEntity = factManager.getFactType(UUID.fromString(type));
} catch (IllegalArgumentException ignored) {
// Can't convert 'type' field to UUID, try to fetch FactType by name.
typeEntity = factManager.getFactType(type);
}
if (typeEntity == null) {
throw new InvalidArgumentException().addValidationError("FactType does not exist.", "fact.type.not.exist", "type", type);
}
return typeEntity;
}
/**
* Resolves the FactType used for retracting Facts. It will create the required FactType if it does not exist yet.
* <p>
* TODO: Creating the FactType should be moved to a bootstrap method (together with other system types).
*
* @return Retraction FactType
*/
public FactTypeEntity resolveRetractionFactType() {
FactTypeEntity typeEntity = factManager.getFactType(RETRACTION_FACT_TYPE_ID);
if (typeEntity == null) {
// Need to create Retraction FactType. It doesn't need any bindings because it will directly reference the retracted Fact.
typeEntity = factManager.saveFactType(new FactTypeEntity()
.setId(RETRACTION_FACT_TYPE_ID)
.setNamespaceID(GLOBAL_NAMESPACE)
.setName(createRetractionFactTypeName())
.setValidator("TrueValidator"));
}
return typeEntity;
}
private String createRetractionFactTypeName() {
// This is needed to avoid an unlikely name collision (a FactType's name needs to be unique) when a user created a
// "Retraction" FactType first, but still the authoritative FactType created here should be used for Retraction.
// Should not be necessary any longer once a bootstrap method is implemented which creates the "Retraction" FactType on first start up.
FactTypeEntity collision = factManager.getFactType(RETRACTION_FACT_TYPE_NAME);
return collision == null ? RETRACTION_FACT_TYPE_NAME : RETRACTION_FACT_TYPE_NAME + "-" + UUID.randomUUID().toString().substring(0, 8);
}
}
| 40.75 | 139 | 0.743558 |
c40bc169ae70b1390fc14674bdbce80b26207b79 | 1,796 | /*
* Copyright 2018-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.atomix.core.test;
import java.util.concurrent.atomic.AtomicInteger;
import io.atomix.cluster.MemberId;
import io.atomix.cluster.discovery.BootstrapDiscoveryProvider;
import io.atomix.core.Atomix;
import io.atomix.core.AtomixBuilder;
import io.atomix.core.test.partition.TestPartitionGroup;
import io.atomix.utils.component.Component;
import io.atomix.utils.net.Address;
/**
* Test Atomix factory.
*/
public class TestAtomixFactory {
private final AtomicInteger memberId = new AtomicInteger();
/**
* Returns a new Atomix instance.
*
* @return a new Atomix instance
*/
public Atomix newInstance() {
int id = memberId.incrementAndGet();
return new AtomixBuilder(Component.Scope.TEST)
.withMemberId(MemberId.from(String.valueOf(id)))
.withMembershipProvider(BootstrapDiscoveryProvider.builder().build())
.withAddress(Address.from("localhost", 5000 + id))
.withManagementGroup(TestPartitionGroup.builder("system")
.withNumPartitions(1)
.build())
.addPartitionGroup(TestPartitionGroup.builder("test")
.withNumPartitions(3)
.build())
.build();
}
}
| 33.259259 | 77 | 0.722717 |
c8c763851a17d4e12ed9ce74c0c814e2aa21fc2d | 9,146 | /*
* Copyright (c) 2016 Kristjan Veskimae
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.pdfextractor.restapi.config;
import org.pdfextractor.db.domain.dictionary.AppAuthority;
import org.pdfextractor.restapi.controller.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter implements AuthenticationFailureHandler {
static Logger log = LoggerFactory.getLogger(SecurityConfig.class);
public static final String LOGIN_URL = "/admin/#/login";
@Autowired
@Qualifier("userDetailsService")
private UserDetailsService userDetailsService;
// @Autowired
// private PasswordEncoder passwordEncoder;
@Override
protected UserDetailsService userDetailsService() {
return userDetailsService;
}
@Autowired
public void registerAuthentication(final AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
// .passwordEncoder(passwordEncoder)
;
}
@Override
public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
String username = httpServletRequest.getParameter("j_username");
log.info("Failed login attempt by user '" + username + "'");
}
/**
* For back office app
*/
@Configuration
@Order(30)
public static class FormConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(final HttpSecurity http) throws Exception {
log.info("Configuring REST API security started");
// SavedRequestAwareAuthenticationSuccessHandler sraush = new SavedRequestAwareAuthenticationSuccessHandler();
// sraush.setDefaultTargetUrl("/admin/");
// @formatter:off
http
.formLogin()
// .failureHandler(this)
//.failureHandler(new SimpleUrlAuthenticationFailureHandler())
// .failureUrl("/login.html?error")
// .successForwardUrl("redirect:/admin/")
.successHandler(new SavedRequestAwareAuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
clearAuthenticationAttributes(request);
getRedirectStrategy().sendRedirect(request, response, "/rest/bootstrapdata");
}
})
.loginPage(LOGIN_URL)
.loginProcessingUrl("/rest/security_check")
// .defaultSuccessUrl("/admin/")
.failureUrl(LOGIN_URL)
.usernameParameter("j_username")
.passwordParameter("j_password")
.permitAll()
.and()
.logout()
.logoutUrl("/rest/logout")
.deleteCookies("remember-me")
.logoutSuccessUrl(LOGIN_URL)
.invalidateHttpSession(true)
.permitAll()
.and()
.authorizeRequests()
.antMatchers("/rest/" + BootstrapDataController.URL_PART + "/**").hasAnyAuthority(AppAuthority.REVIEWER.toString(), AppAuthority.CLIENT.toString())
.antMatchers("/rest/" + InvoiceFileController.URL_PART + "/**").hasAnyAuthority(AppAuthority.REVIEWER.toString(), AppAuthority.CLIENT.toString())
.antMatchers("/rest/" + PhraseTypeController.URL_PART + "/**").hasAnyAuthority(AppAuthority.REVIEWER.toString())
.antMatchers("/rest/" + ProfileController.URL_PART + "/**").authenticated()
.antMatchers("/rest/" + ReloadController.URL_PART + "/**").hasAnyAuthority(AppAuthority.REVIEWER.toString())
.antMatchers("/rest/" + ReviewController.URL_PART + "/**").hasAnyAuthority(AppAuthority.REVIEWER.toString())
.antMatchers("/rest/" + SettingController.URL_PART + "/**").hasAnyAuthority(AppAuthority.ADMIN.toString())
.antMatchers("/rest/" + StatisticsController.URL_PART + "/**").hasAnyAuthority(AppAuthority.ADMIN.toString())
.antMatchers("/rest/" + TrialsController.URL_PART + "/**").hasAnyAuthority(AppAuthority.CLIENT.toString())
.antMatchers("/rest/" + UserController.URL_PART + "/**").hasAnyAuthority(AppAuthority.ADMIN.toString())
.antMatchers("/rest/" + TestController.URL_PART).permitAll()
.anyRequest().denyAll()
.and()
.csrf().disable()
.headers().frameOptions().sameOrigin().httpStrictTransportSecurity().disable()
.xssProtection().disable();
// @formatter:on
log.info("Configuring REST API security finished");
}
}
/**
*
* Configuration for machine-to-machine communication
*
* The value for <tt>@Order</tt> must be smaller than the one for form authentication.
*
*/
@Configuration
@Order(20)
public static class HttpBasicConfiguration extends WebSecurityConfigurerAdapter {
protected void configure(final HttpSecurity http) throws Exception {
log.info("Configuring REST API M2M communication security started");
// @formatter:off
http
.antMatcher("/rest/" + InvoiceWorkflowController.URL_PART + "/**")
.authorizeRequests()
.antMatchers("/rest/" + InvoiceWorkflowController.URL_PART + "/**").hasAnyAuthority(AppAuthority.CLIENT.toString())
// anyRequest().denyAll().
.and()
.httpBasic()
.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint(SecurityConfig.LOGIN_URL) {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
if (authException instanceof InsufficientAuthenticationException) {
SecurityConfig.submitError(request, response, HttpStatus.FORBIDDEN, "You are not logged in");
} else if (authException instanceof BadCredentialsException) {
SecurityConfig.submitError(request, response, HttpStatus.UNAUTHORIZED,"You are lacking valid authentication credentials");
} else {
super.commence(request, response, authException);
}
}
})
.and()
.csrf().disable();
// @formatter:on
log.info("Configuring REST API M2M communication security finished");
}
}
private static void submitError(final HttpServletRequest request, final HttpServletResponse response, final HttpStatus httpStatus, final String errorMsg) throws IOException {
response.setStatus(httpStatus.value());
response.setContentType("application/json;charset=UTF-8");
response.resetBuffer();
response.getWriter().print("{\"url\": \""+request.getRequestURL()+"\", \"errorMsg\": \"" +errorMsg+ "\"}");
}
}
| 45.73 | 182 | 0.760223 |
bac8f8d4fc866dad1db74ce28a5a5803daa23594 | 5,559 | /*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jserver.gameserver.network.clientpackets;
import com.l2jserver.Config;
import com.l2jserver.gameserver.model.TradeList;
import com.l2jserver.gameserver.model.actor.L2Character;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
import com.l2jserver.gameserver.network.SystemMessageId;
import com.l2jserver.gameserver.network.serverpackets.ActionFailed;
import com.l2jserver.gameserver.network.serverpackets.PrivateStoreManageListBuy;
import com.l2jserver.gameserver.network.serverpackets.PrivateStoreMsgBuy;
import com.l2jserver.gameserver.network.serverpackets.SystemMessage;
import com.l2jserver.gameserver.taskmanager.AttackStanceTaskManager;
import com.l2jserver.gameserver.util.Util;
import static com.l2jserver.gameserver.model.itemcontainer.PcInventory.MAX_ADENA;
/**
* This class ...
*
* @version $Revision: 1.2.2.1.2.5 $ $Date: 2005/03/27 15:29:30 $
* CPU Disasm
* Packets: ddhhQQ cddb
*/
public final class SetPrivateStoreListBuy extends L2GameClientPacket
{
private static final String _C__91_SETPRIVATESTORELISTBUY = "[C] 91 SetPrivateStoreListBuy";
private static final int BATCH_LENGTH = 40; // length of the one item
private Item[] _items = null;
@Override
protected void readImpl()
{
int count = readD();
if (count < 1 || count > Config.MAX_ITEM_IN_PACKET || count * BATCH_LENGTH != _buf.remaining())
{
return;
}
_items = new Item[count];
for (int i = 0; i < count; i++)
{
int itemId = readD();
readH();//TODO analyse this
readH();//TODO analyse this
long cnt = readQ();
long price = readQ();
if (itemId < 1 || cnt < 1 || price < 0)
{
_items = null;
return;
}
readC(); // FE
readD(); // FF 00 00 00
readD(); // 00 00 00 00
readB(new byte[7]); // Completely Unknown
_items[i] = new Item(itemId, cnt, price);
}
}
@Override
protected void runImpl()
{
L2PcInstance player = getClient().getActiveChar();
if (player == null)
return;
if (_items == null)
{
player.setPrivateStoreType(L2PcInstance.STORE_PRIVATE_NONE);
player.broadcastUserInfo();
return;
}
if (!player.getAccessLevel().allowTransaction())
{
player.sendPacket(new SystemMessage(SystemMessageId.YOU_ARE_NOT_AUTHORIZED_TO_DO_THAT));
return;
}
if (AttackStanceTaskManager.getInstance().getAttackStanceTask(player) || player.isInDuel())
{
player.sendPacket(new SystemMessage(SystemMessageId.CANT_OPERATE_PRIVATE_STORE_DURING_COMBAT));
player.sendPacket(new PrivateStoreManageListBuy(player));
player.sendPacket(ActionFailed.STATIC_PACKET);
return;
}
if (player.isInsideZone(L2Character.ZONE_NOSTORE))
{
player.sendPacket(new PrivateStoreManageListBuy(player));
player.sendPacket(new SystemMessage(SystemMessageId.NO_PRIVATE_STORE_HERE));
player.sendPacket(ActionFailed.STATIC_PACKET);
return;
}
TradeList tradeList = player.getBuyList();
tradeList.clear();
// Check maximum number of allowed slots for pvt shops
if (_items.length > player.getPrivateBuyStoreLimit())
{
player.sendPacket(new PrivateStoreManageListBuy(player));
player.sendPacket(new SystemMessage(SystemMessageId.YOU_HAVE_EXCEEDED_QUANTITY_THAT_CAN_BE_INPUTTED));
return;
}
long totalCost = 0;
for (Item i : _items)
{
if (!i.addToTradeList(tradeList))
{
Util.handleIllegalPlayerAction(player, "Warning!! Character " + player.getName() + " of account " + player.getAccountName() + " tried to set price more than " + MAX_ADENA + " adena in Private Store - Buy.", Config.DEFAULT_PUNISH);
return;
}
totalCost += i.getCost();
if (totalCost > MAX_ADENA)
{
Util.handleIllegalPlayerAction(player, "Warning!! Character " + player.getName() + " of account " + player.getAccountName() + " tried to set total price more than " + MAX_ADENA + " adena in Private Store - Buy.", Config.DEFAULT_PUNISH);
return;
}
}
// Check for available funds
if (totalCost > player.getAdena())
{
player.sendPacket(new PrivateStoreManageListBuy(player));
player.sendPacket(new SystemMessage(SystemMessageId.THE_PURCHASE_PRICE_IS_HIGHER_THAN_MONEY));
return;
}
player.sitDown();
player.setPrivateStoreType(L2PcInstance.STORE_PRIVATE_BUY);
player.broadcastUserInfo();
player.broadcastPacket(new PrivateStoreMsgBuy(player));
}
private class Item
{
private final int _itemId;
private final long _count;
private final long _price;
public Item(int id, long num, long pri)
{
_itemId = id;
_count = num;
_price = pri;
}
public boolean addToTradeList(TradeList list)
{
if ((MAX_ADENA / _count) < _price)
return false;
list.addItemByItemId(_itemId, _count, _price);
return true;
}
public long getCost()
{
return _count * _price;
}
}
@Override
public String getType()
{
return _C__91_SETPRIVATESTORELISTBUY;
}
}
| 29.257895 | 240 | 0.722072 |
68cf80906e77c091faf887333e7ac24dfedea1ed | 7,590 | package bg.connectFour.game;
import bg.connectFour.lang.Language;
import bg.connectFour.popup.MyAlert;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.geometry.HPos;
import javafx.geometry.Pos;
import javafx.scene.control.Alert;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.util.Duration;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class GameApp extends GridPane {
private int playerID;
private final GameClient gameClient;
private boolean yourTurn, playable = false;
private final int ROWS = 6;
private final int COLUMNS = 7;
private final Disc[][] board;
private final List<Combo> combos = new ArrayList<>();
private final String yourName, opName;
public int parties_won, parties_lost, drawCount;
private MyAlert results_alert;
public GameApp(Socket gameSocket, String name, String opName) {
this.yourName = name;
this.opName = opName;
gameClient = new GameClient(gameSocket);
gameClient.handShake();
board = new Disc[COLUMNS][ROWS];
setAlignment(Pos.CENTER);
createGUI();
}
private void createGUI() {
for (int x = 0; x < COLUMNS; x++) {
for (int y = 0; y < ROWS; y++) {
Disc disk = new Disc(this, x, y);
GridPane.setHalignment(disk, HPos.CENTER);
GridPane.setFillHeight(disk, true);
add(disk, x, y);
board[x][y] = disk;
}
}
for (int j = 0; j < 4; j++) {
for (int i = 0; i < 6; i++) {
combos.add(new Combo(new Disc[]{board[j][i], board[j + 1][i], board[j + 2][i], board[j + 3][i]}));
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 7; j++) {
combos.add(new Combo(new Disc[]{board[j][i], board[j][i + 1], board[j][i + 2], board[j][i + 3]}));
}
}
for (int i = 0; i < 3; i++) {
for (int j = 3; j < 7; j++) {
combos.add(new Combo(
new Disc[]{board[j][i], board[j - 1][i + 1], board[j - 2][i + 2], board[j - 3][i + 3]}));
}
}
for (int i = 0; i < 3; i++) {
for (int j = 3; j > -1; j--) {
combos.add(new Combo(
new Disc[]{board[j][i], board[j + 1][i + 1], board[j + 2][i + 2], board[j + 3][i + 3]}));
}
}
}
public void waitForYourTurn() {
Thread t = new Thread(() -> {
int[] coor = gameClient.receive();
board[coor[0]][coor[1]].play();
});
t.start();
}
public void startNewGame(boolean youWon) {
Platform.runLater(() -> {
for (int x = 0; x < COLUMNS; x++) {
for (int y = 0; y < ROWS; y++) {
board[x][y].reset();
}
}
if (!youWon) {
waitForYourTurn();
}
setYourTurn(youWon);
setPlayable(true);
});
}
public boolean isFull() {
for (int x = COLUMNS - 1; x >= 0; x--) {
for (int y = ROWS - 1; y >= 0; y--) {
if (board[x][y].getValue().equals(""))
return false;
}
}
return true;
}
public boolean isLegal(int x, int y) {
return y == 5 || !board[x][y + 1].getValue().isEmpty();
}
public void blink(List<Disc> Discs, boolean youWon) {
Platform.runLater(() -> {
Timeline timeLine = new Timeline();
for (Disc disc : Discs) {
timeLine.getKeyFrames().add(
new KeyFrame(Duration.seconds(1), new KeyValue(disc.getCircle().fillProperty(), Paint.valueOf("#FFD400"))));
}
timeLine.setAutoReverse(true);
timeLine.setCycleCount(4);
timeLine.play();
timeLine.setOnFinished(e -> {
showResults(false);
startNewGame(youWon);
});
});
}
public void showResults(boolean shortcut) {
if (results_alert != null && results_alert.isShowing())
if (shortcut) return;
else results_alert.close();
Platform.runLater(() -> {
String text = yourName + " : " + parties_won + "\n";
text += opName + " : " + parties_lost + "\n";
text += Language.DRAWS.get() + drawCount;
if (results_alert == null) results_alert = new MyAlert(Alert.AlertType.INFORMATION, Language.GR_H, text);
else results_alert.update(text);
results_alert.show();
});
}
public synchronized void closeGameApp() {
gameClient.closeConn();
Platform.runLater(() -> getChildren().clear());
}
class GameClient {
private Socket gameSocket;
private DataInputStream dataIn;
private DataOutputStream dataOut;
public GameClient(Socket gameSocket) {
try {
this.gameSocket = gameSocket;
dataOut = new DataOutputStream(this.gameSocket.getOutputStream());
dataIn = new DataInputStream(this.gameSocket.getInputStream());
} catch (IOException ignore) {
}
}
public void closeConn() {
try {
dataOut.close();
dataIn.close();
gameSocket.close();
} catch (IOException ignore) {
}
}
public void handShake() {
try {
playerID = dataIn.readInt();
if (playerID == 1) {
yourTurn = true;
Thread t = new Thread(() -> {
try {
playable = dataIn.readBoolean();
} catch (IOException ignore) {
}
});
t.start();
} else {
yourTurn = false;
playable = true;
waitForYourTurn();
}
} catch (IOException ignore) {
}
}
public void sendCoor(int x, int y) {
try {
dataOut.writeInt(x);
dataOut.writeInt(y);
dataOut.flush();
} catch (IOException ignore) {
}
}
public int[] receive() {
int[] coor = new int[2];
try {
coor[0] = dataIn.readInt();
coor[1] = dataIn.readInt();
} catch (IOException ignore) {
}
return coor;
}
}
public void setYourTurn(boolean yourTurn) {
this.yourTurn = yourTurn;
}
public void sendCoor(int x, int y) {
gameClient.sendCoor(x, y);
}
public List<Combo> getCombo() {
return combos;
}
public boolean isPlayable() {
return playable;
}
public void setPlayable(boolean playable) {
this.playable = playable;
}
public boolean isYourTurn() {
return yourTurn;
}
public int getDrawCount() {
return drawCount;
}
public int getPlayerID() {
return playerID;
}
}
| 30.119048 | 132 | 0.493808 |
c7c2dedc33a24d1084d953bcbaa8368a8e43c0bc | 3,261 | package scratch.kevin.ucerf3;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipException;
import org.dom4j.DocumentException;
import org.opensha.commons.util.ComparablePairing;
import org.opensha.refFaultParamDb.vo.FaultSectionPrefData;
import org.opensha.sha.earthquake.faultSysSolution.FaultSystemRupSet;
import org.opensha.sha.faultSurface.FaultSection;
import com.google.common.base.Joiner;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Table;
import scratch.UCERF3.utils.U3FaultSystemIO;
public class SectionCombinationCalc {
public static void main(String[] args) throws ZipException, IOException, DocumentException {
FaultSystemRupSet rupSet = U3FaultSystemIO.loadRupSet(new File("/home/kevin/workspace/OpenSHA/dev/scratch/UCERF3/data/scratch/"
+ "InversionSolutions/2013_05_10-ucerf3p3-production-10runs_COMPOUND_SOL_FM3_1_MEAN_BRANCH_AVG_SOL.zip"));
Table<Integer, Integer, String> sectMap = HashBasedTable.create();
sectMap.put(651, 0, "RC"); // Rodgers Creek - Healdsburg 2011 CFM
sectMap.put(639, 1, "HN"); // Hayward (No) 2011 CFM
sectMap.put(638, 2, "HS"); // Hayward (So) 2011 CFM
sectMap.put(637, 3, "HSE"); // Hayward (So) extension 2011 CFM
sectMap.put(601, 4, "CN"); // Calaveras (No) 2011 CFM
sectMap.put(602, 5, "CC"); // Calaveras (Central) 2011 CFM
sectMap.put(603, 6, "CS"); // Calaveras (So) 2011 CFM
sectMap.put(621, 7, "CSE"); // Calaveras (So) - Paicines extension 2011 CFM"
HashSet<Integer> potentialRups = new HashSet<Integer>();
for (int sect : sectMap.rowKeySet())
potentialRups.addAll(rupSet.getRupturesForParentSection(sect));
Map<String, Double> maxMagForCombos = Maps.newHashMap();
for (int rup : potentialRups) {
boolean allOnSects = true;
HashSet<Integer> mySects = new HashSet<Integer>();
for (FaultSection sect : rupSet.getFaultSectionDataForRupture(rup)) {
if (!sectMap.containsRow(sect.getParentSectionId())) {
allOnSects = false;
break;
}
mySects.add(sect.getParentSectionId());
}
if (allOnSects) {
String key = getKey(mySects, sectMap);
double myMag = rupSet.getMagForRup(rup);
Double maxMag = maxMagForCombos.get(key);
if (maxMag == null || myMag > maxMag)
maxMagForCombos.put(key, myMag);
}
}
List<String> keys = Lists.newArrayList(maxMagForCombos.keySet());
Collections.sort(keys);
for (String key : keys)
System.out.println(key+": "+maxMagForCombos.get(key).floatValue());
}
private static Joiner j = Joiner.on("+");
private static String getKey(HashSet<Integer> sects, Table<Integer, Integer, String> sectMap) {
List<String> labels = Lists.newArrayList();
List<Integer> orders = Lists.newArrayList();
for (int sect : sects) {
Map<Integer, String> row = sectMap.row(sect);
int order = row.keySet().iterator().next();
String label = row.values().iterator().next();
labels.add(label);
orders.add(order);
}
List<String> sortedLabeles = ComparablePairing.getSortedData(orders, labels);
return j.join(sortedLabeles);
}
}
| 37.918605 | 129 | 0.729837 |
55ccd06e509e505ee626b3c811986352ee7f7aa3 | 305 | package com.enjoy;
import lombok.Data;
/**
* @Author:waken
* @Date: Created in 2019/4/25 20:52
* @Description:
*/
@Data
public class Person {
private String name;
private Integer age;
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
}
| 13.863636 | 45 | 0.609836 |
187689c29d5d825a0dd25941daccd7497ed2636a | 6,137 | package cn.yiya.shiji.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import cn.yiya.shiji.R;
import cn.yiya.shiji.adapter.ScoreAdapter;
import cn.yiya.shiji.business.ApiRequest;
import cn.yiya.shiji.business.HttpMessage;
import cn.yiya.shiji.business.MsgCallBack;
import cn.yiya.shiji.business.RetrofitRequest;
import cn.yiya.shiji.entity.ScoreObject;
import cn.yiya.shiji.utils.NetUtil;
public class ScoreActivity extends BaseAppCompatActivity implements View.OnClickListener{
private ImageView ivBack;
private TextView tvTitle;
private RecyclerView scoreList;
private ScoreAdapter mAdapter;
private int nOffset;
private boolean isBottom;
private int lastVisibleItemPosition;
private static final int REQUEST_SCORE_LIST = 222;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score);
initViews();
initEvents();
init();
}
private void getData(){
nOffset = 0;
new RetrofitRequest<ScoreObject>(ApiRequest.getApiShiji().getScore(String.valueOf(nOffset))).handRequest(
new MsgCallBack() {
@Override
public void onResult(HttpMessage msg) {
if (msg.isSuccess()) {
ScoreObject obj = (ScoreObject) msg.obj;
if (obj.list != null && obj.list.size() > 0) {
mAdapter.setList(obj.list);
mAdapter.notifyDataSetChanged();
setSuccessView(scoreList);
} else {
isBottom = true;
setNullView(scoreList);
}
}else {
if(!NetUtil.IsInNetwork(ScoreActivity.this)){
setOffNetView(scoreList);
}
}
}
}
);
}
private void loadMore(){
nOffset += 20;
new RetrofitRequest<ScoreObject>(ApiRequest.getApiShiji().getScore(String.valueOf(nOffset))).handRequest(
new MsgCallBack() {
@Override
public void onResult(HttpMessage msg) {
if (msg.isSuccess()) {
ScoreObject obj = (ScoreObject) msg.obj;
if (obj.list != null && obj.list.size() > 0) {
mAdapter.getList().addAll(obj.list);
mAdapter.notifyDataSetChanged();
} else {
isBottom = true;
}
}else {
if(!NetUtil.IsInNetwork(ScoreActivity.this)){
setOffNetView(scoreList);
}
}
}
});
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.title_back:
setResult(RESULT_CANCELED);
finish();
break;
case R.id.tv_reload:
getData();
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_CANCELED && requestCode == REQUEST_SCORE_LIST){
getData();
}
}
@Override
protected void initViews() {
ivBack = (ImageView)findViewById(R.id.title_back);
tvTitle = (TextView)findViewById(R.id.title_txt);
tvTitle.setText("积分明细");
findViewById(R.id.title_right).setVisibility(View.GONE);
scoreList = (RecyclerView)findViewById(R.id.score_detail_list);
scoreList.setItemAnimator(new DefaultItemAnimator());
scoreList.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new ScoreAdapter(this);
scoreList.setAdapter(mAdapter);
addDefaultNullView();
initDefaultNullView(R.mipmap.zanwujifen, "暂无积分~", this);
}
@Override
protected void initEvents() {
scoreList.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
//获取适配器的Item个数以及最后可见的Item
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
int visivleItemCount = layoutManager.getChildCount();
int totalItemCount = layoutManager.getItemCount();
//如果最后可见的item比总数小1,则表示最后一个,这里小3,预加载的意思
if (visivleItemCount > 0 && newState == RecyclerView.SCROLL_STATE_IDLE &&
(lastVisibleItemPosition) >= totalItemCount - 3 && !isBottom) {
loadMore();
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
LinearLayoutManager gridLayoutManager = (LinearLayoutManager) layoutManager;
lastVisibleItemPosition = gridLayoutManager.findLastCompletelyVisibleItemPosition();
}
});
ivBack.setOnClickListener(this);
}
@Override
protected void init() {
getData();
}
}
| 37.650307 | 114 | 0.560697 |
220839b6cad937961a9b952bef864fd2adb3cdd6 | 3,247 | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.picasso;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import java.io.File;
import java.io.IOException;
import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/** A {@link Downloader} which uses OkHttp to download images. */
public final class OkHttp3Downloader implements Downloader {
@VisibleForTesting final Call.Factory client;
private final Cache cache;
private boolean sharedClient = true;
/**
* Create new downloader that uses OkHttp. This will install an image cache into your application
* cache directory.
*/
public OkHttp3Downloader(final Context context) {
this(Utils.createDefaultCacheDir(context));
}
/**
* Create new downloader that uses OkHttp. This will install an image cache into the specified
* directory.
*
* @param cacheDir The directory in which the cache should be stored
*/
public OkHttp3Downloader(final File cacheDir) {
this(cacheDir, Utils.calculateDiskCacheSize(cacheDir));
}
/**
* Create new downloader that uses OkHttp. This will install an image cache into your application
* cache directory.
*
* @param maxSize The size limit for the cache.
*/
public OkHttp3Downloader(final Context context, final long maxSize) {
this(Utils.createDefaultCacheDir(context), maxSize);
}
/**
* Create new downloader that uses OkHttp. This will install an image cache into the specified
* directory.
*
* @param cacheDir The directory in which the cache should be stored
* @param maxSize The size limit for the cache.
*/
public OkHttp3Downloader(final File cacheDir, final long maxSize) {
this(new OkHttpClient.Builder().cache(new Cache(cacheDir, maxSize)).build());
sharedClient = false;
}
/**
* Create a new downloader that uses the specified OkHttp instance. A response cache will not be
* automatically configured.
*/
public OkHttp3Downloader(OkHttpClient client) {
this.client = client;
this.cache = client.cache();
}
/** Create a new downloader that uses the specified {@link Call.Factory} instance. */
public OkHttp3Downloader(Call.Factory client) {
this.client = client;
this.cache = null;
}
@NonNull @Override public Response load(@NonNull Request request) throws IOException {
return client.newCall(request).execute();
}
@Override public void shutdown() {
if (!sharedClient && cache != null) {
try {
cache.close();
} catch (IOException ignored) {
}
}
}
}
| 31.524272 | 99 | 0.719741 |
282df5bf8a8554430f6444e171ba9eb1bee94fa3 | 314 | package com.vida.android.util;
/**
* Created by heaven7 on 2019/5/8.
*/
public class Reflection {
static {
System.loadLibrary("c++_shared");
System.loadLibrary("music_annotator");
}
//jni impl is build by qtcreator. see src of qt/music_annotator
public native String hello();
}
| 20.933333 | 67 | 0.656051 |
bd3f999908ec15132d2806e06be2f3a459b31f7a | 972 | package demo;
import io.smallrye.mutiny.Multi;
import io.smallrye.mutiny.Uni;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.transaction.Transactional;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
@Path("/products")
public class CatalogApi {
private static final Logger logger = LoggerFactory.getLogger(CatalogApi.class);
@GET
public Multi<Product> listProducts() {
logger.info("listProducts");
return Product.all();
}
@POST
@Transactional
public Uni<Product> createProduct(Product product) {
logger.info("register");
return product.persistAndFlush().replaceWith(product);
}
@GET
@Path("/{id}")
public Uni<Product> getProduct(Long id) {
logger.info("createProduct");
return Product.findById(id);
}
@GET
@Path("/named/{name}")
public Uni<Product> getProductByName(String name) {
logger.info("getProductByName");
return Product.findByName(name);
}
}
| 21.6 | 81 | 0.713992 |
ae59506d7be6c022fd7a07f985b9ec479d9cd978 | 5,773 | package dev.turgaycan.springboothttp2.configuration;
import lombok.extern.log4j.Log4j2;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import javax.net.ssl.*;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static dev.turgaycan.springboothttp2.constant.Constants.SSL_SERVER_PEM_FILE_NAME;
@Log4j2
@Configuration
public class OkClientConfiguration {
@Value("server.ssl.trust-store-password")
private String trustStorePassword;
@Value("server.ssl.trust-store-alias")
private String trustStoreAlias;
@Value("${server.ssl.client-ssl-enabled:true}")
private boolean clientSslEnabled;
@Bean
@Qualifier("okRestTemplate")
public RestTemplate okRestTemplate() throws NoSuchAlgorithmException, KeyManagementException, CertificateException, KeyStoreException, IOException {
OkHttpClient.Builder okHttpClientBuilder = clientSslEnabled ? buildSslHttpClient() : buildUnsafeOkHttpClient();
final OkHttpClient okHttpClient = okHttpClientBuilder
.protocols(List.of(Protocol.HTTP_2, Protocol.HTTP_1_1))
.addInterceptor(new LoggingInterceptor())
.addNetworkInterceptor(new LoggingInterceptor())
.build();
final OkHttp3ClientHttpRequestFactory requestFactory = new OkHttp3ClientHttpRequestFactory(okHttpClient);
return new RestTemplate(requestFactory);
}
private OkHttpClient.Builder buildSslHttpClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, CertificateException, IOException {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, trustStorePassword.toCharArray());
InputStream certInputStream = new ClassPathResource(SSL_SERVER_PEM_FILE_NAME).getInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(certInputStream);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
while (bufferedInputStream.available() > 0) {
Certificate cert = certificateFactory.generateCertificate(bufferedInputStream);
keyStore.setCertificateEntry(trustStoreAlias, cert);
}
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagers, null);
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
okHttpClientBuilder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustManagers[0]);
okHttpClientBuilder.hostnameVerifier((hostname, session) -> true);
return okHttpClientBuilder;
}
private OkHttpClient.Builder buildUnsafeOkHttpClient() throws NoSuchAlgorithmException, KeyManagementException {
final TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};
final SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
okHttpClientBuilder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
okHttpClientBuilder.hostnameVerifier((hostname, session) -> true);
return okHttpClientBuilder;
}
class LoggingInterceptor implements Interceptor {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
final long start = System.nanoTime();
LOG.info("Sending request {} on {} {} {}",
request.url(), chain.connection(), request.headers());
Response response = chain.proceed(request);
final long finish = System.nanoTime();
LOG.info("Received response for {} in {} ms {}",
response.request().url(), TimeUnit.NANOSECONDS.toMillis(finish - start), response.headers());
return response;
}
}
}
| 45.101563 | 165 | 0.718864 |
c1fc09a21f316b0cc285a1fc2a446c4f70cc95bc | 947 | /*
* 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 info.novatec.jcache.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("guests")
public class GuestRestController {
private AggregationService aggregationService;
@Autowired
public GuestRestController(AggregationService aggregationService) {
this.aggregationService = aggregationService;
}
@RequestMapping(path = "{id}/balance", method = RequestMethod.GET)
public ResponseEntity getBalance(@PathVariable("id") String id) {
String charges = aggregationService.getCharges(id);
return ResponseEntity.ok().body(charges);
}
} | 30.548387 | 79 | 0.73812 |
a9851bea5458cbd5ef44972e8e420a6b74a46de7 | 7,765 | package com.comxa.makemore.easybudget;
import android.app.Activity;
import android.app.Notification;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.reflect.Type;
/**
* Created by Artyom on 19.07.2016.
*/
public class reg_frame_class extends Activity {
EditText login,pass1,pass2;
Button Next,Cancel;
TextView hi,pass22;
Switch show_p;
Boolean check = false, br=true;
int def_type;
DB_helper db;
String name = "", pass= "",s_pass="";
private Toast toast;
long RowId = 0;
SQLiteDatabase open_db;
Cursor c;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reg_frame);
hi = (TextView)findViewById(R.id.textView4);
pass22 = (TextView)findViewById(R.id.textView5);
login = (EditText)findViewById(R.id.editText);
pass1 = (EditText)findViewById(R.id.editText2);
pass2 = (EditText)findViewById(R.id.editText3);
Next = (Button)findViewById(R.id.button3);
Cancel = (Button)findViewById(R.id.button4);
show_p = (Switch)findViewById(R.id.switch1);
if (getIntent().getExtras().get("log") != null)
check = getIntent().getExtras().getBoolean("log",false);
def_type = pass1.getInputType();
toast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
hi.setText("Регистрация нового аккаунта.");
pass22.setVisibility(View.VISIBLE);
pass2.setVisibility(View.VISIBLE);
db = new DB_helper(this);
try {
open_db = db.getWritableDatabase();
} catch (Exception e) {
toast.setText("Ошибка доступа базы данных");
toast.show();
}
if (check){
pass2.setVisibility(View.INVISIBLE);
pass22.setVisibility(View.INVISIBLE);
hi.setText("Добро пожаловать!");
}
show_p.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (show_p.isChecked()) {
pass1.setInputType(1);
pass2.setInputType(1);
} else {
pass1.setInputType(def_type);
pass2.setInputType(def_type);
}
}
});
Next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ContentValues cv = new ContentValues();
if (!(check)) { //testing login%passwords registration
try {
br = false;
name = login.getText().toString();
c = open_db.query("users", null, null, null, null, null, null);
//c.moveToFirst();
if (c.moveToFirst()) {
// определяем номера столбцов по имени
int nameColIndex = c.getColumnIndex("login");
do {
if (!(name.equals(c.getString(nameColIndex)))) {
br = true;
} else {
toast.setText("Данный пользователь уже существует");
toast.show();
br = false;
break;
}
//следующей нет, то выходим из цикла
} while (c.moveToNext());
} else {//empty table
br = true;
}
if (br) { // check for copy
try {
pass = pass1.getText().toString();
s_pass = pass2.getText().toString();
} catch (Exception e) {
br = false;
toast.setText("Поле ввода пароля имеет недопустимое значение");
toast.show();
}
if (pass.equals(s_pass)) {
cv.put("login", name);
cv.put("pass", pass);
RowId = open_db.insert("users", null, cv);
} else {
br = false;
toast.setText("Введенные пароли не совпадают");
toast.show();
}
}
} catch (Exception e) {
br = false;
toast.setText("Ошибка ввода, проверьте заполненные поля");
toast.show();
}
} else {//login
try {
br = false;
name = login.getText().toString();
pass = pass1.getText().toString();
} catch (Exception e) {
toast.setText("Поля ввода имеют недопустимые значение");
toast.show();
}
c = open_db.query("users", null, null, null, null, null, null);
if (c.moveToFirst()) {
// определяем номера столбцов по имени
int nameColIndex = c.getColumnIndex("login");
int passColIndex = c.getColumnIndex("pass");
do {
if (name.equals(c.getString(nameColIndex))) {
if (pass.equals(c.getString(passColIndex))) {
br = true;
} else {
toast.setText("Пароль не подходит");
toast.show();
br = false;
break;
}
}
//следующей нет, то выходим из цикла
} while (c.moveToNext());
} else {
toast.setText("База данных пуста");
toast.show();
}
}
if (br) { // check for copy
Intent intent = new Intent(reg_frame_class.this, MainManuActivity.class);
intent.putExtra("bd_name", name);
startActivity(intent);
}
}
});
Cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(reg_frame_class.this, WelcomeActivity.class);
startActivity(intent);
}
});
}
}
| 35.619266 | 96 | 0.438506 |
c702292f7729a8e8cb58a422a03135ca1b0a67c5 | 2,214 | package humanize.measure;
import humanize.Humanize;
import humanize.spi.MessageFormat;
import humanize.text.FormatFactory;
import java.text.Format;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import javax.measure.Measure;
import javax.measure.MeasureFormat;
import javax.measure.unit.NonSI;
import javax.measure.unit.SI;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestHumanizeIntegration
{
@Test
public void testExplicitRegistration()
{
Map<String, FormatFactory> registry = new HashMap<String, FormatFactory>();
registry.put("measure", new FormatFactory()
{
@Override
public Format getFormat(String name, String args, Locale locale)
{
return MeasureFormat.getInstance();
}
});
MessageFormat mf = new MessageFormat("measure: {0, measure}", Locale.ENGLISH, registry);
Assert.assertEquals(mf.render(Measure.valueOf(100, SI.GRAM.times(1000))), "measure: 100 kg");
Assert.assertEquals(mf.render(Measure.valueOf(100, SI.KILOGRAM.times(1000))), "measure: 100 t");
Assert.assertEquals(mf.render(Measure.valueOf(100, NonSI.MILES_PER_HOUR)), "measure: 100 mph");
}
@Test
public void testRegistration()
{
MessageFormat mf = new MessageFormat("{1,number} weight: {0, measure}", Locale.ENGLISH);
Assert.assertEquals(mf.render(Measure.valueOf(1000, SI.GRAM.times(1000)), 1), "1 weight: 1,000 kg");
Assert.assertEquals(mf.render(Measure.valueOf(100, SI.KILOGRAM.times(1000)), 1), "1 weight: 100 t");
Assert.assertEquals(Humanize.format("{0, measure}", Measure.valueOf(100, SI.GRAM.times(1000))), "100 kg");
Assert.assertEquals(Humanize.format("{0, measure, standard}", Measure.valueOf(100, SI.GRAM.times(1000))),
"100 kg");
MessageFormat esFormat = Humanize.messageFormat("{0, measure}", new Locale("es"));
Assert.assertEquals(esFormat.render(Measure.valueOf(1000, SI.GRAM.times(1000))), "1.000 kg");
Assert.assertEquals(esFormat.render(Measure.valueOf(1000, NonSI.DAY_SIDEREAL)), "1.000 day_sidereal");
}
}
| 33.044776 | 114 | 0.677958 |
22c6654d0e1ceffc5c2f5f3a7411644a643daaea | 557 | package com.kkbnart.wordis.exception;
public class BlockCreateException extends Exception {
private static final long serialVersionUID = 7637854732310798213L;
public static final int ID_OVERFLOW = 1;
public BlockCreateException() {
String msg = "Can not create block";
System.err.println(msg);
}
public BlockCreateException(final int cause) {
String msg = "Can not create block";
switch (cause) {
case ID_OVERFLOW:
msg += " because new number can not be assigned.";
break;
default:
break;
}
System.err.println(msg);
}
}
| 22.28 | 67 | 0.721724 |
0cb1734e2fffbd2008c08246b69c1e6234c9dc82 | 3,680 | package seedu.address.logic.parser;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.address.logic.parser.CliSyntax.PREFIX_ADDRESS;
import static seedu.address.logic.parser.CliSyntax.PREFIX_AUTHOR;
import static seedu.address.logic.parser.CliSyntax.PREFIX_CATEGORY;
import static seedu.address.logic.parser.CliSyntax.PREFIX_EMAIL;
import static seedu.address.logic.parser.CliSyntax.PREFIX_ISBN;
import static seedu.address.logic.parser.CliSyntax.PREFIX_NAME;
import static seedu.address.logic.parser.CliSyntax.PREFIX_PUBLISHER;
import static seedu.address.logic.parser.CliSyntax.PREFIX_STOCKING;
import static seedu.address.logic.parser.CliSyntax.PREFIX_TIMES;
import java.util.Set;
import java.util.stream.Stream;
import seedu.address.logic.commands.AddCommand;
import seedu.address.logic.parser.exceptions.ParseException;
import seedu.address.model.book.Address;
import seedu.address.model.book.Author;
import seedu.address.model.book.Book;
import seedu.address.model.book.Email;
import seedu.address.model.book.Isbn;
import seedu.address.model.book.Name;
import seedu.address.model.book.Publisher;
import seedu.address.model.book.Stocking;
import seedu.address.model.book.Times;
import seedu.address.model.category.Category;
/**
* Parses input arguments and creates a new AddCommand object
*/
public class AddCommandParser implements Parser<AddCommand> {
/**
* Parses the given {@code String} of arguments in the context of the AddCommand
* and returns an AddCommand object for execution.
* @throws ParseException if the user input does not conform the expected format
*/
public AddCommand parse(String args) throws ParseException {
ArgumentMultimap argMultimap =
ArgumentTokenizer.tokenize(args, PREFIX_NAME, PREFIX_ISBN, PREFIX_EMAIL, PREFIX_ADDRESS,
PREFIX_CATEGORY, PREFIX_STOCKING, PREFIX_TIMES, PREFIX_AUTHOR, PREFIX_PUBLISHER);
if (!arePrefixesPresent(argMultimap, PREFIX_NAME, PREFIX_ISBN, PREFIX_ADDRESS, PREFIX_EMAIL)
|| !argMultimap.getPreamble().isEmpty()) {
throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
}
System.out.println("debug");
Name name = ParserUtil.parseName(argMultimap.getValue(PREFIX_NAME).get());
Isbn isbn = ParserUtil.parseIsbn(argMultimap.getValue(PREFIX_ISBN).get());
Email email = ParserUtil.parseEmail(argMultimap.getValue(PREFIX_EMAIL).get());
Address address = ParserUtil.parseAddress(argMultimap.getValue(PREFIX_ADDRESS).get());
Times times = ParserUtil.parseTimes(argMultimap.getValue(PREFIX_TIMES).get());
Set<Category> categoryList = ParserUtil.parseCategories(argMultimap.getAllValues(PREFIX_CATEGORY));
Stocking stocking = ParserUtil.parseStocking(argMultimap.getValue(PREFIX_STOCKING).get());
Author author = ParserUtil.parseAuthor(argMultimap.getValue(PREFIX_AUTHOR).get()); // to be implemented
Publisher publisher = ParserUtil.parsePublisher(argMultimap.getValue(PREFIX_PUBLISHER).get());
Book book = new Book(name, isbn, email, address, times, categoryList, stocking,
author, publisher);
return new AddCommand(book);
}
/**
* Returns true if none of the prefixes contains empty {@code Optional} values in the given
* {@code ArgumentMultimap}.
*/
private static boolean arePrefixesPresent(ArgumentMultimap argumentMultimap, Prefix... prefixes) {
return Stream.of(prefixes).allMatch(prefix -> argumentMultimap.getValue(prefix).isPresent());
}
}
| 48.421053 | 111 | 0.759239 |
b6b4414dbcde81f7cd02505151ecaa90df39ec84 | 931 | package com.example.springboot.service.impl;
import com.example.springboot.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public Integer getAllUser() {
return jdbcTemplate.queryForObject("select COUNT(1) from User ", Integer.class);
}
@Override
public void deleteByName(String name) {
jdbcTemplate.update("delete from User where name=?",name);
}
@Override
public void insertUser(Long id,String name,Integer age) {
jdbcTemplate.update("insert into User(id,name,age) values (?,?,?)",id,name,age);
}
@Override
public void deleteUser() {
jdbcTemplate.update("delete from User");
}
}
| 26.6 | 88 | 0.717508 |
0799fbd5068b9f689a3f600e6f82c7c129efffa6 | 4,412 | /**
* Copyright (C) 2015 Johannes Schnatterer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Copyright (C) 2013 Johannes Schnatterer
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package info.schnatterer.songbirddbapi4j.domain.util;
import static org.junit.Assert.*;
import info.schnatterer.songbirddbapi4j.domain.MemberMediaItem;
import info.schnatterer.songbirddbapi4j.domain.util.MemberMediaItemComparator;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import org.junit.Test;
public class MemberMediaItemComparatorTest {
public static final String TEST_0 = "72.31.0.20.2.0.-1.-1.1.-1.0";
public static final String TEST_1 = "72.31.0.20.2.0.-1.-1.1";
public static final String TEST_2 = "72.31.0.20.2.0.-1.-1.0";
public static final String TEST_3 = "72.31.0.20.2.0.1.1.8";
public static final String TEST_4 = "72.31.0.20.2.0.1.1.7";
public static final String TEST_5 = "100";
public static final String TEST_6 = "71.0";
public static final String TEST_7 = "168.813.45.0.238.0.2.13.466.140.14.1.52.298.1.277.117.0.40.0.68.13.115.40.0.1.1.56.9";
public static final String TEST_8 = "168.813.45.0.238.0.2.13.466.140.14.1.52.298.1.277.117.0.40.0.68.13.115.40.0.1.1.56.8";
@Test
public void testSortingNoDots() {
boolean descending = false;
MemberMediaItemComparator comp = new MemberMediaItemComparator(
descending);
assertTrue("First arg must be greater than second",
comp.compare(TEST_5, TEST_6) > 0);
}
@Test
public void testSortingNoDots2() {
MemberMediaItemComparator comp = new MemberMediaItemComparator(false);
assertTrue("First arg must be less than second",
comp.compare(TEST_5, TEST_8) < 0);
}
@Test
public void testDifferentLength() {
MemberMediaItemComparator comp = new MemberMediaItemComparator(false);
// 1 shorter than 0
assertTrue("First arg must be less than second",
comp.compare(TEST_1, TEST_0) < 0);
}
@Test
public void testNegative() {
MemberMediaItemComparator comp = new MemberMediaItemComparator(false);
// 1 shorter than 0
assertTrue("First arg must be less than second",
comp.compare(TEST_2, TEST_3) < 0);
}
@Test
public void testSorting() {
List<MemberMediaItem> list = new LinkedList<MemberMediaItem>();
addMember(list, TEST_0); // 0
addMember(list, TEST_1); // 1
addMember(list, TEST_2); // 2
addMember(list, TEST_3); // 3
addMember(list, TEST_4); // 4
addMember(list, TEST_5); // 5
addMember(list, TEST_6); // 6
addMember(list, TEST_7); // 7
addMember(list, TEST_8); // 8
/* Compare: Expected order: 7, 4, 3, 2, 1, 0, 6, 9, 8 */
Collections.sort(list, new MemberMediaItemComparator(false));
List<String> actual = new LinkedList<String>();
for (MemberMediaItem memberMediaItem : list) {
actual.add(memberMediaItem.getOridnal());
}
List<String> expected = Arrays.asList(TEST_6, TEST_2, TEST_1, TEST_0,
TEST_4, TEST_3, TEST_5, TEST_8, TEST_7);
assertEquals(expected, actual);
}
private void addMember(List<MemberMediaItem> list, String ordinal) {
MemberMediaItem member = new MemberMediaItem();
member.setOridnal(ordinal);
// MediaItem mediaItem = new MediaItem();
// mediaItem.setId(list.size());
// member.setMember(mediaItem);
list.add(member);
}
}
| 34.740157 | 124 | 0.727335 |
285e57680fe98807c96f0038826a83cba4cca819 | 15,928 | /* This file is part of VoltDB.
* Copyright (C) 2008-2020 VoltDB Inc.
*
* This file contains original code and/or modifications of original code.
* Any modifications made by VoltDB Inc. are licensed under the following
* terms and conditions:
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
/* Copyright (C) 2008
* Evan Jones
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package org.voltcore.network;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.GatheringByteChannel;
import java.nio.channels.SelectionKey;
import java.util.concurrent.atomic.AtomicLong;
import org.voltcore.utils.EstTime;
import org.voltcore.utils.EstTimeUpdater;
import org.voltdb.AdmissionControlGroup;
import junit.framework.TestCase;
public class TestNIOWriteStream extends TestCase {
private class MockPort extends VoltPort {
@Override
public String toString() {
return null;
}
public MockPort() throws UnknownHostException {
super(null, null, new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 21212), pool);
}
@Override
public void setInterests(int opsToAdd, int opsToRemove) {
this.opsToAdd = opsToAdd;
}
public boolean checkWriteSet() {
if (opsToAdd == SelectionKey.OP_WRITE) {
opsToAdd = 0;
return true;
}
return false;
}
int opsToAdd;
}
NetworkDBBPool pool;
@Override
public void setUp() {
//Use low size for each buffer in pool
pool = new NetworkDBBPool(64, 4);
}
@Override
public void tearDown() {
pool.clear();
}
/**
* Mock channel that will either consume all, some or no
* bytes from the buffer.
*/
private static class MockChannel implements GatheringByteChannel {
MockChannel(int behavior, int closeafter) {
m_behavior = behavior;
this.closeAfter = closeafter;
}
private int writeCount = 0;
private final int closeAfter;
private boolean didOversizeWrite = false;
private boolean wrotePartial = false;
public boolean m_open = true;
public int m_behavior;
public static int SINK = 0; // accept all data
public static int FULL = 1; // accept no data
public static int PARTIAL = 2; // accept some data
@Override
public int write(ByteBuffer src) throws IOException {
if (!m_open) throw new IOException();
if (closeAfter > 0 && ++writeCount >= closeAfter) {
m_open = false;
}
if (!src.isDirect()) {
if (src.remaining() > 1024 * 256) {
didOversizeWrite = true;
}
}
if (m_behavior == SINK) {
int remaining = src.remaining();
src.position(src.limit());
return remaining;
}
else if (m_behavior == FULL) {
return 0;
}
else if (m_behavior == PARTIAL) {
if (wrotePartial) {
return 0;
} else {
wrotePartial = true;
}
ByteBuffer copy = ByteBuffer.allocate(src.remaining());
src.get(copy.array(), 0, src.remaining()/2);
return src.remaining();
}
assert(false);
return -1;
}
@Override
public long write(ByteBuffer src[]) throws IOException {
if (!m_open) throw new IOException();
if (closeAfter > 0 && ++writeCount >= closeAfter) {
m_open = false;
}
if (m_behavior == SINK) {
int remaining = src[0].remaining();
src[0].position(src[0].limit());
return remaining;
}
else if (m_behavior == FULL) {
return 0;
}
else if (m_behavior == PARTIAL) {
if (wrotePartial) {
return 0;
} else {
wrotePartial = true;
}
ByteBuffer copy = ByteBuffer.allocate(src[0].remaining());
src[0].get(copy.array(), 0, src[0].remaining()/2);
return src[0].remaining();
}
assert(false);
return -1;
}
@Override
public void close() throws IOException {
// TODO Auto-generated method stub
}
@Override
public boolean isOpen() {
return m_open;
}
@Override
public long write(ByteBuffer[] srcs, int offset, int length)
throws IOException {
// TODO Auto-generated method stub
return 0;
}
}
public void testSink() throws IOException {
MockChannel channel = new MockChannel(MockChannel.SINK, 0);
MockPort port = new MockPort();
VoltNIOWriteStream wstream = new VoltNIOWriteStream(port);
assertTrue(wstream.isEmpty());
ByteBuffer tmp = ByteBuffer.allocate(2);
tmp.put((byte) 1);
tmp.put((byte) 2);
tmp.flip();
wstream.enqueue(tmp);
assertTrue(port.checkWriteSet());
assertEquals(1, wstream.getOutstandingMessageCount());
wstream.serializeQueuedWrites(pool);
assertEquals(2, wstream.drainTo(channel));
assertTrue(wstream.isEmpty());
assertEquals(0, wstream.getOutstandingMessageCount());
wstream.shutdown();
port.toString();
}
public void testFull() throws IOException {
MockChannel channel = new MockChannel(MockChannel.FULL, 0);
MockPort port = new MockPort();
VoltNIOWriteStream wstream = new VoltNIOWriteStream(port);
assertTrue(wstream.isEmpty());
ByteBuffer tmp = ByteBuffer.allocate(4);
tmp.put((byte)1);
tmp.put((byte)2);
tmp.put((byte)3);
tmp.put((byte)4);
tmp.flip();
wstream.enqueue(tmp);
assertTrue(port.checkWriteSet());
assertEquals(1, wstream.getOutstandingMessageCount());
wstream.serializeQueuedWrites(pool);
wstream.drainTo(channel);
assertFalse(wstream.isEmpty());
channel.m_behavior = MockChannel.SINK;
wstream.serializeQueuedWrites(pool);
int wrote = wstream.drainTo(channel);
assertEquals(4, wrote);
assertTrue(wstream.isEmpty());
assertEquals(0, wstream.getOutstandingMessageCount());
wstream.shutdown();
}
public void testPartial() throws IOException {
MockChannel channel = new MockChannel(MockChannel.PARTIAL, 0);
MockPort port = new MockPort();
VoltNIOWriteStream wstream = new VoltNIOWriteStream(port);
assertTrue(wstream.isEmpty());
ByteBuffer tmp = ByteBuffer.allocate(4);
tmp.put((byte)1);
tmp.put((byte)2);
tmp.put((byte)3);
tmp.put((byte)4);
tmp.flip();
wstream.enqueue(tmp);
assertTrue(port.checkWriteSet());
wstream.serializeQueuedWrites(pool);
int wrote = wstream.drainTo(channel);
assertFalse(wstream.isEmpty());
assertEquals(2, wrote);
channel.wrotePartial = false;
ByteBuffer tmp2 = ByteBuffer.allocate(4);
tmp2.put((byte)5);
tmp2.put((byte)6);
tmp2.put((byte)7);
tmp2.put((byte)8);
tmp2.flip();
wstream.enqueue(tmp2);
wstream.serializeQueuedWrites(pool);
wrote += wstream.drainTo( channel);
assertFalse(wstream.isEmpty());
// wrote half of half of the first buffer (note +=)
assertEquals(3, wrote);
channel.m_behavior = MockChannel.SINK;
wstream.serializeQueuedWrites(pool);
wrote += wstream.drainTo( channel);
assertEquals(8, wrote);
assertTrue(wstream.isEmpty());
wstream.shutdown();
}
public void testClosed() throws IOException {
MockChannel channel = new MockChannel(MockChannel.FULL, 0);
MockPort port = new MockPort();
VoltNIOWriteStream wstream = new VoltNIOWriteStream(port);
ByteBuffer tmp = ByteBuffer.allocate(4);
tmp.put((byte)1);
tmp.put((byte)2);
tmp.put((byte)3);
tmp.put((byte)4);
tmp.flip();
wstream.enqueue(tmp);
assertTrue(port.checkWriteSet());
wstream.serializeQueuedWrites(pool);
int closed = wstream.drainTo(channel);
assertEquals(closed, 0);
channel.m_open = false;
boolean threwException = false;
try {
wstream.serializeQueuedWrites(pool);
assertEquals( -1, wstream.drainTo( channel));
} catch (IOException e) {
threwException = true;
}
assertTrue(threwException);
wstream.shutdown();
}
public void testClosedWithBackPressure() throws IOException {
MockChannel channel = new MockChannel(MockChannel.SINK, 1);
MockPort port = new MockPort();
AdmissionControlGroup acg = new AdmissionControlGroup(2, 1024);
VoltNIOWriteStream wstream = new VoltNIOWriteStream(port, null, null, acg);
ByteBuffer tmp = ByteBuffer.allocate(6);
tmp.put((byte)1);
tmp.put((byte)2);
tmp.put((byte)3);
tmp.put((byte)4);
tmp.put((byte)5);
tmp.put((byte)6);
tmp.flip();
ByteBuffer tmp2 = ByteBuffer.allocate(4);
tmp2.put((byte)1);
tmp2.put((byte)2);
tmp2.put((byte)3);
tmp2.put((byte)4);
tmp2.flip();
wstream.enqueue(tmp);
wstream.enqueue(tmp2);
assertTrue(port.checkWriteSet());
boolean threwException = false;
try {
wstream.serializeQueuedWrites(pool);
//First write will succeed leaving 2 in first buffer and 4 in next
wstream.drainTo( channel);
} catch (IOException e) {
threwException = true;
}
assertTrue(threwException);
//Since ACG limit is 2 bytes we should be in backpressure.
assertTrue(acg.hasBackPressure());
assertEquals(6, acg.getPendingBytes());
wstream.shutdown();
//We should be out of backpressure.
assertFalse(acg.hasBackPressure());
//acg pending bytes must be 0
assertEquals(0, acg.getPendingBytes());
}
public void testLargeNonDirectWrite() throws IOException {
MockChannel channel = new MockChannel(MockChannel.SINK, 0);
MockPort port = new MockPort();
VoltNIOWriteStream wstream = new VoltNIOWriteStream(port);
ByteBuffer tmp = ByteBuffer.allocate(262144 * 3);
wstream.enqueue(tmp);
assertTrue(port.checkWriteSet());
wstream.serializeQueuedWrites(pool);
int written = wstream.drainTo( channel);
assertEquals( 262144 * 3, written);
assertFalse(channel.didOversizeWrite);
wstream.shutdown();
}
public void testLastWriteDelta() throws Exception {
EstTimeUpdater.s_pause = true;
Thread.sleep(10);
try {
final MockChannel channel = new MockChannel(MockChannel.SINK, 0);
MockPort port = new MockPort();
VoltNIOWriteStream wstream = new VoltNIOWriteStream(port);
assertEquals( 0, wstream.calculatePendingWriteDelta(999));
EstTimeUpdater.update(System.currentTimeMillis());
/**
* Test the basic write and drain
*/
final ByteBuffer b = ByteBuffer.allocate(5);
wstream.enqueue(b.duplicate());
assertEquals( 5, wstream.calculatePendingWriteDelta(EstTime.currentTimeMillis() + 5));
wstream.serializeQueuedWrites(pool);
wstream.drainTo( channel);
assertEquals( 0, wstream.calculatePendingWriteDelta(EstTime.currentTimeMillis() + 5));
Thread.sleep(20);
EstTimeUpdater.update(System.currentTimeMillis());
wstream.enqueue(b.duplicate());
assertEquals( 5, wstream.calculatePendingWriteDelta(EstTime.currentTimeMillis() + 5));
wstream.enqueue(b.duplicate());
assertEquals( 5, wstream.calculatePendingWriteDelta(EstTime.currentTimeMillis() + 5));
channel.m_behavior = MockChannel.PARTIAL;
wstream.serializeQueuedWrites(pool);
wstream.drainTo( channel );
assertEquals( 5, wstream.calculatePendingWriteDelta(EstTime.currentTimeMillis() + 5));
wstream.shutdown();
} finally {
EstTimeUpdater.s_pause = false;
}
}
public void testQueueMonitor() throws Exception {
final MockChannel channel = new MockChannel(MockChannel.FULL, 0);
MockPort port = new MockPort();
final AtomicLong queue = new AtomicLong();
VoltNIOWriteStream wstream = new VoltNIOWriteStream(port, null, null, new QueueMonitor() {
@Override
public boolean queue(int bytes) {
queue.addAndGet(bytes);
return false;
}
});
wstream.enqueue(ByteBuffer.allocate(32));
wstream.serializeQueuedWrites(pool);
assertEquals(32, queue.get());
wstream.drainTo(channel);
assertEquals(32, queue.get());
wstream.enqueue(ByteBuffer.allocate(32));
wstream.serializeQueuedWrites(pool);
assertEquals(64, queue.get());
wstream.shutdown();
assertEquals(0, queue.get());
}
}
| 34.929825 | 102 | 0.608614 |
0ff41c810de89a4817f09cbae6aaf388b071879b | 6,717 | package com.akjava.gwt.equirectangular.client;
import java.util.List;
import com.akjava.gwt.jszip.client.JSZip;
import com.akjava.gwt.lib.client.LogUtils;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
public class SixCubeFrameIO {
public static final List<String> directions=ImmutableList.of("up","down","front","back","right","left");
public static JSZip toZip(List<UploadImageDataUrls> frames){
JSZip zip=JSZip.newJSZip();
for(int i=0;i<frames.size();i++){
String index=toIndex(i+1);
UploadImageDataUrls frame=frames.get(i);
zip.base64UrlFile(index+"_up"+".png", frame.getUp());
zip.base64UrlFile(index+"_down"+".png", frame.getDown());
zip.base64UrlFile(index+"_front"+".png", frame.getFront());
zip.base64UrlFile(index+"_back"+".png", frame.getBack());
zip.base64UrlFile(index+"_right"+".png", frame.getRight());
zip.base64UrlFile(index+"_left"+".png", frame.getLeft());
}
return zip;
}
public static String getFileName(int index,int direction){
return toIndex(index)+"_"+directions.get(direction)+".png";
}
public static String toIndex(int number){
return Strings.padStart(String.valueOf(number), 5, '0');
}
public static void postImageData(int index,UploadImageDataUrls frame){
simplePostToWrite(toIndex(index)+"_up"+".png", frame.getUp());
simplePostToWrite(toIndex(index)+"_down"+".png", frame.getDown());
simplePostToWrite(toIndex(index)+"_front"+".png", frame.getFront());
simplePostToWrite(toIndex(index)+"_back"+".png", frame.getBack());
simplePostToWrite(toIndex(index)+"_right"+".png", frame.getRight());
simplePostToWrite(toIndex(index)+"_left"+".png", frame.getLeft());
}
public static void postTextData(String nonaPath,int imageSize,int size){
NonaBatchGenerator generator=new NonaBatchGenerator(nonaPath, imageSize);
for(int i=0;i<size;i++){
simplePostToWrite(toIndex(i+1)+".pto",generator.createPto(i+1));
}
simplePostToWrite("nona_cubic2erect.bat",generator.createBatch(size));
simplePostToWrite("ffmpeg_image2movie.bat",new FFMpegBatchGenerator("s:\\download\\ffmpeg2.7.1\\bin\\ffmpeg.exe", 24, "output.mp4").createBatch());
}
/**
* @deprecated now converted interface
* @param size
* @param index
* @param frame
* @param listener
*/
public static void postToServlet(int size,int index,UploadImageDataUrls frame,PostListener listener){
postToSixCube(size,toIndex(index)+".png",frame.getAll(),listener);
}
//post to NonaCubi2ErectServlet
public static void simplePostToWrite(final String fileName,String data){
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, "/write");// TODO
builder.setHeader("Content-type", "application/x-www-form-urlencoded");
StringBuilder sb = new StringBuilder();
sb.append("name").append("=").append(URL.encodeQueryString(fileName));
sb.append("&");
sb.append("data").append("=").append(URL.encodeQueryString(data));
try{
Request response =builder.sendRequest(sb.toString(), new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
LogUtils.log(fileName+"="+response.getText());
}
@Override
public void onError(Request request, Throwable exception) {
LogUtils.log("error:"+fileName+"="+exception.getMessage());
}
});
}catch(Exception e){}
}
public static void callClearImages(final PostListener listener,String pagePath){
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, "/"+pagePath);
builder.setHeader("Content-type", "application/x-www-form-urlencoded");
StringBuilder sb = new StringBuilder();
sb.append("command").append("=").append("clear");
try{
Request response =builder.sendRequest(sb.toString(), new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
if(listener!=null)
listener.onReceived(response.getText());
}
@Override
public void onError(Request request, Throwable exception) {
if(listener!=null)
listener.onError(exception.getMessage());
}
});
}catch(Exception e){}
}
public static void postToSingleFile(final int size,final String fileName,List<String> datas,final PostListener listener){
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, "/base64write");
builder.setHeader("Content-type", "application/x-www-form-urlencoded");
StringBuilder sb = new StringBuilder();
sb.append("size").append("=").append(size);
sb.append("&");
sb.append("name").append("=").append(URL.encodeQueryString(fileName));
//just add single file version
sb.append("&");
sb.append("data").append("=").append(URL.encodeQueryString(datas.get(0)));
try{
Request response =builder.sendRequest(sb.toString(), new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
if(listener!=null)
listener.onReceived(response.getText());
}
@Override
public void onError(Request request, Throwable exception) {
if(listener!=null)
listener.onError(exception.getMessage());
}
});
}catch(Exception e){}
}
public static void postToSixCube(final int size,final String fileName,List<String> datas,final PostListener listener){
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, "/sixcube");
builder.setHeader("Content-type", "application/x-www-form-urlencoded");
StringBuilder sb = new StringBuilder();
sb.append("size").append("=").append(size);
sb.append("&");
sb.append("name").append("=").append(URL.encodeQueryString(fileName));
for(int i=1;i<=6;i++){
sb.append("&");
sb.append("image").append(i+"=").append(URL.encodeQueryString(datas.get(i-1)));
}
try{
Request response =builder.sendRequest(sb.toString(), new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
if(listener!=null)
listener.onReceived(response.getText());
}
@Override
public void onError(Request request, Throwable exception) {
if(listener!=null)
listener.onError(exception.getMessage());
}
});
}catch(Exception e){}
}
//TODO create store system-io version
}
| 35.352632 | 150 | 0.689594 |
a7c138ab633ba0ea3909e5cb020df430b590828f | 1,414 | /***********************************************************************************************
*
* Copyright 2018 Infosys Ltd.
* Use of this source code is governed by MIT license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
***********************************************************************************************/
package org.infy.idp.config.entities;
/**
* Entity for login request
* @author Infosys
*/
public class LoginRequest {
/** The username. */
private String username;
/** The password. */
private String password;
/**
* Constructor
*
* @param username the String
* @param password the String
* */
public LoginRequest(String username,String password){
this.username=username;
this.password=password;
}
/**
* Constructor
* */
public LoginRequest(){
}
/**
* Gets the username.
*
* @return the username
*/
public String getUsername() {
return username;
}
/**
* Sets the username.
*
* @param username
* the new username
*/
public void setUsername(String username) {
this.username = username;
}
/**
* Gets the password.
*
* @return the password
*/
public String getPassword() {
return password;
}
/**
* Sets the password.
*
* @param password
* the new password
*/
public void setPassword(String password) {
this.password = password;
}
} | 18.605263 | 97 | 0.552334 |
1fb369240e6540d83418252e22250286a2694580 | 3,234 | package com.enremmeta.rtb.proto.liverail;
import javax.ws.rs.core.MediaType;
import com.enremmeta.rtb.Bidder;
import com.enremmeta.rtb.Lot49RuntimeException;
import com.enremmeta.rtb.api.Ad;
import com.enremmeta.rtb.api.proto.openrtb.Bid;
import com.enremmeta.rtb.api.proto.openrtb.OpenRtbRequest;
import com.enremmeta.rtb.api.proto.openrtb.OpenRtbResponse;
import com.enremmeta.rtb.config.Lot49Config;
import com.enremmeta.rtb.constants.Lot49Constants;
import com.enremmeta.rtb.constants.Macros;
import com.enremmeta.rtb.proto.ExchangeAdapter;
import com.enremmeta.rtb.proto.ParsedPriceInfo;
import com.enremmeta.util.Utils;
public class LiverailAdapter implements ExchangeAdapter<OpenRtbRequest, OpenRtbResponse> {
private final LiverailConfig config;
private final String seatId;
public LiverailAdapter() {
super();
final Lot49Config conf = Bidder.getInstance().getConfig();
this.config = conf.getExchanges() == null ? new LiverailConfig()
: (conf.getExchanges().getLiverail() == null ? new LiverailConfig()
: conf.getExchanges().getLiverail());
this.seatId = config.getSeatId();
if (this.seatId == null) {
throw new Lot49RuntimeException("seatId is null");
}
}
@Override
public String getSeat(Ad ad) {
return this.seatId;
}
@Override
public String getResponseMediaType() {
return MediaType.APPLICATION_JSON;
}
@Override
public String getName() {
return Lot49Constants.EXCHANGE_LIVERAIL;
}
@Override
public String getWinningPriceMacro() {
return "$WINNING_PRICE";
}
@Override
public boolean localUserMapping() {
return false;
}
@Override
public OpenRtbRequest convertRequest(OpenRtbRequest request) throws Throwable {
request.getLot49Ext().setAdapter(this);
return request;
}
public static final String EXTENSION_TEMPLATE_PART_1 =
"<Extensions><Extension type=\"LR-Pricing\"><Price model=\"CPM\" currency=\"USD\" source=\"Lot49\">";
public static final String EXTENSION_TEMPLATE_PART_2 = "</Price></Extension></Extensions>";
@Override
public OpenRtbResponse convertResponse(OpenRtbRequest req, OpenRtbResponse resp)
throws Throwable {
final Bid bid = resp.getSeatbid().get(0).getBid().get(0);
final String vast = bid.getAdm();
final String ext = EXTENSION_TEMPLATE_PART_1 + bid.getPrice() + EXTENSION_TEMPLATE_PART_2;
final String lrVast = vast.replace(Macros.MACRO_LOT49_VAST_EXTENSIONS, ext);
bid.setAdm(lrVast);
return resp;
}
@Override
public ParsedPriceInfo parse(String winningPriceString, long bidMicros) throws Throwable {
double winPrice = bidMicros * Double.valueOf(winningPriceString);
long winPriceLong = new Double(winPrice).longValue();
return new ParsedPriceInfo(Utils.microToCpm(winPriceLong), winPriceLong, bidMicros);
}
@Override
public String getClickMacro() {
return null;
}
@Override
public String getClickEncMacro() {
return null;
}
}
| 31.096154 | 121 | 0.680581 |
99521e3ca7547b201bf3320c527b956c5c6a56e2 | 1,434 | package com.wteam.delay_queue;
import com.wteam.car.bean.entity.Order;
import com.wteam.car.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Optional;
@Component
public class OrderJobHandler {
private final OrderService orderService;
@Autowired
public OrderJobHandler(OrderService orderService) {
this.orderService = orderService;
}
Thread getThread(OrderJob job) {
return new Thread(job);
}
public class Thread implements Runnable {
private OrderJob job;
Thread(OrderJob job) {
this.job = job;
}
@Override
public void run() {
Optional<Order> optionalOrder = orderService.findById(job.getId());
if (!optionalOrder.isPresent()) return;
Order order = optionalOrder.get();
if (order.getStatus() == 0 || order.getStatus() == 1) {
switch (job.getType()) {
//订单超时
case 0:
order.setStatus(4);
break;
//订单完成
case 1:
order.setStatus(2);
break;
default:
break;
}
}
orderService.save(order);
}
}
}
| 24.724138 | 79 | 0.530683 |
74777173e2cb895b90c3b88d16f81b0257d40e6c | 40,699 | /*
* Copyright (c) 2011 - 2016, Zhenyu Wu, NEC Labs America Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of ZWUtils-Java nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* // @formatter:on
*/
package com.necla.am.zwutils.Logging;
import java.io.File;
import java.io.PrintStream;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.locks.LockSupport;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import org.slf4j.bridge.SLF4JBridgeHandler;
import com.necla.am.zwutils.Config.Container;
import com.necla.am.zwutils.Config.Data;
import com.necla.am.zwutils.Config.DataFile;
import com.necla.am.zwutils.Config.DataMap;
import com.necla.am.zwutils.Logging.Utils.OutStream;
import com.necla.am.zwutils.Logging.Utils.Support;
import com.necla.am.zwutils.Logging.Utils.Support.GroupLogFile.Feature;
import com.necla.am.zwutils.Logging.Utils.Filters.CapturedLogFilter;
import com.necla.am.zwutils.Logging.Utils.Filters.GroupFilter;
import com.necla.am.zwutils.Logging.Utils.Formatters.LogFormatter;
import com.necla.am.zwutils.Logging.Utils.Handlers.BufferedHandler;
import com.necla.am.zwutils.Logging.Utils.Handlers.DRCFileHandler;
import com.necla.am.zwutils.Logging.Utils.Handlers.ForwardHandler;
import com.necla.am.zwutils.Logging.Utils.Handlers.Zabbix.ZabbixHandler;
import com.necla.am.zwutils.Misc.Misc;
import com.necla.am.zwutils.Misc.Misc.TimeUnit;
import com.necla.am.zwutils.Tasks.ITask;
import com.necla.am.zwutils.Tasks.RunnableTask;
import com.necla.am.zwutils.Tasks.Wrappers.DaemonRunner;
/**
* Package logging facility
* <p>
* This logger facility constructs a hierarchy of loggers.
* <ul>
* <li>The LogBase logger is the root logger configured with a custom printing handler;
* <li>The second level loggers act as logging group filters, notably the "Debug" group, which is
* the default logging group.
* <li>The third level loggers are the class loggers, correspond to all descendant classes of the
* LoggedClass.
* </ul>
* Hierarchy map:
*
* <pre>
* /--- Debug --- (LoggedClass Instance 1)
* |--- (Grp 1) --... /--- (LoggedClass Instance 2)
* LogBase -+--- (Grp 2) ---------+--- (LoggedClass Instance 3)
* |--- (Grp 3) --... \--...
* \--...
* </pre>
*
* @author Zhenyu Wu
* @version 0.1 - Sep. 2010: Initial implementation
* @version ...
* @version 0.9 - Oct. 2012: Revision
* @version 0.9 - Jan. 20 2016: Initial public release
* @version 0.95 - Jan. 21 2016: Enable Log4J forwarding
*/
public final class DebugLog {
protected DebugLog() {
Misc.FAIL(IllegalStateException.class, Misc.MSG_DO_NOT_INSTANTIATE);
}
// Fake the base logger as a group logger (for PushLog functions)
private static final Logger LogBase;
public static final IGroupLogger Logger;
public static final String LOGGROUP = "ZWUtils.Logging.DebugLog";
// ------------ Log Level Operations ------------
private static Level GlobalLevel = Level.CONFIG;
/**
* @since 0.7
*/
public static Level getGlobalLevel() {
return GlobalLevel;
}
/**
* Set default log level, applies to all logging groups without custom level
*
* @since 0.7
*/
public static void setGlobalLevel(Level LogLevel) {
if (!GlobalLevel.equals(LogLevel)) {
GlobalLevel = LogLevel;
Logger.Config("Switching global log level to '%s'", LogLevel);
LogBase.setLevel(LogLevel);
}
}
/**
* Reset all logging groups to default log level
*
* @since 0.8
*/
protected static synchronized void resetAllLogLevels() {
GroupLoggers.values().forEach(LogGroup -> LogGroup.setLevel(null));
}
/**
* Set log level of a specific logging groups
*
* @since 0.8
*/
public static void setGrpLogLevel(String LogGrp, Level LogLevel) {
setGrpLogLevel(getLogGroup(LogGrp), LogLevel);
}
/**
* Set log level of a specific logging groups
*
* @since 0.8
*/
public static void setGrpLogLevel(Logger LogGroup, Level LogLevel) {
Level GroupLevel = LogGroup.getLevel();
if (((GroupLevel == null) && (LogLevel != null))
|| ((GroupLevel != null) && !GroupLevel.equals(LogLevel))) {
LogGroup.setLevel(LogLevel);
if ((LogLevel == null) && (LogGroup.getParent() == null)) {
Logger.Config("Reset group '%s' log level to '%s'", LogGroup.getName(), GlobalLevel);
logGroupSetImplicitLevel(LogGroup, GlobalLevel);
} else {
Logger.Config("Switched group '%s' log level to '%s'", LogGroup.getName(), LogLevel);
}
}
}
// ------------ Log Daemon Operations ------------
private static Daemon DaemonTask = null;
private static ITask.Run LogDaemon = null;
/**
* Enable the threaded logging daemon
*/
public static void useDaemon() {
if (isConfigured()) {
Misc.FAIL("Logger already configured");
}
if (DaemonTask == null) {
Logger.Config("Creating log daemon...");
DaemonTask = new Daemon(LOGGROUP + '.' + Daemon.class.getSimpleName());
for (Handler LogHandler : LogBase.getHandlers()) {
if (LogHandler != preConfigBuffer) {
LogBase.removeHandler(LogHandler);
DaemonTask.Sink.addHandler(LogHandler);
LogHandler.setLevel(Level.ALL);
}
}
} else {
Misc.ASSERT(false, "Logger already uses daemon");
}
}
// ------------ Log Handler Operations ------------
private static Handler ConsoleHandler = null;
/**
* Create a console log handler
*
* @return Log handler
*/
public static Handler createConsoleHandler() {
Logger.Config("Creating console log handler...");
Handler LogHandler = new ConsoleHandler();
LogHandler.setLevel(Level.ALL);
LogHandler.setFormatter(new LogFormatter.Delegator(LogHandler, LOGGROUP));
return LogHandler;
}
/**
* Create a file log handler
*
* @return Log handler
*/
public static Handler createFileHandler(Support.GroupLogFile logFile, String LogGroup) {
Handler Ret = null;
try {
if (!logFile.Features.contains(Feature.DAILYROTATE)) {
Logger.Config("Creating file log handler '%s'...", logFile.FileName);
Ret = new FileHandler(logFile.FileName, logFile.Features.contains(Feature.APPEND));
} else {
Logger.Config("Creating daily rotating file log handler '%s'...", logFile.FileName);
Ret = new DRCFileHandler(logFile.FileName, logFile.Features.contains(Feature.APPEND),
logFile.Features.contains(Feature.COMPRESSROTATED));
}
LogFormatter Formatter;
if (LogGroup != null) {
Formatter = new LogFormatter.Delegator(null, LogGroup);
} else {
Formatter = new LogFormatter.Delegator(Ret, DebugLog.LOGGROUP);
}
Ret.setFormatter(Formatter);
Ret.setEncoding("UTF-8");
} catch (Exception e) {
Misc.CascadeThrow(e);
// PERF: code analysis tool doesn't recognize custom throw functions
throw new IllegalStateException(Misc.MSG_SHOULD_NOT_REACH);
}
return Ret;
}
public static final String FORWARD_ROOTLOGGER_NAME = "(LogRoot)";
public static Handler createLog4JHandler(String LogGroup) {
return new SLF4JBridgeHandler() {
@Override
public void publish(LogRecord record) {
if (record.getLoggerName() == null) {
record.setLoggerName(FORWARD_ROOTLOGGER_NAME);
}
super.publish(record);
}
};
}
/**
* Enable console logging output
*/
public static void attachConsoleHandler() {
if (ConsoleHandler == null) {
ConsoleHandler = createConsoleHandler();
if (DaemonTask == null) {
if (!isConfigured()) {
ConsoleHandler.setLevel(Level.OFF);
}
LogBase.addHandler(ConsoleHandler);
} else {
DaemonTask.Sink.addHandler(ConsoleHandler);
}
} else {
Misc.ASSERT(false, "Console handler already attached");
}
}
/**
* Add a file logging target
*
* @param logFile
* - Log file name
*/
public static void attachFileHandler(Support.GroupLogFile logFile) {
Handler FileHandler = createFileHandler(logFile, null);
if (DaemonTask == null) {
if (!isConfigured()) {
FileHandler.setLevel(Level.OFF);
}
LogBase.addHandler(FileHandler);
} else {
DaemonTask.Sink.addHandler(FileHandler);
}
Logger.Config("File log handler attached");
}
/**
* Add a log4j forwarding logging target
*/
public static void attachLog4JHandler() {
Handler Log4jHandler = createLog4JHandler(LOGGROUP);
if (DaemonTask == null) {
if (!isConfigured()) {
Log4jHandler.setLevel(Level.OFF);
}
LogBase.addHandler(Log4jHandler);
} else {
DaemonTask.Sink.addHandler(Log4jHandler);
}
Logger.Config("Log4J forwarding handler attached");
}
/**
* Attach specified handler to a logger
*
* @param Logger
* - Logger to attach handler to
* @param LogHandler
* - Log handler to attach
* @param propagate
* - Whether to propagate log to parent handlers
* @since 0.85
*/
public static void setLogHandler(Logger Logger, Handler LogHandler, boolean propagate) {
for (Handler logHandler : Logger.getHandlers()) {
Logger.removeHandler(logHandler);
logHandler.flush();
}
if (LogHandler != null) {
Logger.addHandler(LogHandler);
}
Logger.setUseParentHandlers(propagate);
}
/**
* Set log handler of a specific logging groups
*
* @since 0.8
*/
protected static void setGrpLogHandler(String LogGrp, Handler LogHandler, boolean propagate) {
setLogHandler(getLogGroup(LogGrp), LogHandler, propagate);
}
/**
* Set log handler of a specific logging groups
*
* @since 0.8
*/
protected static void setGrpLogHandler(Logger LogGroup, Handler LogHandler, boolean propagate) {
setLogHandler(LogGroup, LogHandler, propagate);
}
protected static Handler ZabbixHandler = null;
public static boolean ZabbixSupport() {
return ZabbixHandler != null;
}
protected static void enableZabbix(String Scope) {
int DelimPos = Scope.lastIndexOf('.');
ZabbixHandler = new ZabbixHandler(Scope.substring(0, DelimPos), Scope.substring(DelimPos + 1));
LogBase.addHandler(ZabbixHandler);
}
// ------------ Output Redirection Operations ------------
/**
* Create a console output redirection stream
*
* @param Name
* - Name of the stream
* @return Output redirection stream
*/
private static OutStream createConsoleOutStream(String Name) {
GroupLogger _Log = new GroupLogger("Console." + Name);
_Log.AddFrameDepth(3);
return new OutStream(Name, _Log);
}
protected static PrintStream StdErr = null;
/**
* Redirect StdErr to log
*/
public static void logStdErr() {
if (StdErr == null) {
StdErr = System.err;
System.setErr(new PrintStream(createConsoleOutStream("STDERR")));
Logger.Config("Redirected StdErr to log");
} else {
Misc.ASSERT(false, "StdErr already redirected");
}
}
protected static PrintStream StdOut = null;
/**
* Redirect StdOut to log
*/
public static void logStdOut() {
if (StdOut == null) {
StdOut = System.out;
System.setOut(new PrintStream(createConsoleOutStream("STDOUT")));
Logger.Config("Redirected StdOut to log");
} else {
Misc.ASSERT(false, "StdOut already redirected");
}
}
public static PrintStream DirectErrOut() {
return StdErr == null? System.err : StdErr;
}
protected static Handler[] RootHandlers = null;
protected static void captureRoot() {
if (RootHandlers == null) {
LogManager Manager = LogManager.getLogManager();
Logger RootLogger = Manager.getLogger("");
Logger ExternalGroup = getLogGroup("External");
ExternalGroup.setFilter(null); // Disable the group filter
Handler ForwardHandler = new ForwardHandler(ExternalGroup);
ForwardHandler.setFilter(new CapturedLogFilter(ExternalGroup));
// Save the handlers
RootHandlers = RootLogger.getHandlers();
for (Handler LogHandler : RootHandlers) {
RootLogger.removeHandler(LogHandler);
}
RootLogger.addHandler(ForwardHandler);
Logger.Config("Root logger captured");
} else {
Misc.ASSERT(false, "Root logger already captured");
}
}
protected static void releaseRoot() {
if (RootHandlers != null) {
LogManager Manager = LogManager.getLogManager();
Logger RootLogger = Manager.getLogger("");
for (Handler LogHandler : RootLogger.getHandlers()) {
RootLogger.removeHandler(LogHandler);
}
for (Handler LogHandler : RootHandlers) {
RootLogger.addHandler(LogHandler);
}
RootHandlers = null;
Logger.Config("Root logger released");
} else {
Misc.ASSERT(false, "Root logger not captured");
}
}
// ------------ Setup / Shutdown Operations ------------
/**
* Signal that logging will be terminated
*
* @since 0.82
*/
static synchronized void close() {
// Close all group logger handlers
GroupLoggers.values().forEach(LogGroup -> {
for (Handler LogHandler : LogGroup.getHandlers()) {
LogGroup.removeHandler(LogHandler);
LogHandler.flush();
LogHandler.close();
}
});
// Close all base logger handlers
for (Handler LogHandler : LogBase.getHandlers()) {
LogBase.removeHandler(LogHandler);
LogHandler.flush();
LogHandler.close();
}
}
/**
* Termination hook to gracefully shutdown the logging framework
*/
static class Cleanup implements Runnable {
@Override
public void run() {
if (StdErr != null) {
PrintStream LogErr = System.err;
System.setErr(StdErr);
LogErr.flush();
LogErr.close();
}
if (StdOut != null) {
PrintStream LogOut = System.out;
System.setOut(StdOut);
LogOut.flush();
LogOut.close();
}
if (ZabbixHandler != null) {
// Zabbix handler has to be detached earlier
ZabbixHandler.close();
LogBase.removeHandler(ZabbixHandler);
}
if (DaemonTask != null) {
DaemonTask.Queue.flush();
LogBase.removeHandler(DaemonTask.Queue);
for (Handler LogHandler : DaemonTask.Sink.getHandlers()) {
DaemonTask.Sink.removeHandler(LogHandler);
LogBase.addHandler(LogHandler);
}
DaemonTask.Queue.close();
try {
LogDaemon.Join(-1);
} catch (Exception e) {
Logger.logExcept(e, "Log daemon termination join failed");
}
}
if (RootHandlers != null) {
releaseRoot();
}
// Craft the very last log message
LogBase.log(new LogRecord(Level.OFF, "@$Logging terminated"));
close();
}
}
/**
* Re-dispatching log entries through their original log group
*
* @since 0.9
*/
private static class RedispatchHandler extends Handler {
@Override
public void close() {
// Do Nothing
}
@Override
public void flush() {
// Do Nothing
}
@Override
public void publish(LogRecord record) {
String LogGrp = record.getLoggerName();
if (LogGrp != null) {
Logger LogGroup = DebugLog.getLogGroup(LogGrp);
LogGroup.log(record);
} else {
LogBase.log(record);
}
}
}
static BufferedHandler preConfigBuffer;
/**
* Check if logging framework has been configured
*
* @return If logging framework is configured
* @since 0.85
*/
public static boolean isConfigured() {
return preConfigBuffer == null;
}
private static Map<Logger, BufferedHandler> LogGroupBufferMap = null;
/**
* Signal that logging configurations have been loaded
*
* @since 0.82
*/
static void setConfigured(ConfigData.ReadOnly Config) {
if (!isConfigured()) {
if (DaemonTask == null) {
LogBase.removeHandler(preConfigBuffer);
for (Handler LogHandler : LogBase.getHandlers()) {
LogHandler.setLevel(Level.ALL);
}
} else {
StartLogDaemon();
}
SwitchBufferedHandlers();
// The LogBase handlers need to receive update from LogFormatter configurations
// Note: The '.' ensures normal group names could not collide on this special notifier
Logger FormatterConfig = CreateLogger(null, null);
FormatterConfig.setLevel(Level.ALL);
for (Handler LogHandler : LogBase.getHandlers()) {
FormatterConfig.addHandler(LogHandler);
}
LogFormatter.SubscribeConfigChange(".", new GroupLogger(FormatterConfig));
// Install termination hook
Runtime.getRuntime().addShutdownHook(new Thread(new Cleanup()));
if (Config.ZabbixScope != null) {
enableZabbix(Config.ZabbixScope);
}
} else {
Misc.ASSERT(false, "Logger already configured");
}
}
private static void SwitchBufferedHandlers() {
if (LogGroupBufferMap != null) {
// Switch all logging group buffer handlers to file handlers
LogGroupBufferMap.forEach((LogGroup, LogBuffer) -> {
LogGroup.removeHandler(LogBuffer);
LogGroup.addHandler(LogBuffer.getHandler());
});
}
preConfigBuffer.flush();
preConfigBuffer.close();
preConfigBuffer = null;
Logger.Fine("Flushed pre-configuration log buffer");
if (LogGroupBufferMap != null) {
// Flush and close all logging group buffer handlers
LogGroupBufferMap.values().forEach(LogBuffer -> {
LogBuffer.flush();
LogBuffer.setHandler(null);
LogBuffer.close();
});
LogGroupBufferMap = null;
}
}
private static void StartLogDaemon() {
Logger.Fine("Starting log daemon thread...");
LogDaemon = DaemonRunner.LowPriorityTaskDaemon(DaemonTask);
try {
LogDaemon.Start(-1);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
Misc.CascadeThrow(e);
}
Logger.Fine("Log daemon thread started");
// Wait for the daemon to become idle
DaemonTask.Queue.flush();
// Perform the log handler switch
LogBase.removeHandler(preConfigBuffer);
LogBase.addHandler(DaemonTask.Queue);
}
// ------------ Configuration Operations ------------
public static class ConfigData {
protected ConfigData() {
Misc.FAIL(IllegalStateException.class, Misc.MSG_DO_NOT_INSTANTIATE);
}
public static class Mutable extends Data.Mutable {
// Default logging level
public Level LogLevel;
// Whether to use console handler
public boolean LogConsole;
// Whether to use file handler
public Support.GroupLogFile LogFile;
// Whether to send logs to Log4J
public boolean Log4J;
// Whether to redirect StdErr
public boolean LogStdErr;
// Whether to redirect StdOut
public boolean LogStdOut;
// Whether to redirect StdOut
public boolean UseDaemon;
// Whether to capture root logger output
public boolean CaptureRoot;
// Whether to enable Zabbix support
public String ZabbixScope;
// Per logging group level
public Map<String, Level> GroupLevels;
// Per logging group log file
public Map<String, Support.GroupLogFile> GroupFiles;
@Override
public void loadDefaults() {
LogLevel = GlobalLevel;
LogConsole = true;
LogFile = null;
Log4J = false;
LogStdErr = true;
LogStdOut = false;
UseDaemon = false;
CaptureRoot = true;
ZabbixScope = null;
GroupLevels = new HashMap<>();
GroupFiles = new HashMap<>();
}
private static final String CONFIG_LOGLEVEL = "LogLevel";
private static final String CONFIG_CONSOLE = "Console";
private static final String CONFIG_FILE = "File";
private static final String CONFIG_LOG4J = "Log4J";
private static final String CONFIG_STDERR = "StdErr";
private static final String CONFIG_STDOUT = "StdOut";
private static final String CONFIG_DAEMON = "Daemon";
private static final String CONFIG_CAPROOT = "CapRoot";
private static final String CONFIG_ZBXSCOPE = "ZabbixScope";
private static final String CONFIG_GROUPLEVELS_KEYBASE = "LevelOf.";
private static final String CONFIG_GROUPFILE_KEYBASE = "FileOf.";
@Override
public void loadFields(DataMap confMap) {
LogLevel = Level.parse(confMap.getTextDef(CONFIG_LOGLEVEL, LogLevel.getName()));
LogConsole = confMap.getBoolDef(CONFIG_CONSOLE, LogConsole);
if (confMap.containsKey(CONFIG_FILE)) {
LogFile = confMap.getObject(CONFIG_FILE, Support.GroupLogFile.ParseFromString,
Support.GroupLogFile.ParseToString);
}
Log4J = confMap.getBoolDef(CONFIG_LOG4J, Log4J);
LogStdErr = confMap.getBoolDef(CONFIG_STDERR, LogStdErr);
LogStdOut = confMap.getBoolDef(CONFIG_STDOUT, LogStdOut);
UseDaemon = confMap.getBoolDef(CONFIG_DAEMON, UseDaemon);
CaptureRoot = confMap.getBoolDef(CONFIG_CAPROOT, CaptureRoot);
ZabbixScope = confMap.getText(CONFIG_ZBXSCOPE);
confMap.keySet(CONFIG_GROUPLEVELS_KEYBASE).forEach(Key -> {
String ConfigKey = String.class.cast(Key);
if (ConfigKey.startsWith(CONFIG_GROUPLEVELS_KEYBASE)) {
String SubKey = ConfigKey.substring(CONFIG_GROUPLEVELS_KEYBASE.length());
GroupLevels.put(SubKey,
confMap.getObject(ConfigKey, Support.StringToLevel, Support.StringFromLevel));
}
});
confMap.keySet(CONFIG_GROUPFILE_KEYBASE).forEach(Key -> {
String ConfigKey = String.class.cast(Key);
if (ConfigKey.startsWith(CONFIG_GROUPFILE_KEYBASE)) {
String SubKey = ConfigKey.substring(CONFIG_GROUPFILE_KEYBASE.length());
GroupFiles.put(SubKey, confMap.getObject(ConfigKey,
Support.GroupLogFile.ParseFromString, Support.GroupLogFile.ParseToString));
}
});
}
protected class Validation implements Data.Mutable.Validation {
protected void ProbeLogFile(String LogFileName) {
File LogOutputFile = new File(LogFileName);
if (!LogOutputFile.exists()) {
try {
// Make sure the log file have proper parent directory
File LogOutputDir = LogOutputFile.getParentFile();
if ((LogOutputDir != null) && LogOutputDir.mkdirs()) {
Logger.Fine("Created log directory '%s'", Misc.stripFileName(LogFileName));
}
if (!LogOutputFile.createNewFile()) {
Logger.Warn("Log file '%s' was concurrently created",
Misc.stripFileName(LogFileName));
}
} catch (Exception e) {
Misc.FAIL("Failed to create log file '%s' - %s", LogFile, e.getLocalizedMessage());
}
}
if (!LogOutputFile.canWrite()) {
Misc.FAIL("Could not write to log file '%s'", LogFile);
}
}
@Override
public void validateFields() throws Exception {
if (ZabbixScope != null) {
if (ZabbixScope.isEmpty()) {
ZabbixScope = null;
} else {
int DelimPos = ZabbixScope.indexOf('.');
if ((DelimPos <= 0) || (DelimPos >= (ZabbixScope.length() - 1))) {
Misc.FAIL("Invalid Zabbix Scope '%s'", ZabbixScope);
}
}
}
if ((LogFile != null) && !LogFile.FileName.isEmpty()) {
Logger.Fine("Checking log output file '%s'...", LogFile);
ProbeLogFile(LogFile.FileName);
}
GroupFiles.keySet().forEach(LogGroup -> {
Support.GroupLogFile GLogEntry = GroupFiles.get(LogGroup);
if (!GLogEntry.FileName.isEmpty()) {
Logger.Fine("Checking log group '%s' output file '%s'...", LogGroup,
GLogEntry.FileName);
ProbeLogFile(GLogEntry.FileName);
}
});
}
}
@Override
protected Validation needValidation() {
return new Validation();
}
}
public static class ReadOnly extends Data.ReadOnly {
public final String ZabbixScope;
public ReadOnly(IGroupLogger Logger, Mutable Source) {
super(Logger, Source);
// Apply configurations
if (Source.LogConsole) {
attachConsoleHandler();
}
if ((Source.LogFile != null) && !Source.LogFile.FileName.isEmpty()) {
attachFileHandler(Source.LogFile);
}
if (Source.Log4J) {
attachLog4JHandler();
}
if (Source.LogStdErr) {
logStdErr();
}
if (Source.LogStdOut) {
logStdOut();
}
if (Source.UseDaemon) {
useDaemon();
}
if (Source.CaptureRoot) {
captureRoot();
}
ZabbixScope = Source.ZabbixScope;
Source.GroupLevels.forEach(DebugLog::setGrpLogLevel);
if (!Source.GroupFiles.isEmpty()) {
LogGroupBufferMap = new HashMap<>();
Source.GroupFiles.forEach((LogGroup, GLogFile) -> {
if (!GLogFile.FileName.isEmpty()) {
Handler GroupLogHandler = createFileHandler(GLogFile, LogGroup);
// Each handler needs to receive update from LogFormatter configurations
Logger FormatterConfig = CreateLogger(null, null);
FormatterConfig.setLevel(Level.ALL);
FormatterConfig.addHandler(GroupLogHandler);
LogFormatter.SubscribeConfigChange(LogGroup, new GroupLogger(FormatterConfig));
BufferedHandler GroupLogBuffer = new BufferedHandler(GroupLogHandler);
GroupLogBuffer.setEnabled(!GLogFile.Features.contains(Feature.APPEND));
setGrpLogHandler(LogGroup, GroupLogBuffer,
GLogFile.Features.contains(Feature.APPEND));
LogGroupBufferMap.put(getLogGroup(LogGroup), GroupLogBuffer);
Logger.Fine("Logging group '%s' to output file '%s'", LogGroup, GLogFile.FileName);
}
});
}
/**
* Note: it is essential to set the default log level the last, so that no previously logged
* messages are filtered out before this point (in order for per group filtering to work for
* initializations)
*/
if (!GlobalLevel.equals(Source.LogLevel)) {
setGlobalLevel(Source.LogLevel);
}
}
}
public static final File ConfigFile = DataFile.DeriveConfigFile("ZWUtils.");
private static final String CONFIG_KEYBASE = DebugLog.class.getSimpleName() + ".";
protected static Container<Mutable, ReadOnly> Create() throws Exception {
return Container.Create(Mutable.class, ReadOnly.class, LOGGROUP + ".Config", ConfigFile,
CONFIG_KEYBASE);
}
}
// ------------ Logger Management Operations ------------
private static final Constructor<Logger> LoggerConstructor;
private static final Field LoggerManagerField;
private static final Field LoggerAnonymousField;
private static final Field LoggerLevelValueField;
private static final Field LoggerKidsField;
private static final Method LoggerUpdateEffectiveLevelMethod;
/**
* Note: we actually need "strong" references to the named loggers, because they are used as
* logging groups, which may have custom filtering and logging settings applied to them
*/
private static final Map<String, Logger> GroupLoggers;
/**
* Find named logger instance
*
* @param LoggerName
* - Name of the logger, null if anonymous
* @return Existing named logger instance or null
* @since 0.9
*/
public static synchronized Logger FindLogger(String LoggerName) {
if ((LoggerName != null) && (LoggerName.isEmpty())) return null;
return GroupLoggers.get(LoggerName);
}
/**
* Create named logger instance
*
* @param LoggerName
* - Name of the logger, null if anonymous
* @return New named logger instance
* @since 0.9
*/
protected static synchronized Logger CreateLogger(String LoggerName, Logger ParentLogger) {
if (LoggerName != null) {
if (LoggerName.isEmpty()) {
LoggerName = null;
} else {
if (GroupLoggers.containsKey(LoggerName)) {
Misc.ERROR("Logger '%s' already exists", LoggerName);
}
}
}
Logger Ret = null;
try {
Ret = LoggerConstructor.newInstance(LoggerName);
LoggerManagerField.set(Ret, LogManager.getLogManager());
LoggerAnonymousField.set(Ret, LoggerName == null);
if (ParentLogger != null) {
Ret.setParent(ParentLogger);
}
} catch (Exception e) {
Misc.CascadeThrow(e);
// PERF: code analysis tool doesn't recognize custom throw functions
throw new IllegalStateException(Misc.MSG_SHOULD_NOT_REACH);
}
if (LoggerName != null) {
GroupLoggers.put(LoggerName, Ret);
}
return Ret;
}
@SuppressWarnings("unchecked")
protected static void logGroupSetImplicitLevel(Logger LogGroup, Level LogLevel) {
try {
LoggerLevelValueField.set(LogGroup, LogLevel.intValue());
ArrayList<?> Kids = (ArrayList<?>) LoggerKidsField.get(LogGroup);
if (Kids != null) {
for (Object Kid : Kids) {
WeakReference<Logger> ChildRef = (WeakReference<Logger>) Kid;
Logger Child = ChildRef.get();
if (Child != null) {
LoggerUpdateEffectiveLevelMethod.invoke(Child);
}
}
}
} catch (Exception e) {
Misc.CascadeThrow(e);
}
}
public static final Pattern LOGGROUP_SEPARATOR = Pattern.compile("[.\\[\\]()<>{}]+");
/**
* Find or create a logging group with given name
*
* @param LogGrp
* - The unique name identifies the logging group
* @return Group logger instance of the specified logging group
* @since 0.8
*/
protected static Logger getLogGroup(String LogGrp) {
return getLogGroup(LogGrp, LogBase);
}
/**
* Find or create a logging group with given name and parent logging group
* <p>
* The logging group name is hierarchical, rooted from the given parent logging group. All
* intermediate parent logging groups will be created if necessary. <br>
* For example, given name "c.d" and parent logging group "a.b", the following hierarchy will be
* established:<br>
* <code>
* a.b <- a.b.c <- a.b.c.d
* </code>
*
* @param LogGrp
* - The unique name identifies the logging group
* @return Group logger instance of the specified logging group
* @since 0.9
*/
protected static synchronized Logger getLogGroup(String LogGrp, Logger ParentGroup) {
if (LogGrp == null) {
Misc.ERROR("Log group must be named");
// PERF: code analysis tool doesn't recognize custom throw functions
throw new IllegalStateException(Misc.MSG_SHOULD_NOT_REACH);
}
String[] GroupTokens = LOGGROUP_SEPARATOR.split(LogGrp);
String GroupName = ParentGroup.getName();
for (String GroupToken : GroupTokens) {
GroupName = GroupName == null? GroupToken : (GroupName + '.' + GroupToken);
Logger LogGroup = FindLogger(GroupName);
if (LogGroup == null) {
LogGroup = createLogGroup(GroupName, ParentGroup);
}
ParentGroup = LogGroup;
}
return ParentGroup;
}
/**
* Create a logging group with given name
*
* @param LogGrp
* - The unique name identifies the logging group
* @return Group logger instance of the specified logging group
* @since 0.9
*/
protected static Logger createLogGroup(String LogGrp, Logger ParentGroup) {
if ((LogGrp == null) || LogGrp.isEmpty()) {
Misc.ERROR("Log group must be named");
// PERF: code analysis tool doesn't recognize custom throw functions
throw new IllegalStateException(Misc.MSG_SHOULD_NOT_REACH);
}
Logger LogGroup = CreateLogger(LogGrp, ParentGroup);
LogGroup.setFilter(new GroupFilter(LogGroup));
if (isConfigured()) {
Logger.Fine("Log group '%s' created", LogGrp);
}
return LogGroup;
}
/**
* Create a new anonymous logger attached to a given logging group
*
* @param LogGroup
* - Group logger instance
* @return Unique logger instance of the specified logging group
* @since 0.8
*/
protected static Logger newGroupLogger(Logger LogGroup) {
Logger Ret = CreateLogger(null, LogGroup);
if (LogGroup != null) {
Ret.setFilter(LogGroup.getFilter());
}
return Ret;
}
/**
* Create a new group logger attached to the logging group of specified name
*
* @param LogGrp
* - The unique name identifies the logging group
* @return Unique logger instance of the specified logging group
* @since 0.2
*/
public static Logger newLogger(String LogGrp) {
if ((LogGrp == null) || (LogGrp.isEmpty())) {
LogGrp = LOGGROUP;
}
return newGroupLogger(getLogGroup(LogGrp));
}
/**
* Create a new group logger attached to the logging group of specified name and parent logging
* group name
*
* @param LogGrp
* - The unique name identifies the logging group
* @param ParentGroup
* - The parent logging group logger name
* @return Unique logger instance of the specified logging group
* @since 0.2
*/
protected static Logger newLogger(String LogGrp, String ParentGroup) {
if ((LogGrp == null) || (LogGrp.isEmpty())) {
LogGrp = LOGGROUP;
}
return newGroupLogger(getLogGroup(LogGrp, getLogGroup(ParentGroup)));
}
// ------------ Utility Functions ------------
public static final String LOGMSG_SOURCELINE_DELIM = ":";
public static String PrintSourceLocation(StackTraceElement Frame) {
return new StringBuilder().append(Frame.getFileName()).append(LOGMSG_SOURCELINE_DELIM)
.append(Frame.getLineNumber()).toString();
}
public static final String LOGMSG_CLASSMETHOD_DELIM = ":";
public static String PrintClassMethod(StackTraceElement Frame) {
return new StringBuilder().append(Frame.getClassName()).append(LOGMSG_CLASSMETHOD_DELIM)
.append(Frame.getMethodName()).toString();
}
// ------------ Initialization ------------
static {
{
Map<String, Logger> _GroupLoggers = null;
Constructor<Logger> _LoggerConstructor = null;
Field _LoggerManagerField = null;
Field _LoggerAnonymousField = null;
Field _LoggerLevelValueField = null;
Field _LoggerKidsField = null;
Method _LoggerUpdateEffectiveLevelMethod = null;
try {
_GroupLoggers = new HashMap<>();
_LoggerConstructor = Logger.class.getDeclaredConstructor(String.class);
_LoggerConstructor.setAccessible(true);
_LoggerManagerField = Logger.class.getDeclaredField("manager");
_LoggerManagerField.setAccessible(true);
_LoggerAnonymousField = Logger.class.getDeclaredField("anonymous");
_LoggerAnonymousField.setAccessible(true);
_LoggerLevelValueField = Logger.class.getDeclaredField("levelValue");
_LoggerLevelValueField.setAccessible(true);
_LoggerKidsField = Logger.class.getDeclaredField("kids");
_LoggerKidsField.setAccessible(true);
_LoggerUpdateEffectiveLevelMethod = Logger.class.getDeclaredMethod("updateEffectiveLevel");
_LoggerUpdateEffectiveLevelMethod.setAccessible(true);
} catch (Exception e) {
DirectErrOut().println(String.format(
"Failed first stage pre-initialization for %s: %s, program will terminate.",
DebugLog.class.getSimpleName(), e.getLocalizedMessage()));
e.printStackTrace(DirectErrOut());
Misc.CascadeThrow(e);
}
GroupLoggers = _GroupLoggers;
LoggerConstructor = _LoggerConstructor;
LoggerManagerField = _LoggerManagerField;
LoggerAnonymousField = _LoggerAnonymousField;
LoggerLevelValueField = _LoggerLevelValueField;
LoggerKidsField = _LoggerKidsField;
LoggerUpdateEffectiveLevelMethod = _LoggerUpdateEffectiveLevelMethod;
}
{
Logger _LogBase = null;
try {
_LogBase = CreateLogger(null, null);
_LogBase.setLevel(GlobalLevel);
// Insert pre-configuration buffer
preConfigBuffer = new BufferedHandler(new RedispatchHandler());
_LogBase.addHandler(preConfigBuffer);
// Craft the very first log message
_LogBase.log(new LogRecord(Level.OFF, "@$Logging started"));
} catch (Exception e) {
DirectErrOut().println(String.format(
"Failed second stage pre-initialization for %s: %s, program will terminate.",
DebugLog.class.getSimpleName(), e.getLocalizedMessage()));
e.printStackTrace(DirectErrOut());
Misc.CascadeThrow(e);
}
LogBase = _LogBase;
}
{
GroupLogger _Log = null;
try {
_Log = new GroupLogger(LOGGROUP);
_Log.AddFrameDepth(1);
} catch (Exception e) {
DirectErrOut().println(String.format(
"Failed third stage pre-initialization for %s: %s, program will terminate.",
DebugLog.class.getSimpleName(), e.getLocalizedMessage()));
e.printStackTrace(DirectErrOut());
Misc.CascadeThrow(e);
}
Logger = _Log;
}
ConfigData.ReadOnly Config = null;
try {
Config = ConfigData.Create().reflect();
} catch (Exception e) {
DirectErrOut()
.println(String.format("Failed to load configrations for %s: %s, program will terminate.",
DebugLog.class.getSimpleName(), e.getLocalizedMessage()));
e.printStackTrace(DirectErrOut());
Misc.CascadeThrow(e);
}
Logger.Entry("+Initializing...");
try {
// Now we are configured
setConfigured(Config);
} catch (Exception e) {
DirectErrOut().println(String.format("Failed to initialize %s: %s, program will terminate.",
DebugLog.class.getSimpleName(), e.getLocalizedMessage()));
e.printStackTrace(DirectErrOut());
Misc.CascadeThrow(e);
}
Logger.Exit("*Initialized");
}
/**
* Daemon log worker
* <p>
* Handles logging in the background
*
* @author Zhenyu Wu
* @see DebugLog
* @version 0.1 - Initial implementation
*/
protected static class Daemon extends RunnableTask {
private Thread LogThread = null;
private volatile boolean Waiting = false;
class InputHandler extends Handler {
private volatile boolean Closed = false;
private Queue<LogRecord> Container = new ConcurrentLinkedQueue<>();
@Override
public synchronized void close() {
if (isClosed()) {
Misc.FAIL("Handler already closed");
}
if (!Closed) {
Closed = true;
_flush();
}
}
public boolean isClosed() {
return Closed;
}
@Override
public synchronized void flush() {
if (isClosed()) {
Misc.FAIL("Handler already closed");
}
_flush();
}
synchronized void _flush() {
LockSupport.unpark(LogThread);
try {
while (!Container.isEmpty()) {
wait();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
Misc.CascadeThrow(e);
}
}
@Override
public void publish(LogRecord record) {
if (isClosed()) {
Misc.FAIL("Handler already closed");
}
Container.add(record);
if ((LogThread != null) && Waiting) {
Waiting = false;
LockSupport.unpark(LogThread);
}
}
protected LogRecord handle() {
return Container.poll();
}
}
public final Logger Sink = DebugLog.CreateLogger(null, null);
public final InputHandler Queue = new InputHandler();
public Daemon(String Name) {
super(Name);
Sink.setLevel(Level.ALL);
}
@Override
protected void preTask() {
super.preTask();
LogThread = Thread.currentThread();
}
@Override
protected void doTask() {
try {
while (!tellState().isTerminating() || !Queue.Container.isEmpty()) {
LogRecord record = Queue.handle();
if (record == null) {
synchronized (Queue) {
// Check and notify flush waiters
Queue.notifyAll();
// Check if queue has been closed
if (Queue.isClosed() && tellState().isRunning()) {
EnterState(State.TERMINATING);
}
}
if (tellState().isRunning()) {
// Wait for new message with a timeout
Waiting = true;
LockSupport.parkNanos(this, TimeUnit.MSEC.Convert(100, TimeUnit.NSEC));
Waiting = false;
}
} else {
Sink.log(record);
}
}
} catch (Exception e) {
DebugLog.StdErr.println("Unhandled log daemon exception - " + e.getLocalizedMessage());
e.printStackTrace(DebugLog.StdErr);
}
}
}
}
| 29.816117 | 97 | 0.684955 |
a02590d93fe282cdc61fc366d8ace76991741fac | 1,919 | package com.example;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class EventbriteUser {
private String id;
private String name;
private String first_name;
private String last_name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
@Override
public String toString() {
return "EventbriteUser{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", first_name='" + first_name + '\'' +
", last_name='" + last_name + '\'' +
'}';
}
private static class Email {
private String email;
private boolean verified;
private boolean primary;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isVerified() {
return verified;
}
public void setVerified(boolean verified) {
this.verified = verified;
}
public boolean isPrimary() {
return primary;
}
public void setPrimary(boolean primary) {
this.primary = primary;
}
@Override
public String toString() {
return "[ verified=" + verified + ", primary=" + primary + "]";
}
}
}
| 24.291139 | 75 | 0.540386 |
0fb7e4c989366ab0461973bf90d6b2c5f637fc20 | 1,664 | package com.guigarage.shell.service;
import com.canoo.dolphin.server.event.DolphinEventBus;
import com.guigarage.shell.event.Topics;
import com.guigarage.shell.event.VarData;
import jdk.jshell.JShell;
import jdk.jshell.SnippetEvent;
import jdk.jshell.VarSnippet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Stream;
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
@Service
public class ShellService {
private JShell shell;
private List<VarData> variables = new CopyOnWriteArrayList<>();
@Autowired
private DolphinEventBus eventBus;
@PostConstruct
public void init() {
shell = JShell.builder().build();
}
public Stream<VarData> getVariables() {
return variables.stream();
}
public synchronized void eval(String command) {
List<SnippetEvent> events = shell.eval(command);
for(SnippetEvent event : events) {
if(event.snippet() instanceof VarSnippet) {
String type = ((VarSnippet) event.snippet()).typeName();
String name = ((VarSnippet) event.snippet()).name();
String value = event.value();
VarData varData = new VarData(type, name, value);
eventBus.publish(Topics.VAR_CREATED_TOPIC, varData);
variables.add(varData);
}
}
}
}
| 31.396226 | 72 | 0.700721 |
3ecd550d0043c4e801582b84a7ba39405378d08d | 271 | package top.chengdongqing.common.pay.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 交易通道
*
* @author Luyao
*/
@Getter
@AllArgsConstructor
public enum TradeChannel {
WXPAY("微信"),
ALIPAY("支付宝");
private final String description;
}
| 13.55 | 43 | 0.704797 |
5f22d67e527cf1578798c127b8e8969a8aa27c7c | 3,186 | package ru.job4j.optimization;
import java.sql.SQLException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.PreparedStatement;
public class Connect {
/**
* Count of numbers witch need add to database.
*/
private int field;
private String url;
private java.sql.Connection cn = null;
private Statement st = null;
private PreparedStatement pst = null;
private ResultSet rs = null;
/**
* Open connection to database.
*/
public void openConnections() {
try {
cn = DriverManager.getConnection(url);
st = cn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Create new table if it not exist in database.
*/
public void initTable() {
try {
Class.forName("org.sqlite.JDBC");
st.execute("CREATE TABLE IF NOT EXISTS test(field INTEGER)");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Add numbers to database.
*/
public void addNumbers() {
try {
st.execute("DELETE FROM test");
cn.setAutoCommit(false);
System.out.println(String.format("Start adding %s entryes to DB...", field));
long s = System.currentTimeMillis();
for (int i = 1; i <= this.field; i++) {
pst = cn.prepareStatement("INSERT INTO test(field) VALUES (?)");
pst.setInt(1, i);
pst.executeUpdate();
if (i > 500 && i % 500 == 0) {
pst.executeBatch();
}
}
long res = System.currentTimeMillis() - s;
System.out.println(String.format("Finish adding to DB %s ms", res));
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Get numbers from database.
* @return int[].
*/
public int[] getNumbers() {
int[] result = new int[this.field];
int index = 0;
try {
pst = cn.prepareStatement("SELECT test.field FROM test");
rs = pst.executeQuery();
while (rs.next()) {
result[index++] = rs.getInt("field");
}
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
/**
* Close all opening connections.
*/
public void closeConnections() {
if (cn != null) {
try {
cn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* Set url - address for getting connection to database.
* @param url - address.
*/
public void setURL(String url) {
this.url = url;
}
/**
* Set count of numbers.
* @param field - count of number.
*/
public void setN(int field) {
this.field = field;
}
} | 27.230769 | 89 | 0.500314 |
72cd908f64332742accb030e3b6b91c3dd1aeb92 | 153 | public class ItemCameraTransforms {
// Failed to decompile, took too long to decompile: net/minecraft/client/renderer/block/model/ItemCameraTransforms
} | 51 | 115 | 0.823529 |
b354b0dbbb3cdf61f054b837af013a3d5ac4c2c2 | 1,412 | package no.bibsys.web.model;
import no.bibsys.utils.JsonUtils;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Map;
@Provider
@Produces({CustomMediaType.APPLICATION_RDF, CustomMediaType.APPLICATION_TURTLE, CustomMediaType.APPLICATION_RDF_XML,
CustomMediaType.APPLICATION_N_TRIPLES, CustomMediaType.APPLICATION_JSON_LD, MediaType.APPLICATION_JSON})
public class RegistryRdfMessageBodyWriter extends CustomMessageBodyWriter<RegistryDto> {
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return type == RegistryDto.class;
}
@Override
public void writeTo(RegistryDto registry, Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream outputStream) throws IOException {
Map<String, Object> metadata = registry.getMetadata();
String body = JsonUtils.newJsonParser().writeValueAsString(metadata);
String serialized = serializeRdf(mediaType, body);
writerStringToOutputStream(outputStream, serialized);
}
}
| 34.439024 | 121 | 0.755666 |
5030bfe71c2a2772eeb71521562994730ccc4c56 | 1,568 | package com.bluegosling.util;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* A marker interface for "value types". A value type is a concrete class that is both final and
* immutable (but not an enum). In addition to not having sub-classes (since they are final), value
* types may also not have super-classes (other than {@code Object}). Furthermore, a value type's
* {@code equals}, {@code hashCode}, and {@code toString} methods should be implemented solely in
* terms of its field values, not in terms of its identity (which means they should all be
* overridden as the logic inherited from {@code Object} is not suitable).
*
* <p>Value types could theoretically be passed around by value/copy, instead of by reference,
* without changing the behavior of a program. Code that uses value types should not perform any
* operations that rely on the value's address. For example, this means no testing for reference
* equality ({@code ==}), no usage of {@link System#identityHashCode}, and no usage of the object as
* a synchronizer/lock.
*
* <p>For more information, see the JRE's description of
* <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/doc-files/ValueBased.html">
* value-based classes</a>.
*
* @author Joshua Humphries (jhumphries131@gmail.com)
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
public @interface ValueType {
}
| 44.8 | 100 | 0.752551 |
18bca51bb1a603e2c814eaaa4a490f31af5823b2 | 3,993 | /**
* Copyright (c) 2018 AppDynamics LLC and its affiliates
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.appdynamics.iot;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class CollectorChannelTest {
private URL testUrl;
CollectorChannel collectorChannel;
@Before
public void setup() {
CollectorChannelFactory collectorChannelFactory = new CollectorChannelFactory() {
@Override
public CollectorChannel getCollectorChannel() {
return new CollectorChannel() {
@Override
public OutputStream getOutputStream() throws IOException {
return null;
}
@Override
public InputStream getInputStream() throws IOException {
return null;
}
@Override
public InputStream getErrorStream() throws IOException {
return null;
}
@Override
public int getResponseCode() throws IOException {
return 200;
}
@Override
public Map<String, List<String>> getHeaderFields() throws IOException {
return null;
}
@Override
public String getResponseMessage() throws IOException {
return "response message";
}
};
}
};
collectorChannel = collectorChannelFactory.getCollectorChannel();
}
@Test
public void testURL() throws Exception {
URL testUrl = new URL("https://test.mydomain.com");
collectorChannel.setURL(testUrl);
assertEquals(testUrl, collectorChannel.getURL());
}
@Test
public void testConnectTimeout() throws Exception {
collectorChannel.setConnectTimeout(100);
assertEquals(100, collectorChannel.getConnectTimeout());
}
@Test
public void testSetReadTimeout() throws Exception {
collectorChannel.setReadTimeout(100);
assertEquals(100, collectorChannel.getReadTimeout());
collectorChannel.setReadTimeout(50);
assertEquals(50, collectorChannel.getReadTimeout());
}
@Test
public void testRequestProperty() throws Exception {
String key1 = "key1";
String value1 = "value1";
String value11 = "value11";
String key2 = "key2";
String value2 = "value2";
collectorChannel.addRequestProperty(key1, value1);
assertEquals(value1, collectorChannel.getRequestProperties().get(key1).get(0));
collectorChannel.addRequestProperty(key1, value11);
assertEquals(value11, collectorChannel.getRequestProperties().get(key1).get(1));
collectorChannel.addRequestProperty(key2, value2);
assertEquals(value2, collectorChannel.getRequestProperties().get(key2).get(0));
}
@Test
public void testRequestMethod() throws Exception {
collectorChannel.setRequestMethod("request method");
assertEquals("request method", collectorChannel.getRequestMethod());
}
} | 33.554622 | 91 | 0.620586 |
68a3537c9cac8ab0b340e2672d9b4db2538f3606 | 39,759 | package org.onebillion.onecourse.mainui.generic;
import android.animation.Animator;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.RectF;
import android.graphics.Typeface;
import org.onebillion.onecourse.controls.OBControl;
import org.onebillion.onecourse.controls.OBGroup;
import org.onebillion.onecourse.controls.OBLabel;
import org.onebillion.onecourse.controls.OBPath;
import org.onebillion.onecourse.mainui.MainActivity;
import org.onebillion.onecourse.mainui.OC_SectionController;
import org.onebillion.onecourse.mainui.oc_countingpractice.OC_CountingPractice;
import org.onebillion.onecourse.mainui.oc_lettersandsounds.OC_Wordcontroller;
import org.onebillion.onecourse.utils.OBAnim;
import org.onebillion.onecourse.utils.OBAnimationGroup;
import org.onebillion.onecourse.utils.OBAudioManager;
import org.onebillion.onecourse.utils.OBAudioPlayer;
import org.onebillion.onecourse.utils.OBConditionLock;
import org.onebillion.onecourse.utils.OBGeneralAudioPlayer;
import org.onebillion.onecourse.utils.OBPhoneme;
import org.onebillion.onecourse.utils.OBUserPressedBackException;
import org.onebillion.onecourse.utils.OBUtils;
import org.onebillion.onecourse.utils.OB_Maths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.onebillion.onecourse.utils.OB_Maths.PointDistance;
import static org.onebillion.onecourse.utils.OB_Maths.randomInt;
import static org.onebillion.onecourse.utils.OB_Maths.relativePointInRectForLocation;
/**
* OC_Generic_Event
* Main Class for generic Events that are present in Maths and Letter and Sounds activities
* Has a set of standard functions to handle touches on the screen, dragging objects, handling correct and wrong answers
* <p>
* Created by pedroloureiro on 20/06/16.
*/
public class OC_Generic_Event extends OC_SectionController
{
public static float FIRST_REMINDER_DELAY = 6.0f;
public static float SECOND_REMINDER_DELAY = 4.0f;
int currentDemoAudioIndex;
int savedStatus;
List<Object> savedReplayAudio;
OBAnimationGroup returnToOriginalPositionAnimation;
//
public double lastActionTakenTimestamp;
public interface RunLambdaWithTimestamp
{
void run (double timestamp) throws Exception;
}
public OC_Generic_Event ()
{
super();
}
public void updateLastActionTakenTimeStamp ()
{
lastActionTakenTimestamp = getCurrentTimeDouble();
}
public void prepare ()
{
super.prepare();
loadFingers();
loadEvent("master1");
String scenes = (String) eventAttributes.get(action_getScenesProperty());
if (scenes != null)
{
String[] eva = scenes.split(",");
events = Arrays.asList(eva);
}
else
{
events = new ArrayList<>();
}
//
if (currentEvent() != null)
{
doVisual(currentEvent());
}
//
updateLastActionTakenTimeStamp();
checkAndUpdateFinale();
}
public void start ()
{
final long timeStamp = setStatus(STATUS_WAITING_FOR_TRACE);
//
OBUtils.runOnOtherThread(new OBUtils.RunLambda()
{
@Override
public void run () throws Exception
{
try
{
if (!performSel("demo", currentEvent()))
{
doBody(currentEvent());
}
//
OBUtils.runOnOtherThreadDelayed(3, new OBUtils.RunLambda()
{
@Override
public void run () throws Exception
{
if (!statusChanged(timeStamp))
{
playAudioQueuedScene(currentEvent(), "REMIND", false);
}
}
});
}
catch (OBUserPressedBackException e)
{
stopAllAudio();
throw e;
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
public void doAudio (String scene) throws Exception
{
setReplayAudioScene(currentEvent(), "REPEAT");
playAudioQueuedScene(scene, "PROMPT", false);
}
public void doReminder () throws Exception
{
long stTime = statusTime;
waitForSecs(FIRST_REMINDER_DELAY);
doReminderWithStatusTime(stTime, true);
}
public void doReminderWithStatusTime (final long stTime, Boolean playAudio) throws Exception
{
if (statusChanged(stTime)) return;
//
List reminderAudio = (List<String>) ((Map<String, Object>) audioScenes.get(currentEvent())).get("REMINDER");
if (reminderAudio != null)
{
if (playAudio)
{
playAudioQueued(reminderAudio, true);
}
OBUtils.runOnOtherThreadDelayed(SECOND_REMINDER_DELAY, new OBUtils.RunLambda()
{
@Override
public void run () throws Exception
{
doReminderWithStatusTime(stTime, false);
}
});
}
}
public boolean isStatusIdle ()
{
return status() == STATUS_IDLE || status() == STATUS_WAITING_FOR_DRAG || status() == STATUS_AWAITING_CLICK || status() == STATUS_WAITING_FOR_TRACE || status() == STATUS_WAITING_FOR_TRACE;
}
public String getReminderKey ()
{
return this.currentEvent();
}
public void doReminderWithKey (final String key, final double reminderDelay, final RunLambdaWithTimestamp block) throws Exception
{
if (key == null) return;
//
if (!key.equals(getReminderKey())) return;
//
if (lastActionTakenTimestamp == -1) return;
//
double timestamp = lastActionTakenTimestamp;
double elapsed = getCurrentTimeDouble() - lastActionTakenTimestamp;
if (this.isStatusIdle() && elapsed > reminderDelay)
{
if (block != null)
{
block.run(timestamp);
}
}
else
{
OBUtils.runOnOtherThreadDelayed(1.0f, new OBUtils.RunLambda()
{
public void run () throws Exception
{
OBUtils.runOnOtherThread(new OBUtils.RunLambda()
{
public void run () throws Exception
{
doReminderWithKey(key, reminderDelay, block);
}
});
}
});
}
}
public void doMainXX () throws Exception
{
playAudioQueuedScene(currentEvent(), "DEMO", true);
//
doAudio(currentEvent());
//
setStatus(STATUS_AWAITING_CLICK);
}
@Override
public void setSceneXX (String scene)
{
MainActivity.log("OC_Generic_Event.setSceneXX");
//
ArrayList<OBControl> oldControls = new ArrayList<>(objectDict.values());
//
loadEvent(scene);
//
String masterEvent = eventAttributes.get("master");
if (masterEvent != null)
{
Map<String, String> currentEventAttributes = new HashMap<>(eventAttributes);
loadEvent(masterEvent);
//
eventAttributes = currentEventAttributes;
}
//
Boolean redraw = eventAttributes.get("redraw") != null && eventAttributes.get("redraw").equals("true");
if (redraw)
{
for (OBControl control : oldControls)
{
if (control == null) continue;
detachControl(control);
String id = (String) control.attributes().get("id");
if (id != null)
{
OBControl remainder = objectDict.get(id);
if (remainder != null && remainder.equals(control))
{
objectDict.remove(id);
}
}
}
//
for (OBControl control : filterControls(".*"))
{
Map attributes = control.attributes();
if (attributes != null)
{
String fit = (String) attributes.get("fit");
if (fit != null && fit.equals("fitwidth"))
{
float scale = bounds().width() / control.width();
PointF position = OC_Generic.copyPoint(control.position());
float originalHeight = control.height();
control.setScale(scale * control.scale());
float heightDiff = control.height() - originalHeight;
position.y += heightDiff / 2;
control.setPosition(position);
}
}
}
}
//
targets = filterControls(action_getObjectPrefix() + ".*");
//
// for (OBControl control : targets)
// {
// PointF originalPosition = new PointF(control.position().x, control.position().y);
// control.setProperty("originalPosition", originalPosition);
// }
//
currentDemoAudioIndex = 0;
//
OC_Generic.colourObjectsWithScheme(this);
//
action_prepareScene(scene, redraw);
}
public void action_prepareScene (String scene, Boolean redraw)
{
for (OBControl control : filterControls(".*"))
{
control.setProperty("originalPosition", OC_Generic.copyPoint(control.getWorldPosition()));
//control.setProperty("originalPosition", OC_Generic.copyPoint(control.position()));
//
if (OBPath.class.isInstance(control))
{
OBPath path = (OBPath) control;
// PointF position = path.getWorldPosition();
PointF position = path.position();
path.sizeToBoundingBoxIncludingStroke();
path.setPosition(position);
}
}
}
public void action_playNextDemoSentence (Boolean waitAudio) throws Exception
{
playAudioQueuedSceneIndex(currentEvent(), "DEMO", currentDemoAudioIndex, waitAudio);
currentDemoAudioIndex++;
waitForSecs(0.05);
}
public PointF closestDestinationForPosition (PointF origin, List<PointF> destinations)
{
PointF bestMatch = origin;
float bestDistance = -1;
for (PointF destination : destinations)
{
float distance = PointDistance(origin, destination);
if (bestDistance == -1 || distance < bestDistance)
{
bestMatch = destination;
bestDistance = distance;
}
}
return bestMatch;
}
public PointF getInboundPosition (OBControl object, PointF position, OBControl container, float margin)
{
PointF result = position;
float marginX = container.width() * margin;
float marginY = container.height() * margin;
float width = object.width();
float height = object.height();
float left = result.x - width / 2 - marginX;
float right = result.x + width / 2 + marginX;
float top = result.y - height / 2 - marginY;
float bottom = result.y + height / 2 + marginY;
if (left < container.left())
{
result.x += container.left() - left;
}
if (right > container.right())
{
result.x -= right - container.right();
}
if (top < container.top())
{
result.y += container.top() - top;
}
if (bottom > container.bottom())
{
result.y -= bottom - container.bottom();
}
return result;
}
public void action_moveObjectsToPosition (Map<String, PointF> positions, OBControl container, float time, boolean keepInBound)
{
Set<String> keys = positions.keySet();
// play drop sound
for (String key : keys)
{
OBControl control = objectDict.get(key);
PointF relativePosition = positions.get(key);
PointF destination = OB_Maths.locationForRect(relativePosition, container.frame());
if (keepInBound)
{
destination = getInboundPosition(control, destination, container, 0.03f);
}
control.moveToPoint(destination, time, false);
control.setProperty("currentPosition", OC_Generic.copyPoint(destination));
}
}
public void action_repositionObjectsInContainer (OBControl container, boolean keepInBound, OBControl addedObject)
{
List<OBControl> objectsContained = (List<OBControl>) container.propertyValue("objects");
int totalObjects = objectsContained.size();
//
int totalLines = 1;
if (eventAttributes.get("lines") != null)
{
totalLines = Integer.parseInt(eventAttributes.get("lines"));
}
List positions = new ArrayList();
for (int i = 0; i < totalObjects; i++)
{
float x = (float) (i + 1) / (totalObjects + 1);
float y = 0.5f;
if (totalLines > 1) y = (float) (i + 1) / (totalObjects + 1);
positions.add(new PointF(x, y));
}
//
Map<String, PointF> repositioning = new HashMap();
//
if (addedObject != null)
{
PointF destination = closestDestinationForPosition(relativePointInRectForLocation(addedObject.position(), container.frame), positions);
positions.remove(destination);
String key = (String) addedObject.attributes().get("id");
//
repositioning.put(key, OC_Generic.copyPoint(destination));
}
//
for (OBControl control : objectsContained)
{
if (addedObject == control) continue;
PointF destination = closestDestinationForPosition(relativePointInRectForLocation(control.position(), container.frame), positions);
positions.remove(destination);
String key = (String) addedObject.attributes().get("id");
//
repositioning.put(key, OC_Generic.copyPoint(destination));
}
action_moveObjectsToPosition(repositioning, container, 0.2f, keepInBound);
}
public void action_removeObjectFromContainers (OBControl object, boolean keepInBound)
{
List<OBControl> containers = filterControls("box.*");
for (OBControl container : containers)
{
List<OBControl> containedObjects = (List<OBControl>) container.propertyValue("objects");
if (containedObjects != null && containedObjects.contains(object))
{
containedObjects.remove(object);
container.setProperty("objects", containedObjects);
action_repositionObjectsInContainer(container, keepInBound, null);
}
}
}
public void moveObjectToPoint (OBControl control, PointF position, float time, boolean withSound) throws Exception
{
if (withSound) playSfxAudio("dropObject", false);
control.moveToPoint(position, time, false);
control.setProperty("currentPosition", OC_Generic.copyPoint(position));
}
public void moveObjectToOriginalPosition (OBControl control, boolean withSound, boolean keepInBound) throws Exception
{
action_removeObjectFromContainers(control, keepInBound);
PointF originalPosition = (PointF) control.propertyValue("originalPosition");
moveObjectToPoint(control, originalPosition, 0.3f, withSound);
}
public boolean action_addObjectAndRearrangeContainer (OBControl object, OBControl container, int maxObjectsPerContainer, boolean keepInBound) throws Exception
{
List<OBControl> objectsContained = (List<OBControl>) container.propertyValue("objects");
if (objectsContained == null)
{
objectsContained = new ArrayList<>();
}
int objectCount = (int) objectsContained.size();
if (objectsContained.contains(object))
{
moveObjectToOriginalPosition(object, true, keepInBound);
}
else
{
if (objectCount == maxObjectsPerContainer)
{
moveObjectToOriginalPosition(object, true, keepInBound);
}
else
{
action_removeObjectFromContainers(object, keepInBound);
objectsContained.add(object);
container.setProperty("objects", objectsContained);
//
action_repositionObjectsInContainer(container, keepInBound, object);
return true;
}
}
return false;
}
public void action_moveObjectToOriginalPosition (OBControl control, Boolean wait)
{
if (returnToOriginalPositionAnimation != null)
{
returnToOriginalPositionAnimation.flags = OBAnimationGroup.ANIM_CANCEL;
}
OBAnim anim = OBAnim.moveAnim((PointF) control.propertyValue("originalPosition"), control);
returnToOriginalPositionAnimation = OBAnimationGroup.runAnims(Arrays.asList(anim), 0.3, wait, OBAnim.ANIM_EASE_IN_EASE_OUT, this);
}
public void action_moveObjectIntoContainer (OBControl control, OBControl container)
{
List<OBControl> contained = (List<OBControl>) container.propertyValue("contained");
if (contained == null) contained = new ArrayList<OBControl>();
//
if (contained.contains(control))
{
action_moveObjectToOriginalPosition(control, false);
}
else
{
contained.add(control);
container.setProperty("contained", contained);
//
List<OBAnim> animations = new ArrayList<OBAnim>();
// horizontal displacement
float deltaH = container.width() / (contained.size() + 1);
for (int i = 0; i < contained.size(); i++)
{
PointF newPosition = OC_Generic.copyPoint(container.position());
newPosition.x = container.left() + deltaH * (i + 1);
OBControl placedObject = contained.get(i);
animations.add(OBAnim.moveAnim(newPosition, placedObject));
}
OBAnimationGroup.runAnims(animations, 0.15, true, OBAnim.ANIM_EASE_IN_EASE_OUT, this);
}
}
public void action_animatePlatform (OBControl platform, boolean wait) throws Exception
{
String platformName = (String) platform.attributes().get("id");
String platformNumber = platformName.split("_")[1];
List<OBControl> controls = filterControls(".*_" + platformNumber + "_.*");
//
List<OBAnim> list_animMove1 = new ArrayList<OBAnim>();
List<OBAnim> list_animMove2 = new ArrayList<OBAnim>();
//
for (OBControl item : controls)
{
PointF startPosition = new PointF();
startPosition.set(item.position());
//
PointF endPosition = new PointF();
endPosition.set(startPosition);
endPosition.y -= 1.25 * item.height();
//
list_animMove1.add(OBAnim.moveAnim(endPosition, item));
list_animMove1.add(OBAnim.rotationAnim((float) Math.toRadians(-180.0f), item));
list_animMove2.add(OBAnim.moveAnim(startPosition, item));
list_animMove1.add(OBAnim.rotationAnim((float) Math.toRadians(-360.0f), item));
// OBAnim anim_move1 = OBAnim.moveAnim(endPosition, item);
// OBAnim anim_move2 = OBAnim.moveAnim(startPosition, item);
// OBAnim anim_rotate1 = OBAnim.rotationAnim((float) Math.toRadians(-180.0f), item);
// OBAnim anim_rotate2 = OBAnim.rotationAnim((float) Math.toRadians(-360.0f), item);
// OBAnimationGroup.chainAnimations(Arrays.asList(Arrays.asList(anim_move1,anim_rotate1),Arrays.asList(anim_move2,anim_rotate2)), Arrays.asList(0.4f,0.4f), false, Arrays.asList(OBAnim.ANIM_EASE_IN, OBAnim.ANIM_EASE_OUT), 1, this);
// waitForSecs(0.05);
}
OBAnimationGroup og = new OBAnimationGroup();
og.chainAnimations(Arrays.asList(list_animMove1, list_animMove2), Arrays.asList(0.4f, 0.4f), wait, Arrays.asList(OBAnim.ANIM_EASE_IN, OBAnim.ANIM_EASE_OUT), 1, this);
}
public OBControl action_getCorrectAnswer ()
{
String correctString = action_getObjectPrefix() + "_" + eventAttributes.get("correctAnswer");
return objectDict.get(correctString);
}
public String action_getObjectPrefix ()
{
return "number";
}
public String action_getContainerPrefix ()
{
return "box";
}
public String action_getScenesProperty ()
{
return "scenes";
}
public OBLabel action_createLabelForControl (OBControl control)
{
return action_createLabelForControl(control, 1.0f, false);
}
public OBLabel action_createLabelForControl (OBControl control, float finalResizeFactor)
{
return action_createLabelForControl(control, finalResizeFactor, true);
}
public OBLabel action_createLabelForControl (OBControl control, float finalResizeFactor, Boolean insertIntoGroup)
{
return OC_Generic.action_createLabelForControl(control, finalResizeFactor, insertIntoGroup, this);
}
public OBLabel action_createLabelForControl (OBControl control, String text, int colour, float finalResizeFactor)
{
control.setProperty("text", text);
OBLabel result = OC_Generic.action_createLabelForControl(control, finalResizeFactor, false, this);
result.setColour(colour);
return result;
}
public List breakdownLabel (OBLabel mLabel)
{
List result = new ArrayList<>();
String text = mLabel.text();
Typeface tf = mLabel.typeface();
float size = mLabel.fontSize();
int totalLength = 0;
//
for (int i = 0; i < mLabel.text().length(); i++)
{
totalLength += 1;
String subtx = text.substring(0, totalLength);
RectF r = OC_Wordcontroller.boundingBoxForText(subtx, tf, size);
float f = r.width();
//
OBLabel l = new OBLabel(mLabel.text().substring(i, i + 1), tf, size);
l.sizeToBoundingBox();
l.setZPosition(mLabel.zPosition() + 0.01f);
l.setColour(mLabel.colour());
l.sizeToBoundingBox();
l.setPosition(mLabel.position());
l.setRight(mLabel.left() + f);
l.setProperty("original_position", l.getWorldPosition());
result.add(l);
}
return result;
}
// Finger and Touch functions
public OBControl findTarget (PointF pt)
{
return finger(-1, 2, targets, pt, true);
}
public Boolean audioSceneExists (String audioScene)
{
if (audioScenes == null) return false;
//
Map<String, List<String>> sc = (Map<String, List<String>>) audioScenes.get(currentEvent());
//
if (sc == null) return false;
//
List<Object> arr = (List<Object>) (Object) sc.get(audioScene);
return arr != null;
}
public List<Object> audioForScene (String audioScene)
{
if (audioScenes == null) return null;
//
Map<String, List<String>> sc = (Map<String, List<String>>) audioScenes.get(currentEvent());
//
if (sc == null) return null;
//
return (List<Object>) (Object) sc.get(audioScene);
}
// Miscelaneous Functions
public OBConditionLock playSceneAudio (String scene, Boolean wait) throws Exception
{
OBConditionLock lock = playAudioQueuedScene(currentEvent(), scene, wait);
if (!wait) waitForSecs(0.01);
return lock;
}
public void playSceneAudioIndex (String scene, int index, Boolean wait) throws Exception
{
playAudioQueuedSceneIndex(currentEvent(), scene, index, wait);
if (!wait) waitForSecs(0.1);
}
// CHECKING functions
public void saveStatusClearReplayAudioSetChecking ()
{
savedStatus = status();
setStatus(STATUS_CHECKING);
//
savedReplayAudio = _replayAudio;
setReplayAudio(null);
}
public long revertStatusAndReplayAudio ()
{
long time = setStatus(savedStatus);
setReplayAudio(savedReplayAudio);
return time;
}
public void setReplayAudioScene (String scene, String event)
{
Map<String, List<String>> sc = (Map<String, List<String>>) audioScenes.get(scene);
if (sc != null)
{
List<Object> arr = (List<Object>) (Object) sc.get(event); //yuk!
if (arr != null)
{
setReplayAudio(arr);
savedReplayAudio = arr;
}
}
}
public void physics_verticalDrop (List<OBControl> objects, float maxDelta, String soundEffectOnCollision)
{
try
{
Boolean floorCollision = false;
Boolean atRest = false;
float g = 9.8f * 200;
double startTime = OC_Generic.currentTime();
float initialSpeed = 0;
//
for (OBControl control : objects)
{
control.setProperty("initial", control.getWorldPosition());
}
//
while (!atRest)
{
double t = OC_Generic.currentTime() - startTime;
//
float deltaY = (float) (initialSpeed * t + 0.5f * g * t * t);
//
if (!floorCollision && deltaY >= maxDelta)
{
playSfxAudio(soundEffectOnCollision, false);
startTime = OC_Generic.currentTime();
initialSpeed = (float) (-0.3f * g * t);
floorCollision = true;
//
for (OBControl control : objects)
{
control.setProperty("initial", control.getWorldPosition());
}
deltaY = maxDelta;
}
else if (floorCollision && deltaY >= 0)
{
atRest = true;
deltaY = 0;
}
//
if (atRest)
{
lockScreen();
//
for (OBControl control : objects)
{
PointF originalPosition = OC_Generic.copyPoint((PointF) control.propertyValue("originalPosition"));
control.setPosition(originalPosition);
}
unlockScreen();
}
else
{
lockScreen();
for (OBControl control : objects)
{
PointF initial = OC_Generic.copyPoint((PointF) control.propertyValue("initial"));
initial.y += deltaY;
control.setPosition(initial);
}
unlockScreen();
}
//
waitForSecs(0.01);
}
}
catch (Exception e)
{
MainActivity.log("OC_Generic_Event:physics_verticalDrop:exception caught");
e.printStackTrace();
}
}
public void physics_bounceObjectsWithPlacements (List<OBControl> objects, List<OBControl> placements, String soundEffectOnFloorCollision)
{
try
{
float g = 9.8f * 200;
float floorHeight = bounds().height() * 0.95f;
int totalCount = objects.size();
//
for (int i = 1; i <= totalCount; i++)
{
OBControl control = objects.get(i - 1);
control.setShouldTexturise(true);
//
OBControl placement = placements.get(i - 1);
PointF destination = placement.getWorldPosition();
PointF initialPosition = control.getWorldPosition();
//
float distanceX = destination.x - initialPosition.x;
PointF midway = new PointF(initialPosition.x + distanceX * 0.75f, floorHeight);
//
float height = Math.abs(floorHeight - initialPosition.y);
float flightHeight = 1.2f * height;
float flightTime_phase1 = (float) Math.sqrt((2 * (flightHeight - height)) / g);
float freeFallTime = (float) Math.sqrt((2 * flightHeight) / g);
float totalTime_phase1 = flightTime_phase1 + freeFallTime;
//
float initialSpeedX_phase1 = (midway.x - initialPosition.x) / totalTime_phase1;
float initialSpeedY_phase1 = (float) Math.sqrt((flightHeight - height) * 2 * g);
PointF phase1 = new PointF(initialSpeedX_phase1, initialSpeedY_phase1);
//
float height_phase2 = Math.abs(floorHeight - destination.y);
float initialSpeedY_phase2 = (float) Math.sqrt(2 * g * height_phase2);
float flightTime_phase2 = initialSpeedY_phase2 / g;
float initalSpeedX_phase2 = (destination.x - midway.x) / flightTime_phase2;
PointF phase2 = new PointF(initalSpeedX_phase2, initialSpeedY_phase2);
//
control.setProperty("phase1", OC_Generic.copyPoint(phase1));
control.setProperty("phase2", OC_Generic.copyPoint(phase2));
control.setProperty("startTime", OC_Generic.currentTime() + i * 0.1);
control.setProperty("floorCollision", false);
control.setProperty("atRest", false);
control.setProperty("initialPosition", OC_Generic.copyPoint(initialPosition));
control.setProperty("midway", OC_Generic.copyPoint(midway));
control.setProperty("destination", OC_Generic.copyPoint(destination));
//
Map<String, Object> sfx_map = (Map<String, Object>) audioScenes.get("sfx");
List<String> sfx_array = (List<String>) sfx_map.get(soundEffectOnFloorCollision);
String soundEffect = sfx_array.get(0);
// MainActivity.log("OC_Generic_Event:physics:bounceObjectsWithPlacements:soundEffect:" + soundEffect);
OBAudioManager.audioManager.prepareForChannel(soundEffect, String.format("bounce_%d", i));
}
//
boolean animationComplete = false;
//
while (!animationComplete)
{
lockScreen();
for (int i = 1; i <= totalCount; i++)
{
OBControl control = objects.get(i - 1);
double startTime = (double) control.propertyValue("startTime");
boolean floorCollision = (boolean) control.propertyValue("floorCollision");
boolean atRest = (boolean) control.propertyValue("atRest");
PointF midway = (PointF) control.propertyValue("midway");
//
double t = OC_Generic.currentTime() - startTime;
//
if (t < 0) continue;
if (atRest) continue;
//
PointF newPosition;
if (!floorCollision)
{
PointF phase1 = (PointF) control.propertyValue("phase1");
PointF initialPosition = (PointF) control.propertyValue("initialPosition");
//
float newX = (float) (initialPosition.x + phase1.x * t);
float newY = (float) (initialPosition.y + 0.5f * g * t * t - phase1.y * t);
newPosition = new PointF(newX, newY);
//
if (newPosition.y > floorHeight)
{
control.setProperty("startTime", OC_Generic.currentTime());
control.setProperty("floorCollision", true);
newPosition = OC_Generic.copyPoint(midway);
//
OBGeneralAudioPlayer player = OBAudioManager.audioManager.playerForChannel(String.format("bounce_%d", i));
player.play();
}
}
else
{
PointF phase2 = (PointF) control.propertyValue("phase2");
PointF destination = (PointF) control.propertyValue("destination");
float newX = (float) (midway.x + phase2.x * t);
float newY = (float) (midway.y - phase2.y * t + 0.5f * g * t * t);
newPosition = new PointF(newX, newY);
//
float distanceToTarget = Math.abs(newPosition.y - destination.y);
if (distanceToTarget <= 2)
{
control.setProperty("atRest", true);
newPosition = OC_Generic.copyPoint(destination);
//
animationComplete = true;
for (OBControl otherControl : objects)
{
animationComplete = animationComplete && (boolean) otherControl.propertyValue("atRest");
}
}
}
//
control.setPosition(OC_Generic.copyPoint(newPosition));
}
unlockScreen();
//
waitForSecs(0.01f);
}
}
catch (Exception e)
{
MainActivity.log("OC_Generic_Event:physics_bounce:exception caught");
e.printStackTrace();
}
}
public void action_showShadow (OBControl control)
{
float shadowRadius = 5;
List<OBControl> members = new ArrayList<>();
members.add(control);
//
lockScreen();
//
OBGroup shadowGroup = new OBGroup(members);
shadowGroup.outdent(shadowRadius);
attachControl(shadowGroup);
control.setProperty("shadowGroup", shadowGroup);
control.setShadow(shadowRadius, 1.0f, shadowRadius / 2, shadowRadius / 2, Color.DKGRAY);
shadowGroup.setShouldTexturise(true);
//
unlockScreen();
}
public void action_removeShadow (OBControl control)
{
lockScreen();
//
OBGroup shadowGroup = (OBGroup) control.propertyValue("shadowGroup");
if (shadowGroup != null)
{
shadowGroup.removeMember(control);
attachControl(control);
detachControl(shadowGroup);
control.setShadow(0, 0, 0, 0, Color.BLACK);
}
//
unlockScreen();
}
public List<OBLabel> action_addLabelsToObjects (String pattern, float finalResizeFactor, boolean insertIntoGroup)
{
List<OBControl> numbers = sortedFilteredControls(pattern);
List<OBLabel> createdLabels = new ArrayList<>();
float smallestFontSize = 1000000000;
//
for (OBControl number : numbers)
{
OBLabel label = action_createLabelForControl(number, finalResizeFactor, insertIntoGroup);
if (label.fontSize() < smallestFontSize) smallestFontSize = label.fontSize();
//
createdLabels.add(label);
}
//
for (OBLabel label : createdLabels)
{
label.setFontSize(smallestFontSize);
label.sizeToBoundingBox();
//
label.setProperty("originalPosition", OC_Generic.copyPoint(label.getWorldPosition()));
if (!insertIntoGroup)
{
attachControl(label);
}
}
return createdLabels;
}
public PointF getRelativePositionForObject (OBControl control)
{
PointF position = control.position();
OBControl parent = control.parent;
RectF dimensions;
if (parent != null) dimensions = parent.bounds();
else dimensions = boundsf();
//
PointF relativePosition = new PointF(position.x / dimensions.width(), position.y / dimensions.height());
return relativePosition;
}
public PointF getAbsoluteOffsetWithParent (OBControl control)
{
PointF relativePosition = getRelativePositionForObject(control);
PointF relativeOffset = OB_Maths.DiffPoints(new PointF(0.5f, 0.5f), relativePosition);
RectF dimensions = control.parent.bounds();
PointF absoluteOffset = new PointF(relativeOffset.x * dimensions.width(), relativeOffset.y * dimensions.height());
return absoluteOffset;
}
public PointF action_getMiddleOfGroup (String pattern)
{
PointF average = new PointF(0f, 0f);
List<OBControl> controls = filterControls(pattern);
for (OBControl control : controls)
{
average = OB_Maths.AddPoints(control.getWorldPosition(), average);
}
average = new PointF(average.x / controls.size(), average.y / controls.size());
return average;
}
public int randomNumberBetween(int min, int max)
{
return randomInt(min, max);
}
public double getCurrentTimeDouble()
{
return (new Date().getTime() / 1000.0);
}
@Override
public void replayAudio ()
{
updateLastActionTakenTimeStamp();
//
super.replayAudio();
}
public void checkAndUpdateFinale()
{
String finaleScene = events.size() > 0 ? String.format("finale%s", events.get(events.size() - 1)) : "";
if (audioScenes.get(finaleScene) != null && ((Map<String,Object>)audioScenes.get(finaleScene)).get("FINAL") != null)
{
audioScenes.put("finale", audioScenes.get(finaleScene));
//
if (!events.contains("finale"))
{
events = new ArrayList<>(events);
events.add("finale");
}
}
else if (audioScenes.get("finale") != null && !events.contains("finale"))
{
events = new ArrayList<>(events);
events.add("finale");
}
}
public void setScenefinale()
{
// do nothing
}
public void demofinale() throws Exception
{
setStatus(STATUS_DOING_DEMO);
//
playSceneAudio("FINAL", true);
waitForSecs(0.3);
//
nextScene();
}
}
| 35.883574 | 241 | 0.56264 |
19346475a4427249dd6c1666b28bb04d6c7f0cc2 | 1,168 | package ru.job4j.map;
import java.util.Calendar;
import java.util.Objects;
/**
* Класс, в котором переопределены оба метода и equals() и hashCode()
*/
public class UserHashAndEquals {
private String name;
private int children;
private Calendar birthday;
public UserHashAndEquals(String name, int children, Calendar birthday) {
this.name = name;
this.children = children;
this.birthday = birthday;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UserHashAndEquals that = (UserHashAndEquals) o;
return children == that.children
&& Objects.equals(name, that.name)
&& Objects.equals(birthday, that.birthday);
}
@Override
public int hashCode() {
return Objects.hash(name, children, birthday);
}
@Override
public String toString() {
return "UserHashAndEquals{"
+ "name='" + name + '\''
+ ", children=" + children
+ '}';
}
}
| 24.333333 | 76 | 0.561644 |
b54dbf6c9b42d9eefcd94f82bfb6e52a708a5c05 | 5,923 | //
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.bstek.urule.runtime.builtinaction;
import com.bstek.urule.Utils;
import com.bstek.urule.model.library.action.annotation.ActionBean;
import com.bstek.urule.model.library.action.annotation.ActionMethod;
import com.bstek.urule.model.library.action.annotation.ActionMethodParameter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
@ActionBean(
name = "List集合"
)
public class ListAction {
public ListAction() {
}
@ActionMethod(
name = "求List大小"
)
@ActionMethodParameter(
names = {"集合对象"}
)
public int size(List<Object> var1) {
return var1.size();
}
@ActionMethod(
name = "求List中所有的数字最大值"
)
@ActionMethodParameter(
names = {"包含所有数字的集合对象"}
)
public Number max(List<Object> var1) {
if (var1.size() == 0) {
return null;
} else {
double var2 = Utils.toBigDecimal(var1.get(0)).doubleValue();
BigDecimal var6;
for(Iterator var4 = var1.iterator(); var4.hasNext(); var2 = Math.max(var2, var6.doubleValue())) {
Object var5 = var4.next();
var6 = Utils.toBigDecimal(var5);
}
return var2;
}
}
@ActionMethod(
name = "求List中所有的数字最小值"
)
@ActionMethodParameter(
names = {"包含所有数字的集合对象"}
)
public Number min(List<Object> var1) {
if (var1.size() == 0) {
return null;
} else {
double var2 = Utils.toBigDecimal(var1.get(0)).doubleValue();
BigDecimal var6;
for(Iterator var4 = var1.iterator(); var4.hasNext(); var2 = Math.min(var2, var6.doubleValue())) {
Object var5 = var4.next();
var6 = Utils.toBigDecimal(var5);
}
return var2;
}
}
@ActionMethod(
name = "向List中添加对象"
)
@ActionMethodParameter(
names = {"集合对象", "要添加的对象"}
)
public void add(List<Object> var1, Object var2) {
var1.add(var2);
}
@ActionMethod(
name = "集合排序"
)
@ActionMethodParameter(
names = {"集合对象", "属性名", "排序方式"}
)
public List<Object> sort(List<Object> var1, final String var2, String var3) {
final boolean var4 = this.a(var3);
Collections.sort(var1, new Comparator<Object>() {
public int compare(Object var1, Object var2x) {
int var3 = 0;
String[] var4x = var2.split(",");
String[] var5 = var4x;
int var6 = var4x.length;
for(int var7 = 0; var7 < var6; ++var7) {
String var8 = var5[var7];
var3 = this.a(var8, var4, var1, var2x);
if (var3 != 0) {
break;
}
}
return var3;
}
private int a(String var1, boolean var2x, Object var3, Object var4x) {
Object var5 = Utils.getObjectProperty(var3, var1);
Object var6 = Utils.getObjectProperty(var4x, var1);
if (var5 == null) {
return var2x ? 0 : 1;
} else if (var6 == null) {
return var2x ? 1 : 0;
} else if (var5 instanceof String) {
return var2x ? ((String)var5).compareTo(var6.toString()) : ((String)var6).compareTo(var5.toString());
} else if (var5 instanceof Date) {
return var2x ? ((Date)var5).compareTo((Date)var6) : ((Date)var6).compareTo((Date)var5);
} else if (var5 instanceof Number) {
BigDecimal var7 = Utils.toBigDecimal(var5);
BigDecimal var8 = Utils.toBigDecimal(var6);
return var2x ? var7.compareTo(var8) : var8.compareTo(var7);
} else {
return 0;
}
}
});
return var1;
}
private boolean a(String var1) {
if (var1 == null) {
return true;
} else {
return var1.equals("1") || var1.equals("true") || var1.equals("正序");
}
}
@ActionMethod(
name = "抽取集合属性"
)
@ActionMethodParameter(
names = {"集合对象", "属性名"}
)
public List<Object> retrive(List<Object> var1, String var2) {
ArrayList var3 = new ArrayList();
if (var1 == null) {
return var3;
} else {
Iterator var4 = var1.iterator();
while(var4.hasNext()) {
Object var5 = var4.next();
Object var6 = Utils.getObjectProperty(var5, var2);
var3.add(var6);
}
return var3;
}
}
@ActionMethod(
name = "从List中删除对象"
)
@ActionMethodParameter(
names = {"集合对象", "要删除的对象"}
)
public void remove(List<Object> var1, Object var2) {
var1.remove(var2);
}
@ActionMethod(
name = "指定对象是否存在"
)
@ActionMethodParameter(
names = {"集合对象", "要判断的对象"}
)
public boolean contains(List<Object> var1, Object var2) {
return var1.contains(var2);
}
@ActionMethod(
name = "List是否为空"
)
@ActionMethodParameter(
names = {"集合对象"}
)
public boolean isEmpty(List<Object> var1) {
return var1.isEmpty();
}
@ActionMethod(
name = "实例化一个ArrayList"
)
@ActionMethodParameter(
names = {}
)
public ArrayList<Object> newArrayListInstance() {
return new ArrayList();
}
}
| 28.07109 | 121 | 0.517474 |
eddb8c95c03be387845c8f291686af9266340212 | 6,162 | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See License.txt in the repository root.
package com.microsoft.tfs.client.common.framework.resources.filter;
import org.eclipse.core.resources.IResource;
import com.microsoft.tfs.client.common.framework.resources.compatibility.LinkedResources;
import com.microsoft.tfs.util.Check;
/**
* <p>
* {@link ResourceFilters}s is a utility class that exposes a number of static
* {@link ResourceFilter}s. Each of the available {@link ResourceFilter}s is a
* stateless, singleton instance obtained by referencing a public static field
* of this class.
* </p>
*
* <p>
* The {@link ResourceFilter}s available through this class cover many of the
* general implementations of {@link ResourceFilter} that only depend on the
* resources API.
* </p>
*
* <p>
* Clients will often combine together multiple {@link ResourceFilter}s from
* this class (as well as custom {@link ResourceFilter}s) by using the
* {@link CompositeResourceFilter} class.
* </p>
*
* @see ResourceFilter
* @see CompositeResourceFilter
*/
public class ResourceFilters {
/**
* <p>
* Returns a new {@link ResourceFilter} that is the inverse of the specified
* filter. If the specified filter would reject a resource, the inverse
* filter will accept that resource.
* </p>
*
* <p>
* Precisely, the inverse filter will return the inverse
* {@link ResourceFilterResult} for any resource that the input filter
* returns. The inverse result mapping is defined by the
* {@link ResourceFilterResult#getInverse()} method.
* </p>
*
* <p>
* Warning: this simply inverts the results. If your filter is particularly
* complex (for example, takes a RepositoryUnavailablePolicy), then this may
* lead to incorrect results.
* </p>
*
* @param input
* the {@link ResourceFilter} to get the inverse of (must not be
* <code>null</code>)
* @return a new resource filter that is the inverse of the specified filter
* (must not be <code>null</code>)
*/
public static ResourceFilter getInverse(final ResourceFilter input) {
Check.notNull(input, "input"); //$NON-NLS-1$
return new ResourceFilter() {
@Override
public ResourceFilterResult filter(final IResource resource, final int flags) {
return input.filter(resource, flags).getInverse();
}
};
}
/**
* An {@link ResourceFilter} that filters out derived resources (resources
* that return <code>true</code> from {@link IResource#isDerived()}).
*/
public static final ResourceFilter DERIVED_RESOURCES_FILTER = new DerivedResourcesFilter();
/**
* An {@link ResourceFilter} that filters out team private resources
* (resources that return <code>true</code> from
* {@link IResource#isTeamPrivateMember()}).
*/
public static final ResourceFilter TEAM_PRIVATE_RESOURCES_FILTER = new TeamPrivateResourcesFilter();
/**
* <p>
* An {@link ResourceFilter} that filters out linked resources.
* </p>
*
* <p>
* This filter respects the
* {@link ResourceFilter#FILTER_FLAG_TREE_OPTIMIZATION} flag. If this flag
* is passed, a more efficient check for linked resources is performed. The
* more efficient check will only detect directly linked resources, not
* resources that are the descendants of links.
* </p>
*/
public static final ResourceFilter LINKED_RESOURCES_FILTER = new LinkedResourcesFilter();
/**
* An {@link ResourceFilter} that filters out non-file resources (resources
* that do not return {@link IResource#FILE} from
* {@link IResource#getType()}).
*/
public static final ResourceFilter NON_FILE_RESOURCES_FILTER = new ResourceTypeFilter(IResource.FILE);
/**
* An {@link ResourceFilter} that filters out non-folder resources
* (resources that do not return {@link IResource#FOLDER} from
* {@link IResource#getType()}).
*/
public static final ResourceFilter NON_FOLDER_RESOURCES_FILTER = new ResourceTypeFilter(IResource.FOLDER);
/**
* An {@link ResourceFilter} that filters out non-project resources
* (resources that do not return {@link IResource#PROJECT} from
* {@link IResource#getType()}).
*/
public static final ResourceFilter NON_PROJECT_RESOURCES_FILTER = new ResourceTypeFilter(IResource.PROJECT);
/**
* An {@link ResourceFilter} that filters out non-accessible resources
* (resources that return <code>false</code> from
* {@link IResource#isAccessible()}).
*/
public static final ResourceFilter NON_ACCESSIBLE_RESOURCES_FILTER = new NonAccessibleResourcesFilter();
private static class NonAccessibleResourcesFilter extends ResourceFilter {
@Override
public ResourceFilterResult filter(final IResource resource, final int flags) {
return !resource.isAccessible() ? REJECT_AND_REJECT_CHILDREN : ACCEPT;
}
}
private static class DerivedResourcesFilter extends ResourceFilter {
@Override
public ResourceFilterResult filter(final IResource resource, final int flags) {
return resource.isDerived() ? REJECT_AND_REJECT_CHILDREN : ACCEPT;
}
}
private static class TeamPrivateResourcesFilter extends ResourceFilter {
@Override
public ResourceFilterResult filter(final IResource resource, final int flags) {
return resource.isTeamPrivateMember() ? REJECT_AND_REJECT_CHILDREN : ACCEPT;
}
}
private static class LinkedResourcesFilter extends ResourceFilter {
@Override
public ResourceFilterResult filter(final IResource resource, final int flags) {
if ((flags & FILTER_FLAG_TREE_OPTIMIZATION) != 0) {
return resource.isLinked() ? REJECT_AND_REJECT_CHILDREN : ACCEPT;
} else {
return LinkedResources.isLinked(resource) ? REJECT_AND_REJECT_CHILDREN : ACCEPT;
}
}
}
}
| 38.5125 | 112 | 0.682895 |
80bb415853ac3d9bf7192a67530941fe14eb7611 | 3,367 | package org.javers.repository.sql.repositories;
import org.javers.common.exception.JaversException;
import org.javers.common.exception.JaversExceptionCode;
import org.javers.core.commit.CommitId;
import org.javers.core.commit.CommitMetadata;
import org.javers.core.json.typeadapter.util.UtilTypeCoreAdapters;
import org.javers.repository.sql.schema.SchemaNameAware;
import org.javers.repository.sql.schema.TableNameProvider;
import org.javers.repository.sql.session.Session;
import org.polyjdbc.core.type.Timestamp;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.Optional;
import static org.javers.repository.sql.schema.FixedSchemaFactory.*;
/**
* @author pawel szymczyk
*/
public class CommitMetadataRepository extends SchemaNameAware {
public CommitMetadataRepository(TableNameProvider tableNameProvider) {
super(tableNameProvider);
}
public long save(String author, Map<String, String> properties, LocalDateTime date, Instant dateInstant, CommitId commitId, Session session) {
if (isCommitPersisted(commitId, session)) {
throw new JaversException(JaversExceptionCode.CANT_SAVE_ALREADY_PERSISTED_COMMIT, commitId);
}
long commitPk = session.insert("Commit")
.into(getCommitTableNameWithSchema())
.value(COMMIT_AUTHOR, author)
.value(COMMIT_COMMIT_DATE, date)
.value(COMMIT_COMMIT_DATE_INSTANT, UtilTypeCoreAdapters.serialize(dateInstant))
.value(COMMIT_COMMIT_ID, commitId.valueAsNumber())
.sequence(COMMIT_PK, getCommitPkSeqWithSchema())
.executeAndGetSequence();
insertCommitProperties(commitPk, properties, session);
return commitPk;
}
private void insertCommitProperties(long commitPk, Map<String, String> properties, Session session) {
for (Map.Entry<String, String> property : properties.entrySet()) {
session.insert("CommitProperty")
.into(getCommitPropertyTableNameWithSchema())
.value(COMMIT_PROPERTY_COMMIT_FK, commitPk)
.value(COMMIT_PROPERTY_NAME, property.getKey())
.value(COMMIT_PROPERTY_VALUE, property.getValue())
.execute();
}
}
boolean isCommitPersisted(CommitId commitId, Session session) {
long count = session.select("count(*)")
.from(getCommitTableNameWithSchema())
.and(COMMIT_COMMIT_ID, commitId.valueAsNumber())
.queryForLong("isCommitPersisted");
return count > 0;
}
private Timestamp toTimestamp(LocalDateTime commitMetadata) {
return new Timestamp(UtilTypeCoreAdapters.toUtilDate(commitMetadata));
}
public CommitId getCommitHeadId(Session session) {
Optional<BigDecimal> maxCommitId = selectMaxCommitId(session);
return maxCommitId.map(max -> CommitId.valueOf(maxCommitId.get()))
.orElse(null);
}
private Optional<BigDecimal> selectMaxCommitId(Session session) {
return session.select("MAX(" + COMMIT_COMMIT_ID + ")")
.from(getCommitTableNameWithSchema())
.queryForOptionalBigDecimal("max CommitId");
}
}
| 39.151163 | 146 | 0.697951 |
8a25c79deb07ce6d7027b1954329d6aac18fe87d | 7,830 | package com.robert.image.compose.demo;
import android.app.Activity;
import android.content.Context;
import android.graphics.*;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
/**
* Created by michael on 13-12-25.
*/
public class HSVActivity extends Activity {
private ImageView mImage;
private EditText mH;
private EditText mS;
private EditText mV;
private View make;
private int startColor = 0xff27b52a;
private int endColor = 0xff1ca08a;
private float[] hsvAdjust = new float[3];
private Bitmap grayImage;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hsv_just);
mImage = (ImageView) findViewById(R.id.image);
mH = (EditText) findViewById(R.id.hue);
mS = (EditText) findViewById(R.id.su);
mV = (EditText) findViewById(R.id.bright);
grayImage = ((BitmapDrawable) getResources().getDrawable(R.drawable.test_hsv)).getBitmap();
grayImage = convertGrayImg(grayImage);
mImage.setImageBitmap(grayImage);
mH.setText("120.0");
mS.setText("0.0");
mV.setText("0.0");
make = findViewById(R.id.make);
make.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hsvAdjust[0] = Float.valueOf(mH.getText().toString());
hsvAdjust[1] = Float.valueOf(mS.getText().toString());
hsvAdjust[2] = Float.valueOf(mV.getText().toString());
// final Bitmap bt = covertBitmapWithHSB(grayImage);
Bitmap bt = bitmapHSB(grayImage, startColor, endColor);
mImage.setImageBitmap(bt);
Toast.makeText(getApplicationContext(), "调整成功", Toast.LENGTH_LONG).show();
}
});
}
private Bitmap bitmapHSB(Bitmap bt, int startColor, int endColor) {
Bitmap out = Bitmap.createBitmap(bt.getWidth(), bt.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(out);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setDither(true);
paint.setColor(Color.WHITE);
float[] start = new float[3];
float[] end = new float[3];
Color.colorToHSV(startColor, start);
start[1] = 0;
start[2] = 0;
Color.colorToHSV(endColor, end);
end[1] = 0;
end[2] = 0;
bt = covertBitmapWithHSBWithHChanged(bt, start, end);
ColorMatrix allMatrix = new ColorMatrix();
ColorMatrix colorMatrix = new ColorMatrix();
setContrast(colorMatrix, 160, 120);
allMatrix.postConcat(colorMatrix);
//
paint.setColorFilter(new ColorMatrixColorFilter(allMatrix));
canvas.drawBitmap(bt, 0, 0, paint);
return out;
}
private static void setContrast(ColorMatrix cm, int contrast, int illumination) {
//contrast 0~200
float c = (contrast * 1.0f - 100) / 100;
float matrixContrast = (float) Math.tan((45 + 44 * c) / 180 * Math.PI);
float matrixIllumination = (illumination - 100) / (1.0f * 100);
float translate = -127.5f * (1 - matrixIllumination) * matrixContrast + 127.5f * (1 + matrixIllumination);
cm.set(new float[]{matrixContrast, 0, 0, 0, translate,
0, matrixContrast, 0, 0, translate,
0, 0, matrixContrast, 0, translate,
0, 0, 0, 1, 0});
}
private int getGradientColor(int startColor, int endColor, float ratio) {
if (ratio <= 0.000001) {
return startColor;
}
if (ratio >= 1.0) {
return endColor;
}
int a1 = Color.alpha(startColor);
int r1 = Color.red(startColor);
int g1 = Color.green(startColor);
int b1 = Color.blue(startColor);
int a2 = Color.alpha(endColor);
int r2 = Color.red(endColor);
int g2 = Color.green(endColor);
int b2 = Color.blue(endColor);
int a3 = (int) (a1 + (a2 - a1) * ratio);
int r3 = (int) (r1 + (r2 - r1) * ratio);
int g3 = (int) (g1 + (g2 - g1) * ratio);
int b3 = (int) (b1 + (b2 - b1) * ratio);
return Color.argb(a3, r3, g3, b3);
}
public Bitmap convertGrayImg(Bitmap bt) {
int w = bt.getWidth(), h = bt.getHeight();
int[] pix = new int[w * h];
bt.getPixels(pix, 0, w, 0, 0, w, h);
int alpha = 0xFF << 24;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
// 获得像素的颜色
int color = pix[w * i + j];
int red = ((color & 0x00FF0000) >> 16);
int green = ((color & 0x0000FF00) >> 8);
int blue = color & 0x000000FF;
// color = (red + green + blue) / 3;
color = (red * 77 + green * 151 + blue * 28) >> 8;
color = alpha | (color << 16) | (color << 8) | color;
pix[w * i + j] = color;
}
}
Bitmap result = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
result.setPixels(pix, 0, w, 0, 0, w, h);
return result;
}
public Bitmap covertBitmapWithHSBWithHChanged(Bitmap bt, float[] startHSVAdjust, float[] endHSVAdjust) {
int w = bt.getWidth(), h = bt.getHeight();
int[] pix = new int[w * h];
bt.getPixels(pix, 0, w, 0, 0, w, h);
float hueDeta = (endHSVAdjust[0] - startHSVAdjust[0]) / h;
float[] pixelHSV = new float[3];
int alpha = 0xFF << 24;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
int color = pix[w * i + j];
Color.colorToHSV(color, pixelHSV);
pixelHSV[0] = startHSVAdjust[0] + hueDeta * i;
pixelHSV[1] = 1 - pixelHSV[2];
color = Color.HSVToColor(pixelHSV);
color = alpha | color;
pix[w * i + j] = color;
}
}
Bitmap result = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
result.setPixels(pix, 0, w, 0, 0, w, h);
return result;
}
public Bitmap covertBitmapWithHSB(Bitmap bt) {
int w = bt.getWidth(), h = bt.getHeight();
int[] pix = new int[w * h];
bt.getPixels(pix, 0, w, 0, 0, w, h);
float[] pixelHSV = new float[3];
int alpha = 0xFF << 24;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
int color = pix[w * i + j];
int red = Color.red(color);
int green = Color.green(color);
int blue = Color.blue(color);
Color.RGBToHSV(red, green, blue, pixelHSV);
pixelHSV[0] = hsvAdjust[0];
pixelHSV[1] = pixelHSV[1] + hsvAdjust[1];
// if (pixelHSV[1] < 0.0f) {
// pixelHSV[1] = 0.0f;
// } else if (pixelHSV[1] > 1.0f) {
// pixelHSV[1] = 1.0f;
// }
//
// pixelHSV[2] = pixelHSV[2] + hsvAdjust[2];
// if (pixelHSV[2] < 0.0f) {
// pixelHSV[2] = 0.0f;
// } else if (pixelHSV[2] > 1.0f) {
// pixelHSV[2] = 1.0f;
// }
color = Color.HSVToColor(pixelHSV);
color = alpha | color;
pix[w * i + j] = color;
}
}
Bitmap result = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
result.setPixels(pix, 0, w, 0, 0, w, h);
return result;
}
} | 34.955357 | 114 | 0.527331 |
9c7948dc8cf89eaee40acbf160a5c5f964831bb2 | 327 | package com.factorydesign.serviceImpl;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
@Qualifier("HeadFirstJava")
public class HeadFirstJava implements Book {
@Override
public String getBook() {
return "This is Head First Java Book Object.";
}
}
| 20.4375 | 62 | 0.792049 |
261e9ecf4e6688dd52d8cde830ccc92697200ec3 | 1,455 | package link.linkmerge;
import java.io.*;
class link1
{
lnk first,newlink,cur,cur1;
lnk1 first1,newlink1,cur3;
int k;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public link1()
{
first=null;
first1=null;
k=1;
}
void isempty()
{
if(first==null || first1==null )
return;
}
void insert()throws IOException
{
newlink=new lnk();
newlink.input();
newlink.l=first;
first=newlink;
}
void display()
{
cur=first;
while(cur!=null)
{
cur.disp();
cur=cur.l;
}
}
void insert1()throws IOException
{
link1 l=new link1();
link1 l1=new link1();
while(k>0)
{
l.insert();
l1.insert();
System.out.println("Want another:");
k=Integer.parseInt(br.readLine());
}
l.display();
l1.display();
while(l.first!=null && l1.first!=null)
{
newlink1=new lnk1();
newlink1.input( l.first, l1.first);
newlink1.l=first1;
first1=newlink1;
l.first=l.first.l;
l1.first=l1.first.l;
}
} void disp1()
{
cur3=first1;
while(cur3!=null)
{
cur3.disp();
cur3=cur3.l;
}
}
}
| 19.4 | 75 | 0.457045 |
eed67023d7ac346eea73e74c467c742ab2c4a7a0 | 465 | package forms;
import services.question.types.DropdownQuestionDefinition;
import services.question.types.QuestionType;
/** Form for updating a dropdown question. */
public class DropdownQuestionForm extends MultiOptionQuestionForm {
public DropdownQuestionForm() {
super();
}
public DropdownQuestionForm(DropdownQuestionDefinition qd) {
super(qd);
}
@Override
public QuestionType getQuestionType() {
return QuestionType.DROPDOWN;
}
}
| 21.136364 | 67 | 0.765591 |
2bde155e9d0ad60678db07008f4335259b83d6a9 | 616 | package org.keycloak.testsuite.console.page.roles;
import org.jboss.arquillian.graphene.page.Page;
/**
*
* @author tkyjovsk
*/
public class Role extends RealmRoles {
public static final String ROLE_ID = "roleId";
@Override
public String getUriFragment() {
return super.getUriFragment() + "/{" + ROLE_ID + "}";
}
public void setRoleId(String id) {
setUriParameter(ROLE_ID, id);
}
public String getRoleId() {
return getUriParameter(ROLE_ID).toString();
}
@Page
private RoleForm form;
public RoleForm form() {
return form;
}
}
| 18.117647 | 61 | 0.633117 |
2f9f1f07b5954f593f6dcf9aff36a2d280c3f629 | 46,701 | /* ===========================================================
* AFreeChart : a free chart library for Android(tm) platform.
* (based on JFreeChart and JCommon)
* ===========================================================
*
* (C) Copyright 2010, by ICOMSYSTECH Co.,Ltd.
* (C) Copyright 2000-2008, by Object Refinery Limited and Contributors.
*
* Project Info:
* AFreeChart: http://code.google.com/p/afreechart/
* JFreeChart: http://www.jfree.org/jfreechart/index.html
* JCommon : http://www.jfree.org/jcommon/index.html
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* [Android is a trademark of Google Inc.]
*
* ---------------------------
* XYLineAndShapeRenderer.java
* ---------------------------
*
* (C) Copyright 2010, by ICOMSYSTECH Co.,Ltd.
*
* Original Author: shiraki (for ICOMSYSTECH Co.,Ltd);
* Contributor(s): Sato Yoshiaki ;
* Niwano Masayoshi;
*
* Changes (from 19-Nov-2010)
* --------------------------
* 19-Nov-2010 : port JFreeChart 1.0.13 to Android as "AFreeChart"
*
* ------------- JFreeChart ---------------------------------------------
* (C) Copyright 2004-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 27-Jan-2004 : Version 1 (DG);
* 10-Feb-2004 : Minor change to drawItem() method to make cut-and-paste
* overriding easier (DG);
* 25-Feb-2004 : Replaced CrosshairInfo with CrosshairState (DG);
* 25-Aug-2004 : Added support for chart entities (required for tooltips) (DG);
* 24-Sep-2004 : Added flag to allow whole series to be drawn as a path
* (necessary when using a dashed stroke with many data
* items) (DG);
* 04-Oct-2004 : Renamed BooleanUtils --> BooleanUtilities (DG);
* 11-Nov-2004 : Now uses ShapeUtilities to translate shapes (DG);
* 27-Jan-2005 : The getLegendItem() method now omits hidden series (DG);
* 28-Jan-2005 : Added new constructor (DG);
* 09-Mar-2005 : Added fillPaint settings (DG);
* 20-Apr-2005 : Use generators for legend tooltips and URLs (DG);
* 22-Jul-2005 : Renamed defaultLinesVisible --> baseLinesVisible,
* defaultShapesVisible --> baseShapesVisible and
* defaultShapesFilled --> baseShapesFilled (DG);
* 29-Jul-2005 : Added code to draw item labels (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 20-Jul-2006 : Set dataset and series indices in LegendItem (DG);
* 06-Feb-2007 : Fixed bug 1086307, crosshairs with multiple axes (DG);
* 21-Feb-2007 : Fixed bugs in clone() and equals() (DG);
* 20-Apr-2007 : Updated getLegendItem() for renderer change (DG);
* 18-May-2007 : Set dataset and seriesKey for LegendItem (DG);
* 08-Jun-2007 : Fix for bug 1731912 where entities are created even for data
* items that are not displayed (DG);
* 26-Oct-2007 : Deprecated override attributes (DG);
* 02-Jun-2008 : Fixed tooltips at lower edges of data area (DG);
* 17-Jun-2008 : Apply legend shape, font and paint attributes (DG);
* 19-Sep-2008 : Fixed bug with drawSeriesLineAsPath - patch by Greg Darke (DG);
*
*/
package org.afree.chart.renderer.xy;
import java.io.Serializable;
import org.afree.util.BooleanList;
import org.afree.util.BooleanUtilities;
import org.afree.ui.RectangleEdge;
import org.afree.util.ShapeUtilities;
import org.afree.chart.LegendItem;
import org.afree.chart.axis.ValueAxis;
import org.afree.data.xy.XYDataset;
import org.afree.chart.entity.EntityCollection;
import org.afree.chart.event.RendererChangeEvent;
import org.afree.chart.plot.CrosshairState;
import org.afree.chart.plot.PlotOrientation;
import org.afree.chart.plot.PlotRenderingInfo;
import org.afree.chart.plot.XYPlot;
import org.afree.graphics.geom.LineShape;
import org.afree.graphics.geom.PathShape;
import org.afree.graphics.geom.RectShape;
import org.afree.graphics.geom.Shape;
import org.afree.graphics.PaintType;
import org.afree.graphics.PaintUtility;
import android.graphics.Canvas;
import android.graphics.Paint;
/**
* A renderer that connects data points with lines and/or draws shapes at each
* data point. This renderer is designed for use with the {@link XYPlot} class.
* The example shown here is generated by the
* <code>XYLineAndShapeRendererDemo2.java</code> program included in the
* AFreeChart demo collection: <br>
* <br>
* <img src="../../../../../images/XYLineAndShapeRendererSample.png"
* alt="XYLineAndShapeRendererSample.png" />
*
*/
public class XYLineAndShapeRenderer extends AbstractXYItemRenderer implements XYItemRenderer,
Cloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = -7435246895986425885L;
/**
* A flag that controls whether or not lines are visible for ALL series.
*
* @deprecated As of JFreeChart 1.0.7.
*/
private Boolean linesVisible;
/**
* A table of flags that control (per series) whether or not lines are
* visible.
*/
private BooleanList seriesLinesVisible;
/** The default value returned by the getLinesVisible() method. */
private boolean baseLinesVisible;
/** The shape that is used to represent a line in the legend. */
private transient Shape legendLine;
/**
* A flag that controls whether or not shapes are visible for ALL series.
*
* @deprecated As of JFreeChart 1.0.7.
*/
private Boolean shapesVisible;
/**
* A table of flags that control (per series) whether or not shapes are
* visible.
*/
private BooleanList seriesShapesVisible;
/** The default value returned by the getShapeVisible() method. */
private boolean baseShapesVisible;
/**
* A flag that controls whether or not shapes are filled for ALL series.
*
* @deprecated As of JFreeChart 1.0.7.
*/
private Boolean shapesFilled;
/**
* A table of flags that control (per series) whether or not shapes are
* filled.
*/
private BooleanList seriesShapesFilled;
/** The default value returned by the getShapeFilled() method. */
private boolean baseShapesFilled;
/** A flag that controls whether outlines are drawn for shapes. */
private boolean drawOutlines;
/**
* A flag that controls whether the fill paint is used for filling shapes.
*/
private boolean useFillPaintType;
/**
* A flag that controls whether the outline paint is used for drawing shape
* outlines.
*/
private boolean useOutlinePaintType;
/**
* A flag that controls whether or not each series is drawn as a single
* path.
*/
private boolean drawSeriesLineAsPath;
/**
* Creates a new renderer with both lines and shapes visible.
*/
public XYLineAndShapeRenderer() {
this(true, true);
}
/**
* Creates a new renderer.
*
* @param lines
* lines visible?
* @param shapes
* shapes visible?
*/
public XYLineAndShapeRenderer(boolean lines, boolean shapes) {
this.linesVisible = null;
this.seriesLinesVisible = new BooleanList();
this.baseLinesVisible = lines;
this.legendLine = new LineShape(-7.0, 0.0, 7.0, 0.0);
this.shapesVisible = null;
this.seriesShapesVisible = new BooleanList();
this.baseShapesVisible = shapes;
this.shapesFilled = null;
this.useFillPaintType = false; // use item paint for fills by default
this.seriesShapesFilled = new BooleanList();
this.baseShapesFilled = true;
this.drawOutlines = true;
this.useOutlinePaintType = false; // use item paint for outlines by
// default, not outline paint
this.drawSeriesLineAsPath = false;
}
/**
* Returns a flag that controls whether or not each series is drawn as a
* single path.
*
* @return A boolean.
*
* @see #setDrawSeriesLineAsPath(boolean)
*/
public boolean getDrawSeriesLineAsPath() {
return this.drawSeriesLineAsPath;
}
/**
* Sets the flag that controls whether or not each series is drawn as a
* single path and sends a {@link RendererChangeEvent} to all registered
* listeners.
*
* @param flag
* the flag.
*
* @see #getDrawSeriesLineAsPath()
*/
public void setDrawSeriesLineAsPath(boolean flag) {
if (this.drawSeriesLineAsPath != flag) {
this.drawSeriesLineAsPath = flag;
fireChangeEvent();
}
}
/**
* Returns the number of passes through the data that the renderer requires
* in order to draw the chart. Most charts will require a single pass, but
* some require two passes.
*
* @return The pass count.
*/
public int getPassCount() {
return 2;
}
// LINES VISIBLE
/**
* Returns the flag used to control whether or not the shape for an item is
* visible.
*
* @param series
* the series index (zero-based).
* @param item
* the item index (zero-based).
*
* @return A boolean.
*/
public boolean getItemLineVisible(int series, int item) {
Boolean flag = this.linesVisible;
if (flag == null) {
flag = getSeriesLinesVisible(series);
}
if (flag != null) {
return flag.booleanValue();
} else {
return this.baseLinesVisible;
}
}
// /**
// * Sets a flag that controls whether or not lines are drawn between the
// * items in ALL series, and sends a {@link RendererChangeEvent} to all
// * registered listeners. You need to set this to <code>null</code> if you
// * want the "per series" settings to apply.
// *
// * @param visible the flag (<code>null</code> permitted).
// *
// * @see #getLinesVisible()
// *
// * @deprecated As of 1.0.7, use the per-series and base level settings.
// */
// public void setLinesVisible(Boolean visible) {
// this.linesVisible = visible;
// fireChangeEvent();
// }
/**
* Sets a flag that controls whether or not lines are drawn between the
* items in ALL series, and sends a {@link RendererChangeEvent} to all
* registered listeners.
*
* @param visible
* the flag.
*
* @see #getLinesVisible()
*
* @deprecated As of JFreeChart 1.0.7, use the per-series and base level settings.
*/
public void setLinesVisible(boolean visible) {
// we use BooleanUtilities here to preserve JRE 1.3.1 compatibility
setLinesVisible(BooleanUtilities.valueOf(visible));
}
/**
* Returns the flag used to control whether or not the lines for a series
* are visible.
*
* @param series
* the series index (zero-based).
*
* @return The flag (possibly <code>null</code>).
*
* @see #setSeriesLinesVisible(int, Boolean)
*/
public Boolean getSeriesLinesVisible(int series) {
return this.seriesLinesVisible.getBoolean(series);
}
/**
* Sets the 'lines visible' flag for a series and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series
* the series index (zero-based).
* @param flag
* the flag (<code>null</code> permitted).
*
* @see #getSeriesLinesVisible(int)
*/
public void setSeriesLinesVisible(int series, Boolean flag) {
this.seriesLinesVisible.setBoolean(series, flag);
fireChangeEvent();
}
/**
* Sets the 'lines visible' flag for a series and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series
* the series index (zero-based).
* @param visible
* the flag.
*
* @see #getSeriesLinesVisible(int)
*/
public void setSeriesLinesVisible(int series, boolean visible) {
setSeriesLinesVisible(series, BooleanUtilities.valueOf(visible));
}
/**
* Returns the base 'lines visible' attribute.
*
* @return The base flag.
*
* @see #setBaseLinesVisible(boolean)
*/
public boolean getBaseLinesVisible() {
return this.baseLinesVisible;
}
/**
* Sets the base 'lines visible' flag and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param flag
* the flag.
*
* @see #getBaseLinesVisible()
*/
public void setBaseLinesVisible(boolean flag) {
this.baseLinesVisible = flag;
fireChangeEvent();
}
/**
* Returns the shape used to represent a line in the legend.
*
* @return The legend line (never <code>null</code>).
*
* @see #setLegendLine(Shape)
*/
public Shape getLegendLine() {
return this.legendLine;
}
/**
* Sets the shape used as a line in each legend item and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param line
* the line (<code>null</code> not permitted).
*
* @see #getLegendLine()
*/
public void setLegendLine(Shape line) {
if (line == null) {
throw new IllegalArgumentException("Null 'line' argument.");
}
this.legendLine = line;
fireChangeEvent();
}
// SHAPES VISIBLE
/**
* Returns the flag used to control whether or not the shape for an item is
* visible.
* <p>
* The default implementation passes control to the
* <code>getSeriesShapesVisible</code> method. You can override this method
* if you require different behaviour.
*
* @param series
* the series index (zero-based).
* @param item
* the item index (zero-based).
*
* @return A boolean.
*/
public boolean getItemShapeVisible(int series, int item) {
Boolean flag = this.shapesVisible;
if (flag == null) {
flag = getSeriesShapesVisible(series);
}
if (flag != null) {
return flag.booleanValue();
} else {
return this.baseShapesVisible;
}
}
// /**
// * Sets the 'shapes visible' for ALL series and sends a
// * {@link RendererChangeEvent} to all registered listeners.
// *
// * @param visible the flag (<code>null</code> permitted).
// *
// * @see #getShapesVisible()
// *
// * @deprecated As of 1.0.7, use the per-series and base level settings.
// */
// public void setShapesVisible(Boolean visible) {
// this.shapesVisible = visible;
// fireChangeEvent();
// }
/**
* Sets the 'shapes visible' for ALL series and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param visible
* the flag.
*
* @see #getShapesVisible()
*
* @deprecated As of JFreeChart 1.0.7, use the per-series and base level settings.
*/
public void setShapesVisible(boolean visible) {
setShapesVisible(BooleanUtilities.valueOf(visible));
}
/**
* Returns the flag used to control whether or not the shapes for a series
* are visible.
*
* @param series
* the series index (zero-based).
*
* @return A boolean.
*
* @see #setSeriesShapesVisible(int, Boolean)
*/
public Boolean getSeriesShapesVisible(int series) {
return this.seriesShapesVisible.getBoolean(series);
}
/**
* Sets the 'shapes visible' flag for a series and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series
* the series index (zero-based).
* @param visible
* the flag.
*
* @see #getSeriesShapesVisible(int)
*/
public void setSeriesShapesVisible(int series, boolean visible) {
setSeriesShapesVisible(series, BooleanUtilities.valueOf(visible));
}
/**
* Sets the 'shapes visible' flag for a series and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series
* the series index (zero-based).
* @param flag
* the flag.
*
* @see #getSeriesShapesVisible(int)
*/
public void setSeriesShapesVisible(int series, Boolean flag) {
this.seriesShapesVisible.setBoolean(series, flag);
fireChangeEvent();
}
/**
* Returns the base 'shape visible' attribute.
*
* @return The base flag.
*
* @see #setBaseShapesVisible(boolean)
*/
public boolean getBaseShapesVisible() {
return this.baseShapesVisible;
}
/**
* Sets the base 'shapes visible' flag and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param flag
* the flag.
*
* @see #getBaseShapesVisible()
*/
public void setBaseShapesVisible(boolean flag) {
this.baseShapesVisible = flag;
fireChangeEvent();
}
// SHAPES FILLED
/**
* Returns the flag used to control whether or not the shape for an item is
* filled.
* <p>
* The default implementation passes control to the
* <code>getSeriesShapesFilled</code> method. You can override this method
* if you require different behaviour.
*
* @param series
* the series index (zero-based).
* @param item
* the item index (zero-based).
*
* @return A boolean.
*/
public boolean getItemShapeFilled(int series, int item) {
Boolean flag = this.shapesFilled;
if (flag == null) {
flag = getSeriesShapesFilled(series);
}
if (flag != null) {
return flag.booleanValue();
} else {
return this.baseShapesFilled;
}
}
/**
* Sets the 'shapes filled' for ALL series and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param filled
* the flag (<code>null</code> permitted).
*
* @deprecated As of JFreeChart 1.0.7, use the per-series and base level settings.
*/
public void setShapesFilled(Boolean filled) {
this.shapesFilled = filled;
fireChangeEvent();
}
/**
* Returns the flag used to control whether or not the shapes for a series
* are filled.
*
* @param series
* the series index (zero-based).
*
* @return A boolean.
*
* @see #setSeriesShapesFilled(int, Boolean)
*/
public Boolean getSeriesShapesFilled(int series) {
return this.seriesShapesFilled.getBoolean(series);
}
/**
* Sets the 'shapes filled' flag for a series and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series
* the series index (zero-based).
* @param flag
* the flag.
*
* @see #getSeriesShapesFilled(int)
*/
public void setSeriesShapesFilled(int series, boolean flag) {
setSeriesShapesFilled(series, BooleanUtilities.valueOf(flag));
}
/**
* Sets the 'shapes filled' flag for a series and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series
* the series index (zero-based).
* @param flag
* the flag.
*
* @see #getSeriesShapesFilled(int)
*/
public void setSeriesShapesFilled(int series, Boolean flag) {
this.seriesShapesFilled.setBoolean(series, flag);
fireChangeEvent();
}
/**
* Returns the base 'shape filled' attribute.
*
* @return The base flag.
*
* @see #setBaseShapesFilled(boolean)
*/
public boolean getBaseShapesFilled() {
return this.baseShapesFilled;
}
/**
* Sets the base 'shapes filled' flag and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param flag
* the flag.
*
* @see #getBaseShapesFilled()
*/
public void setBaseShapesFilled(boolean flag) {
this.baseShapesFilled = flag;
fireChangeEvent();
}
/**
* Returns <code>true</code> if outlines should be drawn for shapes, and
* <code>false</code> otherwise.
*
* @return A boolean.
*
* @see #setDrawOutlines(boolean)
*/
public boolean getDrawOutlines() {
return this.drawOutlines;
}
/**
* Sets the flag that controls whether outlines are drawn for shapes, and
* sends a {@link RendererChangeEvent} to all registered listeners.
* <P>
* In some cases, shapes look better if they do NOT have an outline, but
* this flag allows you to set your own preference.
*
* @param flag
* the flag.
*
* @see #getDrawOutlines()
*/
public void setDrawOutlines(boolean flag) {
this.drawOutlines = flag;
fireChangeEvent();
}
/**
* Returns <code>true</code> if the renderer should use the fill paint
* setting to fill shapes, and <code>false</code> if it should just use the
* regular paint.
* <p>
* Refer to <code>XYLineAndShapeRendererDemo2.java</code> to see the effect
* of this flag.
*
* @return A boolean.
*
* @see #setUseFillPaint(boolean)
* @see #getUseOutlinePaint()
*/
public boolean getUseFillPaint() {
return this.useFillPaintType;
}
/**
* Sets the flag that controls whether the fill paint is used to fill
* shapes, and sends a {@link RendererChangeEvent} to all registered
* listeners.
*
* @param flag
* the flag.
*
* @see #getUseFillPaint()
*/
public void setUseFillPaint(boolean flag) {
this.useFillPaintType = flag;
fireChangeEvent();
}
/**
* Returns <code>true</code> if the renderer should use the outline paint
* setting to draw shape outlines, and <code>false</code> if it should just
* use the regular paint.
*
* @return A boolean.
*
* @see #setUseOutlinePaint(boolean)
* @see #getUseFillPaint()
*/
public boolean getUseOutlinePaint() {
return this.useOutlinePaintType;
}
/**
* Sets the flag that controls whether the outline paint is used to draw
* shape outlines, and sends a {@link RendererChangeEvent} to all registered
* listeners.
* <p>
* Refer to <code>XYLineAndShapeRendererDemo2.java</code> to see the effect
* of this flag.
*
* @param flag
* the flag.
*
* @see #getUseOutlinePaint()
*/
public void setUseOutlinePaint(boolean flag) {
this.useOutlinePaintType = flag;
fireChangeEvent();
}
/**
* Records the state for the renderer. This is used to preserve state
* information between calls to the drawItem() method for a single chart
* drawing.
*/
public static class State extends XYItemRendererState {
/** The path for the current series. */
public PathShape seriesPath;
/**
* A flag that indicates if the last (x, y) point was 'good' (non-null).
*/
private boolean lastPointGood;
/**
* Creates a new state instance.
*
* @param info
* the plot rendering info.
*/
public State(PlotRenderingInfo info) {
super(info);
}
/**
* Returns a flag that indicates if the last point drawn (in the current
* series) was 'good' (non-null).
*
* @return A boolean.
*/
public boolean isLastPointGood() {
return this.lastPointGood;
}
/**
* Sets a flag that indicates if the last point drawn (in the current
* series) was 'good' (non-null).
*
* @param good
* the flag.
*/
public void setLastPointGood(boolean good) {
this.lastPointGood = good;
}
/**
* This method is called by the {@link XYPlot} at the start of each
* series pass. We reset the state for the current series.
*
* @param dataset
* the dataset.
* @param series
* the series index.
* @param firstItem
* the first item index for this pass.
* @param lastItem
* the last item index for this pass.
* @param pass
* the current pass index.
* @param passCount
* the number of passes.
*/
public void startSeriesPass(XYDataset dataset, int series, int firstItem, int lastItem,
int pass, int passCount) {
this.seriesPath.reset();
this.lastPointGood = false;
super.startSeriesPass(dataset, series, firstItem, lastItem, pass, passCount);
}
}
/**
* Initialises the renderer.
* <P>
* This method will be called before the first item is rendered, giving the
* renderer an opportunity to initialise any state information it wants to
* maintain. The renderer can do nothing if it chooses.
*
* @param canvas
* the graphics device.
* @param dataArea
* the area inside the axes.
* @param plot
* the plot.
* @param data
* the data.
* @param info
* an optional info collection object to return data back to the
* caller.
*
* @return The renderer state.
*/
public XYItemRendererState initialise(Canvas canvas, RectShape dataArea, XYPlot plot,
XYDataset data, PlotRenderingInfo info) {
State state = new State(info);
state.seriesPath = new PathShape();
return state;
}
/**
* Draws the visual representation of a single data item.
*
* @param canvas
* the graphics device.
* @param state
* the renderer state.
* @param dataArea
* the area within which the data is being drawn.
* @param info
* collects information about the drawing.
* @param plot
* the plot (can be used to obtain standard color information
* etc).
* @param domainAxis
* the domain axis.
* @param rangeAxis
* the range axis.
* @param dataset
* the dataset.
* @param series
* the series index (zero-based).
* @param item
* the item index (zero-based).
* @param crosshairState
* crosshair information for the plot (<code>null</code>
* permitted).
* @param pass
* the pass index.
*/
public void drawItem(Canvas canvas, XYItemRendererState state, RectShape dataArea,
PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis,
XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) {
// do nothing if item is not visible
if (!getItemVisible(series, item)) {
return;
}
// first pass draws the background (lines, for instance)
if (isLinePass(pass)) {
if (getItemLineVisible(series, item)) {
if (this.drawSeriesLineAsPath) {
drawPrimaryLineAsPath(state, canvas, plot, dataset, pass, series, item, domainAxis,
rangeAxis, dataArea);
} else {
drawPrimaryLine(state, canvas, plot, dataset, pass, series, item, domainAxis,
rangeAxis, dataArea);
}
}
}
// second pass adds shapes where the items are ..
else if (isItemPass(pass)) {
// setup for collecting optional entity info...
EntityCollection entities = null;
if (info != null) {
entities = info.getOwner().getEntityCollection();
}
drawSecondaryPass(canvas, plot, dataset, pass, series, item, domainAxis, dataArea,
rangeAxis, crosshairState, entities);
}
}
/**
* Returns <code>true</code> if the specified pass is the one for drawing
* lines.
*
* @param pass
* the pass.
*
* @return A boolean.
*/
protected boolean isLinePass(int pass) {
return pass == 0;
}
/**
* Returns <code>true</code> if the specified pass is the one for drawing
* items.
*
* @param pass
* the pass.
*
* @return A boolean.
*/
protected boolean isItemPass(int pass) {
return pass == 1;
}
/**
* Draws the item (first pass). This method draws the lines connecting the
* items.
*
* @param canvas
* the graphics device.
* @param state
* the renderer state.
* @param dataArea
* the area within which the data is being drawn.
* @param plot
* the plot (can be used to obtain standard color information
* etc).
* @param domainAxis
* the domain axis.
* @param rangeAxis
* the range axis.
* @param dataset
* the dataset.
* @param pass
* the pass.
* @param series
* the series index (zero-based).
* @param item
* the item index (zero-based).
*/
protected void drawPrimaryLine(XYItemRendererState state, Canvas canvas, XYPlot plot,
XYDataset dataset, int pass, int series, int item, ValueAxis domainAxis,
ValueAxis rangeAxis, RectShape dataArea) {
if (item == 0) {
return;
}
// get the data point...
double x1 = dataset.getXValue(series, item);
double y1 = dataset.getYValue(series, item);
if (Double.isNaN(y1) || Double.isNaN(x1)) {
return;
}
double x0 = dataset.getXValue(series, item - 1);
double y0 = dataset.getYValue(series, item - 1);
if (Double.isNaN(y0) || Double.isNaN(x0)) {
return;
}
RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
double transX0 = domainAxis.valueToJava2D(x0, dataArea, xAxisLocation);
double transY0 = rangeAxis.valueToJava2D(y0, dataArea, yAxisLocation);
double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation);
double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation);
// only draw if we have good values
if (Double.isNaN(transX0) || Double.isNaN(transY0) || Double.isNaN(transX1)
|| Double.isNaN(transY1)) {
return;
}
PlotOrientation orientation = plot.getOrientation();
if (orientation == PlotOrientation.HORIZONTAL) {
state.workingLine.setLine(transY0, transX0, transY1, transX1);
} else if (orientation == PlotOrientation.VERTICAL) {
state.workingLine.setLine(transX0, transY0, transX1, transY1);
}
if (state.workingLine.intersects(dataArea)) {
drawFirstPassShape(canvas, pass, series, item, state.workingLine);
}
}
/**
* Draws the first pass shape.
*
* @param canvas
* the graphics device.
* @param pass
* the pass.
* @param series
* the series index.
* @param item
* the item index.
* @param shape
* the shape.
*/
protected void drawFirstPassShape(Canvas canvas, int pass, int series, int item, Shape shape) {
Paint paint = PaintUtility.createPaint(Paint.ANTI_ALIAS_FLAG, getItemPaintType(series,
item), getItemStroke(series, item), getItemEffect(series, item));
shape.draw(canvas, paint);
}
/**
* Draws the item (first pass). This method draws the lines connecting the
* items. Instead of drawing separate lines, a PathShape is constructed and
* drawn at the end of the series painting.
*
* @param canvas
* the graphics device.
* @param state
* the renderer state.
* @param plot
* the plot (can be used to obtain standard color information
* etc).
* @param dataset
* the dataset.
* @param pass
* the pass.
* @param series
* the series index (zero-based).
* @param item
* the item index (zero-based).
* @param domainAxis
* the domain axis.
* @param rangeAxis
* the range axis.
* @param dataArea
* the area within which the data is being drawn.
*/
protected void drawPrimaryLineAsPath(XYItemRendererState state, Canvas canvas, XYPlot plot,
XYDataset dataset, int pass, int series, int item, ValueAxis domainAxis,
ValueAxis rangeAxis, RectShape dataArea) {
RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
// get the data point...
double x1 = dataset.getXValue(series, item);
double y1 = dataset.getYValue(series, item);
double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation);
double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation);
State s = (State) state;
// update path to reflect latest point
if (!Double.isNaN(transX1) && !Double.isNaN(transY1)) {
float x = (float) transX1;
float y = (float) transY1;
PlotOrientation orientation = plot.getOrientation();
if (orientation == PlotOrientation.HORIZONTAL) {
x = (float) transY1;
y = (float) transX1;
}
if (s.isLastPointGood()) {
s.seriesPath.lineTo(x, y);
} else {
s.seriesPath.moveTo(x, y);
}
s.setLastPointGood(true);
} else {
s.setLastPointGood(false);
}
// if this is the last item, draw the path ...
if (item == s.getLastItemIndex()) {
// draw path
drawFirstPassShape(canvas, pass, series, item, s.seriesPath);
}
}
/**
* Draws the item shapes and adds chart entities (second pass). This method
* draws the shapes which mark the item positions. If <code>entities</code>
* is not <code>null</code> it will be populated with entity information for
* points that fall within the data area.
*
* @param canvas
* the graphics device.
* @param plot
* the plot (can be used to obtain standard color information
* etc).
* @param domainAxis
* the domain axis.
* @param dataArea
* the area within which the data is being drawn.
* @param rangeAxis
* the range axis.
* @param dataset
* the dataset.
* @param pass
* the pass.
* @param series
* the series index (zero-based).
* @param item
* the item index (zero-based).
* @param crosshairState
* the crosshair state.
* @param entities
* the entity collection.
*/
protected void drawSecondaryPass(Canvas canvas, XYPlot plot, XYDataset dataset, int pass,
int series, int item, ValueAxis domainAxis, RectShape dataArea, ValueAxis rangeAxis,
CrosshairState crosshairState, EntityCollection entities) {
Shape entityArea = null;
// get the data point...
double x1 = dataset.getXValue(series, item);
double y1 = dataset.getYValue(series, item);
if (Double.isNaN(y1) || Double.isNaN(x1)) {
return;
}
PlotOrientation orientation = plot.getOrientation();
RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation);
double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation);
if (getItemShapeVisible(series, item)) {
Shape shape = getItemShape(series, item);
if (orientation == PlotOrientation.HORIZONTAL) {
shape = ShapeUtilities.createTranslatedShape(shape, transY1, transX1);
} else if (orientation == PlotOrientation.VERTICAL) {
shape = ShapeUtilities.createTranslatedShape(shape, transX1, transY1);
}
entityArea = shape;
if (shape.intersects(dataArea)) {
if (getItemShapeFilled(series, item)) {
PaintType paintType;
if (this.useFillPaintType) {
paintType = getItemFillPaintType(series, item);
} else {
paintType = getItemPaintType(series, item);
}
Paint paint = PaintUtility.createPaint(
Paint.ANTI_ALIAS_FLAG,
paintType);
shape.fill(canvas, paint);
}
if (this.drawOutlines) {
PaintType paintType;
if (getUseOutlinePaint()) {
paintType = getItemOutlinePaintType(series, item);
} else {
paintType = getItemPaintType(series, item);
}
Paint paint = PaintUtility.createPaint(Paint.ANTI_ALIAS_FLAG, paintType,
getItemStroke(series, item), getItemEffect(series, item));
shape.draw(canvas, paint);
}
}
}
double xx = transX1;
double yy = transY1;
if (orientation == PlotOrientation.HORIZONTAL) {
xx = transY1;
yy = transX1;
}
// draw the item label if there is one...
if (isItemLabelVisible(series, item)) {
drawItemLabel(canvas, orientation, dataset, series, item, xx, yy, (y1 < 0.0));
}
int domainAxisIndex = plot.getDomainAxisIndex(domainAxis);
int rangeAxisIndex = plot.getRangeAxisIndex(rangeAxis);
updateCrosshairValues(crosshairState, x1, y1, domainAxisIndex, rangeAxisIndex, transX1,
transY1, orientation);
// add an entity for the item, but only if it falls within the data
// area...
if (entities != null && isPointInRect(dataArea, xx, yy)) {
addEntity(entities, entityArea, dataset, series, item, xx, yy);
}
}
/**
* Returns a legend item for the specified series.
*
* @param datasetIndex
* the dataset index (zero-based).
* @param series
* the series index (zero-based).
*
* @return A legend item for the series.
*/
public LegendItem getLegendItem(int datasetIndex, int series) {
XYPlot plot = getPlot();
if (plot == null) {
return null;
}
LegendItem result = null;
XYDataset dataset = plot.getDataset(datasetIndex);
if (dataset != null) {
if (getItemVisible(series, 0)) {
String label = getLegendItemLabelGenerator().generateLabel(dataset, series);
String description = label;
boolean shapeIsVisible = getItemShapeVisible(series, 0);
Shape shape = lookupLegendShape(series);
boolean shapeIsFilled = getItemShapeFilled(series, 0);
PaintType fillPaintType = (this.useFillPaintType ? lookupSeriesFillPaintType(series)
: lookupSeriesPaintType(series));
boolean shapeOutlineVisible = this.drawOutlines;
PaintType outlinePaintType = (this.useOutlinePaintType ? lookupSeriesOutlinePaintType(series)
: lookupSeriesPaintType(series));
Float outlineStroke = lookupSeriesOutlineStroke(series);
boolean lineVisible = getItemLineVisible(series, 0);
Float lineStroke = lookupSeriesStroke(series);
PaintType linePaintType = lookupSeriesPaintType(series);
result = new LegendItem(label, description, "", "", shapeIsVisible, shape,
shapeIsFilled, fillPaintType, shapeOutlineVisible, outlinePaintType
, outlineStroke, lineVisible, this.legendLine,
lineStroke, linePaintType);
result.setLabelFont(lookupLegendTextFont(series));
PaintType labelPaint = lookupLegendTextPaintType(series);
if (labelPaint != null) {
result.setLabelPaintType(labelPaint);
}
result.setSeriesKey(dataset.getSeriesKey(series));
result.setSeriesIndex(series);
result.setDataset(dataset);
result.setDatasetIndex(datasetIndex);
}
}
return result;
}
/*
* @Override public Font getItemLabelFont() { // TODO Auto-generated method
* stub return null; }
*
* @Override public Paint getItemLabelPaint() { // TODO Auto-generated
* method stub return null; }
*
* @Override public ItemLabelPosition getNegativeItemLabelPosition() { //
* TODO Auto-generated method stub return null; }
*
* @Override public ItemLabelPosition getPositiveItemLabelPosition() { //
* TODO Auto-generated method stub return null; }
*
* @Override public Boolean getSeriesVisible() { // TODO Auto-generated
* method stub return null; }
*
* @Override public Boolean getSeriesVisibleInLegend() { // TODO
* Auto-generated method stub return null; }
*
* @Override public void setBaseOutlineStroke(Float stroke) { // TODO
* Auto-generated method stub
*
* }
*
* @Override public void setBaseStroke(Float stroke) { // TODO
* Auto-generated method stub
*
* }
*
* @Override public void setItemLabelFont(Font font) { // TODO
* Auto-generated method stub
*
* }
*
* @Override public void setItemLabelGenerator(XYItemLabelGenerator
* generator) { // TODO Auto-generated method stub
*
* }
*
* @Override public void setItemLabelPaint(Paint paint) { // TODO
* Auto-generated method stub
*
* }
*
* @Override public void setItemLabelsVisible(boolean visible) { // TODO
* Auto-generated method stub
*
* }
*
* @Override public void setItemLabelsVisible(Boolean visible) { // TODO
* Auto-generated method stub
*
* }
*
* @Override public void setItemLabelsVisible(Boolean visible, boolean
* notify) { // TODO Auto-generated method stub
*
* }
*
* @Override public void setNegativeItemLabelPosition(ItemLabelPosition
* position) { // TODO Auto-generated method stub
*
* }
*
* @Override public void setNegativeItemLabelPosition(ItemLabelPosition
* position, boolean notify) { // TODO Auto-generated method stub
*
* }
*
* @Override public void setOutlinePaint(Paint paint) { // TODO
* Auto-generated method stub
*
* }
*
* @Override public void setOutlineStroke(Float stroke) { // TODO
* Auto-generated method stub
*
* }
*
* @Override public void setPaint(Paint paint) { // TODO Auto-generated
* method stub
*
* }
*
* @Override public void setPositiveItemLabelPosition(ItemLabelPosition
* position) { // TODO Auto-generated method stub
*
* }
*
* @Override public void setPositiveItemLabelPosition(ItemLabelPosition
* position, boolean notify) { // TODO Auto-generated method stub
*
* }
*
* @Override public void setSeriesOutlineStroke(int series, Float stroke) {
* // TODO Auto-generated method stub
*
* }
*
* @Override public void setSeriesStroke(int series, Float stroke) { // TODO
* Auto-generated method stub
*
* }
*
* @Override public void setSeriesVisible(Boolean visible) { // TODO
* Auto-generated method stub
*
* }
*
* @Override public void setSeriesVisible(Boolean visible, boolean notify) {
* // TODO Auto-generated method stub
*
* }
*
* @Override public void setSeriesVisibleInLegend(Boolean visible) { // TODO
* Auto-generated method stub
*
* }
*
* @Override public void setSeriesVisibleInLegend(Boolean visible, boolean
* notify) { // TODO Auto-generated method stub
*
* }
*
* @Override public void setShape(Shape shape) { // TODO Auto-generated
* method stub
*
* }
*
* @Override public void setStroke(Float stroke) { // TODO Auto-generated
* method stub
*
* }
*/
}
| 32.795646 | 109 | 0.584441 |
b4125a89a056180be4c1e4adb26065c41965da13 | 114 | package com.lilypuree.caloric.api;
/**
* Public Caloric Capabilities
*/
public class CaloricCapabilities {
}
| 11.4 | 34 | 0.736842 |
b12cda9401669080023fe6dd0f3319bf8a3362c4 | 3,521 | /*
* Copyright (C) 2015-2017 NS Solutions Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.htmlhifive.pitalium.core.model;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.htmlhifive.pitalium.common.util.JSONUtils;
import com.htmlhifive.pitalium.image.model.RectangleArea;
/**
* 画面上の特定の領域をセレクタおよび矩形領域で表すクラス。
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ScreenArea implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 領域のセレクタ
*/
private DomSelector selector;
/**
* 領域の矩形オブジェクト
*/
private RectangleArea rectangle;
/**
* 空のオブジェクトを生成します。
*/
public ScreenArea() {
}
/**
* セレクタを指定して領域オブジェクトを生成します。
*
* @param selector セレクタ
*/
public ScreenArea(DomSelector selector) {
this.selector = selector;
}
/**
* 矩形領域を指定して領域オブジェクトを生成します。
*
* @param rectangle 矩形領域
*/
public ScreenArea(RectangleArea rectangle) {
this.rectangle = rectangle;
}
/**
* セレクタを使用して画面上の領域を指定します。
*
* @param type セレクタの種別
* @param value セレクタの値
* @return 画面上の領域を表すオブジェクト
*/
public static ScreenArea of(SelectorType type, String value) {
return new ScreenArea(new DomSelector(type, value));
}
/**
* セレクタを使用して画面上の領域を指定します。
*
* @param type セレクタの種別
* @param value セレクタの値
* @param frameSelectorType フレームを指定するセレクタの種別
* @param frameSelectorValue フレームを指定するセレクタの値
* @return 画面上の領域を表すオブジェクト
*/
public static ScreenArea of(SelectorType type, String value, SelectorType frameSelectorType,
String frameSelectorValue) {
return new ScreenArea(new DomSelector(type, value, new DomSelector(frameSelectorType, frameSelectorValue)));
}
/**
* 座標を直接指定して画面上の領域を指定します。
*
* @param x 領域の左上のx座標
* @param y 領域の左上のy座標
* @param width 領域の幅
* @param height 領域の高さ
* @return 画面上の領域を表すオブジェクト
*/
public static ScreenArea of(double x, double y, double width, double height) {
return new ScreenArea(new RectangleArea(x, y, width, height));
}
/**
* 領域のセレクタを取得します。
*
* @return セレクタ
*/
public DomSelector getSelector() {
return selector;
}
/**
* 矩形領域を取得します。
*
* @return 矩形領域
*/
public RectangleArea getRectangle() {
return rectangle;
}
/**
* 同じ領域を指すかどうか調べます。
*
* @param o 比較対象オブジェクト
* @return セレクタ・矩形領域が一致すればtrue
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ScreenArea that = (ScreenArea) o;
if (selector != null ? !selector.equals(that.selector) : that.selector != null) {
return false;
}
return !(rectangle != null ? !rectangle.equals(that.rectangle) : that.rectangle != null);
}
@Override
public int hashCode() {
int result = selector != null ? selector.hashCode() : 0;
final int hashPrime = 31;
result = hashPrime * result + (rectangle != null ? rectangle.hashCode() : 0);
return result;
}
@Override
public String toString() {
return JSONUtils.toString(this);
}
}
| 22.28481 | 110 | 0.697813 |
416f937cbbffdc3da45c68877135143bbc90d932 | 1,899 | package com.sensepost.yeti.persistence.dao;
import com.sensepost.yeti.persistence.HibernateUtil;
import com.sensepost.yeti.persistence.entities.HostAttribute;
import java.util.List;
import org.hibernate.Query;
/**
*
* @author Johan Snyman
*/
public class HostAttributeDao extends DatabaseEntityDao<HostAttribute> {
@Override
public HostAttribute saveOrUpdate(HostAttribute e) {
HostAttribute ha = findByKeyAndHost(e.getKey(), e.getHost().getId());
if (ha == null) {
super.saveOrUpdate(e);
return e;
}
return ha;
}
public List<HostAttribute> findByHostName(String hostName) {
String hql = "from HostAttribute where host.name = :hostName";
Query query = HibernateUtil.getSession().createQuery(hql);
query.setParameter("hostName", hostName);
return query.list();
}
public HostAttribute findByKeyAndHost(String key, int hostId) {
String hql = "from HostAttribute where key = :key and host.id = :hostId";
Query query = HibernateUtil.getSession().createQuery(hql);
query.setParameter("key", key);
query.setParameter("hostId", hostId);
List<HostAttribute> list = query.list();
if (list != null && !list.isEmpty()) {
return list.get(0);
}
return null;
}
public void deleteHostAtrribute(String hostName, String key, String value, int footprintId) {
String hql = "delete from HostAttribute where host.name = :hostName and key = : key and value = :value and footprint.id = :footprintId";
Query query = HibernateUtil.getSession().createQuery(hql);
query.setParameter("hostName", hostName);
query.setParameter("key", key);
query.setParameter("value", value);
query.setParameter("footprintId", footprintId);
query.executeUpdate();
}
}
| 35.830189 | 144 | 0.652975 |
8d812356c85b722d36079df49a9ddfbec23c8031 | 1,130 | package com.nukkitx.protocol.bedrock.compat;
import protocol.bedrock.BedrockPacketCodec;
import com.nukkitx.protocol.bedrock.compat.serializer.DisconnectSerializerCompat;
import com.nukkitx.protocol.bedrock.compat.serializer.LoginSerializerCompat;
import com.nukkitx.protocol.bedrock.compat.serializer.PlayStatusSerializerCompat;
import com.nukkitx.protocol.bedrock.packet.DisconnectPacket;
import com.nukkitx.protocol.bedrock.packet.LoginPacket;
import com.nukkitx.protocol.bedrock.packet.PlayStatusPacket;
public class BedrockCompat {
/**
* This is for servers when figuring out the protocol of a client joining.
*/
public static BedrockPacketCodec COMPAT_CODEC = BedrockPacketCodec.builder()
.helper(NoopBedrockPacketHelper.INSTANCE)
.registerPacket(LoginPacket.class, LoginSerializerCompat.INSTANCE, 1)
.registerPacket(PlayStatusPacket.class, PlayStatusSerializerCompat.INSTANCE, 2)
.registerPacket(DisconnectPacket.class, DisconnectSerializerCompat.INSTANCE, 5)
.protocolVersion(0)
.minecraftVersion("0.0.0")
.build();
}
| 47.083333 | 91 | 0.770796 |
ecb88c2e35d32b4b3753b757091cf2c46a2b9479 | 3,095 | /*
* gml-objects - A Java mapping for the OGC Geography Markup Language (GML)
* https://github.com/xmlobjects/gml-objects
*
* Copyright 2019-2020 Claus Nagel <claus.nagel@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.xmlobjects.gml.adapter.coverage;
import org.xmlobjects.builder.ObjectBuildException;
import org.xmlobjects.builder.ObjectBuilder;
import org.xmlobjects.gml.adapter.GMLSerializerHelper;
import org.xmlobjects.gml.model.coverage.IncrementOrder;
import org.xmlobjects.gml.model.coverage.SequenceRule;
import org.xmlobjects.gml.model.coverage.SequenceRuleEnumeration;
import org.xmlobjects.gml.util.GMLConstants;
import org.xmlobjects.serializer.ObjectSerializeException;
import org.xmlobjects.serializer.ObjectSerializer;
import org.xmlobjects.stream.XMLReadException;
import org.xmlobjects.stream.XMLReader;
import org.xmlobjects.stream.XMLWriteException;
import org.xmlobjects.stream.XMLWriter;
import org.xmlobjects.xml.Attributes;
import org.xmlobjects.xml.Element;
import org.xmlobjects.xml.Namespaces;
import org.xmlobjects.xml.TextContent;
import javax.xml.namespace.QName;
public class SequenceRuleAdapter implements ObjectBuilder<SequenceRule>, ObjectSerializer<SequenceRule> {
@Override
public SequenceRule createObject(QName name, Object parent) throws ObjectBuildException {
return new SequenceRule();
}
@Override
public void initializeObject(SequenceRule object, QName name, Attributes attributes, XMLReader reader) throws ObjectBuildException, XMLReadException {
reader.getTextContent().ifPresent(v -> object.setValue(SequenceRuleEnumeration.fromValue(v)));
attributes.getValue("order").ifPresent(v -> object.setAxisOrders(IncrementOrder.fromValue(v)));
attributes.getValue("axisOrder").ifList(object::setAxisOrders);
}
@Override
public void initializeElement(Element element, SequenceRule object, Namespaces namespaces, XMLWriter writer) throws ObjectSerializeException, XMLWriteException {
element.addTextContent(object.getValue().toValue());
if (!object.getAxisOrders().isEmpty()) {
if (GMLConstants.GML_3_2_NAMESPACE.equals(GMLSerializerHelper.getGMLBaseNamespace(namespaces)))
element.addAttribute("axisOrder", TextContent.ofList(object.getAxisOrders()));
else {
IncrementOrder order = IncrementOrder.fromAxisOrders(object.getAxisOrders());
if (order != null)
element.addAttribute("order", order.toValue());
}
}
}
}
| 43.591549 | 165 | 0.757674 |
8812d38ee34d7b78f2a0a04616de5200438e2209 | 1,241 | package uk.ac.ox.cs.diadem.webapi.dom.mutation;
import java.util.Set;
import uk.ac.ox.cs.diadem.webapi.dom.DOMElement;
public interface MutationFormSummary {
Set<DOMElement> getFieldsHavingNewOptions();
Set<DOMElement> getFieldsHavingRemovedOptions();
Set<DOMElement> getNewEnabledFields();
Set<DOMElement> getNewDisabledFields();
// Set<DOMElement> getAppearedFields();
Set<DOMElement> getAppearedEnabledFields();
Set<DOMElement> getAppearedDisabledFields();
Set<DOMElement> getEnabledFields();
Set<DOMElement> getDisabledFields();
Set<String> getAppearedText();
boolean isFormChanged();
Set<DOMElement> getFieldswithCSSChange();
Set<DOMElement> getRemovedFields();
Set<DOMElement> getDisappearedFields();
Long countElementsWithVisibilityChange();
// countNodesWithVisibilityChange: 0
// fieldsWithNewOptions : [],
// fieldsWithRemovedOptions : [],
// newEnabledFields : [],
// newDisabledFields : [],
// appearedEnabledFields : [],
// appearedDisabledFields : [],
// enabledFields : [],
// disabledFields : [],
// // strings
// textVaried : [],//strings
// //removedElements : [],
// removedFields : [],
// disappearedFields : [],
// fieldsWithCSSChange : []
}
| 22.981481 | 50 | 0.709911 |
30b57b15303deec4be4c22697f10e19292133fae | 549 | package com.ma.home;
class Building
{
Building()
{
System.out.println("Geek-Buiding");
}
Building(String name)
{
this();
System.out.println("Geek-building: String Constructor " + name);
}
}
public class House extends Building
{
House()
{
System.out.println("Geek-House ");
}
House(String name)
{
this();
System.out.println("Geek-house: String Constructor " + name);
}
public static void main(String[] args)
{
new House("Geek");
}
}
| 17.709677 | 72 | 0.551913 |
b4e0efb264f9e1a2e86a9de0491b7c43471e96d9 | 254 | package htmlcompiler.pojos.httpmock;
public class Header {
public final String name;
public final String value;
public Header(final String name, final String value) {
this.name = name;
this.value = value;
}
}
| 21.166667 | 59 | 0.633858 |
493edf82cfd0371879740e812ba49b0c905839db | 300 | package com.example.administrator.testone.util;
import android.util.Log;
/**
* 日志类
*/
public class LL {
private static boolean flag = true;
private static String TAG = "日志";
public static void d(Object msg) {
if (flag) {
Log.d(TAG, " " + msg);
}
}
}
| 15.789474 | 47 | 0.57 |
6302d77194b7eaf789e5b03e5d234d07efc33de2 | 3,912 | package com.amazon.ion.impl.bin.utf8;
import com.amazon.ion.IonException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
/**
* Decodes {@link String}s from UTF-8. Instances of this class are reusable but are NOT threadsafe.
*
* Instances are vended by {@link Utf8StringDecoderPool#getOrCreate()}.
*
* Users are expected to call {@link #close()} when the decoder is no longer needed.
*
* There are two ways of using this class:
* <ol>
* <li>Use {@link #decode(ByteBuffer, int)} to decode the requested number of bytes from the given ByteBuffer in
* a single step. Or,</li>
* <li>Use the following sequence of method calls:
* <ol>
* <li>{@link #prepareDecode(int)} to prepare the decoder to decode the requested number of bytes.</li>
* <li>{@link #partialDecode(ByteBuffer, boolean)} to decode the available bytes from the byte buffer. This may
* be repeated as more bytes are made available in the ByteBuffer, which is the caller's responsibility.</li>
* <li>{@link #finishDecode()} to finish decoding and return the resulting String.</li>
* </ol>
* Note: {@link #decode(ByteBuffer, int)} must not be called between calls to {@link #prepareDecode(int)} and
* {@link #finishDecode()}.
* </li>
* </ol>
*/
public class Utf8StringDecoder extends Poolable<Utf8StringDecoder> {
// The size of the UTF-8 decoding buffer.
private static final int UTF8_BUFFER_SIZE_IN_BYTES = 4 * 1024;
private final CharBuffer reusableUtf8DecodingBuffer;
private final CharsetDecoder utf8CharsetDecoder;
private CharBuffer utf8DecodingBuffer;
Utf8StringDecoder(Pool<Utf8StringDecoder> pool) {
super(pool);
reusableUtf8DecodingBuffer = CharBuffer.allocate(UTF8_BUFFER_SIZE_IN_BYTES);
utf8CharsetDecoder = Charset.forName("UTF-8").newDecoder();
}
/**
* Prepares the decoder to decode the given number of UTF-8 bytes.
* @param numberOfBytes the number of bytes to decode.
*/
public void prepareDecode(int numberOfBytes) {
utf8CharsetDecoder.reset();
utf8DecodingBuffer = reusableUtf8DecodingBuffer;
if (numberOfBytes > reusableUtf8DecodingBuffer.capacity()) {
utf8DecodingBuffer = CharBuffer.allocate(numberOfBytes);
}
}
/**
* Decodes the available bytes from the given ByteBuffer.
* @param utf8InputBuffer a ByteBuffer containing UTF-8 bytes.
* @param endOfInput true if the end of the UTF-8 sequence is expected to occur in the buffer; otherwise, false.
*/
public void partialDecode(ByteBuffer utf8InputBuffer, boolean endOfInput) {
CoderResult coderResult = utf8CharsetDecoder.decode(utf8InputBuffer, utf8DecodingBuffer, endOfInput);
if (coderResult.isError()) {
throw new IonException("Illegal value encountered while validating UTF-8 data in input stream. " + coderResult.toString());
}
}
/**
* Finishes decoding and returns the resulting String.
* @return the decoded Java String.
*/
public String finishDecode() {
utf8DecodingBuffer.flip();
return utf8DecodingBuffer.toString();
}
/**
* Decodes the given number of UTF-8 bytes from the given ByteBuffer into a Java String.
* @param utf8InputBuffer a ByteBuffer containing UTF-8 bytes.
* @param numberOfBytes the number of bytes from the utf8InputBuffer to decode.
* @return the decoded Java String.
*/
public String decode(ByteBuffer utf8InputBuffer, int numberOfBytes) {
prepareDecode(numberOfBytes);
utf8DecodingBuffer.position(0);
utf8DecodingBuffer.limit(utf8DecodingBuffer.capacity());
partialDecode(utf8InputBuffer, true);
return finishDecode();
}
}
| 39.918367 | 135 | 0.697086 |
268566af549843baf9d18d5b7063bca317a1723d | 1,001 | package in.mahabhujal.mahabhujal.borewellApi;
import in.mahabhujal.mahabhujal.model.BorewellRegisterModel;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
public interface BorewellRegisterApi {
@FormUrlEncoded
@POST("borewellregisterpost/")
Call<BorewellRegisterModel> borewellRegister(@Field("borewellid") String borewellid,
@Field("image") String image,
@Field("ownername") String ownername,
@Field("location") String location,
@Field("elevation") String elevation,
@Field("depth") String depth,
@Field("ownership")String ownership,
@Field("purpose")String purpose);}
| 40.04 | 88 | 0.517483 |
e29ff06775bb1976fe2562eddc5a224eeba6b69a | 606 | package search;
import java.util.LinkedList;
public class PriorityQueue {
private LinkedList<Task> tasks = new LinkedList<>();
/**
* Метод вставляет в нужную позицию элемент
* @param task
*/
public void put(Task task) {
int count = (int) tasks.stream().filter(element -> element.getPriority() < task.getPriority()).count();
tasks.add(count, task);
}
public Task take() {
return this.tasks.poll();
}
public void getAll() {
for (var i = 0; i < tasks.size(); i++) {
System.out.println(tasks.get(i));
}
}
}
| 21.642857 | 110 | 0.574257 |
d68f4f7a78f624c2517f103f08b578e83ad3ee9c | 2,143 |
package controller;
import dao.UnidadeSaudeDao;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import model.UnidadeSaudeModel;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import util.ReportUtils;
public class UnidadeSaudeController implements GenericController<UnidadeSaudeModel> {
UnidadeSaudeDao unidadeSaudeDao;
public UnidadeSaudeController() {
unidadeSaudeDao = new UnidadeSaudeDao();
}
@Override
public void incluir(UnidadeSaudeModel obj) throws Exception{
unidadeSaudeDao.incluir(obj);
}
@Override
public void alterar(UnidadeSaudeModel obj) throws Exception{
unidadeSaudeDao.alterar(obj);
}
@Override
public void excluir(UnidadeSaudeModel obj) throws Exception{
unidadeSaudeDao.excluir(obj);
}
@Override
public ArrayList<UnidadeSaudeModel> consultar(String filtro) {
return unidadeSaudeDao.consultar(filtro);
}
@Override
public void gravar(UnidadeSaudeModel obj, String operacao) throws Exception{
if (operacao.equals("incluir")) {
incluir(obj);
} else {
alterar(obj);
}
}
@Override
public Exception imprimir() {
Exception retorno = null;
InputStream inputStream = getClass().getResourceAsStream("/relatorios/RelatorioUnidadeSaude.jasper");
// btnPRIMEIRO.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/primeiro.png"))); // NOI18N
Map parametros = new HashMap();
List dados = consultar("");
// criando o datasource com os dados criados
JRDataSource ds = new JRBeanCollectionDataSource(dados);
try {
// passando o datasource para o método de criação e exibição do relatório
ReportUtils.openReport("Unidade Saude - Bean Collection Data Source", inputStream, parametros, ds);
} catch (Exception ex) {
retorno = ex;
}
return retorno;
}
}
| 28.197368 | 116 | 0.680355 |
7faab34d34b14163aeadd2fac02ac7e49e3a0016 | 218 | package com.testsigma.automator.actions.mobile.mobileweb.ifconditional;
import com.testsigma.automator.actions.mobile.mobileweb.verify.VerifyTextAction;
public class ElementHasTextAction extends VerifyTextAction {
}
| 31.142857 | 80 | 0.862385 |
fd4f34ac8f71657a757ef8d451879a576f347bdf | 2,348 | package org.gbif.pipelines.validator.rules;
import static org.gbif.validator.api.EvaluationType.*;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.gbif.api.model.pipelines.StepType;
import org.gbif.validator.api.EvaluationType;
import org.gbif.validator.api.Metrics;
import org.gbif.validator.api.Metrics.FileInfo;
import org.gbif.validator.api.Validation.Status;
/**
* Class defining the "rule" to determine if a resource can be indexed or not. needed, add the
* mapping between the ValidationProfile and the rule
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class IndexableRules {
/** {@link EvaluationType} that makes the resource non-indexable. */
private static final Set<EvaluationType> NON_INDEXABLE_EVALUATION_TYPE =
new HashSet<>(
Arrays.asList(
DWCA_UNREADABLE,
DWCA_META_XML_NOT_FOUND,
DWCA_META_XML_SCHEMA,
UNREADABLE_SECTION_ERROR,
CORE_ROWTYPE_UNDETERMINED,
RECORD_IDENTIFIER_NOT_FOUND,
RECORD_REFERENTIAL_INTEGRITY_VIOLATION,
RECORD_NOT_UNIQUELY_IDENTIFIED,
OCCURRENCE_NOT_UNIQUELY_IDENTIFIED,
DUPLICATED_TERM,
LICENSE_MISSING_OR_UNKNOWN));
/** Check that all steps were completed(except current) and there is no non-indexable issue */
public static boolean isIndexable(StepType ignoreStepType, Metrics metrics) {
boolean finishedAllSteps =
metrics.getStepTypes().stream()
.filter(x -> !x.getStepType().equals(ignoreStepType.name()))
.noneMatch(y -> y.getStatus() != Status.FINISHED);
boolean noNonIndexableIssue =
metrics.getFileInfos().stream()
.map(FileInfo::getIssues)
.flatMap(Collection::stream)
.map(
x -> {
try {
return EvaluationType.valueOf(x.getIssue());
} catch (Exception ex) {
return null;
}
})
.filter(Objects::nonNull)
.noneMatch(NON_INDEXABLE_EVALUATION_TYPE::contains);
return finishedAllSteps && noNonIndexableIssue;
}
}
| 35.575758 | 96 | 0.66184 |
1ffadb680b39baff4b183b911c8be32975fd8337 | 161 | class Test {
void simpleMethod() {
int x = 0;
int y = 0;
Runnable t = () -> System.out.println(x);
int k = <caret>1;
}
}
| 17.888889 | 49 | 0.440994 |
50a262eade01e7251b740526f65214d9363213bc | 6,640 | package Zigzag;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import static java.time.temporal.ChronoUnit.MINUTES;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class User {
public static void main(String[] args) {
ZigZag.levelonfloor();
//Graphical user interface for the user input
//obtain user input from JOption dialog for the length
String length =
JOptionPane.showInputDialog("Length of the zigzag?(cm) between 20cm and 80cm");
if (length == null) {
JOptionPane.showMessageDialog(null, "You can always come back and try the project again :)", null, JOptionPane.ERROR_MESSAGE);;
System.exit(0);
}
else if (length == "") {
JOptionPane.showMessageDialog(null, "You can always come back and try the project again :)", null, JOptionPane.ERROR_MESSAGE);;
System.exit(0);
}
/*else if (length.equalsIgnoreCase("")) {
System.out.println("This is OK button without input");
}*/
//convert String inputs to int values for the use of calculation
int intLen = Integer.parseInt(length);
//Validation rules for the input
while(intLen<20 || intLen>80)
try {
intLen = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter the length of line 'must be between(20cm to 80 cm)"));
}
catch (NumberFormatException e)
{
System.out.println("The exception is: " + e);
JOptionPane.showMessageDialog(null, "Only numeric values accepted", null, JOptionPane.ERROR_MESSAGE);
}
//obtain user input from JOption dialog for the number
String number =
JOptionPane.showInputDialog("How many zigzags?(even number from 2-10)");
if (number == null) {
JOptionPane.showMessageDialog(null, "You can always come back and try the project again :)", null, JOptionPane.ERROR_MESSAGE);;
System.exit(0);
}
// convert String inputs to int values for the use of calculation
int intNum = Integer.parseInt(number);
//Validation rules for the input
while((intNum<2 || intNum>10) || (intNum % 2 != 0)) {
try {
intNum = Integer.parseInt(JOptionPane.showInputDialog(null, "How many zigzags?(even number from 2-10)"));
}
catch (NumberFormatException e)
{
System.out.println("The exception is: " + e);
JOptionPane.showMessageDialog(null, "Only numeric values accepted", null, JOptionPane.ERROR_MESSAGE);
}
}
//display results in JOptionPane message dialog
JOptionPane.showMessageDialog(null, "The finch will move for " + intLen + "cm " +
"and for " + intNum + " section", "Movment", JOptionPane.PLAIN_MESSAGE);
//System.out.print("The length is: " + length + "cm");
//Constructor to pass the arguments to the ZigZag class
ZigZag movement = new ZigZag(intLen,intNum);
//This will be the length * by the motor speed
//The motor speed times 0.11 velocity against motor speed
int time = (intLen * 85);
//int time = (intLen * 100);
//Create a random integer between (100-255) for the speed
int RandNum = ThreadLocalRandom.current().nextInt(80,150);
int rightwheel = (int) (RandNum*1.08); //Just to make the straight line movement straight excatly
int leftwheel = RandNum*1;
//for loop for the finch to draw the zigzag line based on the input
//when i is less than the user input, increament i
//if i is an even number call line1 method from the ZigZag class
//if i is an odd number call line2 method from the ZigZag class
//when the loop is done rotate the finch
int i;
ZigZag.dance(); //make the finch dance
LocalTime StartTime = java.time.LocalTime.now();
ZigZag.Start(); //
for(i=0; i < intNum; i++)
{
if(i%2 == 0) //if "i" an even number
{
movement.line1(time, rightwheel, leftwheel);
if(i != intNum)
{
movement.pRotation();
}
}
else{
movement.line2(time, rightwheel, leftwheel);
if(i != intNum)
{
movement.nRotation();
}
}
}
movement.FullRotation();
//for loop for the finch to retrace its movement
// it repeats the same process as the previous loop
//Just the methods are swapped
for(i=0; i < intNum; i++)
{
if(i%2 == 0) //if "i" an even number
{
movement.line2(time, rightwheel, leftwheel);
if(i != intNum)
{
movement.nRotation();
}
}else{
movement.line1(time, rightwheel, leftwheel);
if(i != intNum)
{
movement.pRotation();
}
}
}
movement.StartRotation(); //Rotate bnack to its original place
ZigZag.Finish(); //Text to speech that it finish
LocalTime EndTime = java.time.LocalTime.now();
//Calculations for the user log
int LineDistance = (intLen * intNum); //calculate the line distance
double travDistance = (Math.sqrt(Math.pow(intLen, 2) + Math.pow(intLen, 2))) * intNum/2; //calculate distance from start to END of the zigzag line
//Print the calculations into a text file
String filename ="Output.txt"; //Name of the text file
try {
PrintWriter outputStream = new PrintWriter(filename);
outputStream.println("The line distance is: " + Math.round(LineDistance) + "cm"); //Stores in the RAM first //calculate the line distance
outputStream.println("distance from start/End of zigzag line: " + Math.round(travDistance) + "cm "); //calculate the distance from start to end of zigzag line");
outputStream.println("Speed: " + RandNum);
outputStream.println("The time to start is: " + StartTime);
outputStream.println("The End time is: " + EndTime);
outputStream.close();//Push the data to the file
System.out.println("Done");
}catch(FileNotFoundException e) {
e.printStackTrace();
}
JOptionPane.showMessageDialog(null, "The line distance is: " + Math.round(LineDistance) + "cm" +
"\n" + "distance from start/END of zigzag line: " + Math.round(travDistance) + "cm " +
"\n" + "Speed: " + RandNum + "\n" + "The time to start is: " + StartTime +
"\n" + "The End time is: " + EndTime , "Output", JOptionPane.PLAIN_MESSAGE);
}
}
| 33.877551 | 166 | 0.649548 |
432ec9568682e73004b2fe1302c3f879a9b916cd | 9,299 | /*
* Copyright 2021 vg2902.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.vg2902.synchrotask.jdbc;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.vg2902.synchrotask.core.api.LockTimeout;
import org.vg2902.synchrotask.core.api.SynchroTask;
import javax.sql.DataSource;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Set;
import java.util.stream.Stream;
import static java.util.Collections.singleton;
import static java.util.stream.Collectors.toSet;
import static org.vg2902.synchrotask.core.api.LockTimeout.SYSTEM_DEFAULT;
import static org.vg2902.synchrotask.jdbc.EntryCreationResult.CREATION_RESULT_ALREADY_EXISTS;
import static org.vg2902.synchrotask.jdbc.EntryCreationResult.CREATION_RESULT_OK;
import static org.vg2902.synchrotask.jdbc.EntryLockResult.LOCK_RESULT_LOCKED_BY_ANOTHER_TASK;
import static org.vg2902.synchrotask.jdbc.EntryLockResult.LOCK_RESULT_NOT_FOUND;
import static org.vg2902.synchrotask.jdbc.EntryLockResult.LOCK_RESULT_OK;
import static org.vg2902.synchrotask.jdbc.EntryRemovalResult.REMOVAL_RESULT_NOT_FOUND;
import static org.vg2902.synchrotask.jdbc.EntryRemovalResult.REMOVAL_RESULT_OK;
/**
* MySQL-specific {@link SQLRunner} implementation with the following features:
*
* <ul>
* <li>duplicate key error code is <b>1062</b>;</li>
* <li>lock acquire error codes are <b>1205, 3572</b>;</li>
* <li>SQL exception vendor codes are retrieved using {@link SQLException#getErrorCode()}</li>
* <li><b>SELECT FOR UPDATE</b> does not support <b>WAIT</b> clause.
* Instead, the implementation adjusts <b>innodb_lock_wait_timeout</b> {@link java.sql.Connection} parameter.</li>
* </ul>
*
* @see SynchroTask
* @see SynchroTaskJdbcService
*/
@Getter
@Slf4j
final class MySQLRunner<T> extends AbstractSQLRunner<T> {
private static final long MYSQL_MAX_LOCK_TIMEOUT_IN_SECONDS = 1073741824L;
private static final Set<Integer> duplicateKeyErrorCodes = singleton(1062);
private static final Set<Integer> cannotAcquireLockErrorCodes = Stream.of(1205, 3572).collect(toSet());
private final String insertQuery;
private final String selectForUpdateQuery;
private final String selectForUpdateNoWaitQuery;
private final String deleteQuery;
private final String getLockTimeoutQuery;
private final String updateLockTimeoutQuery;
MySQLRunner(DataSource datasource, String tableName, SynchroTask<T> task) throws SQLException {
super(datasource, tableName, task);
insertQuery = "INSERT INTO " + tableName + "(task_name, task_id, creation_time) VALUES (?, ?, ?)";
selectForUpdateQuery = "SELECT task_name, task_id FROM " + tableName + " WHERE task_name = ? AND task_id = ? FOR UPDATE";
selectForUpdateNoWaitQuery = selectForUpdateQuery + " NOWAIT";
deleteQuery = "DELETE FROM " + tableName + " WHERE task_name = ? AND task_id = ?";
getLockTimeoutQuery = "SELECT @@SESSION.innodb_lock_wait_timeout";
updateLockTimeoutQuery = "SET @@SESSION.innodb_lock_wait_timeout = ?";
}
@Override
public EntryCreationResult createLockEntry() throws SQLException {
super.checkNotClosed();
log.debug("Creating a lock entry for {}", task);
try {
selectForUpdate(true);
} catch (SQLException e) {
if (isCannotAcquireLock(e)) {
connection.rollback();
return CREATION_RESULT_ALREADY_EXISTS;
} else {
throw e;
}
}
try {
insert();
} catch (SQLException e) {
if (isDuplicateKey(e)) {
log.debug("Lock entry for {} already exists", task);
connection.rollback();
return CREATION_RESULT_ALREADY_EXISTS;
} else {
throw e;
}
}
log.debug("Lock entry for {} is successfully created", task);
return CREATION_RESULT_OK;
}
private void insert() throws SQLException {
log.debug(insertQuery);
try (PreparedStatement stmt = super.connection.prepareStatement(insertQuery)) {
stmt.setString(1, String.valueOf(task.getTaskName()));
stmt.setString(2, String.valueOf(task.getTaskId()));
stmt.setTimestamp(3, Timestamp.valueOf(LocalDateTime.now()));
stmt.executeUpdate();
super.connection.commit();
}
}
@Override
public boolean isDuplicateKey(SQLException e) {
return isExceptionErrorCodeIn(e, duplicateKeyErrorCodes);
}
@Override
public EntryLockResult acquireLock() throws SQLException {
super.checkNotClosed();
log.debug("Acquiring lock for {}", task);
LockTimeout lockTimeout = getTask().getLockTimeout();
boolean isLockTimeoutAdjustmentRequired = lockTimeout != SYSTEM_DEFAULT;
int currentLockTimeoutInSeconds = 0;
if (isLockTimeoutAdjustmentRequired)
currentLockTimeoutInSeconds = adjustLockTimeout();
try {
boolean noWait = lockTimeout.getValueInMillis() == 0;
boolean isLocked = selectForUpdate(noWait);
if (!isLocked)
return LOCK_RESULT_NOT_FOUND;
} catch (SQLException e) {
if (isCannotAcquireLock(e)) {
return LOCK_RESULT_LOCKED_BY_ANOTHER_TASK;
} else {
throw e;
}
} finally {
if (isLockTimeoutAdjustmentRequired)
updateLockTimeout(currentLockTimeoutInSeconds);
}
return LOCK_RESULT_OK;
}
private int adjustLockTimeout() throws SQLException {
int currentLockTimeoutInSeconds = getLockTimeoutInSeconds();
log.debug("Current lock timeout: {}s", currentLockTimeoutInSeconds);
LockTimeout lockTimeout = getTask().getLockTimeout();
long lockTimeoutInSecondsOverride = lockTimeout.getValueInMillis() / 1000L;
if (lockTimeoutInSecondsOverride > MYSQL_MAX_LOCK_TIMEOUT_IN_SECONDS)
log.warn("Provided lock timeout " + lockTimeoutInSecondsOverride + " exceeds MySQL max supported value and will be adjusted to " + MYSQL_MAX_LOCK_TIMEOUT_IN_SECONDS);
if (lockTimeout == LockTimeout.MAX_SUPPORTED || lockTimeoutInSecondsOverride > MYSQL_MAX_LOCK_TIMEOUT_IN_SECONDS)
lockTimeoutInSecondsOverride = MYSQL_MAX_LOCK_TIMEOUT_IN_SECONDS;
updateLockTimeout((int) lockTimeoutInSecondsOverride);
return currentLockTimeoutInSeconds;
}
private boolean selectForUpdate(boolean noWait) throws SQLException {
String sql = noWait ? selectForUpdateNoWaitQuery : selectForUpdateQuery;
log.debug(sql);
try (PreparedStatement stmt = super.connection.prepareStatement(sql)) {
stmt.setString(1, String.valueOf(task.getTaskName()));
stmt.setString(2, String.valueOf(task.getTaskId()));
ResultSet resultSet = stmt.executeQuery();
return resultSet.next();
}
}
private int getLockTimeoutInSeconds() throws SQLException {
log.debug(getLockTimeoutQuery);
try (Statement currentTimeout = super.connection.createStatement()) {
ResultSet rs = currentTimeout.executeQuery(getLockTimeoutQuery);
rs.next();
return rs.getInt(1);
}
}
private void updateLockTimeout(int lockTimeoutInSeconds) throws SQLException {
log.debug("Updating lock timeout to: {}", lockTimeoutInSeconds);
log.debug(updateLockTimeoutQuery);
try (PreparedStatement updateTimeout = super.connection.prepareStatement(updateLockTimeoutQuery)) {
updateTimeout.setInt(1, lockTimeoutInSeconds);
updateTimeout.executeUpdate();
}
}
@Override
public boolean isCannotAcquireLock(SQLException e) {
return isExceptionErrorCodeIn(e, cannotAcquireLockErrorCodes);
}
@Override
public EntryRemovalResult removeLockEntry() throws SQLException {
super.checkNotClosed();
if (delete())
return REMOVAL_RESULT_OK;
else
return REMOVAL_RESULT_NOT_FOUND;
}
private boolean delete() throws SQLException {
log.debug(deleteQuery);
try (PreparedStatement stmt = super.connection.prepareStatement(deleteQuery)) {
stmt.setString(1, String.valueOf(task.getTaskName()));
stmt.setString(2, String.valueOf(task.getTaskId()));
int cnt = stmt.executeUpdate();
super.connection.commit();
return cnt > 0;
}
}
} | 37.345382 | 178 | 0.684805 |
ade0286cbbf3e98f1c9417b5d2fc543bfbe89931 | 11,387 | package trees.layout;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import trees.style.Orientation;
import trees.style.Size;
import trees.style.Style;
import static trees.layout.Action.*;
/**
* Helper class for wrapping a tree into an internal structure which
* contains all the displaying information.
*
* @author Marcus Deininger
*
*/
public class Node implements Iterable<Node> {
private ModelData model;
private List<Node> children = new ArrayList<>();
private boolean[] hasChild = new boolean[0];
protected Node parent, leftNeighbor;
protected int xCoordinate, yCoordinate, prelim, modifier;
private int width, height;
private Orientation orientation;
private boolean pointerBoxes;
/**
* Constructor for creating a node wrapper.
*
* @param model The object to be wrapped.
* @param style The displaying style to be used.
*/
public Node(ModelData model, Style style) {
this.model = model;
this.resize(style);
}
/**
* Adds some nodes to the current node.
*
* @param children The nodes to be added.
*/
public void add(Node ... children){
int i = hasChild.length;
hasChild = Arrays.copyOf(hasChild, hasChild.length + children.length);
for(Node child : children){
this.children.add(child);
if(child != null)
child.parent = this;
hasChild[i++] = (child != null && !child.isPlaceHolder());
}
}
/* (non-Javadoc)
* @see java.lang.Iterable#iterator()
*/
@Override
public Iterator<Node> iterator() {
return children.iterator();
}
// Printing //////////////////////////////////////////////////////
/**
* Prints the tree in post-order sequence.
*/
public void printPostOrder(){
this.printPostOrder(this);
}
private void printPostOrder(Node node){
if(node == null)
return;
for(Node child : node)
printPostOrder(child);
System.out.println(node.toString());
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
return "Node[" + model.getModelLabel().split("\\n")[0] + ", " + prelim + " + " + modifier + " ->\t" + xCoordinate + "|" + yCoordinate + "]";
}
// Model methods //////////////////////////////////////////////////////
/**
* Returns the class of the wrapped model object.
* @return The class of the wrapped model object.
*/
public Class<?> getModelClass() {
return model.getModelClass();
}
/**
* Returns the wrapped model object.
* @return The wrapped model object.
*/
public Object getModelObject(){
return model.getModelObject();
}
// Display methods //////////////////////////////////////////////////////
/**
* Checks if the wrapped node is a duplicate -
* i.e. already contained in the tree. Actually this means,
* the structure is not really a tree.
* @return true, if the node is already displayed.
*/
public boolean isDuplicate() {
return model.isDuplicate();
}
/**
* Checks if the node is a placeholder for generating space.
* @return true, if the node is a placeholder object.
*/
public boolean isPlaceHolder(){
return model.isPlaceholder();
}
/**
* Returns the x-coordinate of the node which starts top left.
* @return The x-coordinate of the node
*/
public int getX() {
return xCoordinate;
}
/**
* Returns the y-coordinate of the node which starts top left.
* @return The y-coordinate of the node
*/
public int getY() {
return yCoordinate;
}
/**
* Returns the x-coordinate with an added offset.
* @param offset The offset to be added.
* @return The x-coordinate of the node with offset.
*/
public int getX(int offset) {
return xCoordinate + offset;
}
/**
* Returns the y-coordinate with an added offset.
* @param offset The offset to be added.
* @return The y-coordinate of the node with offset.
*/
public int getY(int offset) {
return yCoordinate + offset;
}
/**
* Returns the preliminary coordinate.
* @return The preliminary coordinate of the node.
*/
public int getPrelim() {
return prelim;
}
/**
* Returns the modifier, which gives an additional placement.
* @return The placement modifier.
*/
public int getModifier() {
return modifier;
}
/**
* Returns the size of the contained label.
* @return The size of the contained label.
*/
public Dimension getLabelSize(){
return model.getLabelSize();
}
/**
* Returns the label split into lines.
* @return The lines of the label.
*/
public String[] getLabelLines(){
return model.getLines();
}
/**
* Calculates the rectangle which is taken by the tree
* with respect to the style. By default this rectangle
* starts top left at (0|0). An offset is added later.
* @param style The style for this tree.
* @return The rectangle covered by this tree.
*/
public Rectangle getTreeArea(Style style){
// By definition, the coordinates are without offset
Point p = this.getRightmostPoint(style);
Rectangle area = new Rectangle(0, 0, p.x, p.y);
return area;
}
private Point getRightmostPoint(Style style) {
int x = this.getX() + this.getWidth();
int y = this.getY() + this.getHeight();
for(Node child : children)
if(child != null){
Point p = child.getRightmostPoint(style);
if(p.x > x) x = p.x;
if(p.y > y) y = p.y;
}
Point p = new Point(x, y);
return p;
}
/**
* Returns the rectangle coordinates for this node.
* @return The rectangle coordinates for this node.
*/
public Rectangle getNodeArea(){
return new Rectangle(xCoordinate, yCoordinate, width, height);
}
/**
* Returns the rectangle coordinates for this node with an added offset.
* @param offset The offset to be added.
* @return The rectangle coordinates for this node with an added offset.
*/
public Rectangle getNodeArea(Dimension offset){
return new Rectangle(xCoordinate + offset.width, yCoordinate + offset.height, width, height);
}
/**
* Returns the rectangle coordinates for this nodes' label with an added offset.
* @param offset The offset to be added.
* @return The rectangle coordinates for this label with an added offset.
*/
public Rectangle getLabelArea(Dimension offset){
Rectangle area = this.getLabelArea();
return new Rectangle(area.x + offset.width, area.y + offset.height, area.width, area.height);
}
/**
* Returns the rectangle coordinates for this nodes' label.
* @return The rectangle coordinates for this label.
*/
public Rectangle getLabelArea(){
int xOff = Style.LABEL_MARGIN;
int yOff = Style.LABEL_MARGIN;
int width = this.width - 2 * Style.LABEL_MARGIN;
int height = this.height - 2 * Style.LABEL_MARGIN;
if(this.pointerBoxes)
switch(this.orientation){
case NORTH: height = height - Style.POINTER_BOX_HEIGHT; break;
case SOUTH: height = height - Style.POINTER_BOX_HEIGHT;
yOff = yOff + Style.POINTER_BOX_HEIGHT; break;
case EAST: width = width - Style.POINTER_BOX_HEIGHT;
xOff = xOff + Style.POINTER_BOX_HEIGHT; break;
case WEST: width = width - Style.POINTER_BOX_HEIGHT; break;
}
return new Rectangle(xCoordinate + xOff, yCoordinate + yOff, width, height);
}
// Layout methods //////////////////////////////////////////////////////
/**
* Initializes the tree recursively.
* @param style The style to be used.
* @param action The initialization level.
*/
protected void init(Style style, Action action){
model.align(style);
this.resize(style);
xCoordinate = 0;
yCoordinate = 0;
if(action.atLeast(REPOSITION)){
leftNeighbor = null;
prelim = 0;
modifier = 0;
}
for(Node child : children)
if(child != null)
child.init(style, action);
}
// calculates the nodes width and height with respect to the current style
private void resize(Style style) {
this.pointerBoxes = style.hasPointerBoxes(model.getModelClass());
this.orientation = style.getOrientation();
Size size = style.getSize(model.getModelClass());
if(size.isFixed()){
Dimension dimension = size.getMaximum();
this.width = dimension.width;
this.height = dimension.height;
return;
}
Dimension labelDimension = model.getLabelSize();
this.width = labelDimension.width + 2 * Style.LABEL_MARGIN;
this.height = labelDimension.height + 2 * Style.LABEL_MARGIN;
if(this.pointerBoxes)
if(this.orientation.isHorizontal())
this.width = this.width + Style.POINTER_BOX_HEIGHT;
else
this.height = this.height + Style.POINTER_BOX_HEIGHT;
if(size.hasMaximum()){
Dimension max = size.getMaximum();
if(max.width < this.width)
this.width = max.width;
if(max.height < this.height)
this.height = max.height;
}
if(size.hasMinimum()){
Dimension min = size.getMinimum();
if(min.width > this.width)
this.width = min.width;
if(min.height > this.height)
this.height = min.height;
}
}
// The current node's leftmost offspring
protected Node getFirstChild(){
for(Node child : children)
if(child != null)
return child;
return null;
}
// The current node's closest sibling node on the left
protected Node getLeftSibling(){
if(parent == null) // root
return null;
int thisPos = -1;
for(int i = 0; i < parent.children.size(); i++)
if(parent.children.get(i) == this)
thisPos = i;
for(int i = thisPos - 1; i >= 0; i--)
if(parent.children.get(i) != null)
return parent.children.get(i);
return null;
}
// The current node's closest sibling node on the right
protected Node getRightSibling(){
if(parent == null)
return null;
int thisPos = -1;
for(int i = 0; i < parent.children.size(); i++)
if(parent.children.get(i) == this)
thisPos = i;
for(int i = thisPos + 1; i < parent.children.size(); i++)
if(parent.children.get(i) != null)
return parent.children.get(i);
return null;
}
protected boolean hasRightSibling() {
return this.getRightSibling() != null;
}
protected boolean hasLeftSibling() {
return this.getLeftSibling() != null;
}
/**
* Checks if the node is a leaf.
* @return true, if the node is a leaf.
*/
public boolean isLeaf() {
return !hasChildren();
}
/**
* Checks if the node has at least one child
* which is not null.
* @return true, if the has non-null children.
*/
public boolean hasChildren() {
for(Node child : children)
if(child != null)
return true;
return false;
}
/**
* Checks if the node has a child at index
* which is not null.
* @param index Index of the child to be checked.
* @return true, if the has a non-null child at index.
*/
public boolean hasChild(int index) {
return hasChild[index];
}
/**
* Returns the number of children (null and non-null).
* @return The number of children.
*/
public int getChildrenSlots(){
return hasChild.length;
}
/**
* The height of the node.
* @return The height of the node.
*/
public int getHeight() {
return this.height;
}
/**
* The width of the node.
* @return The width of the node.
*/
public int getWidth() {
return this.width;
}
/**
* The size of the node. This is the height when the style is
* horizontal, else the width.
* @return The size of the node.
*/
protected int getSize(){
if(orientation.isHorizontal())
return this.height;
else
return this.width;
}
}
| 25.026374 | 142 | 0.6597 |
f43c46bd0f4abe82cd54fa69c21be0d385e0db61 | 1,111 | package com.couchbase.lite.android;
import com.couchbase.lite.Context;
import com.couchbase.lite.NetworkReachabilityManager;
import java.io.File;
public class AndroidContext implements Context {
private android.content.Context wrappedContext;
private NetworkReachabilityManager networkReachabilityManager;
public AndroidContext(android.content.Context wrappedContext) {
this.wrappedContext = wrappedContext;
}
@Override
public File getFilesDir() {
return wrappedContext.getFilesDir();
}
@Override
public void setNetworkReachabilityManager(NetworkReachabilityManager networkReachabilityManager) {
this.networkReachabilityManager = networkReachabilityManager;
}
@Override
public NetworkReachabilityManager getNetworkReachabilityManager() {
if (networkReachabilityManager == null) {
networkReachabilityManager = new AndroidNetworkReachabilityManager(this);
}
return networkReachabilityManager;
}
public android.content.Context getWrappedContext() {
return wrappedContext;
}
}
| 27.775 | 102 | 0.747975 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.