auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public List<IBaseEventInfo> getKernelProvider(IProgressMonitor monitor) throws ExecutionException { List<String> command = createCommand(LTTngControlServiceConstants.COMMAND_LIST, LTTngControlServiceConstants.OPTION_KERNEL); ICommandResult result = executeCommand(command, monitor, false); List<IBaseEventInfo> events = new ArrayList<>(); if (result.getErrorOutput().length > 0) { if (ignoredPattern(result.getErrorOutput(), LTTngControlServiceConstants.LIST_KERNEL_NO_KERNEL_PROVIDER_PATTERN)) { return events; } } if (isError(result)) { throw new ExecutionException(Messages.TraceControl_CommandError + " " + toCommandString(command) + "\n" + result.toString()); } getProviderEventInfo(result.getOutput(), 0, events); return events; }

Target:
public List<IBaseEventInfo> getKernelProvider(IProgressMonitor monitor) throws ExecutionException { List<String> command = createCommand(LTTngControlServiceConstants.COMMAND_LIST, LTTngControlServiceConstants.OPTION_KERNEL); ICommandResult result = executeCommand(command, monitor, false); List<IBaseEventInfo> events = new ArrayList<>(); if (ignoredPattern(result.getErrorOutput(), LTTngControlServiceConstants.LIST_KERNEL_NO_KERNEL_PROVIDER_PATTERN)) { return events; } if (isError(result)) { throw new ExecutionException(Messages.TraceControl_CommandError + " " + toCommandString(command) + "\n" + result.toString()); } getProviderEventInfo(result.getOutput(), 0, events); return events; }
Source:
public void beforeUse(AbstractBuild b, FilePath workspace, BuildListener listener) { if (Util.isOverridden(WorkspaceListener.class, getClass(), "beforeUse", Run.class, FilePath.class, BuildListener.class)) { beforeUse((Run) b, workspace, listener); } else { throw new AssertionError("The plugin '" + this.getClass().getName() + "' still uses " + "deprecated beforeUse(AbstractBuild,FilePath,BuildListener) method. " + "Update the plugin to use beforeUse(Run,FilePath,BuildListener) instead."); } }

Target:
@Deprecated public void beforeUse(AbstractBuild b, FilePath workspace, BuildListener listener) { if (Util.isOverridden(WorkspaceListener.class, getClass(), "beforeUse", Run.class, FilePath.class, TaskListener.class)) { beforeUse((Run) b, workspace, listener); } }
Source:
public void tearDown() throws Exception { if (realm != null) { realm.close(); } }

Target:
public void tearDown() { if (realm != null) { realm.close(); } }
Source:
private static JGroupsModel getModelVersion(ModelTestControllerVersion controllerVersion) { switch (controllerVersion) { case EAP_6_4_0: case EAP_6_4_7: return JGroupsModel.VERSION_1_3_0; case EAP_7_0_0: return JGroupsModel.VERSION_4_0_0; case EAP_7_1_0: return JGroupsModel.VERSION_5_0_0; case EAP_7_2_0_TEMP: return JGroupsModel.VERSION_6_0_0; default: throw new IllegalArgumentException(); } }

Target:
private static JGroupsModel getModelVersion(ModelTestControllerVersion controllerVersion) { switch (controllerVersion) { case EAP_6_4_0: case EAP_6_4_7: return JGroupsModel.VERSION_1_3_0; case EAP_7_0_0: return JGroupsModel.VERSION_4_0_0; case EAP_7_1_0: return JGroupsModel.VERSION_5_0_0; case EAP_7_2_0: return JGroupsModel.VERSION_6_0_0; default: throw new IllegalArgumentException(); } }
Source:
public void testExport() { mode = LanguageMode.ECMASCRIPT6; parse("export const x = 1"); parse("export var x = 1"); parse("export function f() {}"); parse("export class c {}"); parse("export {x, y}"); parse("export {x as x1}"); parse("export {x as default, y as y1}"); parseError("export {default as x}", "cannot use keyword 'default' here."); parseError("export {package as x}", "cannot use keyword 'package' here."); parseError("export {package}", "cannot use keyword 'package' here."); parse("export {x as x1, y as y1} from './someModule'"); parse("export {x as x1, y as y1, } from './someModule'"); parse("export {default as d} from './someModule'"); parse("export {x as default, y as y1} from './someModule'"); parse("export {default as default, y as y1} from './someModule'"); parse("export * from './someModule'"); }

Target:
public void testExport() { mode = LanguageMode.ECMASCRIPT6; parse("export const x = 1"); parse("export var x = 1"); parse("export function f() {}"); parse("export class c {}"); parse("export {x, y}"); parse("export {x as x1}"); parse("export {x as x1, y as x2}"); parse("export {x as default, y as class}"); parseError("export {default as x}", "cannot use keyword 'default' here."); parseError("export {package as x}", "cannot use keyword 'package' here."); parseError("export {package}", "cannot use keyword 'package' here."); parse("export {x as x1, y as y1} from './someModule'"); parse("export {x as x1, y as y1, } from './someModule'"); parse("export {default as d} from './someModule'"); parse("export {d as default, c as class} from './someModule'"); parse("export {default as default, class as class} from './someModule'"); parse("export {class} from './someModule'"); parse("export * from './someModule'"); }
Source:
public void testTabletDir() { Master master = EasyMock.createMock(Master.class); VolumeManager volumeManager = EasyMock.createMock(VolumeManager.class); ImportedTableInfo iti = new ImportedTableInfo(); iti.tableId = "5"; String[] volumes = {"hdfs://nn1:8020/apps/accumulo1", "hdfs://nn2:8020/applications/accumulo"}; String tabletDir = "/c-00000001"; EasyMock.expect(master.getFileSystem()).andReturn(volumeManager); EasyMock.expect(volumeManager.choose(Optional.of(iti.tableId), volumes)) .andReturn(volumes[1]); EasyMock.replay(master, volumeManager); PopulateMetadataTable pmt = new PopulateMetadataTable(iti); assertEquals(volumes[1] + "/" + iti.tableId + "/" + tabletDir, pmt.getClonedTabletDir(master, volumes, tabletDir)); EasyMock.verify(master, volumeManager); }

Target:
public void testTabletDir() { Master master = EasyMock.createMock(Master.class); VolumeManager volumeManager = EasyMock.createMock(VolumeManager.class); ImportedTableInfo iti = new ImportedTableInfo(); iti.tableId = "5"; String[] volumes = new String[] {"hdfs://nn1:8020/apps/accumulo1", "hdfs://nn2:8020/applications/accumulo"}; String tabletDir = "/c-00000001"; EasyMock.expect(master.getFileSystem()).andReturn(volumeManager); EasyMock.expect(volumeManager.choose(Optional.of(iti.tableId), volumes)).andReturn(volumes[1]); EasyMock.replay(master, volumeManager); PopulateMetadataTable pmt = new PopulateMetadataTable(iti); assertEquals(volumes[1] + "/" + ServerConstants.TABLE_DIR + "/" + iti.tableId + "/" + tabletDir, pmt.getClonedTabletDir(master, volumes, tabletDir)); EasyMock.verify(master, volumeManager); }
Source:
private void writeChunkToOutputStream(byte[] chunk, int offset, int length) { if (compressor == null) { compressedOutputStream.write(chunk, offset, length); return; } checkArgument(length <= buffer.length, "Write chunk length must be less than compression buffer size"); int minCompressionBufferSize = compressor.maxCompressedLength(length); if (compressionBuffer.length < minCompressionBufferSize) { compressionBuffer = new byte[minCompressionBufferSize]; } int compressedSize = compressor.compress(chunk, offset, length, compressionBuffer, 0, compressionBuffer.length); if (compressedSize < length) { assert PAGE_HEADER_SIZE + compressedSize <= maxBufferSize; int chunkHeader = (compressedSize << 1); compressedOutputStream.write(chunkHeader & 0x00_00FF); compressedOutputStream.write((chunkHeader & 0x00_FF00) >> 8); compressedOutputStream.write((chunkHeader & 0xFF_0000) >> 16); compressedOutputStream.writeBytes(compressionBuffer, 0, compressedSize); } else { assert PAGE_HEADER_SIZE + length <= maxBufferSize; int header = (length << 1) + 1; compressedOutputStream.write(header & 0x00_00FF); compressedOutputStream.write((header & 0x00_FF00) >> 8); compressedOutputStream.write((header & 0xFF_0000) >> 16); compressedOutputStream.writeBytes(chunk, offset, length); } }

Target:
private void writeChunkToOutputStream(byte[] chunk, int offset, int length) { if (compressor == null) { compressedOutputStream.write(chunk, offset, length); return; } checkArgument(length <= buffer.length, "Write chunk length must be less than compression buffer size"); int minCompressionBufferSize = compressor.maxCompressedLength(length); if (compressionBuffer.length < minCompressionBufferSize) { compressionBuffer = new byte[minCompressionBufferSize]; } int compressedSize = compressor.compress(chunk, offset, length, compressionBuffer, 0, compressionBuffer.length); if (compressedSize < length) { int chunkHeader = (compressedSize << 1); compressedOutputStream.write(chunkHeader & 0x00_00FF); compressedOutputStream.write((chunkHeader & 0x00_FF00) >> 8); compressedOutputStream.write((chunkHeader & 0xFF_0000) >> 16); compressedOutputStream.writeBytes(compressionBuffer, 0, compressedSize); } else { int header = (length << 1) + 1; compressedOutputStream.write(header & 0x00_00FF); compressedOutputStream.write((header & 0x00_FF00) >> 8); compressedOutputStream.write((header & 0xFF_0000) >> 16); compressedOutputStream.writeBytes(chunk, offset, length); } }
Source:
public void shouldPassTheValidationIfAllTheFieldsAreNonEmpty() { Config config = new Config(); config.setName(NAME); config.setOpenMrsVersion(OPEN_MRS_VERSION); config.setOpenMrsUrl(OPEN_MRS_URL); config.setUsername(USERNAME); config.setPassword(PASSWORD); config.setMotechPatientIdentifierTypeName(MOTECH_PATIENT_IDENTIFIER_TYPE_NAME); config.setPatientIdentifierTypeNames(new ArrayList<>()); validateConfig(config); }

Target:
public void shouldPassTheValidationIfAllTheFieldsAreNonEmpty() { configValidator(NAME, OPEN_MRS_VERSION, OPEN_MRS_URL, USERNAME, PASSWORD, MOTECH_PATIENT_IDENTIFIER_TYPE_NAME, new ArrayList<>()); }
Source:
private void pullRecords() { ConsumerRecords<K, V> records = consumer.poll(Duration.ofMillis(100)); for (ConsumerRecord record : records) { bufferedRecords.add(record); } consumer.commitSync(); }

Target:
private void pullRecords() { ConsumerRecords<K, V> records = consumer.poll(Duration.ofMillis(100)); for (ConsumerRecord record : records) { bufferedRecords.add(record); } }
Source:
public void damage(double amount, Entity source, DamageCause cause) { if (!DamageCause.LIGHTNING.equals(cause)) { super.damage(amount, source, cause); } world.spawn(this.location, Witch.class); remove(); }

Target:
public void damage(double amount, Entity source, DamageCause cause) { if (!DamageCause.LIGHTNING.equals(cause)) { super.damage(amount, source, cause); return; } Witch witch = world.spawn(this.location, Witch.class); witch.damage(amount, source, cause); witch.setFireTicks(this.getFireTicks()); remove(); }
Source:
public Map<String,List<ProblemDetailInformation>> getDetails() { Map<String,List<ProblemDetailInformation>> jsonObj = new HashMap<String,List<ProblemDetailInformation>>(); List<ProblemDetailInformation> problems = new ArrayList<>(); Map<String,String> tidToNameMap = Tables.getIdToNameMap(HdfsZooInstance.getInstance()); if (Monitor.getProblemException() == null) { for (Entry<String,Map<ProblemType,Integer>> entry : Monitor.getProblemSummary().entrySet()) { ArrayList<ProblemReport> problemReports = new ArrayList<>(); Iterator<ProblemReport> iter = entry.getKey() == null ? ProblemReports.getInstance(Monitor.getContext()).iterator() : ProblemReports.getInstance( Monitor.getContext()).iterator(entry.getKey()); while (iter.hasNext()) problemReports.add(iter.next()); for (ProblemReport pr : problemReports) { String tableName = Tables.getPrintableTableNameFromId(tidToNameMap, pr.getTableName()); problems.add(new ProblemDetailInformation(tableName, entry.getKey(), pr.getProblemType().name(), pr.getServer(), pr.getTime(), pr.getResource(), pr .getException())); } } } jsonObj.put("problemDetails", problems); return jsonObj; }

Target:
public ProblemDetail getDetails() { ProblemDetail problems = new ProblemDetail(); Map<String,String> tidToNameMap = Tables.getIdToNameMap(HdfsZooInstance.getInstance()); if (Monitor.getProblemException() == null) { for (Entry<String,Map<ProblemType,Integer>> entry : Monitor.getProblemSummary().entrySet()) { ArrayList<ProblemReport> problemReports = new ArrayList<>(); Iterator<ProblemReport> iter = entry.getKey() == null ? ProblemReports.getInstance(Monitor.getContext()).iterator() : ProblemReports.getInstance( Monitor.getContext()).iterator(entry.getKey()); while (iter.hasNext()) problemReports.add(iter.next()); for (ProblemReport pr : problemReports) { String tableName = Tables.getPrintableTableNameFromId(tidToNameMap, pr.getTableName()); problems.addProblemDetail(new ProblemDetailInformation(tableName, entry.getKey(), pr.getProblemType().name(), pr.getServer(), pr.getTime(), pr .getResource(), pr.getException())); } } } return problems; }
Source:
public CaseCommentList getComments(String containerId, String caseId, Integer page, Integer pageSize) { Collection<CommentInstance> caseComments = caseService.getCaseComments(caseId, page, pageSize, ConvertUtils.buildQueryContext(page, pageSize)); logger.debug("Comments for case are {}", caseId, caseComments); List<CaseComment> comments = ConvertUtils.transformCaseComments(caseComments); CaseCommentList commentsList = new CaseCommentList(comments); return commentsList; }

Target:
public CaseCommentList getComments(String containerId, String caseId, Integer page, Integer pageSize) { Collection<CommentInstance> caseComments = caseService.getCaseComments(caseId, ConvertUtils.buildQueryContext(page, pageSize)); logger.debug("Comments for case are {}", caseId, caseComments); List<CaseComment> comments = ConvertUtils.transformCaseComments(caseComments); CaseCommentList commentsList = new CaseCommentList(comments); return commentsList; }
Source:
private org.openmrs.module.emrapi.conditionslist.Condition convertCoreConditionToEmrapiCondition(org.openmrs.Condition coreCondition) { org.openmrs.module.emrapi.conditionslist.Condition cListCondition = new org.openmrs.module.emrapi.conditionslist.Condition(); Concept concept = Context.getConceptService().getConceptByUuid(coreCondition.getCondition().getCoded().getUuid()); if(coreCondition.getCondition().getSpecificName() == null) { coreCondition.getCondition().setSpecificName(coreCondition.getCondition().getCoded().getName(Context.getLocale())); } cListCondition.setUuid(coreCondition.getUuid()); cListCondition.setConcept(concept); cListCondition.setAdditionalDetail(coreCondition.getAdditionalDetail()); cListCondition.setPatient(coreCondition.getPatient()); cListCondition.setConditionNonCoded(coreCondition.getCondition().getNonCoded()); cListCondition.setOnsetDate(coreCondition.getOnsetDate()); cListCondition.setVoided(coreCondition.getVoided()); cListCondition.setVoidReason(coreCondition.getVoidReason()); cListCondition.setEndDate(coreCondition.getEndDate()); cListCondition.setCreator(coreCondition.getCreator()); cListCondition.setDateCreated(coreCondition.getDateCreated()); cListCondition.setStatus(convertClinicalStatus(coreCondition.getClinicalStatus())); if (coreCondition.getPreviousVersion() != null) { cListCondition.setPreviousCondition(convertCoreConditionToEmrapiCondition(coreCondition.getPreviousVersion())); } return cListCondition; }

Target:
private org.openmrs.module.emrapi.conditionslist.Condition convertCoreConditionToEmrapiCondition(org.openmrs.Condition coreCondition) { org.openmrs.module.emrapi.conditionslist.Condition cListCondition = new org.openmrs.module.emrapi.conditionslist.Condition(); Concept concept; if (coreCondition.getCondition().getCoded() != null) { concept = Context.getConceptService() .getConceptByUuid(coreCondition.getCondition().getCoded().getUuid()); if(coreCondition.getCondition().getSpecificName() == null) { coreCondition.getCondition().setSpecificName(coreCondition.getCondition().getCoded().getName(Context.getLocale())); } } else { concept = new Concept(); } cListCondition.setUuid(coreCondition.getUuid()); cListCondition.setConcept(concept); cListCondition.setAdditionalDetail(coreCondition.getAdditionalDetail()); cListCondition.setPatient(coreCondition.getPatient()); cListCondition.setConditionNonCoded(coreCondition.getCondition().getNonCoded()); cListCondition.setOnsetDate(coreCondition.getOnsetDate()); cListCondition.setVoided(coreCondition.getVoided()); cListCondition.setVoidReason(coreCondition.getVoidReason()); cListCondition.setEndDate(coreCondition.getEndDate()); cListCondition.setCreator(coreCondition.getCreator()); cListCondition.setDateCreated(coreCondition.getDateCreated()); cListCondition.setStatus(convertClinicalStatus(coreCondition.getClinicalStatus())); if (coreCondition.getPreviousVersion() != null) { cListCondition.setPreviousCondition(convertCoreConditionToEmrapiCondition(coreCondition.getPreviousVersion())); } return cListCondition; }
Source:
private void drawSelectedFilesSegments(Canvas canvas, RotatedTileBox tileBox, List<SelectedGpxFile> selectedGPXFiles, DrawSettings settings) { SelectedGpxFile currentTrack = null; for (SelectedGpxFile g : selectedGPXFiles) { if (g.isShowCurrentTrack()) { currentTrack = g; } else { List<TrkSegment> segments = g.getPointsToDisplay(); for (TrkSegment ts : segments) { GpxDataItem gpxDataItem = view.getApplication().getGpxDatabase().getItem(new File(g.getGpxFile().path)); int color = gpxDataItem != null ? gpxDataItem.getColor() : 0; if (color == 0) { color = ts.getColor(cachedColor); } if (ts.renders.isEmpty() && !ts.points.isEmpty()) { ts.renders.add(new Renderable.StandardTrack(ts.points, 17.2)); } updatePaints(color, g.isRoutePoints(), false, settings, tileBox); ts.drawRenderers(view.getZoom(), paint, canvas, tileBox); } } } if (currentTrack != null) { List<TrkSegment> segments = currentTrack.getPointsToDisplay(); for (TrkSegment ts : segments) { int color = currentTrackColor; if (color == 0) { color = ts.getColor(cachedColor); } if (ts.renders.isEmpty() && !ts.points.isEmpty()) { ts.renders.add(new Renderable.CurrentTrack(ts.points)); } updatePaints(color, currentTrack.isRoutePoints(), true, settings, tileBox); ts.drawRenderers(view.getZoom(), paint, canvas, tileBox); } } }

Target:
private void drawSelectedFilesSegments(Canvas canvas, RotatedTileBox tileBox, List<SelectedGpxFile> selectedGPXFiles, DrawSettings settings) { SelectedGpxFile currentTrack = null; for (SelectedGpxFile g : selectedGPXFiles) { if (g.isShowCurrentTrack()) { currentTrack = g; } else { drawSelectedFileSegments(g, false, canvas, tileBox, settings); } } if (currentTrack != null) { drawSelectedFileSegments(currentTrack, true, canvas, tileBox, settings); } }
Source:
public Session performOpenSession(URI representationsFileURI, IProgressMonitor monitor) { Session session = null; try { monitor.beginTask(Messages.OpenRepresentationsFileJob_loadRepresentationsTask, 16); if (SiriusUtil.SESSION_RESOURCE_EXTENSION.equals(representationsFileURI.fileExtension())) { monitor.worked(1); session = trySessionOpening(representationsFileURI, monitor); monitor.worked(1); } } catch (SiriusResourceVersionMismatchException e) { UICallBack uiCallback = SiriusEditPlugin.getPlugin().getUiCallback(); if (uiCallback != null) { uiCallback.askSessionReopeningWithResourceVersionMismatch(e); try { MigrationUtil.ignoreVersionMismatch = true; session = trySessionOpening(representationsFileURI, monitor); monitor.worked(1); } catch (RuntimeException ex) { SiriusEditPlugin.getPlugin().log(ex); } finally { MigrationUtil.ignoreVersionMismatch = false; } } } catch (RuntimeException e) { SiriusEditPlugin.getPlugin().log(e); } finally { monitor.done(); } return session; }

Target:
public Session performOpenSession(URI representationsFileURI, IProgressMonitor monitor) { Session session = null; try { monitor.beginTask(Messages.OpenRepresentationsFileJob_loadRepresentationsTask, 16); if (SiriusUtil.SESSION_RESOURCE_EXTENSION.equals(representationsFileURI.fileExtension())) { monitor.worked(1); session = trySessionOpening(representationsFileURI, monitor); monitor.worked(1); } } catch (SiriusResourceVersionMismatchException e) { UICallBack uiCallback = SiriusEditPlugin.getPlugin().getUiCallback(); if (uiCallback != null && uiCallback.askSessionReopeningWithResourceVersionMismatch(e)) { try { MigrationUtil.ignoreVersionMismatch = true; session = trySessionOpening(representationsFileURI, monitor); monitor.worked(1); } catch (RuntimeException ex) { SiriusEditPlugin.getPlugin().log(ex); } finally { MigrationUtil.ignoreVersionMismatch = false; } } } catch (RuntimeException e) { SiriusEditPlugin.getPlugin().log(e); } finally { monitor.done(); } return session; }
Source:
public static String repeat(String s, int count) { if (count < 0) { throw new IllegalArgumentException("count is negative, " + count); } if (count == 1) { return s; } byte[] value = s.getBytes(StandardCharsets.UTF_8); final int len = value.length; if (len == 0 || count == 0) { return ""; } if (len == 1) { final byte[] single = new byte[count]; Arrays.fill(single, value[0]); return new String(single, StandardCharsets.UTF_8); } if (Integer.MAX_VALUE / count < len) { throw new OutOfMemoryError(); } final int limit = len * count; final byte[] multiple = new byte[limit]; System.arraycopy(value, 0, multiple, 0, len); int copied = len; for (; copied < limit - copied; copied <<= 1) { System.arraycopy(multiple, 0, multiple, copied, copied); } System.arraycopy(multiple, 0, multiple, copied, limit - copied); return new String(multiple, StandardCharsets.UTF_8); }

Target:
public static String repeat(String s, int count) { if (count < 0) { throw new IllegalArgumentException("count is negative, " + count); } if (count == 1) { return s; } byte[] value = s.getBytes(StandardCharsets.UTF_8); final int len = value.length; if (len == 0 || count == 0) { return ""; } if (len == 1) { final byte[] single = new byte[count]; Arrays.fill(single, value[0]); return new String(single, StandardCharsets.UTF_8); } if (Integer.MAX_VALUE / count < len) { throw new RuntimeException("The produced string is too large."); } final int limit = len * count; final byte[] multiple = new byte[limit]; System.arraycopy(value, 0, multiple, 0, len); int copied = len; for (; copied < limit - copied; copied <<= 1) { System.arraycopy(multiple, 0, multiple, copied, copied); } System.arraycopy(multiple, 0, multiple, copied, limit - copied); return new String(multiple, StandardCharsets.UTF_8); }
Source:
private String buildUrl(String componentId) { return String.join("/", GWT.getHostPageBaseURL(), COMPONENT_SERVER_PATH, componentId, "index.html"); }

Target:
private String buildUrl(String componentId) { return buildUrl(componentId, ""); }
Source:
@Test public void testTwoClasses() throws IllegalArgumentException, CancelException, IOException { runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), Arrays.asList( (IRAssertion) cg -> { final String typeStr = singleInputForTest(); final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy()); final IClass iClass = cg.getClassHierarchy().lookupClass(type); Assert.assertNotNull("Could not find class " + typeStr, iClass); }), true); }

Target:
@Test public void testTwoClasses() throws IllegalArgumentException, CancelException, IOException { runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), Arrays.asList( cg -> { final String typeStr = singleInputForTest(); final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy()); final IClass iClass = cg.getClassHierarchy().lookupClass(type); Assert.assertNotNull("Could not find class " + typeStr, iClass); }), true); }
Source:
protected void addLastModifiedInfo(Layout layout, String caption, String lastModified, String lastModifiedBy) { if (lastModified == null) { return; } StringBuilder sb = new StringBuilder(); sb.append("<span style=\"font-size:x-small\">"); sb.append(HSPACE); if (StringUtils.isNotBlank(caption)) { sb.append(caption).append(": "); } sb.append("last modified ").append(lastModified).append(" by ").append(lastModifiedBy); sb.append("</span>"); Label label = new Label(sb.toString(), Label.CONTENT_XHTML); label.setStyleName("light"); label.addStyleName(STYLE_LABEL); layout.addComponent(label); }

Target:
protected void addLastModifiedInfo(Layout layout, String caption, String lastModified, String lastModifiedBy) { if (lastModified == null) { return; } StringBuilder sb = new StringBuilder(); sb.append("<span style=\"font-size:x-small\">"); sb.append(HSPACE); if (StringUtils.isNotBlank(caption)) { sb.append(caption).append(": "); } sb.append("last modified ").append(lastModified).append(" by ").append(lastModifiedBy); sb.append("</span>"); Label label = asLabel(sb.toString()); label.setStyleName("light"); label.addStyleName(STYLE_LABEL); layout.addComponent(label); }
Source:
public List<IEventDeclaration> getEventDeclarations() { return ImmutableList.copyOf(fEvents); }

Target:
public List<IEventDeclaration> getEventDeclarations() { ImmutableList.Builder<IEventDeclaration> builder = new ImmutableList.Builder<>(); for (IEventDeclaration ied : fEvents) { if (ied != UNASSIGNED) { builder.add(ied); } } return builder.build(); }
Source:
private void setFollowing(boolean follow){ if (follow){ addFollow(); }else{ removeFollow(); } }

Target:
private void setFollowing(boolean follow) { if (threadFollowContainer.isSelected() != follow) { threadFollowContainer.setSelected(follow); threadFollowTextView.setText(follow ? R.string.forum_unfollow : R.string.forum_follow); threadFollowIconImageView.setIconColorResource(follow ? R.color.edx_brand_primary_base : R.color.edx_brand_gray_base); } }
Source:
public Set<String> prepareForDestroy() { try { PrepareForDestroy response = (PrepareForDestroy) invokeInternal(messageFactory.prepareForDestroy(), true); return response.getStores(); } catch (ClusterException | TimeoutException e) { } return null; }

Target:
public Set<String> prepareForDestroy() { try { PrepareForDestroy response = (PrepareForDestroy) invokeInternal(messageFactory.prepareForDestroy(), true); return response.getStores(); } catch (ClusterException e) { } return null; }
Source:
public List<Project.NameKey> call() throws NoSuchProjectException { List<Project.NameKey> ancestors = new ArrayList<Project.NameKey>(); final ProjectControl pc = projectControlFactory.validateFor(projectName, ProjectControl.OWNER | ProjectControl.VISIBLE); ProjectState projectState = pc.getProjectState().getParentState(); Set<Project.NameKey> seen = new HashSet<Project.NameKey>(); Project.NameKey prj; while (projectState != null) { prj = projectState.getProject().getNameKey(); if (!seen.add(prj)) { break; } ancestors.add(prj); projectState = projectState.getParentState(); } return ancestors; }

Target:
public ArrayList<Project.NameKey> call() throws NoSuchProjectException { LinkedHashSet ancestors = new LinkedHashSet(); final ProjectControl pc = projectControlFactory.validateFor(projectName, ProjectControl.OWNER | ProjectControl.VISIBLE); ProjectState projectState = pc.getProjectState().getParentState(); Project.NameKey prj; while (projectState != null) { prj = projectState.getProject().getNameKey(); if (!ancestors.add(prj)) { break; } projectState = projectState.getParentState(); } return new ArrayList<Project.NameKey>(ancestors); }
Source:
private static String toLegacyPathString(String moduleName) { final ModuleIdentifier moduleIdentifier = ModuleIdentifier.fromString(moduleName); return moduleIdentifier.getName().replace('.', '/') + '/' + moduleIdentifier.getSlot() + '/'; }

Target:
private static String toLegacyPathString(String moduleName) { final ModuleIdentifier moduleIdentifier = ModuleIdentifier.fromString(moduleName); return moduleIdentifier.getName().replace('.', '/') + '/' + moduleIdentifier.getSlot(); }
Source:
public void shouldReadFromQueueAndMakeAHttpCallForPost() throws IOException { MotechEvent motechEvent = new MotechEvent(EventSubjects.HTTP_REQUEST, new HashMap<String, Object>() {{ put(EventDataKeys.URL, url); put(EventDataKeys.DATA, data); put(EventDataKeys.METHOD, Method.POST); put(EventDataKeys.HEADERS, headers); }}); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("key1", "value1"); httpHeaders.add("key2", "value2"); request = new HttpEntity<String>(data,httpHeaders); responseEntity = new ResponseEntity<String>(body,HttpStatus.OK); when(restTempate.exchange(eq(url),eq(HttpMethod.POST),eq(request), eq(String.class))).thenReturn((ResponseEntity<String>) responseEntity); httpClientEventListener.handle(motechEvent); HTTPActionRecord httpActionRecord = new HTTPActionRecord(url, request.toString(), responseEntity.getBody().toString(), responseEntity.getStatusCode().toString()); verify(httpActionService,times(1)).create(eq(httpActionRecord)); }

Target:
public void shouldReadFromQueueAndMakeAHttpCallForPost() throws IOException { MotechEvent motechEvent = new MotechEvent(EventSubjects.HTTP_REQUEST, new HashMap<String, Object>() {{ put(EventDataKeys.URL, url); put(EventDataKeys.DATA, data); put(EventDataKeys.METHOD, Method.POST); put(EventDataKeys.HEADERS, headers); }}); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("key1", "value1"); httpHeaders.add("key2", "value2"); request = new HttpEntity<String>(data,httpHeaders); responseEntity = new ResponseEntity<String>(body, HttpStatus.OK); when(restTempate.exchange(eq(url),eq(HttpMethod.POST),eq(request), eq(String.class))).thenReturn((ResponseEntity<String>) responseEntity);; httpClientEventListener.handle(motechEvent); verify(restTempate).exchange(eq(url),eq(HttpMethod.POST),eq(request), eq(String.class)); }
Source:
private void writeMappingTable(Map<String,String> mappings) { createMappingTable(); StringBuffer buffer = new StringBuffer(); buffer.append("BEGIN BATCH "); for (Map.Entry<String,String> entry: mappings.entrySet()) { buffer.append(" INSERT INTO openshift_metrics.metrics_mappings (project_id, project_name) VALUES('"+ entry.getKey() + "','" + entry.getValue() + "');"); } buffer.append(" APPLY BATCH;"); ResultSet resultset = session.execute(buffer.toString()); System.err.println("WRITE RESULT SET"); }

Target:
private void writeMappingTable(Map<String,String> mappings) { createMappingTable(); PreparedStatement pStatement = session.prepare("INSERT INTO openshift_metrics.metrics_mappings (project_id, project_name) VALUES(?,?);"); for (Map.Entry<String,String> entry: mappings.entrySet()) { int maxRetries = 3; int tries = 0; boolean succeeded = false; while (!succeeded && tries < maxRetries) { try { log.debugf("trying to write value to metrics_mapping table: %s %s", entry.getKey(), entry.getValue()); session.execute(pStatement.bind(entry.getKey(), entry.getValue())); log.debugf("wrote value to metrics_mapping table"); succeeded = true; } catch (Exception e) { log.errorf(e, "Error trying to insert entry into the openshift_metrics.metrics_mappings table (%s:%s). Will retry.", entry.getKey(), entry.getValue()); try { Thread.sleep(1000); } catch (InterruptedException ie) { break; } } tries++; } if (!succeeded) { throw new RuntimeException("Could not write all values to the openshift_metrics.metrics_mapping table. Aborting"); } } session.execute(pStatement.bind("%succeeded", "true")); }
Source:
public List<ByteBuffer> readBlocks(SeekableInputStream f, long offset, int length) throws IOException { f.seek(offset); int fullAllocations = length / options.getMaxAllocationSize(); int lastAllocationSize = length % options.getMaxAllocationSize(); int numAllocations = fullAllocations + (lastAllocationSize > 0 ? 1 : 0); List<ByteBuffer> buffers = new ArrayList<>(numAllocations); for (int i = 0; i < fullAllocations; i++) { buffers.add(options.getAllocator().allocate(options.getMaxAllocationSize())); } if (lastAllocationSize > 0) { buffers.add(options.getAllocator().allocate(lastAllocationSize)); } for (ByteBuffer buffer : buffers) { f.readFully(buffer); buffer.flip(); } return buffers; }

Target:
List<ByteBuffer> readBlocks(SeekableInputStream f, long offset, int length) throws IOException { f.seek(offset); int fullAllocations = length / options.getMaxAllocationSize(); int lastAllocationSize = length % options.getMaxAllocationSize(); int numAllocations = fullAllocations + (lastAllocationSize > 0 ? 1 : 0); List<ByteBuffer> buffers = new ArrayList<>(numAllocations); for (int i = 0; i < fullAllocations; i++) { buffers.add(options.getAllocator().allocate(options.getMaxAllocationSize())); } if (lastAllocationSize > 0) { buffers.add(options.getAllocator().allocate(lastAllocationSize)); } for (ByteBuffer buffer : buffers) { f.readFully(buffer); buffer.flip(); } return buffers; }
Source:
private void createSmallBam(final Path outputPath) { final SAMFileWriterFactory factory = new SAMFileWriterFactory(); factory.setCreateIndex(true); factory.setCreateMd5File(true); final SAMFileHeader header = new SAMFileHeader(); header.setSortOrder(SAMFileHeader.SortOrder.coordinate); header.addSequence(new SAMSequenceRecord("chr1", 123)); final SAMFileWriter writer = factory.makeBAMWriter(header, false, outputPath); fillSmallBam(writer); writer.close(); }

Target:
private void createSmallBam(final Path outputPath) { final SAMFileWriterFactory factory = new SAMFileWriterFactory(); factory.setCreateIndex(true); factory.setCreateMd5File(true); final SAMFileHeader header = new SAMFileHeader(); header.setSortOrder(SAMFileHeader.SortOrder.coordinate); header.addSequence(new SAMSequenceRecord("chr1", 123)); try (final SAMFileWriter writer = factory.makeBAMWriter(header, false, outputPath)) { fillSmallBam(writer); } }
Source:
protected HashMap<String, Bitmap> doInBackground(FeatureCollection... params) { QueryFeatureActivity activity = activityRef.get(); HashMap<String, Bitmap> imagesMap = new HashMap<>(); if (activity != null) { LayoutInflater inflater = LayoutInflater.from(activity); featureAtMapClickPoint = params[0].features().get(0); StringBuilder stringBuilder = new StringBuilder(); BubbleLayout bubbleLayout = (BubbleLayout) inflater.inflate( R.layout.activity_query_feature_window_symbol_layer, null); TextView titleTextView = bubbleLayout.findViewById(R.id.info_window_title); titleTextView.setText(activity.getString(R.string.query_feature_marker_title)); for (Map.Entry<String, JsonElement> entry : featureAtMapClickPoint.properties().entrySet()) { stringBuilder.append(String.format("%s - %s", entry.getKey(), entry.getValue())); stringBuilder.append(System.getProperty("line.separator")); } TextView propertiesListTextView = bubbleLayout.findViewById(R.id.info_window_feature_properties_list); propertiesListTextView.setText(stringBuilder.toString()); int measureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); bubbleLayout.measure(measureSpec, measureSpec); int measuredWidth = bubbleLayout.getMeasuredWidth(); bubbleLayout.setArrowPosition(measuredWidth / 2 - 5); Bitmap bitmap = QueryFeatureActivity.SymbolGenerator.generate(bubbleLayout); imagesMap.put(CALLOUT_IMAGE_ID, bitmap); viewMap.put(CALLOUT_IMAGE_ID, bubbleLayout); } return imagesMap; }

Target:
protected HashMap<String, Bitmap> doInBackground(FeatureCollection... params) { QueryFeatureActivity activity = activityRef.get(); HashMap<String, Bitmap> imagesMap = new HashMap<>(); if (activity != null) { LayoutInflater inflater = LayoutInflater.from(activity); featureAtMapClickPoint = params[0].features().get(0); StringBuilder stringBuilder = new StringBuilder(); BubbleLayout bubbleLayout = (BubbleLayout) inflater.inflate( R.layout.activity_query_feature_window_symbol_layer, null); TextView titleTextView = bubbleLayout.findViewById(R.id.info_window_title); titleTextView.setText(activity.getString(R.string.query_feature_marker_title)); for (Map.Entry<String, JsonElement> entry : featureAtMapClickPoint.properties().entrySet()) { stringBuilder.append(String.format("%s - %s", entry.getKey(), entry.getValue())); stringBuilder.append(System.getProperty("line.separator")); } TextView propertiesListTextView = bubbleLayout.findViewById(R.id.info_window_feature_properties_list); propertiesListTextView.setText(stringBuilder.toString()); int measureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); bubbleLayout.measure(measureSpec, measureSpec); int measuredWidth = bubbleLayout.getMeasuredWidth(); bubbleLayout.setArrowPosition(measuredWidth / 2 - 5); Bitmap bitmap = QueryFeatureActivity.SymbolGenerator.generate(bubbleLayout); imagesMap.put(CALLOUT_IMAGE_ID, bitmap); } return imagesMap; }
Source:
private List<AbstractNode> getFollowingSiblings() { final List<AbstractNode> siblings = new ArrayList<>(); for (int i = positionAmongSiblings + 1; i < parent.getChildren().size(); i++) { final AbstractNode following = parent.getChildren().get(i); siblings.add(following); } return siblings; }

Target:
private List<AbstractNode> getFollowingSiblings() { final List<AbstractNode> siblings = parent.getChildren(); return siblings.subList(indexAmongSiblings + 1, siblings.size()); }
Source:
private static boolean isUnderCurrentProjectBuildDir(File moduleRoot) { String buildDir = System.getProperty("project.build.directory"); if (buildDir != null) { File target = new File(buildDir); File parent = moduleRoot.getParentFile(); while (parent != null) { if (target.equals(parent)) { return true; } parent = parent.getParentFile(); } } return false; }

Target:
private static boolean isUnderCurrentProjectBuildDir(File moduleRoot) { String buildDir = System.getProperty("project.build.directory"); if (buildDir == null && System.getProperty("basedir") != null) { buildDir = Paths.get(System.getProperty("basedir"), "target").toString(); } if (buildDir != null) { File target = new File(buildDir); File parent = moduleRoot.getParentFile(); while (parent != null) { if (target.equals(parent)) { return true; } parent = parent.getParentFile(); } } return false; }
Source:
public EventQueryNode(final EventStorage eventStore, final StatementPattern geoPattern, final StatementPattern temporalPattern, final Collection<IndexingExpr> geoFilters, final Collection<IndexingExpr> temporalFilters, final Collection<FunctionCall> usedFilters) throws IllegalStateException { this.geoPattern = requireNonNull(geoPattern); this.temporalPattern = requireNonNull(temporalPattern); this.geoFilters = requireNonNull(geoFilters); this.temporalFilters = requireNonNull(temporalFilters); this.eventStore = requireNonNull(eventStore); this.usedFilters = requireNonNull(usedFilters); bindingNames = new HashSet<>(); verifySameSubjects(getPatterns()); verifyAllPredicatesAreConstants(getPatterns()); final Var subject = patterns.iterator().next().getSubjectVar(); subjectIsConstant = subject.isConstant(); if(subjectIsConstant) { subjectConstant = Optional.of( subject.getValue().toString() ); subjectVar = Optional.empty(); } else { subjectConstant = Optional.empty(); subjectVar = Optional.of( subject.getName() ); } }

Target:
private EventQueryNode(final EventStorage eventStore, final StatementPattern geoPattern, final StatementPattern temporalPattern, final Collection<IndexingExpr> geoFilters, final Collection<IndexingExpr> temporalFilters, final Collection<FunctionCall> usedFilters) throws IllegalStateException { this.geoPattern = requireNonNull(geoPattern); this.temporalPattern = requireNonNull(temporalPattern); this.geoFilters = requireNonNull(geoFilters); this.temporalFilters = requireNonNull(temporalFilters); this.eventStore = requireNonNull(eventStore); this.usedFilters = requireNonNull(usedFilters); bindingNames = new HashSet<>(); verifySameSubjects(getPatterns()); verifyAllPredicatesAreConstants(getPatterns()); final Var subject = patterns.iterator().next().getSubjectVar(); subjectIsConstant = subject.isConstant(); if(subjectIsConstant) { subjectConstant = Optional.of( subject.getValue().toString() ); subjectVar = Optional.empty(); } else { subjectConstant = Optional.empty(); subjectVar = Optional.of( subject.getName() ); } }
Source:
public Collection<AccountGroup.Id> createEntry(final AccountGroup.Id key) throws Exception { final ReviewDb db = schema.open(); try { final ResultSet<AccountGroupIncludedGroup> groups = db.accountGroupIncludedGroups().byIncludedGroup(key); ArrayList<AccountGroup.Id> groupArray = new ArrayList<AccountGroup.Id> (); for (AccountGroupIncludedGroup agig : groups) { groupArray.add(agig.getGroupId()); } return groupArray; } finally { db.close(); } }

Target:
public Collection<AccountGroup.Id> createEntry(final AccountGroup.Id key) throws Exception { final ReviewDb db = schema.open(); try { ArrayList<AccountGroup.Id> groupArray = new ArrayList<AccountGroup.Id> (); for (AccountGroupIncludedGroup agig : db.accountGroupIncludedGroups().byIncludedGroup(key)) { groupArray.add(agig.getGroupId()); } return Collections.unmodifiableCollection(groupArray); } finally { db.close(); } }
Source:
@Override public boolean equals(Object obj) { if (!(obj instanceof TimestampWithTimeZone)) { return false; } TimestampWithTimeZone that = (TimestampWithTimeZone) obj; return this.millisecond == that.millisecond && this.timeZone == that.timeZone; }

Target:
@Override public boolean equals(Object obj) { if (!(obj instanceof TimestampWithTimeZone)) { return false; } TimestampWithTimeZone that = (TimestampWithTimeZone) obj; return this.millisecond == that.millisecond && this.timeZone.equals(that.timeZone); }
Source:
boolean areRequiredNetworksAvailable(VDS vds) { final List<VdsNetworkInterface> allInterfacesForVds = getInterfaceDAO().getAllInterfacesForVds(vds.getId()); final List<Network> clusterNetworks = getNetworkDAO().getAllForCluster(vds.getvds_group_id()); final Map<String, Network> networksByName = NetworkUtils.networksByName(clusterNetworks); boolean onlyRequiredNetworks = Config.<Boolean> GetValue(ConfigValues.OnlyRequiredNetworksMandatoryForVdsSelection); for (final VmNetworkInterface vmIf : getVmNICs()) { boolean found = false; for (final VdsNetworkInterface vdsIf : allInterfacesForVds) { if (!networkRequiredOnVds(vmIf, networksByName, onlyRequiredNetworks) || StringUtils.equals(vmIf.getNetworkName(), vdsIf.getNetworkName())) { found = true; break; } } if (!found) { return false; } } return true; }

Target:
private boolean areRequiredNetworksAvailable(VDS vds) { final List<VdsNetworkInterface> allInterfacesForVds = getInterfaceDAO().getAllInterfacesForVds(vds.getId()); final List<Network> clusterNetworks = getNetworkDAO().getAllForCluster(vds.getvds_group_id()); final Map<String, Network> networksByName = Entities.entitiesByName(clusterNetworks); boolean onlyRequiredNetworks = Config.<Boolean> GetValue(ConfigValues.OnlyRequiredNetworksMandatoryForVdsSelection); for (final VmNetworkInterface vmIf : getVmNICs()) { boolean found = false; for (final VdsNetworkInterface vdsIf : allInterfacesForVds) { if (!networkRequiredOnVds(vmIf, networksByName, onlyRequiredNetworks) || StringUtils.equals(vmIf.getNetworkName(), vdsIf.getNetworkName())) { found = true; break; } } if (!found) { return false; } } return true; }
Source:
public void testResourceHeaders() throws Exception { MockHttpServletResponse response = getAsServletResponse("/rest/resource/mydir2/fake.png"); Assert.assertEquals(FORMAT_HEADER.format(myRes.lastmodified()), response.getHeader("Last-modified")); Assert.assertEquals("/mydir2", response.getHeader("Resource-parent")); Assert.assertEquals("resource", response.getHeader("Resource-type")); Assert.assertEquals("image/png", response.getHeader("Content-type")); }

Target:
public void testResourceHeaders() throws Exception { MockHttpServletResponse response = getAsServletResponse("/rest/resource/mydir2/fake.png"); Assert.assertEquals(FORMAT_HEADER.format(myRes.lastmodified()), response.getHeader("Last-Modified")); Assert.assertEquals("/mydir2", response.getHeader("Resource-Parent")); Assert.assertEquals("resource", response.getHeader("Resource-Type")); Assert.assertEquals("image/png", response.getHeader("Content-Type")); }
Source:
public Obs getObs(Obs obs, String view) { File file = getComplexDataFile(obs); if (ComplexObsHandler.RAW_VIEW.equals(view)) { BufferedImage img = null; try { img = ImageIO.read(file); } catch (IOException e) { log.error("Trying to read file: " + file.getAbsolutePath(), e); } ComplexData complexData = new ComplexData(file.getName(), img); String mimeType = getMimeTypeFromFile(file); mimeType = mimeType != null ? mimeType : "application/octet-stream"; complexData.setMimeType(mimeType); obs.setComplexData(complexData); } else { return null; } return obs; }

Target:
public Obs getObs(Obs obs, String view) { File file = getComplexDataFile(obs); if (ComplexObsHandler.RAW_VIEW.equals(view)) { BufferedImage img = null; try { img = ImageIO.read(file); } catch (IOException e) { log.error("Trying to read file: " + file.getAbsolutePath(), e); } ComplexData complexData = new ComplexData(file.getName(), img); String mimeType = null; try { FileImageInputStream imgStream = new FileImageInputStream(file); Iterator<ImageReader> imgReader = ImageIO.getImageReaders(imgStream); imgStream.close(); if (imgReader.hasNext()) { mimeType = "image/" + imgReader.next().getFormatName().toLowerCase(); } else { log.warn("MIME type of " + file.getAbsolutePath() + " is not known"); } } catch (FileNotFoundException e) { log.error("Image " + file.getAbsolutePath() + " was not found", e); } catch (IOException e) { log.error("Trying to determine MIME type of " + file.getAbsolutePath(), e); } mimeType = mimeType != null ? mimeType : OpenmrsUtil.getFileMimeType(file); complexData.setMimeType(mimeType); obs.setComplexData(complexData); } else { return null; } return obs; }
Source:
private static Gson getTeammatesGson() { return new GsonBuilder().registerTypeAdapter(Date.class, new StandardDateAdapter()) .setPrettyPrinting() .disableHtmlEscaping() .create(); }

Target:
private static Gson getTeammatesGson() { return new GsonBuilder().registerTypeAdapter(Date.class, new TeammatesDateAdapter()) .setPrettyPrinting() .disableHtmlEscaping() .create(); }
Source:
@Nullable @Override protected MetadataMarshalled reduce0(List<ComputeJobResult> results) { if (results.isEmpty()) throw new IgniteException("Empty job results"); if (results.size() > 1) throw new IgniteException("Invalid job results: " + results); if (results.get(0).getException() != null) throw results.get(0).getException(); else return results.get(0).getData(); }

Target:
@Nullable @Override protected MetadataMarshalled reduce0(List<ComputeJobResult> results) { if (results.size() != 1) throw new IgniteException("Invalid job results. Expected exactly 1 result, but was: " + results); if (results.get(0).getException() != null) throw results.get(0).getException(); else return results.get(0).getData(); }