auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static void handleSQLRecoverableException(AutoCloseable dbObject, SQLRecoverableException ex, boolean retry){ log.error("SQLRecoverable exception encountered. Attempting recovery.", ex); try{ dbObject.close(); }catch (SQLRecoverableException recException){ if(retry) { try (Connection connection = getDBConnection(dataSource)){ handleSQLRecoverableException(connection, recException, false); } catch (SQLException | NullPointerException nullOrSqlException){ if(dataSource == null) log.error("Null encountered during recovery", nullOrSqlException); else log.error("Recovery failed for SQLRecoverableError - exiting recovery.", nullOrSqlException); } }else{ dbObject = null; log.error("Recovery failed for SQLRecoverableError - exiting recovery.", recException); } }catch (SQLException sqlEx){ log.error("Error occurred during close operation - continuing with errors" + sqlEx.getMessage(), sqlEx); } catch (Exception e) { log.error("Generic error occurred during close operation" + e.getMessage(), e); } }

Target:
private static void handleSQLRecoverableException(AutoCloseable dbObject, SQLRecoverableException ex, boolean retry){ log.error("SQLRecoverable exception encountered. Attempting recovery.", ex); try{ dbObject.close(); }catch (SQLRecoverableException recException){ if(retry) { try (Connection connection = getDBConnection(dataSource)){ handleSQLRecoverableException(connection, recException, false); } catch (SQLException | NullPointerException nullOrSqlException){ if(dataSource == null) log.error("Null encountered during sqlrecoverable error recovery", nullOrSqlException); else log.error("Recovery failed for SQLRecoverableError - exiting recovery.", nullOrSqlException); } }else{ dbObject = null; log.error("Recovery failed for SQLRecoverableError - exiting recovery.", recException); } }catch (SQLException sqlEx){ log.error("Error occurred during close operation - continuing with errors" + sqlEx.getMessage(), sqlEx); } catch (Exception e) { log.error("Generic error occurred during close operation" + e.getMessage(), e); } }
Source:
public void destroySession(String sessionName, IProgressMonitor monitor) throws ExecutionException { List<String> command = createCommand(LTTngControlServiceConstants.COMMAND_DESTROY_SESSION, sessionName); ICommandResult result = executeCommand(command, monitor, false); String[] errorOutput = result.getErrorOutput(); boolean isError = isError(result); if (isError && (errorOutput.length > 0)) { if (ignoredPattern(result.getErrorOutput(), LTTngControlServiceConstants.SESSION_NOT_FOUND_ERROR_PATTERN)) { isError = false; } } if (isError) { throw new ExecutionException(Messages.TraceControl_CommandError + " " + toCommandString(command) + "\n" + result.toString()); } }

Target:
public void destroySession(String sessionName, IProgressMonitor monitor) throws ExecutionException { List<String> command = createCommand(LTTngControlServiceConstants.COMMAND_DESTROY_SESSION, sessionName); ICommandResult result = executeCommand(command, monitor, false); boolean isError = isError(result); if (isError && !ignoredPattern(result.getErrorOutput(), LTTngControlServiceConstants.SESSION_NOT_FOUND_ERROR_PATTERN)) { throw new ExecutionException(Messages.TraceControl_CommandError + " " + toCommandString(command) + "\n" + result.toString()); } }
Source:
private static void checkAppSuccessFromYarnRMOnce( HttpClient httpClient, Job job, AtomicBoolean succeeded ) throws IOException, InterruptedException, ExecutionException, TimeoutException { log.info("Attempting to retrieve app status from YARN RM."); String appId = StringUtils.replace(job.getJobID().toString(), "job", "application"); String yarnRM = job.getConfiguration().get("yarn.resourcemanager.webapp.address"); log.info("YARN RM address: " + yarnRM); String yarnEndpoint = StringUtils.format("http://%s/ws/v1/cluster/apps/%s", yarnRM, appId); ContentResponse res = httpClient.GET(yarnEndpoint); log.info("App status response from YARN RM: " + res.getContentAsString()); Map<String, Object> respMap = HadoopDruidIndexerConfig.JSON_MAPPER.readValue( res.getContentAsString(), new TypeReference<Map<String, Object>>() { } ); Map<String, Object> appMap = (Map<String, Object>) respMap.get("app"); String state = (String) appMap.get("state"); String finalStatus = (String) appMap.get("finalStatus"); if ("FINISHED".equals(state) && "SUCCEEDED".equals(finalStatus)) { succeeded.set(true); } }

Target:
private static void checkAppSuccessFromYarnRMOnce( HttpClient httpClient, Job job, AtomicBoolean succeeded ) throws IOException, InterruptedException, ExecutionException, TimeoutException { String appId = StringUtils.replace(job.getJobID().toString(), "job", "application"); String yarnRM = job.getConfiguration().get("yarn.resourcemanager.webapp.address"); String yarnEndpoint = StringUtils.format("http://%s/ws/v1/cluster/apps/%s", yarnRM, appId); log.info("Attempting to retrieve app status from YARN ResourceManager at [%s].", yarnEndpoint); ContentResponse res = httpClient.GET(yarnEndpoint); log.info("App status response from YARN RM: " + res.getContentAsString()); Map<String, Object> respMap = HadoopDruidIndexerConfig.JSON_MAPPER.readValue( res.getContentAsString(), new TypeReference<Map<String, Object>>() { } ); Map<String, Object> appMap = (Map<String, Object>) respMap.get("app"); String state = (String) appMap.get("state"); String finalStatus = (String) appMap.get("finalStatus"); if ("FINISHED".equals(state) && "SUCCEEDED".equals(finalStatus)) { succeeded.set(true); } }
Source:
public void testCFRetainCount() { DoubleByReference pi = new DoubleByReference(Math.PI); DoubleByReference e = new DoubleByReference(Math.E); CFNumberRef cfE = CF.CFNumberCreate(null, CFNumberType.kCFNumberDoubleType.typeIndex(), e); CFNumberRef cfPi = CF.CFNumberCreate(null, CFNumberType.kCFNumberDoubleType.typeIndex(), pi); assertEquals(1, CF.CFGetRetainCount(cfE).intValue()); assertEquals(1, CF.CFGetRetainCount(cfPi).intValue()); cfE.retain(); cfPi.retain(); cfPi.retain(); assertEquals(2, CF.CFGetRetainCount(cfE).intValue()); assertEquals(3, CF.CFGetRetainCount(cfPi).intValue()); List<CFTypeRef> irrationalReferences = new ArrayList<>(); irrationalReferences.add(cfE); irrationalReferences.add(cfPi); for (CFTypeRef value : irrationalReferences) { value.release(); } assertEquals(1, CF.CFGetRetainCount(cfE).intValue()); assertEquals(2, CF.CFGetRetainCount(cfPi).intValue()); cfPi.release(); assertEquals(1, CF.CFGetRetainCount(cfPi).intValue()); cfE.release(); cfPi.release(); }

Target:
public void testCFRetainCount() { DoubleByReference pi = new DoubleByReference(Math.PI); DoubleByReference e = new DoubleByReference(Math.E); CFNumberRef cfE = CF.CFNumberCreate(null, CFNumberType.kCFNumberDoubleType.typeIndex(), e); CFNumberRef cfPi = CF.CFNumberCreate(null, CFNumberType.kCFNumberDoubleType.typeIndex(), pi); assertEquals(1, CF.CFGetRetainCount(cfE).intValue()); assertEquals(1, CF.CFGetRetainCount(cfPi).intValue()); cfE.retain(); cfPi.retain(); cfPi.retain(); assertEquals(2, CF.CFGetRetainCount(cfE).intValue()); assertEquals(3, CF.CFGetRetainCount(cfPi).intValue()); List<? extends CFTypeRef> irrationalReferences = Arrays.asList(cfE, cfPi); for (CFTypeRef value : irrationalReferences) { value.release(); } assertEquals(1, CF.CFGetRetainCount(cfE).intValue()); assertEquals(2, CF.CFGetRetainCount(cfPi).intValue()); cfPi.release(); assertEquals(1, CF.CFGetRetainCount(cfPi).intValue()); cfE.release(); cfPi.release(); }
Source:
public boolean remove(Object o) { if (getExtension() != null) { BootstrapLogger.LOG.typeModifiedInAfterTypeDiscovery(getExtension(), o, REMOVE_OPERATION, getViewType()); } return getDelegate().remove(createSource((Class<?>) o, 0)); }

Target:
public boolean remove(Object o) { if (getExtension() != null) { BootstrapLogger.LOG.typeModifiedInAfterTypeDiscovery(getExtension(), o, REMOVE_OPERATION, getViewType()); } return getDelegate().remove(objectToItemIfNeeded(o)); }
Source:
public ChangeScreen2(Change.Id changeId, String base, String revision, boolean openReplyBox) { this.changeId = changeId; this.base = base; this.revision = revision != null && !revision.isEmpty() ? revision : null; this.openReplyBox = openReplyBox; add(uiBinder.createAndBindUi(this)); }

Target:
public ChangeScreen2(Change.Id changeId, String base, String revision, boolean openReplyBox) { this.changeId = changeId; this.base = normalize(base); this.revision = normalize(revision); this.openReplyBox = openReplyBox; add(uiBinder.createAndBindUi(this)); }
Source:
public void runScanTest(boolean populateKeys) throws Exception { logger.info("SCAN TEST -- begin"); if (populateKeys) { for (int i=0; i<500; i++) { logger.info("Writing 500 keys to " ); client.set("DynoClientTest_key-"+i, "value-"+i); } } CursorBasedResult<String> cbi = null; do { cbi = client.dyno_scan(cbi, 100, "DynoClientTest_key-*"); List<String> results = cbi.getStringResult(); for (String res: results) { logger.info(res); } } while (!cbi.isComplete()); logger.info("SCAN TEST -- done"); }

Target:
public void runScanTest(boolean populateKeys) throws Exception { logger.info("SCAN TEST -- begin"); if (populateKeys) { logger.info("Writing 500 keys to " ); for (int i=0; i<500; i++) { client.set("DynoClientTest_key-"+i, "value-"+i); } } CursorBasedResult<String> cbi = null; do { cbi = client.dyno_scan(cbi, 100, "DynoClientTest_key-*"); List<String> results = cbi.getStringResult(); for (String res: results) { logger.info(res); } } while (!cbi.isComplete()); logger.info("SCAN TEST -- done"); }
Source:
public <T> T getReference(Class<T> entityViewClass, Object id) { Constructor<T> constructor = (Constructor<T>) referenceConstructorCache.get(entityViewClass); try { ViewTypeImpl<T> managedViewType = metamodel.view(entityViewClass); if (constructor == null) { Class<? extends T> proxyClass = proxyFactory.getProxy(this, managedViewType); constructor = (Constructor<T>) proxyClass.getConstructor(managedViewType.getIdAttribute().getConvertedJavaType()); referenceConstructorCache.put(entityViewClass, constructor); } if (!managedViewType.getIdAttribute().getJavaType().isInstance(id)) { id = getUpdater(managedViewType, null, null, null).getFullGraphNode().createViewIdByEntityId(id); } return constructor.newInstance(id); } catch (Exception e) { e.printStackTrace(); throw new IllegalArgumentException("Couldn't instantiate entity view object for type: " + entityViewClass.getName() + "\nDid you forget to add a no-args constructor to the view? Consider adding a no-args constructor annotated with @ViewConstructor(\"reference\").", e); } }

Target:
public <T> T getReference(Class<T> entityViewClass, Object id) { Constructor<T> constructor = (Constructor<T>) referenceConstructorCache.get(entityViewClass); try { ViewTypeImpl<T> managedViewType = metamodel.view(entityViewClass); if (constructor == null) { Class<? extends T> proxyClass = proxyFactory.getProxy(this, managedViewType); constructor = (Constructor<T>) proxyClass.getConstructor(managedViewType.getIdAttribute().getConvertedJavaType()); referenceConstructorCache.put(entityViewClass, constructor); } if (!managedViewType.getIdAttribute().getJavaType().isInstance(id)) { id = getUpdater(managedViewType, null, null, null).getFullGraphNode().createViewIdByEntityId(id); } return constructor.newInstance(id); } catch (Exception e) { throw new IllegalArgumentException("Couldn't instantiate entity view object for type: " + entityViewClass.getName() + "\nDid you forget to add a no-args constructor to the view? Consider adding a no-args constructor annotated with @ViewConstructor(\"reference\").", e); } }
Source:
public ValueRange(Object from, Object to) { if (!(from instanceof Comparable)) { throw new IllegalArgumentException("'from' must be an instance of java.lang.Comparable"); } if (!(to instanceof Comparable)) { throw new IllegalArgumentException("'to' must be an instance of java.lang.Comparable"); } this.from = from; this.to = to; }

Target:
public ValueRange(Object from, Object to) { if (!(from instanceof Comparable)) { throw log.argumentMustBeComparable("from"); } if (!(to instanceof Comparable)) { throw log.argumentMustBeComparable("to"); } this.from = from; this.to = to; }
Source:
public void addPilotOrSoldier(Person p) { addPilotOrSoldier(Objects.requireNonNull(p), false); }

Target:
public void addPilotOrSoldier(Person p) { addPilotOrSoldier(p, false); }
Source:
public boolean publish(String message, String color) { boolean result = true; for (String roomId : roomIds) { String url = "https://" + teamDomain + "." + host + "/services/hooks/jenkins-ci?token=" + token; if (StringUtils.isEmpty(baseUrl)) { url = baseUrl + token; } logger.info("Posting: to " + roomId + " on " + teamDomain + " using " + url +": " + message + " " + color); HttpClient client = getHttpClient(); PostMethod post = new PostMethod(url); JSONObject json = new JSONObject(); try { JSONObject field = new JSONObject(); field.put("short", false); field.put("value", message); JSONArray fields = new JSONArray(); fields.put(field); JSONObject attachment = new JSONObject(); attachment.put("fallback", message); attachment.put("color", color); attachment.put("fields", fields); JSONArray mrkdwn = new JSONArray(); mrkdwn.put("pretext"); mrkdwn.put("text"); mrkdwn.put("fields"); attachment.put("mrkdwn_in", mrkdwn); JSONArray attachments = new JSONArray(); attachments.put(attachment); json.put("channel", roomId); json.put("attachments", attachments); post.addParameter("payload", json.toString()); post.getParams().setContentCharset("UTF-8"); int responseCode = client.executeMethod(post); String response = post.getResponseBodyAsString(); if(responseCode != HttpStatus.SC_OK) { logger.log(Level.WARNING, "Slack post may have failed. Response: " + response); result = false; } else { logger.info("Posting succeeded"); } } catch (Exception e) { logger.log(Level.WARNING, "Error posting to Slack", e); result = false; } finally { post.releaseConnection(); } } return result; }

Target:
public boolean publish(String message, String color) { boolean result = true; for (String roomId : roomIds) { String url = "https://" + teamDomain + "." + host + "/services/hooks/jenkins-ci?token=" + token; if (!StringUtils.isEmpty(baseUrl)) { url = baseUrl + token; } logger.info("Posting: to " + roomId + " on " + teamDomain + " using " + url +": " + message + " " + color); HttpClient client = getHttpClient(); PostMethod post = new PostMethod(url); JSONObject json = new JSONObject(); try { JSONObject field = new JSONObject(); field.put("short", false); field.put("value", message); JSONArray fields = new JSONArray(); fields.put(field); JSONObject attachment = new JSONObject(); attachment.put("fallback", message); attachment.put("color", color); attachment.put("fields", fields); JSONArray mrkdwn = new JSONArray(); mrkdwn.put("pretext"); mrkdwn.put("text"); mrkdwn.put("fields"); attachment.put("mrkdwn_in", mrkdwn); JSONArray attachments = new JSONArray(); attachments.put(attachment); json.put("channel", roomId); json.put("attachments", attachments); post.addParameter("payload", json.toString()); post.getParams().setContentCharset("UTF-8"); int responseCode = client.executeMethod(post); String response = post.getResponseBodyAsString(); if(responseCode != HttpStatus.SC_OK) { logger.log(Level.WARNING, "Slack post may have failed. Response: " + response); result = false; } else { logger.info("Posting succeeded"); } } catch (Exception e) { logger.log(Level.WARNING, "Error posting to Slack", e); result = false; } finally { post.releaseConnection(); } } return result; }
Source:
private void email() { if (message == null) { return; } final PatchSetInfo patchSetInfo; try { patchSetInfo = patchSetInfoFactory.get(db, patchSetId); } catch (PatchSetInfoNotAvailableException e) { log.error("Failed to obtain PatchSetInfo for patch set " + patchSetId, e); return; } workQueue.getDefaultQueue() .submit(requestScopePropagator.wrap(new Runnable() { @Override public void run() { try { final CommentSender cm = commentSenderFactory.create(change); cm.setFrom(user.getAccountId()); cm.setPatchSet(patchSet, patchSetInfo); cm.setChangeMessage(message); cm.setPatchLineComments(drafts); cm.send(); } catch (EmailException e) { log.error( "Cannot send comments by email for patch set " + patchSetId, e); } } @Override public String toString() { return "send email for patch set comments"; } })); }

Target:
private void email() { if (message == null) { return; } workQueue.getDefaultQueue() .submit(requestScopePropagator.wrap(new Runnable() { @Override public void run() { PatchSetInfo patchSetInfo; try { ReviewDb reviewDb = schemaFactory.open(); try { patchSetInfo = patchSetInfoFactory.get(reviewDb, patchSetId); } finally { reviewDb.close(); } } catch (PatchSetInfoNotAvailableException e) { log.error( "Failed to obtain PatchSetInfo for patch set " + patchSetId, e); return; } catch (OrmException e) { log.error( "Cannot send comments by email for patch set " + patchSetId, e); return; } try { final CommentSender cm = commentSenderFactory.create(change); cm.setFrom(user.getAccountId()); cm.setPatchSet(patchSet, patchSetInfo); cm.setChangeMessage(message); cm.setPatchLineComments(drafts); cm.send(); } catch (EmailException e) { log.error( "Cannot send comments by email for patch set " + patchSetId, e); } } @Override public String toString() { return "send email for patch set comments"; } })); }
Source:
public void assignSplits(SplitsAssignment<SplitT> assignment) { if (!Thread.currentThread().getName().equals(coordinatorThreadName)) { try { coordinatorExecutor.submit(() -> assignSplits(assignment)).get(); return; } catch (InterruptedException | ExecutionException e) { throw new FlinkRuntimeException("Failed to assign splits due to", e); } } for (Integer subtaskId : assignment.assignment().keySet()) { if (!registeredReaders.containsKey(subtaskId)) { throw new IllegalArgumentException(String.format( "Cannot assign splits %s to subtask %d because the subtask is not registered.", registeredReaders.get(subtaskId), subtaskId)); } } assignmentTracker.recordSplitAssignment(assignment); assignment.assignment().forEach( (id, splits) -> { try { operatorCoordinatorContext.sendEvent(new AddSplitEvent<>(splits), id); } catch (TaskNotRunningException e) { throw new FlinkRuntimeException(String.format( "Failed to assign splits %s to reader %d.", splits, id), e); } }); }

Target:
public void assignSplits(SplitsAssignment<SplitT> assignment) { if (!coordinatorThreadFactory.isCurrentThreadCoordinatorThread()) { try { coordinatorExecutor.submit(() -> assignSplits(assignment)).get(); return; } catch (InterruptedException | ExecutionException e) { throw new FlinkRuntimeException("Failed to assign splits due to", e); } } for (Integer subtaskId : assignment.assignment().keySet()) { if (!registeredReaders.containsKey(subtaskId)) { throw new IllegalArgumentException(String.format( "Cannot assign splits %s to subtask %d because the subtask is not registered.", registeredReaders.get(subtaskId), subtaskId)); } } assignmentTracker.recordSplitAssignment(assignment); assignment.assignment().forEach( (id, splits) -> { try { operatorCoordinatorContext.sendEvent(new AddSplitEvent<>(splits), id); } catch (TaskNotRunningException e) { throw new FlinkRuntimeException(String.format( "Failed to assign splits %s to reader %d.", splits, id), e); } }); }
Source:
private IsWidget getWidget(LimitedEntryCol limitedEntryCol) { if (editingCol() instanceof LimitedEntryActionSetFieldCol52) { return factory().getWidget(editingPattern(), (LimitedEntryActionSetFieldCol52) limitedEntryCol, limitedEntryCol.getValue()); } else if (editingCol() instanceof LimitedEntryConditionCol52) { return factory().getWidget(editingPattern(), (LimitedEntryConditionCol52) limitedEntryCol, limitedEntryCol.getValue()); } else if (editingCol() instanceof LimitedEntryActionInsertFactCol52) { return factory().getWidget((LimitedEntryActionInsertFactCol52) limitedEntryCol, limitedEntryCol.getValue()); } return null; }

Target:
private IsWidget getWidget(LimitedEntryCol limitedEntryCol) { if (editingCol() instanceof LimitedEntryActionSetFieldCol52) { return factory().getWidget(editingPattern(), (LimitedEntryActionSetFieldCol52) limitedEntryCol, limitedEntryCol.getValue()); } else if (editingCol() instanceof LimitedEntryConditionCol52) { return factory().getWidget(editingPattern(), (LimitedEntryConditionCol52) limitedEntryCol, limitedEntryCol.getValue()); } else if (editingCol() instanceof LimitedEntryActionInsertFactCol52) { return factory().getWidget((LimitedEntryActionInsertFactCol52) limitedEntryCol, limitedEntryCol.getValue()); } throw new UnsupportedOperationException("The column type is not supported by the 'LimitedWidget'"); }
Source:
public String call() throws Exception { final Ds3ClientHelpers.ObjectTransferrer getter; if (checksum) { throw new java.lang.RuntimeException("Checksumming is currently not implemented."); } else { getter = new FileObjectGetter(this.outputPath); } if (this.prefix == null) { Logging.log("Getting all objects from " + this.bucketName); return restoreAll(getter); } else { Logging.log("Getting only those objects that start with " + this.prefix); return restoreSome(getter); } }

Target:
public String call() throws Exception { final Ds3ClientHelpers.ObjectTransferrer getter; if (checksum) { throw new RuntimeException("Checksumming is currently not implemented."); } else { getter = new FileObjectGetter(this.outputPath); } if (this.prefix == null) { Logging.log("Getting all objects from " + this.bucketName); return restoreAll(getter); } else { Logging.log("Getting only those objects that start with " + this.prefix); return restoreSome(getter); } }
Source:
public void testGenerator() throws Exception { ClassDefinition classDefinition = new ClassDefinition( (PUBLIC, FINAL), "test/Example", type(Object.class)); Parameter argA = arg("a", int.class); Parameter argB = arg("b", int.class); MethodDefinition method = classDefinition.declareMethod( a(PUBLIC, STATIC), "add", type(int.class), ImmutableList.of(argA, argB)); method.getBody() .append(add(argA, argB)) .retInt(); Path tempDir = createTempDirectory("test"); try { StringWriter writer = new StringWriter(); Class<?> clazz = classGenerator(getClass().getClassLoader()) .fakeLineNumbers(true) .runAsmVerifier(true) .dumpRawBytecode(true) .outputTo(writer) .dumpClassFilesTo(tempDir) .defineClass(classDefinition, Object.class); Method add = clazz.getMethod("add", int.class, int.class); assertEquals(add.invoke(null, 13, 42), 55); assertThat(writer.toString()) .contains("00002 I I : I I : IADD") .contains("public final class test/Example {") .contains(" .contains("LINENUMBER 2002 L1"); assertThat(tempDir.resolve("test/Example.class")).isRegularFile(); } finally { deleteRecursively(tempDir, ALLOW_INSECURE); } }

Target:
public void testGenerator() throws Exception { ClassDefinition classDefinition = new ClassDefinition( a(PUBLIC, FINAL), "test/Example", type(Object.class)); Parameter argA = arg("a", int.class); Parameter argB = arg("b", int.class); MethodDefinition method = classDefinition.declareMethod( a(PUBLIC, STATIC), "add", type(int.class), ImmutableList.of(argA, argB)); method.getBody() .append(add(argA, argB)) .retInt(); Path tempDir = createTempDirectory("test"); try { StringWriter writer = new StringWriter(); Class<?> clazz = classGenerator(getClass().getClassLoader()) .fakeLineNumbers(true) .runAsmVerifier(true) .dumpRawBytecode(true) .outputTo(writer) .dumpClassFilesTo(tempDir) .defineClass(classDefinition, Object.class); Method add = clazz.getMethod("add", int.class, int.class); assertEquals(add.invoke(null, 13, 42), 55); assertThat(writer.toString()) .contains("00002 I I : I I : IADD") .contains("public final class test/Example {") .contains(" .contains("LINENUMBER 2002 L1"); assertThat(tempDir.resolve("test/Example.class")).isRegularFile(); } finally { deleteRecursively(tempDir, ALLOW_INSECURE); } }
Source:
public @UiConstructor EntityModelRadioButtonEditor(String group) { this(group, new VisibilityRenderer.SimpleVisibilityRenderer()); }

Target:
public EntityModelRadioButtonEditor(String group) { this(group, new VisibilityRenderer.SimpleVisibilityRenderer()); }
Source:
private static boolean writeValue(Socket client, String value) { boolean result; BufferedSink out = null; try { out = Okio.buffer(Okio.sink(client.getOutputStream())); out.writeUtf8(value); out.writeUtf8CodePoint('\n'); out.flush(); result = true; } catch (Exception e) { result = false; } finally { if (out != null) { try { out.close(); } catch (IOException e) { result = false; } } } return result; }

Target:
private static boolean writeValue(Socket client, String value) { boolean result; BufferedSink out = null; try { out = Okio.buffer(Okio.sink(client)); out.writeUtf8(value); out.writeUtf8CodePoint('\n'); out.flush(); result = true; } catch (Exception e) { result = false; } finally { if (out != null) { try { out.close(); } catch (IOException e) { result = false; } } } return result; }
Source:
public String getJsonData() throws IOException { long position = writer.getPosition(); try { writer.checkSize(); if (writer.getPosition() != position) { position = writer.getPosition(); } URI id = writeResponse(); writeRequest(id); writeMetadata(id); } catch (IOException e) { throw e; } catch (ParseException e) { LOG.error("Can't get a valid date from: " + url); } return null; }

Target:
public String getJsonData() throws IOException { long position = writer.getPosition(); try { writer.checkSize(); if (writer.getPosition() != position) { position = writer.getPosition(); } URI id = writeResponse(); if (StringUtils.isNotBlank(metadata.get("_request_"))) { writeRequest(id); } } catch (IOException e) { throw e; } catch (ParseException e) { LOG.error("Can't get a valid date from: {}", url); } return null; }
Source:
public synchronized void updateCapacity(Map<String, Integer> capacity) { if (_capacityMetricsMap.keySet().equals(capacity.keySet())) { for (Map.Entry<String, Integer> entry : capacity.entrySet()) { _capacityMetricsMap.get(entry.getKey()).updateValue((long) entry.getValue()); } } else { _capacityMetricsMap.keySet().retainAll(capacity.keySet()); for (Map.Entry<String, Integer> entry : capacity.entrySet()) { String capacityName = entry.getKey(); _capacityMetricsMap.computeIfAbsent(capacityName, metric -> new SimpleDynamicMetric<>(capacityName + "Gauge", 0L)) .updateValue((long) entry.getValue()); } List<DynamicMetric<?, ?>> attributeList = Lists.newArrayList( _totalMessagedReceivedCounter, _disabledPartitionsGauge, _enabledStatusGauge, _onlineStatusGauge, _maxCapacityUsageGauge ); attributeList.addAll(_capacityMetricsMap.values()); updateAttributesInfo(attributeList, "Instance monitor for instance: " + getInstanceName()); } }

Target:
public void updateCapacity(Map<String, Integer> capacity) { synchronized (_dynamicCapacityMetricsMap) { if (_dynamicCapacityMetricsMap.keySet().equals(capacity.keySet())) { for (Map.Entry<String, Integer> entry : capacity.entrySet()) { _dynamicCapacityMetricsMap.get(entry.getKey()).updateValue((long) entry.getValue()); } return; } _dynamicCapacityMetricsMap.keySet().retainAll(capacity.keySet()); for (Map.Entry<String, Integer> entry : capacity.entrySet()) { String capacityName = entry.getKey(); if (_dynamicCapacityMetricsMap.containsKey(capacityName)) { _dynamicCapacityMetricsMap.get(capacityName).updateValue((long) entry.getValue()); } else { _dynamicCapacityMetricsMap.put(capacityName, new SimpleDynamicMetric<>(capacityName + "Gauge", (long) entry.getValue())); } } } updateAttributesInfo(buildAttributeList(), "Instance monitor for instance: " + getInstanceName()); }
Source:
private <C extends Credentials, U extends UserProfile> Promise<U> getProfile(WebContext webContext, Client<C, U> client) throws RequiresHttpAction { C credentials = client.getCredentials(webContext); return Promise.value(client.getUserProfile(credentials, webContext)); }

Target:
private <C extends Credentials, U extends UserProfile> Promise<U> getProfile(WebContext webContext, Client<C, U> client) throws RequiresHttpAction { return Blocking.get(() -> { C credentials = client.getCredentials(webContext); return client.getUserProfile(credentials, webContext); }); }
Source:
public void trimOrdersByPrice(double price, String symbol) { ArrayList<Order> newSellOrders = new ArrayList<Order>(); ArrayList<Order> newBuyOrders = new ArrayList<Order>(); for (Order o : this.sellOrders.get(symbol)) { if (o.getPrice() > price && !o.isMarketOrder) { newBuyOrders.add(o); } } for (Order o : this.buyOrders.get(symbol)) { if (o.getPrice() < price && !o.isMarketOrder) { newSellOrders.add(o); } } this.buyOrders.remove(symbol); this.buyOrders.put(symbol, newBuyOrders); this.sellOrders.remove(symbol); this.sellOrders.put(symbol, newSellOrders); }

Target:
public void trimOrdersByPrice(double price, String symbol) { ArrayList<Order> newSellOrders = new ArrayList<Order>(); ArrayList<Order> newBuyOrders = new ArrayList<Order>(); for (Order order : this.sellOrders.get(symbol)) { if (order.getPrice() > price && !order.isMarketOrder) { newBuyOrders.add(order); } } for (Order order : this.buyOrders.get(symbol)) { if (order.getPrice() < price && !order.isMarketOrder) { newSellOrders.add(order); } } this.buyOrders.remove(symbol); this.buyOrders.put(symbol, newBuyOrders); this.sellOrders.remove(symbol); this.sellOrders.put(symbol, newSellOrders); }
Source:
protected void destroyVm() { if (getVm().getStatus() == VMStatus.MigratingFrom && getVm().getMigratingToVds() != null) { Backend.getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.DestroyVm, new DestroyVmVDSCommandParameters(new Guid(getVm().getMigratingToVds().toString()), getVmId(), true, false, 0)); } if (getVm().getStatus() == VMStatus.Paused) { VmStatic vmStatic = getVm().getStaticData(); decreasePendingVms(getVm().getRunOnVds(), vmStatic.getNumOfCpus(), vmStatic.getMinAllocatedMem(), vmStatic.getName()); } setActionReturnValue(Backend .getInstance() .getResourceManager() .RunVdsCommand(VDSCommandType.DestroyVm, new DestroyVmVDSCommandParameters(getVdsId(), getVmId(), false, false, 0)).getReturnValue()); }

Target:
protected void destroyVm() { if (getVm().getStatus() == VMStatus.MigratingFrom && getVm().getMigratingToVds() != null) { Backend.getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.DestroyVm, new DestroyVmVDSCommandParameters(new Guid(getVm().getMigratingToVds().toString()), getVmId(), true, false, 0)); } if (getVm().getStatus() == VMStatus.Paused && getVm().getVmPauseStatus() == VmPauseStatus.NOERR) { VmStatic vmStatic = getVm().getStaticData(); VmHandler.decreasePendingVms(getVm().getRunOnVds(), vmStatic.getNumOfCpus(), vmStatic.getMinAllocatedMem(), vmStatic.getName()); } setActionReturnValue(Backend .getInstance() .getResourceManager() .RunVdsCommand(VDSCommandType.DestroyVm, new DestroyVmVDSCommandParameters(getVdsId(), getVmId(), false, false, 0)).getReturnValue()); }
Source:
public UserRole getRole(long role) { Session session = null; Transaction tx = null; UserRole result = null; try { session = this.sessionFactory.openSession(); tx = session.beginTransaction(); result = (UserRole) session.createCriteria(UserRole.class).add(Restrictions.eq("roleId", role)).uniqueResult(); }catch(HibernateException e){ LOG.error(e, e); }finally { closeSession(session, false); } return result; }

Target:
public UserRole getRole(long role) { Session session = null; UserRole result = null; try { session = this.sessionFactory.openSession(); result = (UserRole) session.createCriteria(UserRole.class).add(Restrictions.eq("roleId", role)).uniqueResult(); }catch(HibernateException e){ LOG.error(e, e); }finally { closeSession(session, false); } return result; }
Source:
public void newLimitedEntryConditionColumn() { final ConditionCol52 column = new LimitedEntryConditionCol52(); final ConditionPopup popup = new ConditionPopup( model, oracle, presenter, new ConditionColumnCommand() { public void execute( final Pattern52 pattern, final ConditionCol52 column ) { presenter.appendColumn( pattern, column ); } }, column, true, !access.isEditable() ); popup.show(); }

Target:
public void newLimitedEntryConditionColumn() { final ConditionCol52 column = new LimitedEntryConditionCol52(); doNewConditionColumn( column ); }
Source:
public void shouldRefundToAnExistingPaymentSuccessfully() throws Exception { AuthorisationGatewayRequest request = getCardAuthorisationRequest(chargeEntity); PaymentProvider smartpay = getSmartpayPaymentProvider(); GatewayResponse<SmartpayAuthorisationResponse> authoriseResponse = smartpay.authorise(request); assertTrue(authoriseResponse.isSuccessful()); chargeEntity.setGatewayTransactionId(authoriseResponse.getBaseResponse().get().getPspReference()); GatewayResponse<WorldpayCaptureResponse> captureGatewayResponse = smartpay.capture(CaptureGatewayRequest.valueOf(chargeEntity)); assertTrue(captureGatewayResponse.isSuccessful()); RefundEntity refundEntity = new RefundEntity(chargeEntity, 1L, null); RefundGatewayRequest refundRequest = RefundGatewayRequest.valueOf(refundEntity); GatewayResponse refundResponse = smartpay.refund(refundRequest); assertThat(refundResponse.isSuccessful(), is(true)); }

Target:
public void shouldRefundToAnExistingPaymentSuccessfully() throws Exception { AuthorisationGatewayRequest request = getCardAuthorisationRequest(chargeEntity); PaymentProvider smartpay = getSmartpayPaymentProvider(); GatewayResponse<SmartpayAuthorisationResponse> authoriseResponse = smartpay.authorise(request); assertTrue(authoriseResponse.isSuccessful()); chargeEntity.setGatewayTransactionId(authoriseResponse.getBaseResponse().get().getPspReference()); GatewayResponse<WorldpayCaptureResponse> captureGatewayResponse = smartpay.capture(CaptureGatewayRequest.valueOf(chargeEntity)); assertTrue(captureGatewayResponse.isSuccessful()); RefundEntity refundEntity = new RefundEntity(chargeEntity, 1L, userExternalId); RefundGatewayRequest refundRequest = RefundGatewayRequest.valueOf(refundEntity); GatewayResponse refundResponse = smartpay.refund(refundRequest); assertThat(refundResponse.isSuccessful(), is(true)); }
Source:
public String getDisplayName() { return "Create a label on TFS"; }

Target:
public String getDisplayName() { return "Create a label in TFS"; }
Source:
private void setCoursePagination(List<String> coursePaginationList) { String previousPageLink = retrievePreviousPageLink(coursePaginationList); String nextPageLink = retrieveNextPageLink(coursePaginationList); String activeCourse = ""; for (String courseId : coursePaginationList) { if (courseId.equals(this.courseId)) { activeCourse = courseId; } } String userCommentsLink = getStudentCommentsLink(false); coursePagination = new CoursePagination(previousPageLink, nextPageLink, coursePaginationList, activeCourse, userCommentsLink); }

Target:
private void setCoursePagination(List<String> coursePaginationList) { String previousPageLink = retrievePreviousPageLink(coursePaginationList); String nextPageLink = retrieveNextPageLink(coursePaginationList); String activeCourse = coursePaginationList.contains(courseId) ? courseId : ""; String userCommentsLink = getStudentCommentsLink(false); coursePagination = new CoursePagination(previousPageLink, nextPageLink, coursePaginationList, activeCourse, userCommentsLink); }
Source:
public void onNewConnection() { if (commands_.interruptR().isEnabled()) { showError( "The R session is currently busy. Wait for completion or " + "interrupt the current session and retry."); return; } if (!installersUpdated_) { installersUpdated_ = true; server_.updateOdbcInstallers( new DelayedProgressRequestCallback<ConnectionUpdateResult>( "Checking for Updates...") { @Override public void onSuccess(ConnectionUpdateResult result) { installersWarning_ = result.getWarning(); showWizard(); } @Override public void onError(ServerError error) { Debug.logError(error); } } ); } else { showWizard(); } }

Target:
public void onNewConnection() { if (commands_.interruptR().isEnabled()) { showError( "The R session is currently busy. Wait for completion or " + "interrupt the current session and retry."); return; } if (!installersUpdated_) { installersUpdated_ = true; server_.updateOdbcInstallers( new DelayedProgressRequestCallback<ConnectionUpdateResult>( "Checking for Updates...") { @Override public void onSuccess(ConnectionUpdateResult result) { installersWarning_ = result.getWarning(); showWizard(); } @Override public void onError(ServerError error) { Debug.logError(error); globalDisplay_.showErrorMessage("Failed to check for updates", error.getMessage()); } } ); } else { showWizard(); } }
Source:
protected final Exchange matchNotifyResponse(final Response response, final CorrelationContext responseContext) { final Exchange.KeyToken idByToken = Exchange.KeyToken.fromInboundMessage(response); Exchange exchange = null; final Observation obs = observationStore.get(response.getToken()); if (obs != null) { final Request request = obs.getRequest(); request.setDestination(response.getSource()); request.setDestinationPort(response.getSourcePort()); exchange = new Exchange(request, Origin.LOCAL, obs.getContext()); exchange.setRequest(request); LOG.log(Level.FINER, "re-created exchange from original observe request: {0}", request); request.addMessageObserver(new MessageObserverAdapter() { @Override public void onTimeout() { observationStore.remove(request.getToken()); exchangeStore.releaseToken(idByToken); } @Override public void onResponse(Response response) { if (!response.getOptions().hasObserve()) { LOG.log(Level.FINE, "Response to observe request with token {0} does not contain observe option, removing request from observation store", idByToken); observationStore.remove(request.getToken()); exchangeStore.releaseToken(idByToken); } else { notificationListener.onNotification(request, response); } } @Override public void onReject() { observationStore.remove(request.getToken()); exchangeStore.releaseToken(idByToken); } @Override public void onCancel() { observationStore.remove(request.getToken()); exchangeStore.releaseToken(idByToken); } }); } return exchange; }

Target:
protected final Exchange matchNotifyResponse(final Response response, final CorrelationContext responseContext) { final Exchange.KeyToken idByToken = Exchange.KeyToken.fromInboundMessage(response); Exchange exchange = null; final Observation obs = observationStore.get(response.getToken()); if (obs != null) { final Request request = obs.getRequest(); request.setDestination(response.getSource()); request.setDestinationPort(response.getSourcePort()); exchange = new Exchange(request, Origin.LOCAL, obs.getContext()); exchange.setRequest(request); LOG.log(Level.FINER, "re-created exchange from original observe request: {0}", request); request.addMessageObserver(new MessageObserverAdapter() { @Override public void onTimeout() { observationStore.remove(request.getToken()); exchangeStore.releaseToken(idByToken); } @Override public void onResponse(Response resp) { if (!resp.getOptions().hasObserve()) { LOG.log(Level.FINE, "Response to observe request with token {0} does not contain observe option, removing request from observation store", idByToken); observationStore.remove(request.getToken()); exchangeStore.releaseToken(idByToken); } else { notificationListener.onNotification(request, resp); } } @Override public void onReject() { observationStore.remove(request.getToken()); exchangeStore.releaseToken(idByToken); } @Override public void onCancel() { observationStore.remove(request.getToken()); exchangeStore.releaseToken(idByToken); } }); } return exchange; }
Source:
public String toString() { String className = getClass().getSimpleName(); StringBuilder sb = new StringBuilder(className) .append("{key=").append(toStr(key)) .append(", value=").append(toStr(getValue())); if (className.contains("Metadata")) { sb.append(", metadata=").append(getMetadata()); } return sb.append('}').toString(); }

Target:
public String toString() { String className = getClass().getSimpleName(); StringBuilder sb = new StringBuilder(className) .append("{key=").append(toStr(key)) .append(", value=").append(toStr(getValue())); if (hasMetadata()) { sb.append(", metadata=").append(getMetadata()); } return sb.append('}').toString(); }
Source:
public JobDetail demoteContent( @PathParam("env_id") @Verify(Environment.class) String envId, @QueryParam("content") String[] contentIds, @QueryParam("lazy_regen") @DefaultValue("true") Boolean lazyRegen) { Environment e = lookupEnvironment(envId); HashMap<String, EnvironmentContent> demotedContent = new HashMap<String, EnvironmentContent>(); for (String contentId : contentIds) { EnvironmentContent envContent = envContentCurator.lookupByEnvironmentAndContent(e, contentId); if (envContent == null) { throw new NotFoundException(i18n.tr("Content does not exist in environment: {0}", contentId)); } demotedContent.put(contentId, envContent); } for (EnvironmentContent envContent : demotedContent.values()) { this.envContentCurator.delete(envContent); } HashSet<String> demotedContentIds = new HashSet<String>(demotedContent.keySet()); JobDataMap map = new JobDataMap(); map.put(RegenEnvEntitlementCertsJob.ENV, e); map.put(RegenEnvEntitlementCertsJob.CONTENT, demotedContentIds); map.put(RegenEnvEntitlementCertsJob.LAZY_REGEN, lazyRegen); JobDetail detail = newJob(RegenEnvEntitlementCertsJob.class) .withIdentity("regen_entitlement_cert_of_env" + Util.generateUUID()) .usingJobData(map) .build(); return detail; }

Target:
public JobDetail demoteContent( @PathParam("env_id") @Verify(Environment.class) String envId, @QueryParam("content") String[] contentIds, @QueryParam("lazy_regen") @DefaultValue("true") Boolean lazyRegen) { Environment e = lookupEnvironment(envId); Map<String, EnvironmentContent> demotedContent = new HashMap<String, EnvironmentContent>(); for (String contentId : contentIds) { EnvironmentContent envContent = envContentCurator.lookupByEnvironmentAndContent(e, contentId); if (envContent == null) { throw new NotFoundException(i18n.tr("Content does not exist in environment: {0}", contentId)); } demotedContent.put(contentId, envContent); } for (EnvironmentContent envContent : demotedContent.values()) { this.envContentCurator.delete(envContent); } Set<String> demotedContentIds = new HashSet<String>(demotedContent.keySet()); JobDataMap map = new JobDataMap(); map.put(RegenEnvEntitlementCertsJob.ENV, e); map.put(RegenEnvEntitlementCertsJob.CONTENT, demotedContentIds); map.put(RegenEnvEntitlementCertsJob.LAZY_REGEN, lazyRegen); JobDetail detail = newJob(RegenEnvEntitlementCertsJob.class) .withIdentity("regen_entitlement_cert_of_env" + Util.generateUUID()) .usingJobData(map) .build(); return detail; }
Source:
public String readLine(final PositionalBufferedStream stream) { throw new IllegalArgumentException("A BlockCompressedAsciiLineReader class cannot be used to read from a PositionalBufferedStream"); }

Target:
public String readLine(final PositionalBufferedStream stream) { throw new UnsupportedOperationException("A BlockCompressedAsciiLineReader class cannot be used to read from a PositionalBufferedStream"); }
Source:
private ICPPEvaluation createReferenceValue(ActivationRecord record, ConstexprEvaluationContext context, ICPPEvaluation computedInitializerEval) { ICPPEvaluation initValue = initializerEval; if(!(initValue instanceof EvalBinding)) { initValue = initializerEval.getValue(null).get(0); } if(initValue instanceof EvalBinding) { return createReferenceFromBinding(record, context, (EvalBinding) initValue); } else if(initValue instanceof EvalBinary && computedInitializerEval instanceof EvalCompositeAccess) { return createReferenceFromCompositeAccess(record, context, (EvalCompositeAccess) computedInitializerEval); } else { return EvalFixed.INCOMPLETE; } }

Target:
private ICPPEvaluation createReferenceValue(ActivationRecord record, ConstexprEvaluationContext context, ICPPEvaluation computedInitializerEval) { ICPPEvaluation initValue = initializerEval; if(!(initValue instanceof EvalBinding)) { initValue = initializerEval.getValue(context.getPoint()).get(0); } if(initValue instanceof EvalBinding) { return createReferenceFromBinding(record, context, (EvalBinding) initValue); } else if(initValue instanceof EvalBinary && computedInitializerEval instanceof EvalCompositeAccess) { return createReferenceFromCompositeAccess(record, context, (EvalCompositeAccess) computedInitializerEval); } else { return EvalFixed.INCOMPLETE; } }
Source:
private double linearInterpolate(double a, double b, double f) { return a < MIN_ELEVATION ? b : b < MIN_ELEVATION ? a : (a + (b - a) * f); }

Target:
private double linearInterpolate(double a, double b, double f) { return !isValidElevation(a) ? b : !isValidElevation(b) ? a : (a + (b - a) * f); }
Source:
private void resizeElements(int width, int height){ for (BoardPanel board : mGameBoards) { board.rescaleBoard(width, height); } for (JailPanel jailPanel : mJails) { jailPanel.rescaleBoard(width, height); } }

Target:
private void resizeElements(int width, int height){ Stream.of(mGameBoards).forEach(board -> board.rescaleBoard(width, height)); Stream.of(mJails).forEach(jail -> jail.rescaleBoard(width, height)); }
Source:
protected DefaultDataContainer(int concurrencyLevel, int maxEntries, EvictionStrategy strategy, EvictionThreadPolicy policy, Equivalence<? super K> keyEquivalence) { switch (policy) { case PIGGYBACK: case DEFAULT: evictionListener = new DefaultEvictionListener(); break; default: throw new IllegalArgumentException("No such eviction thread policy " + strategy); } Eviction eviction; switch (strategy) { case FIFO: case UNORDERED: case LRU: eviction = Eviction.LRU; break; case LIRS: eviction = Eviction.LIRS; break; default: throw new IllegalArgumentException("No such eviction strategy " + strategy); } entries = new BoundedConcurrentHashMap<K, InternalCacheEntry<K, V>>( maxEntries, concurrencyLevel, eviction, evictionListener, keyEquivalence, AnyEquivalence.getInstance()); }

Target:
protected DefaultDataContainer(int concurrencyLevel, int maxEntries, EvictionStrategy strategy, EvictionThreadPolicy policy, Equivalence<? super K> keyEquivalence) { switch (policy) { case PIGGYBACK: case DEFAULT: evictionListener = new DefaultEvictionListener(); break; default: throw new IllegalArgumentException("No such eviction thread policy " + strategy); } Eviction eviction; switch (strategy) { case FIFO: case UNORDERED: case LRU: eviction = Eviction.LRU; break; case LIRS: eviction = Eviction.LIRS; break; default: throw new IllegalArgumentException("No such eviction strategy " + strategy); } final BoundedConcurrentHashMap<K, InternalCacheEntry<K, V>> boundedMap = new BoundedConcurrentHashMap<K, InternalCacheEntry<K, V>>(maxEntries, concurrencyLevel, eviction, evictionListener, keyEquivalence, AnyEquivalence.getInstance()); entries = boundedMap; extendedMap = new ExtendedMap<K, V>() { @Override public void evict(K key) { boundedMap.evict(key); } @Override public void compute(K key, final ComputeAction<K, V> action) { boundedMap.lock(key); try { InternalCacheEntry<K, V> oldEntry = boundedMap.get(key); InternalCacheEntry<K, V> newEntry = action.compute(key, oldEntry, entryFactory); if (oldEntry == newEntry) { return; } else if (newEntry == null) { boundedMap.remove(key); return; } if (trace) log.tracef("Store %s in container", newEntry); boundedMap.put(key, newEntry); } finally { boundedMap.unlock(key); } } @Override public void putAndActivate(InternalCacheEntry<K, V> newEntry) { boundedMap.put(newEntry.getKey(), newEntry); } }; }
Source:
public GenericIndexedWriter( IOPeon ioPeon, String filenameBase, ObjectStrategy<T> strategy ) { this(ioPeon, filenameBase, strategy, Integer.MAX_VALUE); }

Target:
public GenericIndexedWriter( IOPeon ioPeon, String filenameBase, ObjectStrategy<T> strategy ) { this(ioPeon, filenameBase, strategy, Integer.MAX_VALUE & ~PAGE_SIZE); }