code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public CheckRef createCheckRef(){
CheckRefImpl checkRef=new CheckRefImpl();
return checkRef;
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public static <T1,T2,R>Supplier<R> partial2(final T1 t1,final T2 t2,final BiFunction<T1,T2,R> biFunc){
return null;
}
| Returns a function with 2 arguments applied to the supplied BiFunction |
@Override protected void endBody() throws IOException {
PrintStream out=getPrintStream();
out.println(endBodyText);
}
| Extra stuff printed at the end of the <body> element. |
private void updateView(){
if (!hasEditor()) {
return;
}
ViewEditor editor=getEditor();
relationSetEditor.updateTable(editor.getBuiltinAnalysisPlugins());
relationSetEditor.selectRelations(editor.getDisplayRelations());
}
| Update the view after a change in the model. |
@Override public NotificationChain eInverseRemove(InternalEObject otherEnd,int featureID,NotificationChain msgs){
switch (featureID) {
case UmplePackage.CONSTRAINT_BODY___CONSTRAINT_EXPR_1:
return ((InternalEList<?>)getConstraintExpr_1()).basicRemove(otherEnd,msgs);
case UmplePackage.CONSTRAINT_BODY___ANONYMOUS_CONSTRAINT_BODY_11:
return ((InternalEList<?>)getAnonymous_constraintBody_1_1()).basicRemove(otherEnd,msgs);
}
return super.eInverseRemove(otherEnd,featureID,msgs);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
private void unionRE(Nonterminal nt,RE re){
RE old=getRE(nt);
try {
setRE(nt,old.union(re));
}
catch ( InterruptedException e) {
throw new RuntimeException();
}
}
| Union the parameter regular expression with the existing regular expression mapped to the parameter nonterminal. |
private void closeConnection(IConnection conn){
try {
if (conn != null && conn.isOpen()) conn.close();
}
catch ( OdaException e) {
e.printStackTrace();
}
}
| Attempts to close given ODA connection. |
public DefaultNominator(Agent parentAgent){
this.parentAgent=parentAgent;
logger=new Logger(classLogger,parentAgent.getLogger());
parentAgent.addStateChangeListener(this);
}
| Creates a new instance of this nominator using <tt>parentAgent</tt> as a reference to the <tt>Agent</tt> instance that we should use to nominate pairs. |
private void advance() throws IOException {
close();
if (it.hasNext()) {
current=it.next().getInput();
}
}
| Closes the current reader and opens the next one, if any. |
public static int uninstallSilent(Context context,String packageName,boolean isKeepData){
if (packageName == null || packageName.length() == 0) {
return DELETE_FAILED_INVALID_PACKAGE;
}
StringBuilder command=new StringBuilder().append("LD_LIBRARY_PATH=/vendor/lib:/system/lib pm uninstall").append(isKeepData ? " -k " : " ").append(packageName.replace(" ","\\ "));
ShellUtil.CommandResult commandResult=ShellUtil.execCommand(command.toString(),!isSystemApplication(context),true);
if (commandResult.successMsg != null && (commandResult.successMsg.contains("Success") || commandResult.successMsg.contains("success"))) {
return DELETE_SUCCEEDED;
}
Logger.e(new StringBuilder().append("uninstallSilent successMsg:").append(commandResult.successMsg).append(", ErrorMsg:").append(commandResult.errorMsg).toString());
if (commandResult.errorMsg == null) {
return DELETE_FAILED_INTERNAL_ERROR;
}
if (commandResult.errorMsg.contains("Permission denied")) {
return DELETE_FAILED_PERMISSION_DENIED;
}
return DELETE_FAILED_INTERNAL_ERROR;
}
| uninstall package silent by root <ul> <strong>Attentions:</strong> <li>Don't call this on the ui thread, it may costs some times.</li> <li>You should add <strong>android.permission.DELETE_PACKAGES</strong> in manifest, so no need to request root permission, if you are system app.</li> </ul> |
@AfterClass public static void teardownAfterClass(){
MockStendlRPWorld.reset();
}
| cleanup after tests |
public final void info(Object message){
if (isLevelEnabled(SimpleLog.LOG_LEVEL_INFO)) {
log(SimpleLog.LOG_LEVEL_INFO,message,null);
}
}
| Logs a message with <code>org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_INFO</code>. |
@Override public boolean execute(final Player player,final List<String> args){
return load(player,args);
}
| Executes this script. |
public boolean isClosingHtmlTag(){
return this.htmlTagIndex != -1 && (this.htmlTagIndex & JAVADOC_CLOSED_TAG) != 0;
}
| Returns whether the text is a closing html tag or not. |
protected void appendMove(Game game,int halfMoveNumber){
int currentRow=halfMoveNumber / 2;
if (halfMoveNumber % 2 != 0) {
movesTable.setText(currentRow,1,GameUtils.convertSanToUseUnicode(game.getMoveList().get(halfMoveNumber).toString(),false));
}
else {
int moveNumber=currentRow + 1;
movesTable.appendRow(new String[]{String.valueOf(moveNumber) + ") " + GameUtils.convertSanToUseUnicode(game.getMoveList().get(halfMoveNumber).toString(),true),""});
}
}
| Appends the move at the specified half move number to the movesTable. |
public boolean isReversal(){
return m_IsReversal;
}
| Is Reversal |
@Override public byte[] convertIndexToRGB(final byte[] data){
final byte[] newdata=new byte[3 * 256];
int inpLen=domain.length / 2;
int palLen=data.length / inpLen;
float[] inputs=new float[inpLen];
float[] operand;
int p=0, pp=0, tt;
for (int i=0, ii=Math.min(256,palLen); i < ii; i++) {
for (int j=0; j < inpLen; j++) {
inputs[j]=(data[p++] & 0xff) / 255f;
}
operand=colorMapper.getOperandFloat(inputs);
altCS.setColor(operand,operand.length);
tt=altCS.getColor().getRGB();
newdata[pp++]=(byte)((tt >> 16) & 0xff);
newdata[pp++]=(byte)((tt >> 8) & 0xff);
newdata[pp++]=(byte)(tt & 0xff);
}
return newdata;
}
| create rgb index for color conversion |
private void createECOMConnection(CimConnectionInfo connectionInfo) throws Exception {
String hostAndPort=generateConnectionCacheKey(connectionInfo.getHost(),connectionInfo.getPort());
s_logger.info("Creating connection to ECOM provider on host/port {}",hostAndPort);
try {
EcomConnection connection=new EcomConnection(connectionInfo,_listener,_configuration.getIndicationFilterMap());
connection.connect(_configuration.getSubscriptionsIdentifier(),_configuration.getDeleteStaleSubscriptionsOnConnect());
_connections.put(hostAndPort,connection);
connectionLastTouch.put(hostAndPort,System.currentTimeMillis());
}
catch ( Exception e) {
throw new Exception(MessageFormatter.format("Failed creating connection to ECOM provider on host/port {}",hostAndPort).getMessage(),e);
}
}
| Creates a connection to an ECOM provider using the passed connection info. |
private void updateProgress(int progress){
if (myHost != null && progress != previousProgress) {
myHost.updateProgress(progress);
}
previousProgress=progress;
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
protected AbstractStoringPageFile(int pageSize){
this.emptyPages=new Stack<>();
this.nextPageID=0;
this.pageSize=pageSize;
}
| Creates a new PageFile. |
public RandomPartition(double proba){
this.proba=proba;
random=new Random();
}
| Creates a new vertex filter. |
protected NamedNodeMap createAttributes(){
return new ExtendedNamedNodeHashMap();
}
| Creates the attribute list. |
public ValidatorITCase(String name){
super(name);
}
| Construct a new instance of this test case. |
public Point(Point p){
this(p.x,p.y);
}
| Constructs and initializes a point with the same location as the specified <code>Point</code> object. |
public static void initialiseListOfSupportedEbookFormats(){
if (EBookFormat.getSupportedFormats() != null) {
return;
}
List<EBookFormat> supportedFormats=new LinkedList<EBookFormat>();
InputStream is=ConfigurationManager.getResourceAsStream(Constants.MIMETYPES_FILENAME);
assert is != null;
Scanner scanner=new Scanner(is);
String line;
try {
while (scanner.hasNextLine()) {
line=scanner.nextLine();
if (line.length() == 0 || line.charAt(0) == '#') {
continue;
}
Scanner lineScanner=new Scanner(line);
String formatType=null;
if (lineScanner.hasNext()) formatType=lineScanner.next();
String mimeType=null;
if (lineScanner.hasNext()) mimeType=lineScanner.next();
if (Helper.isNullOrEmpty(formatType) || Helper.isNullOrEmpty(mimeType)) {
logger.error("Invalid line in Mimetypes file '" + line + "'");
continue;
}
supportedFormats.add(new EBookFormat(formatType,mimeType));
}
scanner.close();
is.close();
}
catch ( Exception e) {
}
EBookFormat.setSupportedFormats(supportedFormats);
}
| get the list of supported ebook formats. We use the function that can read from a user configuration file (if present), and if that is not present the default resource file |
public void readRawBinary(BinaryRawReader reader) throws BinaryObjectException {
affKey=BinaryUtils.readIgniteUuid(reader);
status=reader.readInt();
startOff=reader.readLong();
endOff=reader.readLong();
}
| Reads fields from provided reader. |
@Override public boolean markSupported(){
return false;
}
| Since we do not support marking just yet, we return false. |
@Override public String toString(){
return "Cursor: " + index;
}
| Returns the string representation of this cursor. |
public void removeThemeRefreshListener(ActionListener l){
if (themelisteners == null) {
return;
}
themelisteners.removeListener(l);
}
| Removes a Theme refresh listener. |
public JSONWriter object() throws JSONException {
if (this.mode == 'i') {
this.mode='o';
}
if (this.mode == 'o' || this.mode == 'a') {
this.append("{");
this.push(new JSONObject());
this.comma=false;
return this;
}
throw new JSONException("Misplaced object.");
}
| Begin appending a new object. All keys and values until the balancing <code>endObject</code> will be appended to this object. The <code>endObject</code> method must be called to mark the object's end. |
public void fillFieldValues(List<SynapseUpdateRule> ruleList){
OjaRule synapseRef=(OjaRule)ruleList.get(0);
if (!NetworkUtils.isConsistent(ruleList,OjaRule.class,"getNormalizationFactor")) {
tfNormalize.setText(SimbrainConstants.NULL_STRING);
}
else {
tfNormalize.setText(Double.toString(synapseRef.getNormalizationFactor()));
}
if (!NetworkUtils.isConsistent(ruleList,OjaRule.class,"getLearningRate")) {
tfLearningRate.setText(SimbrainConstants.NULL_STRING);
}
else {
tfLearningRate.setText(Double.toString(synapseRef.getLearningRate()));
}
}
| Populate fields with current data. |
void clear(){
zoneInfo.zoneChanged();
}
| Prepare for zone change. |
@SuppressWarnings({"SimplifiableIfStatement","IfMayBeConditional"}) public void finish(){
boolean sync;
if (!F.isEmpty(dhtMap) || !F.isEmpty(nearMap)) sync=finish(dhtMap,nearMap);
else if (!commit && !F.isEmpty(tx.lockTransactionNodes())) sync=rollbackLockTransactions(tx.lockTransactionNodes());
else sync=false;
markInitialized();
if (!sync) onComplete();
}
| Initializes future. |
public static double pow(double x,double y){
final double lns[]=new double[2];
if (y == 0.0) {
return 1.0;
}
if (x != x) {
return x;
}
if (x == 0) {
long bits=Double.doubleToRawLongBits(x);
if ((bits & 0x8000000000000000L) != 0) {
long yi=(long)y;
if (y < 0 && y == yi && (yi & 1) == 1) {
return Double.NEGATIVE_INFINITY;
}
if (y > 0 && y == yi && (yi & 1) == 1) {
return -0.0;
}
}
if (y < 0) {
return Double.POSITIVE_INFINITY;
}
if (y > 0) {
return 0.0;
}
return Double.NaN;
}
if (x == Double.POSITIVE_INFINITY) {
if (y != y) {
return y;
}
if (y < 0.0) {
return 0.0;
}
else {
return Double.POSITIVE_INFINITY;
}
}
if (y == Double.POSITIVE_INFINITY) {
if (x * x == 1.0) {
return Double.NaN;
}
if (x * x > 1.0) {
return Double.POSITIVE_INFINITY;
}
else {
return 0.0;
}
}
if (x == Double.NEGATIVE_INFINITY) {
if (y != y) {
return y;
}
if (y < 0) {
long yi=(long)y;
if (y == yi && (yi & 1) == 1) {
return -0.0;
}
return 0.0;
}
if (y > 0) {
long yi=(long)y;
if (y == yi && (yi & 1) == 1) {
return Double.NEGATIVE_INFINITY;
}
return Double.POSITIVE_INFINITY;
}
}
if (y == Double.NEGATIVE_INFINITY) {
if (x * x == 1.0) {
return Double.NaN;
}
if (x * x < 1.0) {
return Double.POSITIVE_INFINITY;
}
else {
return 0.0;
}
}
if (x < 0) {
if (y >= TWO_POWER_53 || y <= -TWO_POWER_53) {
return pow(-x,y);
}
if (y == (long)y) {
return ((long)y & 1) == 0 ? pow(-x,y) : -pow(-x,y);
}
else {
return Double.NaN;
}
}
double ya;
double yb;
if (y < 8e298 && y > -8e298) {
double tmp1=y * HEX_40000000;
ya=y + tmp1 - tmp1;
yb=y - ya;
}
else {
double tmp1=y * 9.31322574615478515625E-10;
double tmp2=tmp1 * 9.31322574615478515625E-10;
ya=(tmp1 + tmp2 - tmp1) * HEX_40000000 * HEX_40000000;
yb=y - ya;
}
final double lores=log(x,lns);
if (Double.isInfinite(lores)) {
return lores;
}
double lna=lns[0];
double lnb=lns[1];
double tmp1=lna * HEX_40000000;
double tmp2=lna + tmp1 - tmp1;
lnb+=lna - tmp2;
lna=tmp2;
final double aa=lna * ya;
final double ab=lna * yb + lnb * ya + lnb * yb;
lna=aa + ab;
lnb=-(lna - aa - ab);
double z=1.0 / 120.0;
z=z * lnb + (1.0 / 24.0);
z=z * lnb + (1.0 / 6.0);
z=z * lnb + 0.5;
z=z * lnb + 1.0;
z*=lnb;
final double result=exp(lna,z,null);
return result;
}
| Power function. Compute x^y. |
public static Dcsn cs_qr(Dcs A,Dcss S){
double Rx[], Vx[], Ax[], x[], Beta[];
int i, k, p, n, vnz, p1, top, m2, len, col, rnz, s[], leftmost[], Ap[], Ai[], parent[], Rp[], Ri[], Vp[], Vi[], w[], pinv[], q[];
Dcs R, V;
Dcsn N;
if (!Dcs_util.CS_CSC(A) || S == null) return (null);
n=A.n;
Ap=A.p;
Ai=A.i;
Ax=A.x;
q=S.q;
parent=S.parent;
pinv=S.pinv;
m2=S.m2;
vnz=S.lnz;
rnz=S.unz;
leftmost=S.leftmost;
w=new int[m2 + n];
x=new double[m2];
N=new Dcsn();
s=w;
int s_offset=m2;
for (k=0; k < m2; k++) x[k]=0;
N.L=V=Dcs_util.cs_spalloc(m2,n,vnz,true,false);
N.U=R=Dcs_util.cs_spalloc(m2,n,rnz,true,false);
N.B=Beta=new double[n];
Rp=R.p;
Ri=R.i;
Rx=R.x;
Vp=V.p;
Vi=V.i;
Vx=V.x;
for (i=0; i < m2; i++) w[i]=-1;
rnz=0;
vnz=0;
for (k=0; k < n; k++) {
Rp[k]=rnz;
Vp[k]=p1=vnz;
w[k]=k;
Vi[vnz++]=k;
top=n;
col=q != null ? q[k] : k;
for (p=Ap[col]; p < Ap[col + 1]; p++) {
i=leftmost[Ai[p]];
for (len=0; w[i] != k; i=parent[i]) {
s[s_offset + (len++)]=i;
w[i]=k;
}
while (len > 0) s[s_offset + (--top)]=s[s_offset + (--len)];
i=pinv[Ai[p]];
x[i]=Ax[p];
if (i > k && w[i] < k) {
Vi[vnz++]=i;
w[i]=k;
}
}
for (p=top; p < n; p++) {
i=s[s_offset + p];
Dcs_happly.cs_happly(V,i,Beta[i],x);
Ri[rnz]=i;
Rx[rnz++]=x[i];
x[i]=0;
if (parent[i] == k) vnz=Dcs_scatter.cs_scatter(V,i,0,w,null,k,V,vnz);
}
for (p=p1; p < vnz; p++) {
Vx[p]=x[Vi[p]];
x[Vi[p]]=0;
}
Ri[rnz]=k;
double[] beta=new double[1];
beta[0]=Beta[k];
Rx[rnz++]=Dcs_house.cs_house(Vx,p1,beta,vnz - p1);
Beta[k]=beta[0];
}
Rp[n]=rnz;
Vp[n]=vnz;
return N;
}
| Sparse QR factorization of an m-by-n matrix A, A= Q*R |
public boolean isCellEditable(int row,int col){
return false;
}
| Gets the cellEditable attribute of the PropertiesTableModel object |
public JSONArray optJSONArray(String key){
Object o=opt(key);
return o instanceof JSONArray ? (JSONArray)o : null;
}
| Get an optional JSONArray associated with a key. It returns null if there is no such key, or if its value is not a JSONArray. |
@org.hamcrest.Factory public static org.hamcrest.Matcher<Double> equalTo(final Double value){
return equalTo(value,10);
}
| Creates a rounded equal matcher that checks double (near) equality. |
public ChartViewer(JFreeChart chart){
this(chart,true);
}
| Creates a new viewer to display the supplied chart in JavaFX. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-02-24 15:47:29.087 -0500",hash_original_method="B33F4935D7EC88037EE2967518A095D3",hash_generated_method="94868AEDB16628F241D8220AA3C50090") @DSSpec(DSCat.IO) public static String sha512Hex(InputStream data) throws IOException {
return Hex.encodeHexString(sha512(data));
}
| Calculates the SHA-512 digest and returns the value as a hex string. <p> Throws a <code>RuntimeException</code> on JRE versions prior to 1.4.0. </p> |
public VirtualMachineError(java.lang.String s){
super(s);
}
| Constructs a VirtualMachineError with the specified detail message. s - the detail message. |
public Response onCommand(POP3Session session,Request request){
if (session.getHandlerState() == POP3Session.TRANSACTION) {
stat(session);
return POP3Response.OK;
}
else {
return POP3Response.ERR;
}
}
| Handler method called upon receipt of a RSET command. Calls stat() to reset the mailbox. |
public int serverDelivery(Object message,Object consumer,int deliveryCount) throws Exception {
ProtonServerSenderContext protonSender=serverSenders.get(consumer);
if (protonSender != null) {
return protonSender.deliverMessage(message,deliveryCount);
}
return 0;
}
| The consumer object from the broker or the key used to store the sender |
public static void rollbackConnection(@Nullable Connection rsrc,@Nullable IgniteLogger log){
if (rsrc != null) try {
rsrc.rollback();
}
catch ( SQLException e) {
warn(log,"Failed to rollback JDBC connection: " + e.getMessage());
}
}
| Rollbacks JDBC connection logging possible checked exception. |
public void stop(int taskId){
this.readTasks.get(taskId).stop();
}
| Stop the reader for a particular task. |
public TypeEraseFilterFactory(Map<String,String> args){
super(args);
if (!args.isEmpty()) {
throw new IllegalArgumentException("Unknown parameters: " + args);
}
}
| Creates a new PorterStemFilterFactory |
protected void makeRegionData(DrawContext dc){
this.currentData=(RegionData)this.regionDataCache.getEntry(dc.getGlobe());
if (this.currentData == null) {
this.currentData=this.createCacheEntry(dc);
this.regionDataCache.addEntry(this.currentData);
}
if (dc.getFrameTimeStamp() != this.getCurrentData().getFrameNumber()) {
if (this.mustRegenerateData(dc)) {
this.doMakeRegionData(dc);
this.getCurrentData().restartTimer(dc);
this.getCurrentData().setGlobeStateKey(dc.getGlobe().getGlobeStateKey(dc));
this.getCurrentData().setVerticalExaggeration(dc.getVerticalExaggeration());
}
this.getCurrentData().setFrameNumber(dc.getFrameTimeStamp());
}
}
| Produces the data used to determine whether this Region is active for the specified <code>DrawContext</code>. This attempts to re-use <code>RegionData</code> already been calculated this frame, or previously calculated <code>RegionData</code> that is still valid and has not expired. This method is called by <code>isActive</code> prior to determining if this Region is actually active. |
@Override public boolean batchFinished(){
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_Values == null) {
determineValues(getInputFormat());
setOutputFormat();
}
flushInput();
m_NewBatch=true;
m_FirstBatchDone=true;
return (numPendingOutput() != 0);
}
| Signifies that this batch of input to the filter is finished. If the filter requires all instances prior to filtering, output() may now be called to retrieve the filtered instances. |
@Override public T defaultCase(EObject object){
return null;
}
| Returns the result of interpreting the object as an instance of '<em>EObject</em>'. <!-- begin-user-doc --> This implementation returns null; returning a non-null result will terminate the switch, but this is the last case anyway. <!-- end-user-doc --> |
@Override public void environmentConfigure(EnvironmentClassLoader loader) throws ConfigException {
}
| Handles the case where the environment is configuring and registering beans |
@Override protected void mouseClicked(int par1,int par2,int par3) throws IOException {
if (par2 >= 36 && par2 <= height - 57) if (par1 >= width / 2 + 140 || par1 <= width / 2 - 126) altList.elementClicked(-1,false,0,0);
super.mouseClicked(par1,par2,par3);
}
| Called when the mouse is clicked. |
public void paint(Graphics g,Shape a){
Rectangle alloc=(a instanceof Rectangle) ? (Rectangle)a : a.getBounds();
tabBase=alloc.x;
Graphics2D g2d=(Graphics2D)g;
host=(RSyntaxTextArea)getContainer();
int ascent=host.getMaxAscent();
int fontHeight=host.getLineHeight();
int n=getViewCount();
int x=alloc.x + getLeftInset();
int y=alloc.y + getTopInset();
Rectangle clip=g.getClipBounds();
for (int i=0; i < n; i++) {
tempRect.x=x + getOffset(X_AXIS,i);
tempRect.y=y + getOffset(Y_AXIS,i);
tempRect.width=getSpan(X_AXIS,i);
tempRect.height=getSpan(Y_AXIS,i);
if (tempRect.intersects(clip)) {
View view=getView(i);
drawView(g2d,alloc,view,fontHeight,tempRect.y + ascent);
}
}
}
| Paints the word-wrapped text. |
@Override public final void wakeUp() throws AdeException {
super.wakeUp();
createUsageVariables();
}
| Create variables for this class after deserialization. |
public Term(String fld,String text){
this(fld,new BytesRef(text));
}
| Constructs a Term with the given field and text. <p>Note that a null field or null text value results in undefined behavior for most Lucene APIs that accept a Term parameter. |
HeapArrayOfDoublesQuickSelectSketch(final int nomEntries,final int lgResizeFactor,final float samplingProbability,final int numValues,final long seed){
super(numValues,seed);
nomEntries_=ceilingPowerOf2(nomEntries);
lgResizeFactor_=lgResizeFactor;
samplingProbability_=samplingProbability;
theta_=(long)(Long.MAX_VALUE * (double)samplingProbability);
final int startingCapacity=1 << startingSubMultiple(Integer.numberOfTrailingZeros(ceilingPowerOf2(nomEntries) * 2),ResizeFactor.getRF(lgResizeFactor),MIN_LG_ARR_LONGS);
keys_=new long[startingCapacity];
values_=new double[startingCapacity * numValues];
lgCurrentCapacity_=Integer.numberOfTrailingZeros(startingCapacity);
setRebuildThreshold();
}
| This is to create an instance of a QuickSelectSketch with custom resize factor and sampling probability |
public static void main(String[] args){
doMain(args);
}
| Application entry point. |
private static Class<?> toJavaType(DbColumn col){
boolean nullable=col.nullable();
boolean unsigned=col.unsigned();
switch (col.type()) {
case BIT:
case BOOLEAN:
return nullable ? Boolean.class : boolean.class;
case TINYINT:
return unsigned ? (nullable ? Short.class : short.class) : (nullable ? Byte.class : byte.class);
case SMALLINT:
return unsigned ? (nullable ? Integer.class : int.class) : (nullable ? Short.class : short.class);
case INTEGER:
return unsigned ? (nullable ? Long.class : long.class) : (nullable ? Integer.class : int.class);
case BIGINT:
return nullable ? Long.class : long.class;
case REAL:
return nullable ? Float.class : float.class;
case FLOAT:
case DOUBLE:
return nullable ? Double.class : double.class;
case NUMERIC:
case DECIMAL:
return BigDecimal.class;
case CHAR:
case VARCHAR:
case LONGVARCHAR:
case NCHAR:
case NVARCHAR:
case LONGNVARCHAR:
case CLOB:
case NCLOB:
case SQLXML:
return String.class;
case DATE:
return java.sql.Date.class;
case TIME:
return java.sql.Time.class;
case TIMESTAMP:
return java.sql.Timestamp.class;
default :
return Object.class;
}
}
| Convert JDBC data type to java type. |
public Token createToken(){
Token token=tokenList[currentFreeToken];
token.text=null;
token.type=Token.NULL;
token.offset=-1;
token.setNextToken(null);
currentFreeToken++;
if (currentFreeToken == size) augmentTokenList();
return token;
}
| Returns a null token. |
private static synchronized int increment(){
return cyclicCounter++;
}
| The central method to increment the cyclic counter, synchronized to achieve a unique value for each subsequent call <p> there is no problem if the counter reaches the maximum counter value, defined by N_COUNTERS_CHARS, only the right number of bits are taken into account for generating the output |
public SSHFPRecord(Name name,int dclass,long ttl,int alg,int digestType,byte[] fingerprint){
super(name,Type.SSHFP,dclass,ttl);
this.alg=checkU8("alg",alg);
this.digestType=checkU8("digestType",digestType);
this.fingerprint=fingerprint;
}
| Creates an SSHFP Record from the given data. |
protected Control createDialogArea(Composite composite){
list=new List(composite,SWT.SINGLE | SWT.V_SCROLL | SWT.RESIZE);
setList();
list.addSelectionListener(new ShowDeclarationsSelectionListener(EditorUtil.getTLAEditorWithFocus()));
list.addKeyListener(new ShowDeclarationsKeyListener(this));
list.setSelection(0);
return list;
}
| This is the method that puts the content into the popup's dialog area. It puts an org.eclipse.swt.widgets.List (note that this isn't an ordinary Java List) there. |
public HelloMinecraftLookAndFeel() throws ParseException {
this(DEFAULT_SETTINGS);
}
| Creates a new instance of NimbusLookAndFeel |
private static Schema loadWsTrustSchema(){
try {
Schema wsTrustSchema=Util.loadXmlSchemaFromResource(ResponseUnmarshaller.class,WS_TRUST_1_3_SCHEMA);
return wsTrustSchema;
}
catch ( IllegalArgumentException e) {
LoggerFactory.getLogger(SamlTokenImpl.class).error(String.format("Schema resource `%s' is missing.",WS_TRUST_1_3_SCHEMA),e);
throw new RuntimeException(String.format("Schema resource `%s' is missing.",WS_TRUST_1_3_SCHEMA),e);
}
catch ( SAXException e) {
LoggerFactory.getLogger(ResponseUnmarshaller.class).error(ERR_LOADING_WS_TRUST_SCHEMA,e);
throw new RuntimeException(ERR_LOADING_WS_TRUST_SCHEMA,e);
}
}
| Loads WS-Trust schema file. |
public TestProgressBar(Composite parent,int style){
super(parent,style);
colorSkipped=new Color(Display.getCurrent(),230,232,235);
colorPassed=new Color(Display.getCurrent(),198,242,177);
colorFailed=new Color(Display.getCurrent(),242,188,177);
colorError=new Color(Display.getCurrent(),242,188,177);
colorFixme=new Color(Display.getCurrent(),177,231,242);
addPaintListener(null);
addDisposeListener(null);
}
| Create instance. |
public DigesterOutputStream(MessageDigest md,boolean buffer){
this.md=md;
this.buffer=buffer;
if (buffer) {
bos=new UnsyncByteArrayOutputStream();
}
}
| Creates a DigesterOutputStream. |
public static String format(double[] v,int w,int d){
DecimalFormat format=new DecimalFormat();
format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
format.setMinimumIntegerDigits(1);
format.setMaximumFractionDigits(d);
format.setMinimumFractionDigits(d);
format.setGroupingUsed(false);
int width=w + 1;
StringBuilder msg=new StringBuilder();
msg.append('\n');
for (int i=0; i < v.length; i++) {
String s=format.format(v[i]);
int padding=Math.max(1,width - s.length());
for (int k=0; k < padding; k++) {
msg.append(' ');
}
msg.append(s);
}
return msg.toString();
}
| Returns a string representation of this vector. |
private void writeQNameAttribute(java.lang.String namespace,java.lang.String attName,javax.xml.namespace.QName qname,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String attributeNamespace=qname.getNamespaceURI();
java.lang.String attributePrefix=xmlWriter.getPrefix(attributeNamespace);
if (attributePrefix == null) {
attributePrefix=registerPrefix(xmlWriter,attributeNamespace);
}
java.lang.String attributeValue;
if (attributePrefix.trim().length() > 0) {
attributeValue=attributePrefix + ":" + qname.getLocalPart();
}
else {
attributeValue=qname.getLocalPart();
}
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName,attributeValue);
}
else {
registerPrefix(xmlWriter,namespace);
xmlWriter.writeAttribute(namespace,attName,attributeValue);
}
}
| Util method to write an attribute without the ns prefix |
@Deprecated public void showDoneButton(boolean showDone){
setProgressButtonEnabled(showDone);
}
| Shows or hides Done button, replaced with setProgressButtonEnabled |
public void onReloadPreferences(){
SharedPreferences settings=PreferenceManager.getDefaultSharedPreferences(mContext);
boolean enableTapDetection=false;
if (!settings.getString(mContext.getString(R.string.pref_shortcut_single_tap_key),mContext.getString(R.string.pref_shortcut_single_tap_default)).equals(mContext.getString(R.string.shortcut_value_unassigned))) {
enableTapDetection=true;
}
if (!settings.getString(mContext.getString(R.string.pref_shortcut_double_tap_key),mContext.getString(R.string.pref_shortcut_double_tap_default)).equals(mContext.getString(R.string.shortcut_value_unassigned))) {
enableTapDetection=true;
mIntegratedTapDetector.setMaxDoubleTapSpacingNanos(DOUBLE_TAP_SPACING_NANOS);
}
else {
mIntegratedTapDetector.setMaxDoubleTapSpacingNanos(0);
}
if (settings.getString(mContext.getString(R.string.pref_tap_sensitivity_key),mContext.getString(R.string.pref_tap_sensitivity_default)).equals(mContext.getString(R.string.tap_sensitivity_value_lowest))) {
mIntegratedTapDetector.setTapDetectionQuality(IntegratedTapDetector.TAP_QUALITY_HIGHEST);
}
if (settings.getString(mContext.getString(R.string.pref_tap_sensitivity_key),mContext.getString(R.string.pref_tap_sensitivity_default)).equals(mContext.getString(R.string.tap_sensitivity_value_low))) {
mIntegratedTapDetector.setTapDetectionQuality(IntegratedTapDetector.TAP_QUALITY_HIGH);
}
if (settings.getString(mContext.getString(R.string.pref_tap_sensitivity_key),mContext.getString(R.string.pref_tap_sensitivity_default)).equals(mContext.getString(R.string.tap_sensitivity_value_medium))) {
mIntegratedTapDetector.setTapDetectionQuality(IntegratedTapDetector.TAP_QUALITY_MEDIUM);
}
if (settings.getString(mContext.getString(R.string.pref_tap_sensitivity_key),mContext.getString(R.string.pref_tap_sensitivity_default)).equals(mContext.getString(R.string.tap_sensitivity_value_high))) {
mIntegratedTapDetector.setTapDetectionQuality(IntegratedTapDetector.TAP_QUALITY_LOW);
}
mIntegratedTapDetector.setDoubleTapDetectionQuality(IntegratedTapDetector.TAP_QUALITY_LOW);
if (enableTapDetection) {
mIntegratedTapDetector.start();
}
else {
mIntegratedTapDetector.stop();
}
}
| Enables tap detection if appropriate based on preferences. |
protected void calcAngularBounds(NodeItem r){
if (m_prevRoot == null || !m_prevRoot.isValid() || r == m_prevRoot) {
m_prevRoot=r;
return;
}
NodeItem p=m_prevRoot;
while (true) {
NodeItem pp=(NodeItem)p.getParent();
if (pp == r) {
break;
}
else if (pp == null) {
m_prevRoot=r;
return;
}
p=pp;
}
double dt=0;
Iterator iter=sortedChildren(r);
while (iter.hasNext()) {
Node n=(Node)iter.next();
if (n == p) break;
dt+=((Params)n.get(PARAMS)).width;
}
double rw=((Params)r.get(PARAMS)).width;
double pw=((Params)p.get(PARAMS)).width;
dt=-MathLib.TWO_PI * (dt + pw / 2) / rw;
m_theta1=dt + Math.atan2(p.getY() - r.getY(),p.getX() - r.getX());
m_theta2=m_theta1 + MathLib.TWO_PI;
m_prevRoot=r;
}
| Calculates the angular bounds of the layout, attempting to preserve the angular orientation of the display across transitions. |
public void validateNameString(String name){
if (StringUtils.isEmpty(name) || NullColumnValueGetter.getNullStr().equalsIgnoreCase(name)) {
throw APIException.badRequests.requiredParameterMissingOrEmpty("name");
}
}
| Fires APIException.badRequests.requiredParameterMissingOrEmpty if the given collection is empty |
private Node tryAppend(Node s,boolean haveData){
for (Node t=tail, p=t; ; ) {
Node n, u;
if (p == null && (p=head) == null) {
if (casHead(null,s)) return s;
}
else if (p.cannotPrecede(haveData)) return null;
else if ((n=p.next) != null) p=p != t && t != (u=tail) ? (t=u) : (p != n) ? n : null;
else if (!p.casNext(null,s)) p=p.next;
else {
if (p != t) {
while ((tail != t || !casTail(t,s)) && (t=tail) != null && (s=t.next) != null && (s=s.next) != null && s != t) ;
}
return p;
}
}
}
| Tries to append node s as tail. |
public UnconditionalFlowInfo mitigateNullInfoOf(FlowInfo flowInfo){
if ((this.tagBits & NULL_FLAG_MASK) == 0) {
return flowInfo.unconditionalInits();
}
long m, m1, nm1, m2, nm2, m3, a2, a3, a4, s1, s2, ns2, s3, ns3, s4, ns4;
boolean newCopy=false;
UnconditionalFlowInfo source=flowInfo.unconditionalInits();
m1=(s1=source.nullBit1) & (s3=source.nullBit3) & (s4=source.nullBit4)& ((a2=this.nullBit2) | (a4=this.nullBit4));
m2=s1 & (s2=this.nullBit2) & (s3 ^ s4)& ((a3=this.nullBit3) | a4);
m3=s1 & (s2 & (ns3=~s3) & (ns4=~s4)& (a3 | a4) | (ns2=~s2) & s3 & ns4& (a2 | a4) | ns2 & ns3 & s4& (a2 | a3));
if ((m=(m1 | m2 | m3)) != 0) {
newCopy=true;
source=source.unconditionalCopy();
source.nullBit1&=~m;
source.nullBit2&=(nm1=~m1) & ((nm2=~m2) | a4);
source.nullBit3&=(nm1 | a2) & nm2;
source.nullBit4&=nm1 & nm2;
long x=~this.nullBit1 & a2 & a3& a4;
if (x != 0) {
source.nullBit1&=~x;
source.nullBit2|=x;
source.nullBit3|=x;
source.nullBit4|=x;
}
}
if (this.extra != null && source.extra != null) {
int length=this.extra[2].length, sourceLength=source.extra[0].length;
if (sourceLength < length) {
length=sourceLength;
}
for (int i=0; i < length; i++) {
m1=(s1=source.extra[1 + 1][i]) & (s3=source.extra[3 + 1][i]) & (s4=source.extra[4 + 1][i])& ((a2=this.extra[2 + 1][i]) | (a4=this.extra[4 + 1][i]));
m2=s1 & (s2=this.extra[2 + 1][i]) & (s3 ^ s4)& ((a3=this.extra[3 + 1][i]) | a4);
m3=s1 & (s2 & (ns3=~s3) & (ns4=~s4)& (a3 | a4) | (ns2=~s2) & s3 & ns4& (a2 | a4) | ns2 & ns3 & s4& (a2 | a3));
if ((m=(m1 | m2 | m3)) != 0) {
if (!newCopy) {
newCopy=true;
source=source.unconditionalCopy();
}
source.extra[1 + 1][i]&=~m;
source.extra[2 + 1][i]&=(nm1=~m1) & ((nm2=~m2) | a4);
source.extra[3 + 1][i]&=(nm1 | a2) & nm2;
source.extra[4 + 1][i]&=nm1 & nm2;
}
}
}
return source;
}
| Mitigate the definite and protected info of flowInfo, depending on what this null info registry knows about potential assignments and messages sends involving locals. May return flowInfo unchanged, or a modified, fresh copy of flowInfo. |
public void testCertificateFactory01() throws CertificateException {
if (!X509Support) {
fail(NotSupportMsg);
return;
}
for (int i=0; i < validValues.length; i++) {
CertificateFactory certF=CertificateFactory.getInstance(validValues[i]);
assertEquals("Incorrect type: ",validValues[i],certF.getType());
}
}
| Test for <code>getInstance(String type)</code> method Assertion: returns CertificateFactory if type is X.509 |
private void applyFonts(Composite composite){
Dialog.applyDialogFont(composite);
if (titleLabel != null) {
Font font=titleLabel.getFont();
FontData[] fontDatas=font.getFontData();
for (int i=0; i < fontDatas.length; i++) {
fontDatas[i].setStyle(SWT.BOLD);
}
titleFont=new Font(titleLabel.getDisplay(),fontDatas);
titleLabel.setFont(titleFont);
}
if (infoLabel != null) {
Font font=infoLabel.getFont();
FontData[] fontDatas=font.getFontData();
for (int i=0; i < fontDatas.length; i++) {
fontDatas[i].setHeight(fontDatas[i].getHeight() * 9 / 10);
}
infoFont=new Font(infoLabel.getDisplay(),fontDatas);
infoLabel.setFont(infoFont);
}
}
| Apply any desired fonts to the specified composite and its children. |
public static String toStringPretty(JsonElement jsonElt){
return toStringPretty(jsonElt,0);
}
| Returns a pretty printed string of the given Json element. |
protected void deleteLinksOnPort(NodePortTuple npt,String reason){
List<Link> eraseList=new ArrayList<Link>();
if (this.portLinks.containsKey(npt)) {
if (log.isTraceEnabled()) {
log.trace("handlePortStatus: Switch {} port #{} " + "removing links {}",new Object[]{npt.getNodeId().toString(),npt.getPortId(),this.portLinks.get(npt)});
}
eraseList.addAll(this.portLinks.get(npt));
deleteLinks(eraseList,reason);
}
}
| Delete links incident on a given switch port. |
private Token parseSimpleToken(final Token token,int ch) throws IOException {
while (true) {
if (readEndOfLine(ch)) {
token.type=EORECORD;
break;
}
else if (isEndOfFile(ch)) {
token.type=EOF;
token.isReady=true;
break;
}
else if (isDelimiter(ch)) {
token.type=TOKEN;
break;
}
else if (isEscape(ch)) {
final int unescaped=readEscape();
if (unescaped == Constants.END_OF_STREAM) {
token.content.append((char)ch).append((char)in.getLastChar());
}
else {
token.content.append((char)unescaped);
}
ch=in.read();
}
else {
token.content.append((char)ch);
ch=in.read();
}
}
if (ignoreSurroundingSpaces) {
trimTrailingSpaces(token.content);
}
return token;
}
| Parses a simple token. <p/> Simple token are tokens which are not surrounded by encapsulators. A simple token might contain escaped delimiters (as \, or \;). The token is finished when one of the following conditions become true: <ul> <li>end of line has been reached (EORECORD)</li> <li>end of stream has been reached (EOF)</li> <li>an unescaped delimiter has been reached (TOKEN)</li> </ul> |
public void updateHeader(Header header){
if (header == null) {
return;
}
for (int i=0; i < this.headers.size(); i++) {
Header current=(Header)this.headers.get(i);
if (current.getName().equalsIgnoreCase(header.getName())) {
this.headers.set(i,header);
return;
}
}
this.headers.add(header);
}
| Replaces the first occurence of the header with the same name. If no header with the same name is found the given header is added to the end of the list. |
public static <S,A extends Action>Map<S,A> initialPolicyVector(MarkovDecisionProcess<S,A> mdp){
Map<S,A> pi=new LinkedHashMap<S,A>();
List<A> actions=new ArrayList<A>();
for ( S s : mdp.states()) {
actions.clear();
actions.addAll(mdp.actions(s));
if (actions.size() > 0) {
pi.put(s,Util.selectRandomlyFromList(actions));
}
}
return pi;
}
| Create a policy vector indexed by state, initially random. |
@Override public void run(){
amIActive=true;
String inputHeader=null;
String outputHeader=null;
int row, col, x, y;
double z;
float progress=0;
int a;
double slopeX;
double slopeY;
double val;
int[] dX={1,1,1,0,-1,-1,-1,0};
int[] dY={-1,0,1,1,1,0,-1,-1};
double[] maskX={1,1,1,0,-1,-1,-1,0};
double[] maskY={1,0,-1,-1,-1,0,1,1};
int numPixelsInFilter;
boolean reflectAtBorders=false;
if (args.length <= 0) {
showFeedback("Plugin parameters have not been set.");
return;
}
for (int i=0; i < args.length; i++) {
if (i == 0) {
inputHeader=args[i];
}
else if (i == 1) {
outputHeader=args[i];
}
else if (i == 2) {
reflectAtBorders=Boolean.parseBoolean(args[i]);
}
}
if ((inputHeader == null) || (outputHeader == null)) {
showFeedback("One or more of the input parameters have not been set properly.");
return;
}
try {
WhiteboxRaster inputFile=new WhiteboxRaster(inputHeader,"r");
inputFile.isReflectedAtEdges=reflectAtBorders;
int rows=inputFile.getNumberRows();
int cols=inputFile.getNumberColumns();
double noData=inputFile.getNoDataValue();
WhiteboxRaster outputFile=new WhiteboxRaster(outputHeader,"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,noData);
outputFile.setPreferredPalette("grey.pal");
numPixelsInFilter=8;
for (row=0; row < rows; row++) {
for (col=0; col < cols; col++) {
z=inputFile.getValue(row,col);
if (z != noData) {
slopeX=0;
slopeY=0;
for (a=0; a < numPixelsInFilter; a++) {
x=col + dX[a];
y=row + dY[a];
val=inputFile.getValue(y,x);
if (val == noData) {
val=z;
}
slopeX+=val * maskX[a];
slopeY+=val * maskY[a];
}
val=Math.sqrt(slopeX * slopeX + slopeY * slopeY);
outputFile.setValue(row,col,val);
}
else {
outputFile.setValue(row,col,noData);
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress=(float)(100f * row / (rows - 1));
updateProgress((int)progress);
}
outputFile.addMetadataEntry("Created by the " + getDescriptiveName() + " tool.");
outputFile.addMetadataEntry("Created on " + new Date());
inputFile.close();
outputFile.close();
returnData(outputHeader);
}
catch ( OutOfMemoryError oe) {
myHost.showFeedback("An out-of-memory error has occurred during operation.");
}
catch ( Exception e) {
myHost.showFeedback("An error has occurred during operation. See log file for details.");
myHost.logException("Error in " + getDescriptiveName(),e);
}
finally {
updateProgress("Progress: ",0);
amIActive=false;
myHost.pluginComplete();
}
}
| Used to execute this plugin tool. |
public BooleanCondition must(Condition... conditions){
must=add(must,conditions);
return this;
}
| Returns this with the specified mandatory conditions. |
public static final String toBitString(double d[]){
StringBuilder sb=new StringBuilder(d.length);
for ( double b : d) {
sb.append((int)Math.round(b));
}
return sb.toString();
}
| ToBitString - returns a String representation of d[]. |
public void doStoreFront(HtmlPage storeFront) throws Exception {
HtmlSubmitInput button=null;
HtmlTableDataCell cell=null;
String description=null, moreButton=null;
Iterator iter=null;
boolean found=false;
int i;
assertNotNull(storeFront);
List cells=getAllElementsOfGivenClass(storeFront,null,HtmlTableDataCell.class), buttons=getAllElementsOfGivenClass(storeFront,null,HtmlSubmitInput.class);
for (i=0; i < carBundles.length; i++) {
iter=cells.iterator();
description=carBundles[i].getString("description").trim();
while (iter.hasNext()) {
cell=(HtmlTableDataCell)iter.next();
if (-1 != cell.asText().indexOf(description)) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Found description " + description + ".");
}
found=true;
break;
}
}
}
assertTrue("Did not find description: " + description,found);
iter=buttons.iterator();
moreButton=resources.getString("moreButton").trim();
while (iter.hasNext()) {
button=(HtmlSubmitInput)iter.next();
assertTrue(-1 != button.asText().indexOf(moreButton));
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Button text of " + moreButton + " confirmed.");
}
doCarDetail((HtmlPage)button.click());
}
}
| <p>Assumptions: there are exactly four buttons on this page, one for each car model.</p> <p/> <p>Verify that all of the expected cars have their descriptions on the page.</p> <p/> <p>Verify that the text of the "more" button is properly localized.</p> <p/> <p>Press the button for each model and execute doCarDetail() on the result.</p> |
public void showMessage(String str){
ArgumentChecking.notNull(str,"str");
updateLabel(str,false,MESSAGE_FG_COLOR,MESSAGE_BG_COLOR);
}
| It shows a message on the status label. The look of the status label is updated accordingly. |
SavedState(Parcelable superState){
super(superState);
}
| Called by onSaveInstanceState. |
@Override public int hashCode(){
if (triple == null) {
return getDerivation().hashCode();
}
else {
return triple.hashCode();
}
}
| Two statements are the same as long as they represent the same triple. Derivation matters if and only if there is no triple. |
public synchronized void store(THLEvent event,boolean commit) throws ReplicatorException, InterruptedException {
assertWritable();
long maxSeqno=diskLog.getMaxSeqno();
long eventSeqno=event.getSeqno();
short eventFragno=event.getFragno();
if (eventSeqno < maxSeqno) {
throw new LogConsistencyException("Attempt to write new log record with lower seqno value: current max seqno=" + maxSeqno + " attempted new seqno="+ eventSeqno);
}
else if (eventSeqno == maxSeqno && eventFragno <= lastFragno) {
throw new LogConsistencyException("Attempt to write new log record with equal or lower fragno: seqno=" + eventSeqno + " previous stored fragno="+ lastFragno+ " attempted new fragno="+ eventFragno);
}
if (this.cursor == null) {
try {
LogFile lastFile=diskLog.openLastFile(false);
cursor=new LogCursor(lastFile,event.getSeqno());
if (logger.isDebugEnabled()) {
logger.debug("Creating new log cursor: thread=" + Thread.currentThread() + " file="+ lastFile.getFile().getName()+ " seqno="+ event.getSeqno());
}
}
catch ( ReplicatorException e) {
throw new THLException("Failed to open log last log file",e);
}
}
LogFile dataFile=cursor.getLogFile();
if (logger.isDebugEnabled()) {
logger.debug("Using log file for writing: " + dataFile.getFile().getName());
}
try {
if (dataFile.getLength() > logFileSize && event.getFragno() == 0) {
dataFile=diskLog.rotate(dataFile,event.getSeqno());
cursor.release();
cursor=new LogCursor(dataFile,event.getSeqno());
}
LogEventReplWriter eventWriter=new LogEventReplWriter(event,eventSerializer,doChecksum,dataFile.getFile());
LogRecord logRecord=eventWriter.write();
dataFile.writeRecord(logRecord,logFileSize);
diskLog.setMaxSeqno(event.getSeqno());
if (event.getLastFrag()) lastFragno=-1;
else lastFragno=event.getFragno();
if (commit) {
dataFile.flush();
}
}
catch ( IOException e) {
throw new THLException("Error while writing to log file: name=" + dataFile.getFile().getName(),e);
}
}
| Store a THL event at the end of the log. |
private String encodeAttributeValue(final String attributeValue){
if (attributeValue == null) {
return null;
}
int len=attributeValue.length();
boolean encode=false;
for (int pos=0; pos < len; pos++) {
char ch=attributeValue.charAt(pos);
if (ch == '<') {
encode=true;
break;
}
else if (ch == '>') {
encode=true;
break;
}
else if (ch == '\"') {
encode=true;
break;
}
else if (ch == '&') {
encode=true;
break;
}
}
if (encode) {
StringBuilder bf=new StringBuilder();
for (int pos=0; pos < len; pos++) {
char ch=attributeValue.charAt(pos);
if (ch == '<') {
bf.append("<");
}
else if (ch == '>') {
bf.append(">");
}
else if (ch == '\"') {
bf.append(""");
}
else if (ch == '&') {
bf.append("&");
}
else {
bf.append(ch);
}
}
return bf.toString();
}
return attributeValue;
}
| Encodes the given string in such a way that it no longer contains characters that have a special meaning in xml. |
@Bean public ViewResolver jspViewResolver(){
InternalResourceViewResolver resolver=new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}
| Gets a JSP view resolver. |
protected final void endOfInput(boolean streamCancelled) throws IOException {
if (cacheRequest != null) {
cacheBody.close();
}
httpEngine.release(streamCancelled);
}
| Closes the cache entry and makes the socket available for reuse. This should be invoked when the end of the body has been reached. |
public RevisionMetadata parseMetadataNodeList(String revId,NodeList nlEntries,ImmutableList<Revision> parents){
String author="None";
DateTime date=new DateTime(0L);
String description="None";
for (int i=0; i < nlEntries.getLength(); i++) {
Node currNode=nlEntries.item(i);
if (currNode.getNodeName().equals("author")) {
author=currNode.getTextContent();
}
if (currNode.getNodeName().equals("date")) {
date=ISODateTimeFormat.dateTime().parseDateTime(currNode.getTextContent());
}
if (currNode.getNodeName().equals("msg")) {
description=currNode.getTextContent();
}
}
return RevisionMetadata.builder().id(revId).author(author).date(date).description(description).withParents(parents).build();
}
| Helper function for parseMetadata |
@SuppressWarnings("unchecked") public Set<S> children(){
return children;
}
| Get the direct childnodes |
public h5 addElement(Element element){
addElementToRegistry(element);
return (this);
}
| Adds an Element to the element. |
public static long[] convertToLongArray(final byte[] vals){
checkSource(vals.length,8);
final long[] dest=new long[vals.length / 8];
convertToLongArrayInternal(vals,0,vals.length,dest,0);
return dest;
}
| Converts <code>byte[]</code> to <code>long[]</code>, assuming big-endian byte order. |
public java.util.ArrayList<TreeNode<E>> path(E e){
java.util.ArrayList<TreeNode<E>> list=new java.util.ArrayList<>();
TreeNode<E> current=root;
while (current != null) {
list.add(current);
if (e.compareTo(current.element) < 0) {
current=current.left;
}
else if (e.compareTo(current.element) > 0) {
current=current.right;
}
else break;
}
return list;
}
| Return a path from the root leadting to the specified element |
private void firePEPListeners(String from,PEPEvent event){
PEPListener[] listeners=null;
synchronized (pepListeners) {
listeners=new PEPListener[pepListeners.size()];
pepListeners.toArray(listeners);
}
for (int i=0; i < listeners.length; i++) {
listeners[i].eventReceived(from,event);
}
}
| Fires roster exchange listeners. |
public MethodNode popEnclosingMethod(){
return enclosingMethods.removeFirst();
}
| Pops a method from the enclosing methods stack. |
private void readParameterAnnotations(final MethodVisitor mv,final Context context,int v,final boolean visible){
int i;
int n=b[v++] & 0xFF;
int synthetics=Type.getArgumentTypes(context.desc).length - n;
AnnotationVisitor av;
for (i=0; i < synthetics; ++i) {
av=mv.visitParameterAnnotation(i,"Ljava/lang/Synthetic;",false);
if (av != null) {
av.visitEnd();
}
}
char[] c=context.buffer;
for (; i < n + synthetics; ++i) {
int j=readUnsignedShort(v);
v+=2;
for (; j > 0; --j) {
av=mv.visitParameterAnnotation(i,readUTF8(v,c),visible);
v=readAnnotationValues(v + 2,c,true,av);
}
}
}
| Reads parameter annotations and makes the given visitor visit them. |
public StringLiteral createStringLiteral(){
StringLiteralImpl stringLiteral=new StringLiteralImpl();
return stringLiteral;
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.