auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static String getLocalHost() throws UnknownHostException { try { String ip = InetAddress.getLocalHost().getHostAddress(); if (ip.equals("127.0.0.1")) { return getAddress(); } else return ip; <START> } catch (Throwable e) { <END> String ip = getAddress(); if (ip != null && !ip.isEmpty()) { return ip; } throw new UnknownHostException("InetAddress java.net.InetAddress.getLocalHost() throws UnknownHostException," + e.getMessage()); } }</code><technical_language>Please catch exact expected exception type</technical_language>

Target:
public static String getLocalHost() throws UnknownHostException { String ip = InetAddress.getLocalHost().getHostAddress(); if (InetAddress.getLocalHost().isLoopbackAddress()) { return getValidAddress(); } else { return ip; } }
Source:
<code>private static void handleUndoLog(List<UndoAction> undoLog, boolean undo) { if (undoLog == null) { return; } <START> ListIterator<UndoAction> iterator = (undo) ? undoLog.listIterator(undoLog.size()) : undoLog.listIterator(); <END> for (; (undo ? iterator.hasPrevious() : iterator.hasNext());) { if (undo) { iterator.previous().undo(); } else { iterator.next().release(); } } if (undo) { undoLog.clear(); } }</code><technical_language>I simplify this Lists.reverse is a view underlying list Collections.reverse() in place reverse cheaper for smaller lists a view. if (undo) undoLog = Lists.reverse(undoLog) for (UndoAction action : undoLog) if (undo) action.undo() else action.release()</technical_language>

Target:
private static void handleUndoLog(List<UndoAction> undoLog, boolean undo) { if (undoLog == null) { return; } if (undo) { undoLog = Lists.reverse(undoLog); } for (UndoAction action : undoLog) { if (undo) { action.undo(); } else { action.release(); } } if (undo) { undoLog.clear(); } }
Source:
<code>private GlowBlock createMockBlock(Location location, Material type, byte data) { <START> GlowBlock mockBlock = PowerMockito.mock(GlowBlock.class); <END> when(mockBlock.getLocation()).thenReturn(location); when(mockBlock.getType()).thenReturn(type); when(mockBlock.getTypeId()).thenReturn(type.getId()); when(mockBlock.getData()).thenReturn(data); BlockEntity entity = null; BlockType blockType = ItemTable.instance().getBlock(type); if (blockType != null) { entity = blockType.createBlockEntity(mockBlock); } when(mockBlock.getBlockEntity()).thenReturn(entity); return mockBlock; }</code><technical_language>I plain Mockito here, class is longer final</technical_language>

Target:
private GlowBlock createMockBlock(Location location, Material type, byte data) { GlowBlock mockBlock = Mockito.mock(GlowBlock.class); when(mockBlock.getLocation()).thenReturn(location); when(mockBlock.getType()).thenReturn(type); when(mockBlock.getTypeId()).thenReturn(type.getId()); when(mockBlock.getData()).thenReturn(data); BlockEntity entity = null; BlockType blockType = ItemTable.instance().getBlock(type); if (blockType != null) { GlowChunk mockChunk = Mockito.mock(GlowChunk.class); when(mockChunk.getBlock(anyInt(), anyInt(), anyInt())).thenReturn(mockBlock); entity = blockType.createBlockEntity(mockChunk, 0, 0, 0); } when(mockBlock.getBlockEntity()).thenReturn(entity); return mockBlock; }
Source:
<code>public void testHoles() throws IOException { CatalogJanitor janitor = TEST_UTIL.getHBaseCluster().getMaster().getCatalogJanitor(); CatalogJanitor.Report report = janitor.getLastReport(); assertTrue(report.isEmpty()); verifyCornerHoles(janitor, T1); verifyCornerHoles(janitor, T2); verifyMiddleHole(janitor); janitor.scan(); <START> assertEquals(5, janitor.getLastReport().getHoles().size()); <END> }</code><technical_language>Please run MetaFixer verify is processing holes correctly</technical_language>

Target:
public void testHoles() throws IOException { CatalogJanitor janitor = TEST_UTIL.getHBaseCluster().getMaster().getCatalogJanitor(); CatalogJanitor.Report report = janitor.getLastReport(); assertTrue(report.isEmpty()); verifyCornerHoles(janitor, T1); verifyCornerHoles(janitor, T2); verifyMiddleHole(janitor); fixHoles(janitor); }
Source:
<code>protected abstract void updateNewlyCreatedEObjectWithEObjectDragged(T slot, S property) throws ExecutionException; @Override protected CommandResult doRedoWithResult(IProgressMonitor progressMonitor, IAdaptable info) throws ExecutionException { <START> return null; <END> }</code><technical_language>raise exception "not implemented"</technical_language>

Target:
protected abstract void updateNewlyCreatedEObjectWithEObjectDragged(T slot, S property) throws ExecutionException; @Override protected CommandResult doRedoWithResult(IProgressMonitor progressMonitor, IAdaptable info) throws ExecutionException { throw new ExecutionException("not implemented"); }
Source:
<code>private static boolean isTableRow(TagNode node) { <START> return "TR".equalsIgnoreCase(node.getNodeName()); <END> }</code><technical_language>TagNode#equalsElementName</technical_language>

Target:
private static boolean isTableRow(TagNode node) { return node.equalsElementName("TR"); }
Source:
<code>public void shutdown() { if (_server != null) { try { _server.stop(); LOG.info("Helix rest server stopped!"); } catch (Exception ex) { LOG.error("Failed to stop Helix rest server, " + ex); } } _jmxReporterList.forEach(JmxReporter::stop); <START> cleanupResourceConfigs(); <END> }</code><technical_language>clear</technical_language>

Target:
public synchronized void shutdown() { if (_server != null) { try { _server.stop(); LOG.info("Helix rest server stopped!"); } catch (Exception ex) { LOG.error("Failed to stop Helix rest server, " + ex); } } _jmxReporterList.forEach(JmxReporter::stop); _jmxReporterList.clear(); cleanupResourceConfigs(); }
Source:
<code>public double getLogProb(double value) { checkHasParams(); if (value < 0) { return Double.NEGATIVE_INFINITY; } else { <START> return Math.log(lambda) - lambda * value; <END> } }</code><technical_language>cache log of lambda</technical_language>

Target:
public double getLogProb(double value) { checkHasParams(); if (value < 0) { return Double.NEGATIVE_INFINITY; } else { return logLambda - lambda * value; } }
Source:
<code>public boolean acquireWriteLock(String ownerId) { try (Handle handle = rdbi.open()) { final MultiReadSingleWriteLockDAO dao = handle.attach(MultiReadSingleWriteLockDAO.class); while (true) { final int acquiredLock = dao.acquireWriteLock(writeLockKey, ownerId, writeTimeoutMillis); if (acquiredLock > 0) { break; } Thread.sleep(250); } while (true) { final Long readerCount = handle.jedis().zcount(readLockKey, Long.toString(Instant.now().getMillis()), "+inf"); if (readerCount < 1) { return true; } Thread.sleep(250); } } catch (InterruptedException e) { <START> throw new RuntimeException(e); <END> } }</code><technical_language>I realize a change in behavior, call Thread.currentThread().interrupt(), catching InterruptedException</technical_language>

Target:
public boolean acquireWriteLock(String ownerId) { try (Handle handle = rdbi.open()) { final MultiReadSingleWriteLockDAO dao = handle.attach(MultiReadSingleWriteLockDAO.class); while (true) { final int acquiredLock = dao.acquireWriteLock(writeLockKey, ownerId, writeTimeoutMillis); if (acquiredLock > 0) { break; } Thread.sleep(250); } while (true) { final Long readerCount = handle.jedis().zcount(readLockKey, Long.toString(Instant.now().toEpochMilli()), "+inf"); if (readerCount < 1) { return true; } Thread.sleep(250); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return false; }
Source:
<code>public WeekProfile(final String weekProfileName, final DayProfile monday, final DayProfile tuesday, final DayProfile wednesday, final DayProfile thursday, final DayProfile friday, final DayProfile saturday, final DayProfile sunday) { <START> super(); <END> this.weekProfileName = weekProfileName; this.monday = monday; this.tuesday = tuesday; this.wednesday = wednesday; this.thursday = thursday; this.friday = friday; this.saturday = saturday; this.sunday = sunday; }</code><technical_language>Please check remark ActivityCalendar, appears apply well</technical_language>

Target:
public WeekProfile(final String weekProfileName, final DayProfile monday, final DayProfile tuesday, final DayProfile wednesday, final DayProfile thursday, final DayProfile friday, final DayProfile saturday, final DayProfile sunday) { this.weekProfileName = weekProfileName; this.monday = monday; this.tuesday = tuesday; this.wednesday = wednesday; this.thursday = thursday; this.friday = friday; this.saturday = saturday; this.sunday = sunday; }
Source:
<code>public String getMessage() { return relativeError.getMessage(); <START> } <END></code><technical_language>please copy values variables contruction. reason is JSON serialisers GSON do a terrible job errors if member variables (with right names) works better. a simple work JSON cock ups</technical_language>

Target:
public String getMessage() { return message; }
Source:
<code>public void scheduleContainerRestart(String containerId) { StreamingContainerAgent cs = this.getContainerAgent(containerId); if (cs == null || cs.isShutdownRequested()) { return; } LOG.info("Initiating recovery for {}@{}", containerId, cs.container.host); cs.container.setState(PTContainer.State.KILLED); cs.container.bufferServerAddress = null; cs.container.setResourceRequestPriority(-1); cs.container.setAllocatedMemoryMB(0); cs.container.setAllocatedVCores(0); UpdateCheckpointsContext ctx = new UpdateCheckpointsContext(clock, false, getCheckpointGroups()); for (PTOperator oper : cs.container.getOperators()) { updateRecoveryCheckpoints(oper, ctx, false); } includeLocalUpstreamOperators(ctx); LOG.info("Affected operators {}", ctx.visited); deploy(Collections.<PTContainer>emptySet(), ctx.visited, Sets.newHashSet(cs.container), ctx.visited); }</code><technical_language>do code</technical_language>

Target:
public void scheduleContainerRestart(String containerId) { StreamingContainerAgent cs = this.getContainerAgent(containerId); if (cs == null || cs.isShutdownRequested()) { return; } LOG.info("Initiating recovery for {}@{}", containerId, cs.container.host); cs.container.setState(PTContainer.State.KILLED); cs.container.bufferServerAddress = null; cs.container.setResourceRequestPriority(-1); cs.container.setAllocatedMemoryMB(0); cs.container.setAllocatedVCores(0); UpdateCheckpointsContext ctx = new UpdateCheckpointsContext(clock, false, getCheckpointGroups()); for (PTOperator oper : cs.container.getOperators()) { updateRecoveryCheckpoints(oper, ctx, false); } includeLocalUpstreamOperators(ctx); groupingManager.addOrModifyGroupingRequest(containerId, ctx.visited); groupingManager.removeProcessedGroupingRequests(); LOG.info("Affected operators {}", ctx.visited); deploy(Collections.<PTContainer>emptySet(), ctx.visited, Sets.newHashSet(cs.container), ctx.visited); }
Source:
<code>public void testCircularBlockingQueueTakeBlock() throws InterruptedException, ExecutionException { final CircularBlockingQueue<Integer> testQueue = new CircularBlockingQueue<>(2); <START> ExecutorService executor = Executors.newSingleThreadExecutor(); <END> Future<Integer> testTake = executor.submit(() -> { return testQueue.take(); }); while (!testQueue.isConsumerThreadBlocked()) { Thread.sleep(50L); } testQueue.offer(10); Integer result = testTake.get(); Assert.assertEquals(10, result.intValue()); }</code><technical_language>Please shutdown executor (in a finally block)</technical_language>

Target:
public void testCircularBlockingQueueTakeBlock() throws InterruptedException, ExecutionException { final CircularBlockingQueue<Integer> testQueue = new CircularBlockingQueue<>(2); ExecutorService executor = Executors.newSingleThreadExecutor(); try { Future<Integer> testTake = executor.submit(() -> { return testQueue.take(); }); while (!testQueue.isConsumerThreadBlocked()) { Thread.sleep(50L); } testQueue.offer(10); Integer result = testTake.get(); Assert.assertEquals(10, result.intValue()); } finally { executor.shutdown(); } }
Source:
<code>public void testHttpAccessLogGeneration() { BufferedReader bf = null; boolean found = false; String line; try { axis2Client.sendSimpleStockQuoteRequest(getProxyServiceURLHttp("HttpAccessLogsTestProxy"), getBackEndServiceUrl(ESBTestConstant.SIMPLE_STOCK_QUOTE_SERVICE), "WSO2"); File[] files = new File(httpLogDir).listFiles(); Assert.assertTrue(files.length > 0, "nhttp access logs were not written to the configured directory " + httpLogDir); String fileName = null; for (int i = 0; i < files.length; i++) { fileName = files[i].getName(); } Thread.sleep(30000); bf = new BufferedReader(new FileReader(httpLogDir + File.separator + fileName)); while ((line = bf.readLine()) != null) { int indexfound = line.indexOf("HttpAccessLogsTestProxy"); if (indexfound > -1) { found = true; break; } } assertTrue(found, "Access logs not generated for the proxy service."); <START> } catch (IOException e) { <END> log.warn("Error occurred while reading access log file content", e); } catch (InterruptedException e) { log.warn("Error occurred while thread sleep", e); } catch (XPathExpressionException e) { log.warn("Error occurred while sending simple quote request.", e); } finally { if (bf != null) { try { bf.close(); } catch (IOException e) { log.warn("Error occurred while closing buffered reader", e); } } } }</code><technical_language>do catch exceptions. throw</technical_language>

Target:
public void testHttpAccessLogGeneration() throws Exception { BufferedReader bf = null; boolean found = false; String line; try { axis2Client.sendSimpleStockQuoteRequest(getProxyServiceURLHttp("HttpAccessLogsTestProxy"), getBackEndServiceUrl(ESBTestConstant.SIMPLE_STOCK_QUOTE_SERVICE), "WSO2"); File[] files = new File(httpLogDir).listFiles(); Assert.assertTrue(files.length > 0, "nhttp access logs were not written to the configured directory " + httpLogDir); String fileName = null; for (int i = 0; i < files.length; i++) { fileName = files[i].getName(); } Thread.sleep(30000); bf = new BufferedReader(new FileReader(httpLogDir + File.separator + fileName)); while ((line = bf.readLine()) != null) { int indexfound = line.indexOf("HttpAccessLogsTestProxy"); if (indexfound > -1) { found = true; break; } } assertTrue(found, "Access logs not generated for the proxy service."); } finally { if (bf != null) { bf.close(); } } }
Source:
<code>private static void createDummyTrace(String metadata) { File f; try { f = new File(tempTraceDir); if (f.exists()) { deltree(f); } f.mkdirs(); f = new File(tempTraceDir + "/metadata"); FileWriter fw = new FileWriter(f); fw.write(metadata); fw.close(); f.createNewFile(); byte magicLE[] = { (byte) 0xC1, (byte) 0x1F, (byte) 0xFC, (byte) 0xC1 }; byte uuid[] = { (byte) 0xb0, 0x4d, 0x39, 0x1b, (byte) 0xe7, 0x36, 0x44, (byte) 0xc1, (byte) 0x8d, (byte) 0x89, 0x4b, (byte) 0xb4, 0x38, (byte) 0x85, 0x7f, (byte) 0x8d }; int packetSize = 4096; final int size = packetSize + 48; Event ev = new Event(2, 2); ByteBuffer data = ByteBuffer.allocate(size); data.order(ByteOrder.LITTLE_ENDIAN); data.putLong(0); <START> data.putLong(1000000); <END> data.putLong(32672); data.putLong(packetSize*8); data.putInt(0); data.putInt(0); int nbEvents = packetSize/ev.getSize(); for (int i = 0; i < nbEvents; i++) { ev.setEventTimestamp(i+1); ev.writeEvent(data); } f = new File(tempTraceDir + "/dummyChan"); fw = new FileWriter(f); FileOutputStream fos = new FileOutputStream(f); fos.write(magicLE); fos.write(uuid); fos.write(data.array()); fos.close(); fw.close(); f.createNewFile(); } catch (IOException e) { e.printStackTrace(); } finally { f = null; } }</code><technical_language>Needs a stream ID</technical_language>

Target:
private static void createDummyTrace(String metadata) { File f; try { f = new File(tempTraceDir); if (f.exists()) { deltree(f); } f.mkdirs(); f = new File(tempTraceDir + "/metadata"); FileWriter fw = new FileWriter(f); fw.write(metadata); fw.close(); f.createNewFile(); byte magicLE[] = { (byte) 0xC1, (byte) 0x1F, (byte) 0xFC, (byte) 0xC1 }; byte uuid[] = { (byte) 0xb0, 0x4d, 0x39, 0x1b, (byte) 0xe7, 0x36, 0x44, (byte) 0xc1, (byte) 0x8d, (byte) 0x89, 0x4b, (byte) 0xb4, 0x38, (byte) 0x85, 0x7f, (byte) 0x8d }; Event ev = new Event(2, 2); int dataSize = 4096; final int headerSize = 24 + 44; final int packetSize = dataSize + headerSize + 512; final int nbEvents = (dataSize / ev.getSize()) - 1; final int contentSize = (nbEvents * ev.getSize() + headerSize) * 8; ByteBuffer data = ByteBuffer.allocate(packetSize); data.order(ByteOrder.LITTLE_ENDIAN); data.put(magicLE); data.put(uuid); data.putInt(0); data.putLong(0xa500); data.putLong(nbEvents * 0x10000 + 0xa5a6); data.putLong(contentSize); data.putLong(packetSize * 8); data.putLong(0); data.putInt(0); for (int i = 0; i < nbEvents; i++) { ev.setEventTimestamp(i * 0x10000 + 0xa5a5); ev.setEventContent(i); ev.writeEvent(data); } f = new File(tempTraceDir + "/dummyChan"); fw = new FileWriter(f); FileOutputStream fos = new FileOutputStream(f); fos.write(data.array()); fos.close(); fw.close(); f.createNewFile(); } catch (IOException e) { e.printStackTrace(); } finally { f = null; } }
Source:
<code>private <R extends PersistableBusinessObject> void writeResultsDetailsToReportByResultCode(List<RassBusinessObjectUpdateResult<R>> results, Class businessObjectClass, RassObjectUpdateResultCode resultCode) { <START> List<RassBusinessObjectUpdateResult<R>> filteresdResults = results.stream().filter(result -> resultCode.equals(result.getResultCode())) <END> .collect(Collectors.toList()); writeHeaderForResultsDetailsByResultCode(businessObjectClass, resultCode); for (RassBusinessObjectUpdateResult<R> result : filteresdResults) { writeResultDetailToReport(result); } }</code><technical_language>Minor typo in variable name; changed "filteresdResults" "filteredResults" (this is a instance of typo)</technical_language>

Target:
private <R extends PersistableBusinessObject> void writeResultsDetailsToReportByResultCode(List<RassBusinessObjectUpdateResult<R>> results, Class businessObjectClass, RassObjectUpdateResultCode resultCode) { List<RassBusinessObjectUpdateResult<R>> filteredResults = results.stream().filter(result -> resultCode.equals(result.getResultCode())) .collect(Collectors.toList()); writeHeaderForResultsDetailsByResultCode(businessObjectClass, resultCode); for (RassBusinessObjectUpdateResult<R> result : filteredResults) { writeResultDetailToReport(result); } }
Source:
<code><START> private DocumentMetadata.Builder handleAdditionalIds(OafEntity oafEntity, DocumentMetadata.Builder metaBuilder) { <END> if (CollectionUtils.isNotEmpty(oafEntity.getPid())) { Map<CharSequence, CharSequence> additionalIds = new HashMap<CharSequence, CharSequence>(); for (StructuredProperty currentPid : oafEntity.getPid()) { if (StringUtils.isNotBlank(currentPid.getQualifier().getClassid()) && StringUtils.isNotBlank(currentPid.getValue()) && fieldApprover.approve(currentPid.getDataInfo())) { additionalIds.put(currentPid.getQualifier().getClassid(), currentPid.getValue()); } } if (MapUtils.isNotEmpty(additionalIds)) { metaBuilder.setExternalIdentifiers(additionalIds); } } return metaBuilder; }</code><technical_language>return void</technical_language>

Target:
private void handleAdditionalIds(OafEntity oafEntity, DocumentMetadata.Builder metaBuilder) { if (CollectionUtils.isNotEmpty(oafEntity.getPid())) { Map<CharSequence, CharSequence> additionalIds = oafEntity.getPid().stream() .filter(x -> StringUtils.isNotBlank(x.getQualifier().getClassid())) .filter(x -> StringUtils.isNotBlank(x.getValue())) .filter(x -> fieldApprover.approve(x.getDataInfo())) .map(x -> new AbstractMap.SimpleEntry<>(x.getQualifier().getClassid(), x.getValue())) .collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue, (val1, val2) -> val1)); if (MapUtils.isNotEmpty(additionalIds)) { metaBuilder.setExternalIdentifiers(additionalIds); } } }
Source:
<code>public OAuth2AuthorizedClientProviderBuilder authorizationCode() { <START> this.builders.computeIfAbsent(AuthorizationCodeGrantBuilder.class, k -> new AuthorizationCodeGrantBuilder()); <END> return OAuth2AuthorizedClientProviderBuilder.this; }</code><technical_language>feels a odd in provider, provider's class is key, in this method, this provider's builder is key. This means application instances of AuthorizationCodeOAuth2AuthorizedClientProvider in configuration, if app do: java builder .provider(new AuthorizationCodeOAuth2AuthorizedClientProvider()) .authorizationCode()</technical_language>

Target:
public OAuth2AuthorizedClientProviderBuilder authorizationCode() { this.builders.computeIfAbsent(AuthorizationCodeOAuth2AuthorizedClientProvider.class, k -> new AuthorizationCodeGrantBuilder()); return OAuth2AuthorizedClientProviderBuilder.this; }
Source:
<code>public @Nullable IEventDeclaration getEventDeclaration(int eventId) { if (eventId == EventDeclaration.UNSET_EVENT_ID) { <START> return fEvents.get(0); <END> } if (eventId < 0) { throw new IllegalArgumentException("Event ID cannot be negative."); } if (eventId >= fEvents.size()) { return null; } return fEvents.get(eventId); }</code><technical_language>ArrayIndexOutOfBoundsException thrown if list is empty</technical_language>

Target:
public @Nullable IEventDeclaration getEventDeclaration(int eventId) { int eventIndex = (eventId == EventDeclaration.UNSET_EVENT_ID) ? 0 : eventId; if (eventIndex < 0) { throw new IllegalArgumentException("Event ID cannot be negative."); } if (eventIndex >= fEvents.size()) { return null; } return fEvents.get(eventIndex); }
Source:
<code>protected List<Name> getLogNames(LogManager manager, String names) { if (ALL_LOGS.equalsIgnoreCase(names)) { <START> return manager.listAll().stream().filter(name -> !INPUT_STREAM.equals(name)) <END> .collect(Collectors.toList()); } List<Name> ret = Arrays.asList(names.split(",")).stream().map(Name::ofUrn).collect(Collectors.toList()); if (ret.isEmpty()) { throw new IllegalArgumentException("No log name provided or found."); } for (Name name : ret) { if (!manager.exists(name)) { throw new IllegalArgumentException("Unknown log name: " + name); } } return ret; }</code><technical_language>INPUT_STREAM wrapped Name call getName name</technical_language>

Target:
protected List<Name> getLogNames(LogManager manager, String names) { if (ALL_LOGS.equalsIgnoreCase(names)) { return manager.listAllNames().stream().filter(name -> !INPUT_STREAM.equals(name.getName())) .collect(Collectors.toList()); } List<Name> ret = Arrays.stream(names.split(",")).map(Name::ofUrn).collect(Collectors.toList()); if (ret.isEmpty()) { throw new IllegalArgumentException("No log name provided or found."); } for (Name name : ret) { if (!manager.exists(name)) { throw new IllegalArgumentException("Unknown log name: " + name); } } return ret; }
Source:
<code>public CommunicationsManager getCommsManager() { return commsManager; <START> } <END></code><technical_language>I I comfortable making a node class a source for CommunicationsManager. Is motivation for this avoid do Case.getCurrentCase().getSleuthkitCase().getCommunicationsManager(), other reasons</technical_language>

Target:
CommunicationsManager getCommsManager() { return commsManager; }
Source:
<code>public void selectFromListByIndex(String locator, String... indexes) { if (indexes.length == 0) { throw new SeleniumLibraryNonFatalException("No index given."); } <START> List<String> tmp = new ArrayList<>(Arrays.asList(indexes)); <END> String items = String.format("index(es) '%s'", Python.join(", ", tmp)); logging.info(String.format("Selecting %s from list '%s'.", items, locator)); Select select = getSelectList(locator); for (String index : indexes) { select.selectByIndex(Integer.parseInt(index)); } }</code><technical_language>Collections.addAll() instead</technical_language>

Target:
public void selectFromListByIndex(String locator, String... indexes) { if (indexes.length == 0) { throw new SeleniumLibraryNonFatalException("No index given."); } List<String> tmp = new ArrayList<>(); Collections.addAll(tmp, indexes); String items = String.format("index(es) '%s'", Python.join(", ", tmp)); logging.info(String.format("Selecting %s from list '%s'.", items, locator)); Select select = getSelectList(locator); for (String index : indexes) { select.selectByIndex(Integer.parseInt(index)); } }
Source:
<code>private Database getDatabase() { if (database == null) { List<Database> databaseList = documentClient .queryDatabases( "SELECT * FROM root r WHERE r.id='" + databaseId + "'", null).getQueryIterable().toList(); if (databaseList.size() > 0) { database = databaseList.get(0); } else { try { Database databaseDefinition = new Database(); databaseDefinition.setId(databaseId); database = documentClient.createDatabase( databaseDefinition, null).getResource(); } catch (DocumentClientException e) { <START> e.printStackTrace(); <END> } } } return database; }</code><technical_language>errors stderr. example is here: e.printStackTrace(System.err); Another option a logging framework a bigger change</technical_language>

Target:
private Database getDatabase() { if (database == null) { List<Database> databaseList = documentClient .queryDatabases( "SELECT * FROM root r WHERE r.id='" + databaseId + "'", null) .getQueryIterable() .toList(); if (databaseList.size() > 0) { database = databaseList.get(0); } else { try { Database databaseDefinition = new Database(); databaseDefinition.setId(databaseId); database = documentClient.createDatabase(databaseDefinition, null) .getResource(); } catch (DocumentClientException e) { e.printStackTrace(System.err); } } } return database; }
Source:
<code>void setupIndentationLevel() { <START> level.style.marginLeft = margin(20 * presenter.getLevel()); <END> }</code><technical_language>Care move magic number a constant</technical_language>

Target:
void setupIndentationLevel() { final int indentationLevel = presenter.getLevel(); final int pixelsPerLevel = 20; final int marginPixels = pixelsPerLevel * indentationLevel; this.level.style.marginLeft = margin(marginPixels); }
Source:
<code>private static EnsembleProvider createEnsembleProvider( final String type, final String serversAndPort, final String path) { final EnsembleProvider result; <START> if (TYPE_EXHIBITOR.equalsIgnoreCase(type)) { <END> final String[] hostsPort = serversAndPort.split(":"); if (hostsPort.length != 2) { throw new RuntimeException("Failed to parse zookeeper connection configuration, port not found in " + serversAndPort); } final Exhibitors exhibitors = new Exhibitors( Arrays.asList(hostsPort[0].split(",")), Integer.parseInt(hostsPort[1]), () -> { throw new RuntimeException("No backup list exists"); }); final ExhibitorRestClient exhibitorRestClient = new DefaultExhibitorRestClient(); result = new ExhibitorEnsembleProvider( exhibitors, exhibitorRestClient, "/exhibitor/v1/cluster/list", EXHIBITOR_POLLING_MS, new ExponentialBackoffRetry(EXHIBITOR_RETRY_TIME, EXHIBITOR_RETRY_MAX), path); } else if (TYPE_ZOOKEEPER.equalsIgnoreCase(type)) { result = new FixedEnsembleProvider(serversAndPort + path); } else { throw new RuntimeException("Connection type for zookeeper ensemble provider is not supported: " + type); } return result; }</code><technical_language>do need this exhibitor stuff here? For migration period</technical_language>

Target:
private static EnsembleProvider createEnsembleProvider( final String type, final String serversAndPort, final String path) { final EnsembleProvider result; if (TYPE_EXHIBITOR.equalsIgnoreCase(type)) { final String[] hostsPort = serversAndPort.split(":"); if (hostsPort.length != 2) { throw new RuntimeException("Failed to parse zookeeper connection configuration, port not found in " + serversAndPort); } final Exhibitors exhibitors = new Exhibitors( Arrays.asList(hostsPort[0].split(",")), Integer.parseInt(hostsPort[1]), () -> { throw new RuntimeException("No backup list exists"); }); final ExhibitorRestClient exhibitorRestClient = new DefaultExhibitorRestClient(); result = new ExhibitorEnsembleProvider( exhibitors, exhibitorRestClient, "/exhibitor/v1/cluster/list", EXHIBITOR_POLLING_MS, new ExponentialBackoffRetry(EXHIBITOR_RETRY_TIME, EXHIBITOR_RETRY_MAX), path); } else if (TYPE_ZOOKEEPER.equalsIgnoreCase(type)) { final List<String> hosts = Arrays.asList(serversAndPort.split(",")); Collections.shuffle(hosts); result = new FixedEnsembleProvider(String.join(",", hosts) + path); } else { throw new RuntimeException("Connection type for zookeeper ensemble provider is not supported: " + type); } return result; }
Source:
<code><START> private Hosts mapCollection(List<VDS> entities) { <END> ApplicationMode appMode = getCurrent().get(ApplicationMode.class); Hosts collection = new Hosts(); for (VDS entity : entities) { if (appMode == ApplicationMode.GlusterOnly) { collection.getHosts().add(addLinks(populate(map(entity), entity), "storage")); } else { collection.getHosts().add(addLinks(populate(map(entity), entity))); } } return collection; }</code><technical_language>prefer adding mapGlusterCollection() calling accordingly</technical_language>

Target:
private Hosts mapCollection(List<VDS> entities) { Hosts collection = new Hosts(); for (VDS entity : entities) { collection.getHosts().add(addLinks(populate(map(entity), entity))); } return collection; }
Source:
<code>void shouldNotContainNoIssuesSinceLabelWhenTotalIsNotZero() { AnalysisResult analysisResult = createAnalysisResult(Maps.fixedSize.of(), 0, 0, Lists.immutable.empty(), 0, 0); when(analysisResult.getTotalSize()).thenReturn(1); String createdHtml = createTestData(analysisResult).create(); <START> assertThat(createdHtml).doesNotContain("No warnings for"); <END> }</code><technical_language>Positive assertion nutzen .contains("<a href="testResult">One warning</a>") (oder beide verwenden)</technical_language>

Target:
void shouldNotContainNoIssuesSinceLabelWhenTotalIsNotZero() { AnalysisResult analysisResult = createAnalysisResult(Maps.fixedSize.of(), 0, 0, Lists.immutable.empty(), 0, 0); when(analysisResult.getTotalSize()).thenReturn(1); String createdHtml = createTestData(analysisResult).create(); assertThat(createdHtml).doesNotContain("No warnings for"); assertThat(createdHtml).contains("<a href=\"testResult\">One warning</a>"); }
Source:
<code>private boolean validateCategoricalVariableHasAPossibleValue(final MeasurementVariable var) { if (var.getDataTypeId() !=null && var.getDataTypeId() == TermId.CATEGORICAL_VARIABLE.getId()) { <START> return var.getPossibleValues() != null; <END> } return true; }</code><technical_language>@gelli-leafnode , is a scenario getPossibleValues returns empty list instead of null</technical_language>

Target:
private boolean validateCategoricalVariableHasAPossibleValue(final MeasurementVariable var) { if (var.getDataTypeId() !=null && var.getDataTypeId() == TermId.CATEGORICAL_VARIABLE.getId()) { return !CollectionUtils.isEmpty(var.getPossibleValues()); } return true; }
Source:
<code>private AssertionError getThrownErrorPostMapper(Function<StringBuilder, StringBuilder> errorMessageMapper) { try { <START> FxAssert.verifyThat(false, alwaysFail(), errorMessageMapper); <END> throw new AssertionError("Error: verifyThat did not throw an error when it should have."); } catch (AssertionError error) { return error; } }</code><technical_language>static import verifyThat here</technical_language>

Target:
private AssertionError getThrownErrorPostMapper(Function<StringBuilder, StringBuilder> errorMessageMapper) { try { verifyThat(false, alwaysFail(), errorMessageMapper.compose(sb -> new StringBuilder())); throw new AssertionError("Error: verifyThat did not throw an error when it should have."); } catch (AssertionError error) { return error; } }
Source:
<code>public void testFileLock() throws IOException { <START> File file = File.createTempFile("temp", "1"); <END> FileLock lock = new FileLock(file); lock.lock(); Assert.assertFalse(lock.tryLock()); lock.unlock(); Assert.assertTrue(lock.tryLock()); lock.unlock(); lock.destroy(); }</code><technical_language>need call this method, FileLock() creates file. calling this for automatic deletion</technical_language>

Target:
public void testFileLock() throws IOException { File file = File.createTempFile("temp", "1"); file.deleteOnExit(); FileLock lock = new FileLock(file); lock.lock(); Assert.assertFalse(lock.tryLock()); lock.unlock(); Assert.assertTrue(lock.tryLock()); lock.unlock(); lock.destroy(); }
Source:
<code><START> public void freeMemory(AllocationPoint point) { <END> if (point.getAllocationStatus() == AllocationStatus.DEVICE) { this.getMemoryHandler().getMemoryProvider().free(point); point.setAllocationStatus(AllocationStatus.HOST); this.getMemoryHandler().getMemoryProvider().free(point); } else { this.getMemoryHandler().getMemoryProvider().free(point); } allocationsMap.remove(point.getObjectId()); }</code><technical_language>AllocationStatus wrong, ground truth. If wrong - disaster is a matter of time. Short time :)</technical_language>

Target:
public void freeMemory(AllocationPoint point) { if (point.getAllocationStatus() == AllocationStatus.DEVICE) { this.getMemoryHandler().getMemoryProvider().free(point); point.setAllocationStatus(AllocationStatus.HOST); this.getMemoryHandler().getMemoryProvider().free(point); this.getMemoryHandler().forget(point, AllocationStatus.DEVICE); } else { this.getMemoryHandler().getMemoryProvider().free(point); this.getMemoryHandler().forget(point, AllocationStatus.HOST); } allocationsMap.remove(point.getObjectId()); }
Source:
<code>public String getName() { <START> return "Sounds.json"; <END> }</code><technical_language>"Sounds" is fine</technical_language>

Target:
public String getName() { return "Sounds"; }
Source:
<code>public NewYorkTimesDocument next() { <START> if (docRead) return null; <END> NewYorkTimesDocument doc; try { docRead = true; doc = parser.parseFile(path.toFile()); } catch (IOException e) { return null; } return doc; }</code><technical_language>NoSuchElementException is better</technical_language>

Target:
public NewYorkTimesDocument next() { if (docRead) throw new NoSuchElementException(); NewYorkTimesDocument doc; try { docRead = true; doc = parser.parseFile(path.toFile()); } catch (IOException e) { return null; } return doc; }
Source:
<code>public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) { InetSocketAddress address = (InetSocketAddress) bootstrap.getOption("remoteAddress"); int delay = reconnectDelayManager.getReconnectDelayMs(address); timer.newTimeout(new TimerTask() { public void run(Timeout timeout) throws Exception { <START> if (! client.isShutdown()) { <END> bootstrap.connect(); } } }, delay, TimeUnit.MILLISECONDS); client.onDisconnect(); }</code><technical_language>This, me, sounds weird. "active" instead of "shutdown" a wording? client.isActive(). "If client is active" sounds "If client is shutdown". foreword of Effective Java. wait read more :)</technical_language>

Target:
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) { InetSocketAddress address = (InetSocketAddress) bootstrap.getOption("remoteAddress"); int delay = reconnectDelayManager.getReconnectDelayMs(address); timer.newTimeout(new TimerTask() { public void run(Timeout timeout) throws Exception { if (! client.shutdownRequested()) { bootstrap.connect(); } } }, delay, TimeUnit.MILLISECONDS); client.onDisconnect(); }
Source:
<code>public void testAddSecondWorkmanager() { try { cli.sendLine("batch"); cli.sendLine("/subsystem=jca/distributed-workmanager=dwm1:add(name=dwm1)"); cli.sendLine("/subsystem=jca/distributed-workmanager=dwm1/short-running-threads=dwm1:add(max-threads=11,queue-length=22)"); cli.sendLine("/subsystem=jca/distributed-workmanager=dwm2:add(name=dwm2)"); cli.sendLine("/subsystem=jca/distributed-workmanager=dwm2/short-running-threads=dwm2:add(max-threads=11,queue-length=22)"); cli.sendLine("run-batch"); } catch (Exception e) { <START> throw new RuntimeException(e); <END> } }</code><technical_language>method 'throws Exception'</technical_language>

Target:
public void testAddSecondWorkmanager() throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { try { cli.sendLine("batch"); cli.sendLine("/subsystem=jca/distributed-workmanager=dwm1:add(name=dwm1)"); cli.sendLine("/subsystem=jca/distributed-workmanager=dwm1/short-running-threads=dwm1:add(max-threads=11,queue-length=22)"); cli.sendLine("/subsystem=jca/distributed-workmanager=dwm2:add(name=dwm2)"); cli.sendLine("/subsystem=jca/distributed-workmanager=dwm2/short-running-threads=dwm2:add(max-threads=11,queue-length=22)"); cli.sendLine("run-batch"); } finally { cli.sendLine("/subsystem=jca/distributed-workmanager=dwm2:remove"); cli.sendLine("/subsystem=jca/distributed-workmanager=dwm1:remove"); } } }
Source:
<code>protected IndexWriter createIndexWriter(boolean create) throws CorruptIndexException, LockObtainFailedException, IOException { IndexWriterConfig writerConfig = new IndexWriterConfig(TaskAnalyzer.instance()); <START> writerConfig.setInfoStream(InfoStream.NO_OUTPUT); <END> return new IndexWriter(directory, writerConfig); }</code><technical_language>do writerConfig.setOpenMode(create ? OpenMode.CREATE : OpenMode.APPEND)</technical_language>

Target:
protected IndexWriter createIndexWriter(boolean create) throws CorruptIndexException, LockObtainFailedException, IOException { IndexWriterConfig writerConfig = new IndexWriterConfig(TaskAnalyzer.instance()); writerConfig.setInfoStream(InfoStream.NO_OUTPUT); writerConfig.setOpenMode(create ? OpenMode.CREATE : OpenMode.APPEND); return new IndexWriter(directory, writerConfig); }
Source:
<code>public void testRSA(TestHarness th, byte[] n, byte[] e, byte[] d, byte[] message) { RSAPublicKey pubKey = new RSAPublicKey(n, e); RSAPrivateKey privKey = new RSAPrivateKey(n, d); try { Cipher rsa = Cipher.getInstance("RSA"); rsa.init(Cipher.ENCRYPT_MODE, privKey); byte[] encMessage = new byte[privKey.getModulusLen()]; rsa.doFinal(message, 0, message.length, encMessage, 0); Cipher rsa2 = Cipher.getInstance("RSA"); rsa2.init(Cipher.DECRYPT_MODE, pubKey); byte[] decMessage = new byte[pubKey.getModulusLen()]; rsa2.doFinal(encMessage, 0, encMessage.length, decMessage, 0); boolean ok = true; for (int i = 0; i < message.length; i++) { if (message[i] != decMessage[i]) { <START> ok = false; <END> } } th.todo(ok); } catch (Exception ex) { th.fail("Unexpected exception: " + ex); ex.printStackTrace(); } }</code><technical_language>Instead of boolean _ok_, I simply th.check() byte _for_ loop</technical_language>

Target:
public void testRSA(TestHarness th, byte[] n, byte[] e, byte[] d, byte[] message) throws NoSuchAlgorithmException, InvalidKeyException, ShortBufferException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { RSAPublicKey pubKey = new RSAPublicKey(n, e); RSAPrivateKey privKey = new RSAPrivateKey(n, d); Cipher rsa = Cipher.getInstance("RSA"); rsa.init(Cipher.ENCRYPT_MODE, privKey); byte[] encMessage = new byte[privKey.getModulusLen()]; rsa.doFinal(message, 0, message.length, encMessage, 0); Cipher rsa2 = Cipher.getInstance("RSA"); rsa2.init(Cipher.DECRYPT_MODE, pubKey); byte[] decMessage = new byte[pubKey.getModulusLen()]; rsa2.doFinal(encMessage, 0, encMessage.length, decMessage, 0); for (int i = 0; i < message.length; i++) { th.check(decMessage[i], message[i]); } }
Source:
<code>private static DynamicTableSource createSource(DescriptorProperties properties) { return FactoryUtil.createTableSource( null, <START> ObjectIdentifier.of("", "", ""), <END> new CatalogTableImpl(TEST_SCHEMA, properties.asMap(), ""), new Configuration(), Thread.currentThread().getContextClassLoader(), false); }</code><technical_language>a more readable identifier ObjectIdentifier.of("mycatalog", "mydb", "mytable")</technical_language>

Target:
private static DynamicTableSource createSource(DescriptorProperties properties) { return FactoryUtil.createTableSource( null, ObjectIdentifier.of("mycatalog", "mydb", "mytable"), new CatalogTableImpl(TEST_SCHEMA, properties.asMap(), ""), new Configuration(), Thread.currentThread().getContextClassLoader(), false); }
Source:
<code>public void initialize(Context context) { context.registerSyntaxNodeConsumer(Tree.Kind.DICTIONARY_LITERAL, ctx -> { DictionaryLiteral dictionaryLiteral = (DictionaryLiteral) ctx.syntaxNode(); Set<Integer> issueIndexes = new HashSet<>(); for (int i = 0; i < dictionaryLiteral.elements().size(); i++) { if (!dictionaryLiteral.elements().get(i).is(Tree.Kind.KEY_VALUE_PAIR) || issueIndexes.contains(i)) { continue; } <START> Expression key = ((KeyValuePair) dictionaryLiteral.elements().get(i)).key(); <END> List<Tree> duplicateKeys = findIdenticalKeys(i, dictionaryLiteral.elements(), issueIndexes); if (!duplicateKeys.isEmpty()) { PreciseIssue issue = ctx.addIssue(key, "Change or remove duplicates of this key."); duplicateKeys.forEach(d -> issue.secondary(d, "Duplicate key")); } } }); }</code><technical_language>handler in initialize in combination for-loop in findIdenticalKeys quadratic runtime in number of elements of dictionary. a bit surprising for "obviously O(n)" task. If decides a dictionary thousand elements, hurt performance, in larger examples, freeze analyzer altogether. Ideally, split check parts: - normalization, i.e. bringing key some canonical form, a well-defined hash code easy comparison. - actual comparison for equivalence: keys equivalent w.r.t Python's == iff normalized versions equal in Java. That, a HashMap a single loop give a linear algorithm, size of analyzed dictionary matter. I this rule relies CheckUtils.areEquivalent, give normalized, easily hashable / comparable values, difficult fix quickly. add a condition we, for now, inspect dictionaries more than, say, 100 entries, analyzer freeze suddenly confronted longer dictionaries</technical_language>

Target:
public void initialize(Context context) { context.registerSyntaxNodeConsumer(Tree.Kind.DICTIONARY_LITERAL, ctx -> { DictionaryLiteral dictionaryLiteral = (DictionaryLiteral) ctx.syntaxNode(); Set<Integer> issueIndexes = new HashSet<>(); if (dictionaryLiteral.elements().size() > 100) { return; } for (int i = 0; i < dictionaryLiteral.elements().size(); i++) { if (!dictionaryLiteral.elements().get(i).is(Tree.Kind.KEY_VALUE_PAIR) || issueIndexes.contains(i)) { continue; } Expression key = ((KeyValuePair) dictionaryLiteral.elements().get(i)).key(); List<Tree> duplicateKeys = findIdenticalKeys(i, dictionaryLiteral.elements(), issueIndexes); if (!duplicateKeys.isEmpty()) { PreciseIssue issue = ctx.addIssue(key, "Change or remove duplicates of this key."); duplicateKeys.forEach(d -> issue.secondary(d, "Duplicate key")); } } }); }
Source:
<code>private void sendRequest(String addUrl, String query) throws IOException { String charset = "UTF-8"; URLConnection connection = new URL(addUrl).openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Content-Type", "application/xml;charset=" + charset); OutputStream output = null; try { output = connection.getOutputStream(); output.write(query.getBytes(charset)); } finally { if (output != null) { try { output.close(); } catch (IOException logOrIgnore) { <START> log.error("Error while closing the connection"); <END> } } } InputStream response = connection.getInputStream(); String out = "[Fault] No Response."; if (response != null) { StringBuilder sb = new StringBuilder(); byte[] bytes = new byte[1024]; int len; while ((len = response.read(bytes)) != -1) { sb.append(new String(bytes, 0, len)); } out = sb.toString(); } }</code><technical_language>Dont swallow exceptions is throw exceptions catching in test cases</technical_language>

Target:
private void sendRequest(String addUrl, String query) throws IOException { String charset = "UTF-8"; URLConnection connection = new URL(addUrl).openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Content-Type", "application/xml;charset=" + charset); OutputStream output = null; try { output = connection.getOutputStream(); output.write(query.getBytes(charset)); } finally { if (output != null) { output.close(); } } InputStream response = connection.getInputStream(); String out = "[Fault] No Response."; if (response != null) { StringBuilder sb = new StringBuilder(); byte[] bytes = new byte[1024]; int len; while ((len = response.read(bytes)) != -1) { sb.append(new String(bytes, 0, len)); } out = sb.toString(); } }
Source:
<code>private DiffToolConfig(Config rc) { toolName = rc.getString(ConfigConstants.CONFIG_DIFF_SECTION, null, ConfigConstants.CONFIG_KEY_TOOL); guiToolName = rc.getString(ConfigConstants.CONFIG_DIFF_SECTION, null, ConfigConstants.CONFIG_KEY_GUITOOL); prompt = rc.getBoolean(ConfigConstants.CONFIG_DIFFTOOL_SECTION, ConfigConstants.CONFIG_KEY_PROMPT, true); String trustStr = rc.getString(ConfigConstants.CONFIG_DIFFTOOL_SECTION, null, ConfigConstants.CONFIG_KEY_TRUST_EXIT_CODE); if (trustStr != null) { trustExitCode = BooleanOption .defined(Boolean.parseBoolean(trustStr)); } else { trustExitCode = BooleanOption.notDefined(false); } tools = new HashMap<>(); Set<String> subsections = rc .getSubsections(ConfigConstants.CONFIG_DIFFTOOL_SECTION); for (String name : subsections) { String cmd = rc.getString(ConfigConstants.CONFIG_DIFFTOOL_SECTION, name, ConfigConstants.CONFIG_KEY_CMD); String path = rc.getString(ConfigConstants.CONFIG_DIFFTOOL_SECTION, name, ConfigConstants.CONFIG_KEY_PATH); boolean trustExitCodeTool = trustExitCode.toBoolean(); if (!trustExitCode.isDefined()) { <START> trustExitCodeTool = rc.getBoolean( <END> ConfigConstants.CONFIG_DIFFTOOL_SECTION, name, ConfigConstants.CONFIG_KEY_TRUST_EXIT_CODE, false); } if ((cmd != null) || (path != null)) { tools.put(name, new UserDefinedDiffTool(name, path, cmd, trustExitCodeTool)); } } }</code><technical_language>cgit a tool trustExitCode flag for difftools (just for mergetools). Do want it</technical_language>

Target:
private DiffToolConfig(Config rc) { toolName = rc.getString(ConfigConstants.CONFIG_DIFF_SECTION, null, ConfigConstants.CONFIG_KEY_TOOL); guiToolName = rc.getString(ConfigConstants.CONFIG_DIFF_SECTION, null, ConfigConstants.CONFIG_KEY_GUITOOL); prompt = rc.getBoolean(ConfigConstants.CONFIG_DIFFTOOL_SECTION, ConfigConstants.CONFIG_KEY_PROMPT, true); String trustStr = rc.getString(ConfigConstants.CONFIG_DIFFTOOL_SECTION, null, ConfigConstants.CONFIG_KEY_TRUST_EXIT_CODE); if (trustStr != null) { trustExitCode = BooleanOption .defined(Boolean.parseBoolean(trustStr)); } else { trustExitCode = BooleanOption.notDefined(false); } tools = new HashMap<>(); Set<String> subsections = rc .getSubsections(ConfigConstants.CONFIG_DIFFTOOL_SECTION); for (String name : subsections) { String cmd = rc.getString(ConfigConstants.CONFIG_DIFFTOOL_SECTION, name, ConfigConstants.CONFIG_KEY_CMD); String path = rc.getString(ConfigConstants.CONFIG_DIFFTOOL_SECTION, name, ConfigConstants.CONFIG_KEY_PATH); if ((cmd != null) || (path != null)) { tools.put(name, new UserDefinedDiffTool(name, path, cmd)); } } }
Source:
<code>public static <T> T[] concat(T[] first, T[] second) { int aLen = first.length; int bLen = second.length; @SuppressWarnings("unchecked") <START> T[] C = (T[]) Array.newInstance( first.getClass().getComponentType(), aLen + bLen ); <END> System.arraycopy( first, 0, C, 0, aLen ); System.arraycopy( second, 0, C, aLen, bLen ); return C; }</code><technical_language>I nit-picking, upper-case variable name uncommon</technical_language>

Target:
public static <T> T[] concat(T[] first, T[] second) { int firstLength = first.length; int secondLength = second.length; @SuppressWarnings("unchecked") T[] result = (T[]) Array.newInstance( first.getClass().getComponentType(), firstLength + secondLength ); System.arraycopy( first, 0, result, 0, firstLength ); System.arraycopy( second, 0, result, firstLength, secondLength ); return result; }