auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void doHealthCheck(final Health.Builder builder) { val systemUsage = metrics.metric("system.cpu.usage", null).getMeasurements().get(0).getValue(); val systemLoad = metrics.metric("system.load.average.1m", null).getMeasurements().get(0).getValue(); val processUsage = metrics.metric("process.cpu.usage", null).getMeasurements().get(0).getValue(); val jvmUsed = metrics.metric("jvm.memory.used", null).getMeasurements().get(0).getValue(); val jvmCommitted = metrics.metric("jvm.memory.committed", null).getMeasurements().get(0).getValue(); val heapUsed = metrics.metric("jvm.memory.used", List.of("area:heap")).getMeasurements().get(0).getValue(); val heapCommitted = metrics.metric("jvm.memory.committed", List.of("area:heap")).getMeasurements().get(0).getValue(); val uptime = metrics.metric("process.uptime", null).getMeasurements().get(0).getValue(); val reqs = metrics.metric("http.server.requests", null); builder .withDetail("systemUsage", systemUsage) .withDetail("systemLoad", systemLoad) .withDetail("processUsage", processUsage) .withDetail("jvmUsed", jvmUsed) .withDetail("jvmCommitted", jvmCommitted) .withDetail("heapUsed", heapUsed) .withDetail("heapCommitted", heapCommitted) .withDetail("uptime", uptime) .withDetail("requests", reqs != null ? reqs.getMeasurements().get(0).getValue() : 0) .withDetail("maxRequest", reqs != null ? reqs.getMeasurements().get(2).getValue() : 0); if (systemLoad > threshold) { builder.status("WARN"); } else { builder.status(Status.UP); } }

Target:
protected void doHealthCheck(final Health.Builder builder) { val systemLoad = getMetricsFor("system.load.average.1m"); builder .withDetail("systemUsage", getMetricsFor("system.cpu.usage")) .withDetail("systemLoad", getMetricsFor("system.load.average.1m")) .withDetail("processUsage", getMetricsFor("process.cpu.usage")) .withDetail("jvmUsed", getMetricsFor("jvm.memory.used")) .withDetail("jvmCommitted", getMetricsFor("jvm.memory.committed")) .withDetail("heapUsed", getMetricsFor("jvm.memory.used", List.of("area:heap"))) .withDetail("heapCommitted", getMetricsFor("jvm.memory.committed", List.of("area:heap"))) .withDetail("uptime", getMetricsFor("process.uptime")) .withDetail("requests", getMetricsFor("http.server.requests")) .withDetail("maxRequest", getMetricsFor("http.server.requests", 2)); if (systemLoad > threshold) { builder.status("WARN"); } else { builder.status(Status.UP); } }
Source:
public void openConnectionAsync() throws IOException { throwable.set(null); if (loginUrl != null && userName != null && password != null) { JSONObject json = new JSONObject(); try { json.put("userName", userName); json.put("password", password); } catch (JSONException ex) { throw new RuntimeException(ex); } client.preparePost(loginUrl).setHeader("Content-Type", "application/json").setBody(json.toString()) .execute(new AsyncCompletionHandler<Response>() { @Override public Response onCompleted(Response response) throws Exception { List<Cookie> cookies = response.getCookies(); BoundRequestBuilder brb = client.prepareGet(uri.toString()); if (cookies != null) { for (Cookie cookie : cookies) { brb.addCookie(cookie); } } connection = brb .execute(new WebSocketUpgradeHandler.Builder().addWebSocketListener(new PubSubWebSocket()).build()) .get(); return response; } }); } else { client.prepareGet(uri.toString()).execute(new WebSocketUpgradeHandler.Builder().addWebSocketListener( new PubSubWebSocket() { @Override public void onOpen(WebSocket ws) { connection = ws; super.onOpen(ws); } }) .build() ); } }

Target:
public void openConnectionAsync() throws IOException { throwable.set(null); if (loginUrl != null && userName != null && password != null) { JSONObject json = new JSONObject(); try { json.put("userName", userName); json.put("password", password); } catch (JSONException ex) { throw new RuntimeException(ex); } client.preparePost(loginUrl).setHeader("Content-Type", "application/json").setBody(json.toString()) .execute(new AsyncCompletionHandler<Response>() { @Override public Response onCompleted(Response response) throws Exception { List<Cookie> cookies = response.getCookies(); BoundRequestBuilder brb = client.prepareGet(uri.toString()); if (cookies != null) { for (Cookie cookie : cookies) { brb.addCookie(cookie); } } connection = brb.execute(new WebSocketUpgradeHandler.Builder().addWebSocketListener(new PubSubWebSocket()).build()) .get(); return response; } }); } else { final WebSocketUpgradeHandler.Builder socketUpgradeBuilder = new WebSocketUpgradeHandler.Builder().addWebSocketListener(new PubSubWebSocket() { @Override public void onOpen(WebSocket ws) { connection = ws; super.onOpen(ws); } }); client.prepareGet(uri.toString()).execute(socketUpgradeBuilder.build()); } }
Source:
public void executeAndTrigger(Set<String> tables, String sql, Object... args) { execute(sql, args); sendTableTrigger(Collections.unmodifiableSet(tables)); }

Target:
public void executeAndTrigger(Set<String> tables, String sql, Object... args) { execute(sql, args); sendTableTrigger(tables); }
Source:
private void finishInitialization() { String value = property.getValue(); if (value.equals("None") && !choices.containsValue(value)) { property.setValue(""); } }

Target:
private void finishInitialization() { String value = property.getValue(); if (value == choices.getValueAtIndex(0)) { property.setValue(""); } }
Source:
public OkHttpNetworkFetcher(OkHttpClient okHttpClient) { mCallFactory = okHttpClient; mCancellationExecutor = okHttpClient.dispatcher().executorService(); }

Target:
public OkHttpNetworkFetcher(OkHttpClient okHttpClient) { this(okHttpClient, okHttpClient.dispatcher().executorService()); }
Source:
private @Nullable OutputElementStyle getElementStyle(ITimeEvent event) { OutputElementStyle elementStyle; if (fTimeGraphProvider instanceof IStylePresentationProvider) { IStylePresentationProvider provider = (IStylePresentationProvider) fTimeGraphProvider; elementStyle = provider.getElementStyle(event); if (elementStyle == null) { return null; } if (elementStyle.getParentKey() == null && elementStyle.getStyleValues().isEmpty()) { return elementStyle; } return new OutputElementStyle(elementStyle.getParentKey(), applyEventStyleProperties(new HashMap<>(elementStyle.getStyleValues()), event)); } int colorIdx = fTimeGraphProvider.getStateTableIndex(event); if (colorIdx == ITimeGraphPresentationProvider.INVISIBLE) { return null; } if (colorIdx == ITimeGraphPresentationProvider.TRANSPARENT) { return new OutputElementStyle(null, new HashMap<>()); } @NonNull Map<@NonNull String, @NonNull Object> styleMap = StylePropertiesUtils.updateEventStyleProperties(fTimeGraphProvider.getEventStyle(event)); return new OutputElementStyle(null, applyEventStyleProperties(styleMap, event)); }

Target:
private @Nullable OutputElementStyle getElementStyle(ITimeEvent event) { OutputElementStyle elementStyle; if (fTimeGraphProvider instanceof IStylePresentationProvider) { IStylePresentationProvider provider = (IStylePresentationProvider) fTimeGraphProvider; elementStyle = provider.getElementStyle(event); if (elementStyle == null) { return null; } if (elementStyle.getParentKey() == null && elementStyle.getStyleValues().isEmpty()) { return elementStyle; } return new OutputElementStyle(elementStyle.getParentKey(), applyEventStyleProperties(new HashMap<>(elementStyle.getStyleValues()), event)); } if (!(event instanceof MarkerEvent)) { int colorIdx = fTimeGraphProvider.getStateTableIndex(event); if (colorIdx == ITimeGraphPresentationProvider.INVISIBLE) { return null; } if (colorIdx == ITimeGraphPresentationProvider.TRANSPARENT) { return new OutputElementStyle(null, new HashMap<>()); } } @NonNull Map<@NonNull String, @NonNull Object> styleMap = StylePropertiesUtils.updateEventStyleProperties(fTimeGraphProvider.getEventStyle(event)); return new OutputElementStyle(null, applyEventStyleProperties(styleMap, event)); }
Source:
public StateReport getReport(String domain) { StateReport report = new StateReport(domain); report = new StateReport(ReportConstants.CAT); report.setStartTime(new Date(m_startTime)); report.setEndTime(new Date(m_startTime + MINUTE * 60 - 1)); report.getMachines().clear(); String ip = NetworkInterfaceManager.INSTANCE.getLocalHostAddress(); Machine machine = report.findOrCreateMachine(ip); buildStateInfo(machine); StateReport startReport = m_reportManager.getHourlyReport(getStartTime(), ReportConstants.CAT, true); for(String key:machine.getProcessDomains().keySet()){ machine.getProcessDomains().get(key).getIps().addAll(startReport.findOrCreateMachine(ip).getProcessDomains().get(key).getIps()); } return report; }

Target:
public StateReport getReport(String domain) { StateReport report = new StateReport(domain); report = new StateReport(ReportConstants.CAT); report.setStartTime(new Date(m_startTime)); report.setEndTime(new Date(m_startTime + MINUTE * 60 - 1)); report.getMachines().clear(); String ip = NetworkInterfaceManager.INSTANCE.getLocalHostAddress(); Machine machine = report.findOrCreateMachine(ip); buildStateInfo(machine); StateReport startReport = m_reportManager.getHourlyReport(getStartTime(), ReportConstants.CAT, true); Map<String, ProcessDomain> processDomains = startReport.findOrCreateMachine(ip).getProcessDomains(); for(Map.Entry<String, ProcessDomain> entry:machine.getProcessDomains().entrySet()){ entry.getValue().getIps().addAll(processDomains.get(entry.getKey()).getIps()); } return report; }
Source:
public void executeFix(final String endpointId) throws DotDataException, DotSecurityException { DotConnect dc = new DotConnect(); final String getResultsQuery = new StringBuilder("SELECT ") .append(getIntegrityType().getFirstDisplayColumnLabel()) .append(", local_identifier, remote_identifier, local_working_inode, remote_working_inode, local_live_inode, remote_live_inode, language_id FROM ") .append(getIntegrityType().getResultsTableName()).append(" WHERE endpoint_id = ?") .toString(); dc.setSQL(getResultsQuery); dc.addParam(endpointId); List<Map<String, Object>> results = dc.loadObjectResults(); Map<String, Integer> versionCount = new HashMap<String, Integer>(); for (Map<String, Object> result : results) { final String oldIdentifier = (String) result.get("local_identifier"); final Integer counter = versionCount.get(oldIdentifier); if (counter == null) { versionCount.put(oldIdentifier, 1); } else { versionCount.put(oldIdentifier, counter + 1); } } for (Map<String, Object> result : results) { final String oldIdentifier = (String) result.get("local_identifier"); int counter = versionCount.get(oldIdentifier); boolean isTheLastConflict = counter == 1 ? true : false; try{ fixContentletConflicts(result, Structure.STRUCTURE_TYPE_FILEASSET, isTheLastConflict); } catch(IOException e){ throw new DotDataException(e.getMessage(),e); } if (!isTheLastConflict) { versionCount.put(oldIdentifier, counter - 1); } } }

Target:
public void executeFix(final String endpointId) throws DotDataException, DotSecurityException { DotConnect dc = new DotConnect(); final String getResultsQuery = new StringBuilder("SELECT ") .append(getIntegrityType().getFirstDisplayColumnLabel()) .append(", local_identifier, remote_identifier, local_working_inode, remote_working_inode, local_live_inode, remote_live_inode, language_id FROM ") .append(getIntegrityType().getResultsTableName()).append(" WHERE endpoint_id = ?") .toString(); dc.setSQL(getResultsQuery); dc.addParam(endpointId); List<Map<String, Object>> results = dc.loadObjectResults(); Map<String, Integer> versionCount = new HashMap<String, Integer>(); for (Map<String, Object> result : results) { final String oldIdentifier = (String) result.get("local_identifier"); final Integer counter = versionCount.get(oldIdentifier); if (counter == null) { versionCount.put(oldIdentifier, 1); } else { versionCount.put(oldIdentifier, counter + 1); } } for (Map<String, Object> result : results) { final String oldIdentifier = (String) result.get("local_identifier"); int counter = versionCount.get(oldIdentifier); boolean isTheLastConflict = counter == 1 ? true : false; fixContentletConflicts(result, Structure.STRUCTURE_TYPE_FILEASSET, isTheLastConflict); if (!isTheLastConflict) { versionCount.put(oldIdentifier, counter - 1); } } }
Source:
public Void call() throws Exception { ReviewDb db = sysInjector.getInstance(ReviewDb.class); GitRepositoryManager mgr = sysInjector.getInstance(GitRepositoryManager.class); repo = mgr.openRepository(project); try { Map<String, Ref> refs = repo.getAllRefs(); for (Change c : db.changes().all()) { Ref r = refs.get(c.currentPatchSetId().toRefName()); if (r != null) { byId.put(r.getObjectId(), new ChangeData(c)); } } walk(); } finally { repo.close(); RepositoryCache.close(repo); } return null; }

Target:
public Void call() throws Exception { ReviewDb db = sysInjector.getInstance(ReviewDb.class); GitRepositoryManager mgr = sysInjector.getInstance(GitRepositoryManager.class); repo = mgr.openRepository(project); try { Map<String, Ref> refs = repo.getAllRefs(); for (Change c : db.changes().byProject(project)) { Ref r = refs.get(c.currentPatchSetId().toRefName()); if (r != null) { byId.put(r.getObjectId(), new ChangeData(c)); } } walk(); } finally { repo.close(); RepositoryCache.close(repo); } return null; }
Source:
public void tearDown() throws Exception { File credDir = new File("."); File file = new File(credDir, JKS_FILE_NAME); file.delete(); file = new File(credDir, "." + JKS_FILE_NAME + ".crc"); file.delete(); }

Target:
public void tearDown() throws Exception { File file = new File(credDir, JKS_FILE_NAME); file.delete(); file = new File(credDir, "." + JKS_FILE_NAME + ".crc"); file.delete(); }
Source:
long verifyDigestAndReturnLac(ByteBuf dataReceived) throws BKDigestMatchException{ if ((LAC_METADATA_LENGTH + macCodeLength) > dataReceived.readableBytes()) { logger.error("Data received is smaller than the minimum for this digest type." + " Either the packet it corrupt, or the wrong digest is configured. " + " Digest type: {}, Packet Length: {}", this.getClass().getName(), dataReceived.readableBytes()); throw new BKDigestMatchException(); } update(dataReceived.slice(0, LAC_METADATA_LENGTH)); int offset = LAC_METADATA_LENGTH + macCodeLength; update(dataReceived.slice(offset, dataReceived.readableBytes() - offset)); ByteBuf digest = PooledByteBufAllocator.DEFAULT.buffer(macCodeLength); try { populateValueAndReset(digest); if (digest.compareTo(dataReceived.slice(LAC_METADATA_LENGTH, macCodeLength)) != 0) { logger.error("Mac mismatch for ledger-id LAC: " + ledgerId); throw new BKDigestMatchException(); } } finally { digest.release(); } long actualLedgerId = dataReceived.readLong(); long lac = dataReceived.readLong(); if (actualLedgerId != ledgerId) { logger.error("Ledger-id mismatch in authenticated message, expected: " + ledgerId + " , actual: " + actualLedgerId); throw new BKDigestMatchException(); } return lac; }

Target:
long verifyDigestAndReturnLac(ByteBuf dataReceived) throws BKDigestMatchException{ if ((LAC_METADATA_LENGTH + macCodeLength) > dataReceived.readableBytes()) { logger.error("Data received is smaller than the minimum for this digest type." + " Either the packet it corrupt, or the wrong digest is configured. " + " Digest type: {}, Packet Length: {}", this.getClass().getName(), dataReceived.readableBytes()); throw new BKDigestMatchException(); } update(dataReceived.slice(0, LAC_METADATA_LENGTH)); ByteBuf digest = PooledByteBufAllocator.DEFAULT.buffer(macCodeLength); try { populateValueAndReset(digest); if (digest.compareTo(dataReceived.slice(LAC_METADATA_LENGTH, macCodeLength)) != 0) { logger.error("Mac mismatch for ledger-id LAC: " + ledgerId); throw new BKDigestMatchException(); } } finally { digest.release(); } long actualLedgerId = dataReceived.readLong(); long lac = dataReceived.readLong(); if (actualLedgerId != ledgerId) { logger.error("Ledger-id mismatch in authenticated message, expected: " + ledgerId + " , actual: " + actualLedgerId); throw new BKDigestMatchException(); } return lac; }
Source:
protected boolean uploadCertificate(String certificate, String certificateName, long hostId) { SetupDirectDownloadCertificateCommand cmd = new SetupDirectDownloadCertificateCommand(certificate, certificateName); Answer answer = agentManager.easySend(hostId, cmd); if (answer == null || !answer.getResult()) { String msg = "Certificate " + certificateName + " could not be added to host " + hostId; if (answer != null) { msg += " due to: " + answer.getDetails(); } s_logger.info(msg); return false; } s_logger.info("Certificate " + certificateName + " successfully uploaded to host: " + hostId); return true; }

Target:
protected boolean uploadCertificate(String certificate, String certificateName, long hostId) { SetupDirectDownloadCertificateCommand cmd = new SetupDirectDownloadCertificateCommand(certificate, certificateName); Answer answer = agentManager.easySend(hostId, cmd); if (answer == null || !answer.getResult()) { String msg = "Certificate " + certificateName + " could not be added to host " + hostId; if (answer != null) { msg += " due to: " + answer.getDetails(); } s_logger.error(msg); return false; } s_logger.info("Certificate " + certificateName + " successfully uploaded to host: " + hostId); return true; }
Source:
private Sequence remove(final Sequence[] args) throws XPathException { final AbstractMapType map = (AbstractMapType) args[0].itemAt(0); AtomicValue[] keys = new AtomicValue[args[1].getItemCount()]; for (int i = 0; i < keys.length; i++) { keys[i] = (AtomicValue) args[1].itemAt(i); } return map.remove(keys); }

Target:
private Sequence remove(final Sequence[] args) throws XPathException { final AbstractMapType map = (AbstractMapType) args[0].itemAt(0); final int length = args[1].getItemCount(); final AtomicValue[] keys = new AtomicValue[length]; for (int i = 0; i < length; i++) { keys[i] = (AtomicValue) args[1].itemAt(i); } return map.remove(keys); }
Source:
public void signalProcessInstances(List<Long> processInstanceIds) { if (view.getSignalRefText() == null || view.getSignalRefText().isEmpty()) { view.setHelpText(constants.Signal_Name_Required()); return; } for (Long processInstanceId : processInstanceIds) { view.displayNotification(constants.Signaling_Process_Instance() + " (" + constants.Id() + " = " + processInstanceId + ") " + constants.Signal() + " = " + view.getSignalRefText() + " - " + constants.Signal_Data() + " = " + view.getEventText()); } processService.call((Void v) -> { processInstancesUpdatedEvent.fire(new ProcessInstancesUpdateEvent(0L)); bulkActionPerformedEvent.fire(new BulkActionPerformedEvent()); placeManager.closePlace(place); } ).signalProcessInstances(serverTemplateId, Arrays.asList(deploymentId), processInstanceIds, view.getSignalRefText(), view.getEventText()); }

Target:
public void signalProcessInstances(List<Long> processInstanceIds) { if (view.getSignalRefText() == null || view.getSignalRefText().isEmpty()) { view.setHelpText(constants.Signal_Name_Required()); return; } for (Long processInstanceId : processInstanceIds) { view.displayNotification(constants.Signaling_Process_Instance() + " (" + constants.Id() + " = " + processInstanceId + ") " + constants.Signal() + " = " + view.getSignalRefText() + " - " + constants.Signal_Data() + " = " + view.getEventText()); } processService.call((Void v) -> { processInstancesUpdatedEvent.fire(new ProcessInstancesUpdateEvent(0L)); deselectAllItemsEvent.fire(new DeselectAllItemsEvent()); placeManager.closePlace(place); } ).signalProcessInstances(serverTemplateId, Arrays.asList(deploymentId), processInstanceIds, view.getSignalRefText(), view.getEventText()); }
Source:
private Map<Cell, Value> getRowsAllColumns(final TableReference tableRef, final Iterable<byte[]> rows, final long timestamp) { if (Iterables.isEmpty(rows)) { return ImmutableMap.of(); } Map<Cell, Value> toReturn = new HashMap<>(); for (List<byte[]> part : Iterables.partition(rows, PARTITION_SIZE)) { toReturn.putAll(run(ctx -> { Select<? extends Record> query = getLatestTimestampQueryAllColumns( ctx, tableRef, ImmutableList.copyOf(part), timestamp); Result<? extends Record> records = fetchValues(ctx, tableRef, query); Map<Cell, Value> results = Maps.newHashMapWithExpectedSize(records.size()); for (Record record : records) { results.put( Cell.create(record.getValue(A_ROW_NAME), record.getValue(A_COL_NAME)), Value.create(record.getValue(A_VALUE), record.getValue(A_TIMESTAMP))); } return results; })); } return toReturn; }

Target:
private Map<Cell, Value> getRowsAllColumns(final TableReference tableRef, final Iterable<byte[]> rows, final long timestamp) { if (Iterables.isEmpty(rows)) { return ImmutableMap.of(); } return run(ctx -> { Select<? extends Record> query = getLatestTimestampQueryAllColumns( ctx, tableRef, ImmutableList.copyOf(rows), timestamp); Result<? extends Record> records = fetchValues(ctx, tableRef, query); Map<Cell, Value> results = Maps.newHashMapWithExpectedSize(records.size()); for (Record record : records) { results.put( Cell.create(record.getValue(A_ROW_NAME), record.getValue(A_COL_NAME)), Value.create(record.getValue(A_VALUE), record.getValue(A_TIMESTAMP))); } return results; }); }
Source:
private static ArrayList<ArrayList<String>> findCliqueCover(Graph graph, int bestSize, String tabs) { verboseLog(tabs+"findCliqueCover up to "+bestSize+", "+graph.toString()); for (int i=0; i<graph.verts.length; i++) { if (i >= bestSize-1) { verboseLog(tabs+"giving up"); return null; } String v0 = graph.verts[i]; if (!graph.edges.get(v0).isEmpty()) { verboseLog(tabs+"Selected vertex "+v0); String v1 = graph.edges.get(v0).iterator().next(); ArrayList<ArrayList<String>> bestCover0 = findCliqueCover(graph.ntract(v0,v1), bestSize, tabs+"----"); int bestSize0 = bestCover0 == null ? bestSize : bestCover0.size(); graph.removeEdge(v0,v1); ArrayList<ArrayList<String>> bestCover1 = findCliqueCover(graph, bestSize0, tabs+" "); graph.addEdge(v0,v1); if (bestCover1 != null) { return bestCover1; } else { if (bestCover0 != null) { bestCover0.get(i).add(v1); } return bestCover0; } } } verboseLog(tabs+"done, "+graph.verts.length); ArrayList<ArrayList<String>> bestCover = new ArrayList<>(); for (int i=0; i<graph.verts.length; i++) { ArrayList<String> singleton = new ArrayList<>(); singleton.add(graph.verts[i]); bestCover.add(singleton); } return bestCover; }

Target:
private static ArrayList<ArrayList<String>> findCliqueCover(Graph graph, int bestSize, String tabs) { verboseLog(tabs + "findCliqueCover up to " + bestSize + ", " + graph.toString()); for (int i = 0; i < graph.size(); i++) { if (i >= bestSize - 1) { verboseLog(tabs + "giving up"); return null; } String v0 = graph.getVert(i); if (!graph.getEdges(v0).isEmpty()) { verboseLog(tabs + "Selected vertex " + v0); String v1 = graph.getEdges(v0).iterator().next(); ArrayList<ArrayList<String>> bestCover0 = findCliqueCover(graph.ntract(v0, v1), bestSize, tabs + "----"); int bestSize0 = bestCover0 == null ? bestSize : bestCover0.size(); graph.removeEdge(v0, v1); ArrayList<ArrayList<String>> bestCover1 = findCliqueCover(graph, bestSize0, tabs + " "); graph.addEdge(v0, v1); if (bestCover1 != null) { return bestCover1; } else { if (bestCover0 != null) { bestCover0.get(i).add(v1); } return bestCover0; } } } verboseLog(tabs + "done, " + graph.size()); ArrayList<ArrayList<String>> bestCover = new ArrayList<>(); for (int i = 0; i < graph.size(); i++) { ArrayList<String> singleton = new ArrayList<>(); singleton.add(graph.getVert(i)); bestCover.add(singleton); } return bestCover; }
Source:
public ValidationResult canRebalance(GlusterVolumeEntity volumeEntity) { int replicaCount = 0; List<GlusterBrickEntity> bricks = volumeEntity.getBricks(); if (volumeEntity.getVolumeType() == GlusterVolumeType.DISTRIBUTE) { replicaCount = 1; } else if (volumeEntity.getVolumeType() == GlusterVolumeType.DISTRIBUTED_REPLICATE) { replicaCount = volumeEntity.getReplicaCount(); } int i = 0, j = 0; while (i < bricks.size()) { for (j = 0; j < replicaCount; j++) { if (bricks.get(i + j).isOnline()) { i = i + replicaCount; break; } } if (j == replicaCount) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_ONE_OR_MORE_BRICKS_ARE_DOWN); } } return ValidationResult.VALID; }

Target:
public ValidationResult canRebalance(GlusterVolumeEntity volumeEntity) { int replicaCount = 0; List<GlusterBrickEntity> bricks = volumeEntity.getBricks(); if (volumeEntity.getVolumeType().isReplicatedType()) { replicaCount = volumeEntity.getReplicaCount(); } else { replicaCount = 1; } int brickIndex = 0, replicaIndex = 0; while (brickIndex < bricks.size()) { for (replicaIndex = 0; replicaIndex < replicaCount; replicaIndex++) { if (bricks.get(brickIndex + replicaIndex).isOnline()) { brickIndex = brickIndex + replicaCount; break; } } if (replicaIndex == replicaCount) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_ONE_OR_MORE_BRICKS_ARE_DOWN); } } return ValidationResult.VALID; }
Source:
public void editDomain(ActionEvent event) { UpdateDomain updateDomain = new UpdateDomain(); updateDomain.setDomain(selectedDomain); try { directService.updateDomain(updateDomain); selectedDomain = null; refreshDomains(); } catch (CreateDomainException domainException) { FacesContext.getCurrentInstance().validationFailed(); FacesContext.getCurrentInstance().addMessage("domainEditErrors", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Can not update domain: " + domainException.getLocalizedMessage(), "")); LOG.error("Error updating domain: " + domainException.getMessage()); } }

Target:
public void editDomain(ActionEvent event) { UpdateDomain updateDomain = new UpdateDomain(); updateDomain.setDomain(selectedDomain); try { directService.updateDomain(updateDomain); selectedDomain = null; refreshDomains(); } catch (DomainException domainException) { FacesContext.getCurrentInstance().validationFailed(); FacesContext.getCurrentInstance().addMessage("domainEditErrors", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Can not update domain: " + domainException.getLocalizedMessage(), "")); LOG.error("Error updating domain: " + domainException.getMessage()); } }
Source:
public String toQueryString() { HashMap<String, String> parameters = new HashMap<String, String>(); if (transferToId != null) { parameters.put("transferTo", transferToId.toString()); if (transferSheets != null) { parameters.put("transferSheets", transferSheets.toString()); } } if (removeFromSharing != null) { parameters.put("removeFromSharing", removeFromSharing.toString()); } return QueryUtil.generateUrl(null, parameters); }

Target:
public String toQueryString() { HashMap<String, Object> parameters = new HashMap<String, Object>(); parameters.put("transferTo", transferToId); parameters.put("transferSheets", transferSheets); parameters.put("removeFromSharing", removeFromSharing); return QueryUtil.generateUrl(null, parameters); }
Source:
public @NonNull Map<@NonNull String, @NonNull String> getProperties() { Map<@NonNull String, @NonNull String> properties = new HashMap<>(); StateSystemBackendType backend = getBackendType(); properties.put(NonNullUtils.checkNotNull(Messages.TmfStateSystemAnalysisModule_PropertiesBackend), NonNullUtils.checkNotNull(backend.name())); switch (backend) { case FULL: case PARTIAL: File htFile = getSsFile(); if (htFile != null) { if (htFile.exists()) { properties.put(NonNullUtils.checkNotNull(Messages.TmfStateSystemAnalysisModule_PropertiesFileSize), NonNullUtils.checkNotNull(FileUtils.byteCountToDisplaySize(htFile.length()))); } else { properties.put(NonNullUtils.checkNotNull(Messages.TmfStateSystemAnalysisModule_PropertiesFileSize), NonNullUtils.checkNotNull(Messages.TmfStateSystemAnalysisModule_PropertiesAnalysisNotExecuted)); } } break; case INMEM: case NULL: default: break; } return properties; }

Target:
public @NonNull Map<@NonNull String, @NonNull String> getProperties() { Map<@NonNull String, @NonNull String> properties = new HashMap<>(); StateSystemBackendType backend = getBackendType(); properties.put(NonNullUtils.checkNotNull(Messages.TmfStateSystemAnalysisModule_PropertiesBackend), NonNullUtils.checkNotNull(backend.name())); switch (backend) { case FULL: case PARTIAL: File htFile = getSsFile(); if (htFile != null) { if (htFile.exists()) { properties.put(NonNullUtils.checkNotNull(Messages.TmfStateSystemAnalysisModule_PropertiesFileSize), FileUtils.byteCountToDisplaySize(htFile.length())); } else { properties.put(NonNullUtils.checkNotNull(Messages.TmfStateSystemAnalysisModule_PropertiesFileSize), NonNullUtils.checkNotNull(Messages.TmfStateSystemAnalysisModule_PropertiesAnalysisNotExecuted)); } } break; case INMEM: case NULL: default: break; } return properties; }
Source:
public void testInsertNewFieldIfDataTypeIsStructureWhenDataTypeIsStructure() { final DataType dataType = mock(DataType.class); when(dataTypeSelectComponent.getValue()).thenReturn(structure); when(dataType.getSubDataTypes()).thenReturn(emptyList()); doReturn(dataType).when(listItem).getDataType(); doNothing().when(listItem).insertNestedField(); listItem.insertNewFieldIfDataTypeIsStructure(); verify(listItem).insertNestedField(); }

Target:
public void testInsertNewFieldIfDataTypeIsStructureWhenDataTypeIsStructure() { final DataType dataType = mock(DataType.class); final String hash = "hash"; when(dataTypeSelectComponent.getValue()).thenReturn(structure); when(dataType.getSubDataTypes()).thenReturn(emptyList()); doReturn(dataType).when(listItem).getDataType(); doNothing().when(listItem).insertNestedField(); listItem.insertNewFieldIfDataTypeIsStructure(hash); verify(dataTypeList).insertNestedField(hash); }
Source:
public static String getResultObjectName() { return "snapshot"; }

Target:
public static String getResultObjectName() { return ApiConstants.SNAPSHOT; }
Source:
public void update(SolGame game) { float life = 0; Hero hero = game.getHero(); float ts = game.getTimeStep(); if (hero.isDead() || DIRECT_CAM_CONTROL) { applyInput(game); life = hero.getLife(); } else { myPos.set(hero.getPosition()); life = hero.getLife(); } if (life < myPrevHeroLife) { float shakeDiff = .1f * MAX_SHAKE * (myPrevHeroLife - life); myShake = SolMath.approach(myShake, MAX_SHAKE, shakeDiff); } else { myShake = SolMath.approach(myShake, 0, SHAKE_DAMP * ts); } myPrevHeroLife = life; Vector2 pos = SolMath.fromAl(SolMath.rnd(180), myShake); pos.add(myPos); applyPos(pos.x, pos.y); SolMath.free(pos); float desiredAngle = myCamRotStrategy.getRotation(myPos, game); float rotSpd = CAM_ROT_SPD * ts; myAngle = SolMath.approachAngle(myAngle, desiredAngle, rotSpd); applyAngle(); updateMap(game); }

Target:
public void update(SolGame game) { float life = 0; Hero hero = game.getHero(); float ts = game.getTimeStep(); life = hero.getLife(); if (hero.isDead() || DIRECT_CAM_CONTROL) { applyInput(game); } else { Vector2 heroPos = hero.getHull().getBody().getWorldCenter(); if (myZoom * VIEWPORT_HEIGHT < heroPos.dst(myPos)) { myPos.set(heroPos); game.getObjMan().resetDelays(); } else { Vector2 moveDiff = SolMath.getVec(hero.getSpd()); moveDiff.scl(ts); myPos.add(moveDiff); SolMath.free(moveDiff); float moveSpd = MOVE_SPD * ts; myPos.x = SolMath.approach(myPos.x, heroPos.x, moveSpd); myPos.y = SolMath.approach(myPos.y, heroPos.y, moveSpd); } } if (life < myPrevHeroLife) { float shakeDiff = .1f * MAX_SHAKE * (myPrevHeroLife - life); myShake = SolMath.approach(myShake, MAX_SHAKE, shakeDiff); } else { myShake = SolMath.approach(myShake, 0, SHAKE_DAMP * ts); } myPrevHeroLife = life; Vector2 pos = SolMath.fromAl(SolMath.rnd(180), myShake); pos.add(myPos); applyPos(pos.x, pos.y); SolMath.free(pos); float desiredAngle = myCamRotStrategy.getRotation(myPos, game); float rotSpd = CAM_ROT_SPD * ts; myAngle = SolMath.approachAngle(myAngle, desiredAngle, rotSpd); applyAngle(); updateMap(game); }
Source:
private void initCommandExecutor() { if (!cmdExecutorInitialized) { synchronized(LOCK) { if (!cmdExecutorInitialized) { for (CommandEntity cmdEntity : coco.getCommandsWithCallBackEnabled()) { if (!cmdEntity.isCallBackNotified()) { switch(cmdEntity.getCommandStatus()) { case ACTIVE_SYNC: coco.retrieveCommand(cmdEntity.getId()).setCommandStatus(CommandStatus.FAILED_RESTARTED); break; case REJECTED: case NOT_STARTED: executeAsyncCommand(cmdEntity.getCommandType(), cmdEntity.getActionParameters()); break; default: addToCallBackMap(cmdEntity); } } } cmdExecutorInitialized = true; } } } }

Target:
private void initCommandExecutor() { if (!cmdExecutorInitialized) { synchronized(LOCK) { if (!cmdExecutorInitialized) { for (CommandEntity cmdEntity : coco.getCommandsWithCallBackEnabled()) { switch(cmdEntity.getCommandStatus()) { case ACTIVE_SYNC: case NOT_STARTED: coco.retrieveCommand(cmdEntity.getId()).setCommandStatus(CommandStatus.FAILED_RESTARTED); break; default: addToCallBackMap(cmdEntity); break; } } cmdExecutorInitialized = true; } } } }
Source:
public MessageBuilder appendCustomMessage() { AbstractProject<?, ?> project = build.getProject(); String customMessage = Util.fixEmpty(project.getProperty(SlackNotifier.SlackJobProperty.class) .getCustomMessage()); Map<String, String> buildVariables = new HashMap(); buildVariables.putAll(build.getBuildVariables()); try { buildVariables.putAll(build.getEnvironment(new LogTaskListener(logger, INFO))); } catch (IOException e) { logger.log(SEVERE, e.getMessage(), e); } catch (InterruptedException e) { logger.log(SEVERE, e.getMessage(), e); } message.append("\n"); message.append(replaceMacro(customMessage, new VariableResolver.ByMap<String>(buildVariables))); return this; }

Target:
public MessageBuilder appendCustomMessage() { AbstractProject<?, ?> project = build.getProject(); String customMessage = Util.fixEmpty(project.getProperty(SlackNotifier.SlackJobProperty.class) .getCustomMessage()); EnvVars envVars = new EnvVars(); try { envVars = build.getEnvironment(new LogTaskListener(logger, INFO)); } catch (IOException e) { logger.log(SEVERE, e.getMessage(), e); } catch (InterruptedException e) { logger.log(SEVERE, e.getMessage(), e); } message.append("\n"); message.append(envVars.expand(customMessage)); return this; }
Source:
public void onErrorNull() { FlowableProcessor<T> p = create(); try { p.onError(null); fail("No NullPointerException thrown"); } catch (NullPointerException ex) { assertEquals("onError called with null. Null values are generally not allowed in 2.x operators and sources.", ex.getMessage()); } p.test().assertEmpty().cancel();; }

Target:
public void onErrorNull() { FlowableProcessor<T> p = create(); try { p.onError(null); fail("No NullPointerException thrown"); } catch (NullPointerException ex) { assertEquals("onError called with null. Null values are generally not allowed in 2.x operators and sources.", ex.getMessage()); } p.test().assertEmpty().cancel(); }
Source:
protected void service(final HttpServletRequest req, final HttpServletResponse rsp) throws IOException { if (req.getQueryString() == null || req.getQueryString().isEmpty()) { rsp.sendRedirect(req.getContextPath() + "/"); return; } final Map<String, String> params = getParameters(req); if (deniedActions.contains(params.get("a"))) { rsp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } String name = params.get("p"); if (name == null) { rsp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (name.endsWith(".git")) { name = name.substring(0, name.length() - 4); } final ProjectControl project; try { final Project.NameKey nameKey = new Project.NameKey(name); project = projectControl.validateFor(nameKey); if (project.areAllRefsVisible()) { throw new NoSuchProjectException(nameKey); } } catch (NoSuchProjectException e) { rsp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } final Repository repo; try { repo = repoManager.openRepository(name); } catch (RepositoryNotFoundException e) { getServletContext().log("Cannot open repository", e); rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } rsp.setHeader("Expires", "Fri, 01 Jan 1980 00:00:00 GMT"); rsp.setHeader("Pragma", "no-cache"); rsp.setHeader("Cache-Control", "no-cache, must-revalidate"); exec(req, rsp, project, repo); }

Target:
protected void service(final HttpServletRequest req, final HttpServletResponse rsp) throws IOException { if (req.getQueryString() == null || req.getQueryString().isEmpty()) { rsp.sendRedirect(req.getContextPath() + "/"); return; } final Map<String, String> params = getParameters(req); if (deniedActions.contains(params.get("a"))) { rsp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } String name = params.get("p"); if (name == null) { rsp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (name.endsWith(".git")) { name = name.substring(0, name.length() - 4); } final ProjectControl project; try { final Project.NameKey nameKey = new Project.NameKey(name); project = projectControl.validateFor(nameKey); if (!project.isAllRefsVisible()) { throw new NoSuchProjectException(nameKey); } } catch (NoSuchProjectException e) { rsp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } final Repository repo; try { repo = repoManager.openRepository(name); } catch (RepositoryNotFoundException e) { getServletContext().log("Cannot open repository", e); rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } rsp.setHeader("Expires", "Fri, 01 Jan 1980 00:00:00 GMT"); rsp.setHeader("Pragma", "no-cache"); rsp.setHeader("Cache-Control", "no-cache, must-revalidate"); exec(req, rsp, project, repo); }
Source:
public void assertIsPackagePrivate(AssertionInfo info, Class<?> actual) { assertNotNull(info, actual); if ((Modifier.isPublic(actual.getModifiers()) || Modifier.isProtected(actual.getModifiers()) || Modifier.isPrivate(actual.getModifiers()))) { throw failures.failure(info, shouldBePackagePrivate(actual)); } }

Target:
public void assertIsPackagePrivate(AssertionInfo info, Class<?> actual) { assertNotNull(info, actual); final int modifiers = actual.getModifiers(); if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers) || Modifier.isPrivate(modifiers)) { throw failures.failure(info, shouldBePackagePrivate(actual)); } }
Source:
private static boolean isPositiveInteger(final String str) { if (str == null || str.isEmpty()) { return false; } if (str.charAt(0) == '0') { return false; } for (int i = 0; i < str.length(); i++) { final char c = str.charAt(i); if (c < '0' || c > '9') { return false; } } return true; }

Target:
static boolean isPositiveInteger(final String str) { if (str == null || str.isEmpty()) { return false; } if (str.charAt(0) == '0' && str.length() > 1) { return false; } for (int i = 0; i < str.length(); i++) { final char c = str.charAt(i); if (c < '0' || c > '9') { return false; } } return true; }
Source:
public AnalogValue(int rawValue, int type) { if (type < 1 || type > 21) { measureType = TACmiMeasureType.UNSUPPORTED; value = new BigDecimal(rawValue); logger.warn("Got unsupported measure type {}, value is {}", type, rawValue); } else { measureType = TACmiMeasureType.fromInt(type); value = new BigDecimal(rawValue).movePointLeft(factors[type]); logger.debug("Got measure: type {}, raw value {}, converted: {}, {}", type, rawValue, measureType.name(), value); } }

Target:
public AnalogValue(int rawValue, int type) { measureType = TACmiMeasureType.fromInt(type); value = new BigDecimal(rawValue).movePointLeft(measureType.getScale()); if (measureType.equals(TACmiMeasureType.UNSUPPORTED)) { logger.warn("Unsupported measure type {}, value is {}", type, value); } else { logger.debug("Got measure: type {}, raw value {}, converted: {}, {}", type, rawValue, measureType.name(), value); } }
Source:
public void serializeCollectionsSingletonList() { ManageNetworkClustersParameters params = new ManageNetworkClustersParameters( Collections.singletonList(new NetworkCluster( Guid.createGuidFromString("f455686a-79cc-11e6-8c65-54ee755c6cc7"), Guid.createGuidFromString("f970c5f6-79cc-11e6-bc8f-54ee755c6cc7"), NetworkStatus.NON_OPERATIONAL, false, false, false, false, false))); JsonObjectSerializer serializer = new JsonObjectSerializer(); String json = serializer.serialize(params); assertTrue(json.length() > 0); ManageNetworkClustersParameters deserializedParams = new JsonObjectDeserializer().deserialize( json, ManageNetworkClustersParameters.class); assertEquals(params.getExecutionReason(), deserializedParams.getExecutionReason()); }

Target:
public void serializeCollectionsSingletonList() { ManageNetworkClustersParameters params = new ManageNetworkClustersParameters( Collections.singletonList(new NetworkCluster( Guid.newGuid(), Guid.newGuid(), NetworkStatus.NON_OPERATIONAL, false, false, false, false, false))); JsonObjectSerializer serializer = new JsonObjectSerializer(); String json = serializer.serialize(params); assertTrue(json.length() > 0); ManageNetworkClustersParameters deserializedParams = new JsonObjectDeserializer().deserialize( json, ManageNetworkClustersParameters.class); assertEquals(params.getExecutionReason(), deserializedParams.getExecutionReason()); }
Source:
public Configuration deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Configuration configuration = new Configuration(); JsonObject jo = (JsonObject) json; for (Entry<String, JsonElement> e : jo.entrySet()) { JsonPrimitive value = e.getValue().getAsJsonPrimitive(); if (value.isString()) { configuration.put(e.getKey(), value.getAsString()); } else if (value.isNumber()) { configuration.put(e.getKey(), value.getAsBigDecimal()); } else if (value.isBoolean()) { configuration.put(e.getKey(), value.getAsBigDecimal()); } } return configuration; }

Target:
public Configuration deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Configuration configuration = new Configuration(); JsonObject jo = (JsonObject) json; for (Entry<String, JsonElement> e : jo.entrySet()) { JsonPrimitive value = e.getValue().getAsJsonPrimitive(); if (value.isString()) { configuration.put(e.getKey(), value.getAsString()); } else if (value.isNumber()) { configuration.put(e.getKey(), value.getAsBigDecimal()); } else if (value.isBoolean()) { configuration.put(e.getKey(), value.getAsBoolean()); } } return configuration; }
Source:
public SQLQueryEngine(MetaDataStore metaDataStore, com.yahoo.elide.contrib.dynamicconfighelpers.compile.ConnectionDetails defaultConnectionDetails, Map<String, com.yahoo.elide.contrib.dynamicconfighelpers.compile.ConnectionDetails> detailsMap) { if (defaultConnectionDetails == null) { this.defaultConnectionDetails = null; } else { this.defaultConnectionDetails = new ConnectionDetails(defaultConnectionDetails.getDataSource(), SQLDialectFactory.getDialect(defaultConnectionDetails.getDialect())); } if (!(detailsMap == null || detailsMap.size() == 0)) { detailsMap.forEach((name, details) -> { this.connectionDetailsMap.put(name, new ConnectionDetails(details.getDataSource(), SQLDialectFactory.getDialect(details.getDialect()))); }); } this.metaDataStore = metaDataStore; this.metadataDictionary = metaDataStore.getMetadataDictionary(); populateMetaData(metaDataStore); this.tables = metaDataStore.getMetaData(Table.class).stream() .collect(Collectors.toMap(Table::getId, Functions.identity())); this.referenceTable = new SQLReferenceTable(metaDataStore); }

Target:
public SQLQueryEngine(MetaDataStore metaDataStore, com.yahoo.elide.contrib.dynamicconfighelpers.compile.ConnectionDetails defaultConnectionDetails, Map<String, com.yahoo.elide.contrib.dynamicconfighelpers.compile.ConnectionDetails> detailsMap) { Preconditions.checkNotNull(defaultConnectionDetails); Preconditions.checkNotNull(detailsMap); this.defaultConnectionDetails = new ConnectionDetails(defaultConnectionDetails.getDataSource(), SQLDialectFactory.getDialect(defaultConnectionDetails.getDialect())); detailsMap.forEach((name, details) -> { this.connectionDetailsMap.put(name, new ConnectionDetails(details.getDataSource(), SQLDialectFactory.getDialect(details.getDialect()))); }); this.metaDataStore = metaDataStore; this.metadataDictionary = metaDataStore.getMetadataDictionary(); populateMetaData(metaDataStore); this.tables = metaDataStore.getMetaData(Table.class).stream() .collect(Collectors.toMap(Table::getId, Functions.identity())); this.referenceTable = new SQLReferenceTable(metaDataStore); }
Source:
public void execute(List<String> args, PrintStream out) { ISarosSession session = sessionManager.getSession(); if (session == null) { log.error("No Session running, cannot add any resources"); return; } try { args.stream() .map(path -> new ServerProjectImpl(this.workspace, path)) .forEach(project -> session.addSharedResources(project, project.getName(), null)); for (User user : session.getRemoteUsers()) { sessionManager.startSharingProjects(user.getJID()); } } catch (Exception e) { log.error("Error sharing resources", e); } }

Target:
public void execute(List<String> args, PrintStream out) { ISarosSession session = sessionManager.getSession(); if (session == null) { log.error("No Session running, cannot add any resources"); return; } try { Map<IProject, List<IResource>> projects = new HashMap<>(); for (String path : args) { try { IProject project = new ServerProjectImpl(this.workspace, path); projects.put(project, null); } catch (Exception e) { log.error(path + " could not be added to the session", e); } } sessionManager.addResourcesToSession(projects); } catch (Exception e) { log.error("Error sharing resources", e); } }
Source:
public static List<FormOption> getLanguages() { final List<FormOption> languages = new ArrayList<>(); for (String languageCode : Locale.getISOLanguages()) { try { final String languageName = getLanguageNameFromCode(languageCode); if (Character.isUpperCase(languageName.charAt(0)) && languageName.length() > 3) { languages.add(new FormOption(languageName, languageCode)); } } catch (InvalidLocaleException e) { e.printStackTrace(); } } return languages; }

Target:
public static List<FormOption> getLanguages() { final List<FormOption> languages = new ArrayList<>(); for (String languageCode : Locale.getISOLanguages()) { try { final String languageName = getLanguageNameFromCode(languageCode); if (!languageCode.equals(languageName) && !languageCode.equals("zxx")) { languages.add(new FormOption(languageName, languageCode)); } } catch (InvalidLocaleException e) { e.printStackTrace(); } } sortBasedOnLocale(languages); return languages; }