auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void assertAssignTaskProblemFactChangeWasProduced(AssignTaskProblemFactChange change, TaskAssigningSolution solution) { User internalUser = solution.getUserList().stream() .filter(user -> Objects.equals(user.getId(), change.getUser().getId())) <START> .findFirst().orElse(null); <END> assertNotNull(internalUser); Task internalTask = solution.getTaskList().stream() .filter(task -> Objects.equals(task.getId(), change.getTask().getId())) .findFirst().orElse(null); assertNotNull(internalTask); assertEquals(internalUser, internalTask.getUser()); assertTrue(internalTask.isPinned()); TaskOrUser previousTaskOrUser = internalTask.getPreviousTaskOrUser(); while (previousTaskOrUser != null) { if (previousTaskOrUser instanceof Task) { Task previousTask = (Task) previousTaskOrUser; assertTrue(previousTask.isPinned()); assertEquals(internalUser, previousTask.getUser()); previousTaskOrUser = previousTask.getPreviousTaskOrUser(); } else { assertEquals(internalUser, previousTaskOrUser); previousTaskOrUser = null; } } Task nextTask = internalTask.getNextTask(); while (nextTask != null) { assertEquals(internalUser, nextTask.getUser()); nextTask = nextTask.getNextTask(); } }</code><technical_language>Instead of asserting nullity of returned line below, throw exception straight away</technical_language>

Target:
private void assertAssignTaskProblemFactChangeWasProduced(AssignTaskProblemFactChange change, TaskAssigningSolution solution) throws Exception { User internalUser = solution.getUserList().stream() .filter(user -> Objects.equals(user.getId(), change.getUser().getId())) .findFirst().orElseThrow(() -> new Exception("User: " + change.getUser() + " was not found in solution.")); Task internalTask = solution.getTaskList().stream() .filter(task -> Objects.equals(task.getId(), change.getTask().getId())) .findFirst().orElseThrow(() -> new Exception("Task: " + change + " was not found in solution.")); assertEquals(internalUser, internalTask.getUser()); assertTrue(internalTask.isPinned()); TaskOrUser previousTaskOrUser = internalTask.getPreviousTaskOrUser(); while (previousTaskOrUser != null) { if (previousTaskOrUser instanceof Task) { Task previousTask = (Task) previousTaskOrUser; assertTrue(previousTask.isPinned()); assertEquals(internalUser, previousTask.getUser()); previousTaskOrUser = previousTask.getPreviousTaskOrUser(); } else { assertEquals(internalUser, previousTaskOrUser); previousTaskOrUser = null; } } Task nextTask = internalTask.getNextTask(); while (nextTask != null) { assertEquals(internalUser, nextTask.getUser()); nextTask = nextTask.getNextTask(); } }
Source:
<code>public int hashCode() { int result = getDimension().hashCode(); result = 31 * result + getUpper().hashCode(); result = 31 * result + getLower().hashCode(); <START> result = 31 * result + (isLowerStrict() ? 1 : 0); <END> result = 31 * result + (isUpperStrict() ? 1 : 0); result = 31 * result + (isAlphaNumeric() ? 1 : 0); return result; }</code><technical_language>assuming upper non-null</technical_language>

Target:
public int hashCode() { int result = getDimension().hashCode(); result = 31 * result + (getUpper() != null ? getUpper().hashCode() : 0); result = 31 * result + (getLower() != null ? getLower().hashCode() : 0); result = 31 * result + (isLowerStrict() ? 1 : 0); result = 31 * result + (isUpperStrict() ? 1 : 0); result = 31 * result + (isAlphaNumeric() ? 1 : 0); return result; }
Source:
<code>protected int offset( long index ) { <START> return toIntExact( rebase( index ) % entriesPerPage ) * entrySize; <END> }</code><technical_language>expression wrapped toIntExact rebase( index ) % entriesPerPage</technical_language>

Target:
protected int offset( long index ) { return toIntExact( rebase( index ) % entriesPerPage * entrySize ); }
Source:
<code>private void checkClusterApiSupported(ProtocolContext protocolCtx) throws ClientFeatureNotSupportedByServerException { if (!protocolCtx.isFeatureSupported(ProtocolVersionFeature.CLUSTER_API) && !protocolCtx.isFeatureSupported(ProtocolBitmaskFeature.CLUSTER_ADDITIONAL_STATES)) <START> throw new ClientFeatureNotSupportedByServerException(ProtocolBitmaskFeature.CLUSTER_ADDITIONAL_STATES); <END> }</code><technical_language>change exception message 'Cluster API is supported server'</technical_language>

Target:
private void checkClusterApiSupported(ProtocolContext protocolCtx) throws ClientFeatureNotSupportedByServerException { if (!protocolCtx.isFeatureSupported(ProtocolVersionFeature.CLUSTER_API) && !protocolCtx.isFeatureSupported(ProtocolBitmaskFeature.CLUSTER_STATES)) throw new ClientFeatureNotSupportedByServerException(ProtocolBitmaskFeature.CLUSTER_STATES); }
Source:
<code>private void readStreamMessageIfNeeded() { final long lastNotConnectedLogThrottleSeconds = 5; if (isConnected()) { if (isInQueuesAvailable() || helper == null) { startReading(); } else { gatewayMetrics.updateInQueueFullCount(); stopReading(); } } else { long now = System.currentTimeMillis(); <START> if (now - lastNotConnectedLogTime > lastNotConnectedLogThrottleSeconds * 5000) { <END> LOG.info(String.format("Stop reading due to not yet connected to Stream Manager. This " + "message is throttled to emit no more than once every %d seconds.", lastNotConnectedLogThrottleSeconds)); lastNotConnectedLogTime = now; } } }</code><technical_language>* 1000</technical_language>

Target:
private void readStreamMessageIfNeeded() { final long lastNotConnectedLogThrottleSeconds = 5; if (isConnected()) { if (isInQueuesAvailable() || helper == null) { startReading(); } else { gatewayMetrics.updateInQueueFullCount(); stopReading(); } } else { long now = System.currentTimeMillis(); if (now - lastNotConnectedLogTime > lastNotConnectedLogThrottleSeconds * 1000) { LOG.info(String.format("Stop reading due to not yet connected to Stream Manager. This " + "message is throttled to emit no more than once every %d seconds.", lastNotConnectedLogThrottleSeconds)); lastNotConnectedLogTime = now; } } }
Source:
<code>private VdcActionType(int value) { <START> this(value, (ActionGroup) null); END> }</code><technical_language>call this(value, null, true, QuotaDependency.BOTH);</technical_language>

Target:
private VdcActionType(int value) { this(value, null, true, QuotaDependency.BOTH); }
Source:
<code>public RequestTemplate create(Object[] argv) { RequestTemplate mutable = new RequestTemplate(metadata.template()); if (metadata.urlIndex() != null) { int urlIndex = metadata.urlIndex(); checkArgument(argv[urlIndex] != null, "URI parameter %s was null", urlIndex); mutable.insert(0, String.valueOf(argv[urlIndex])); } Map<String, Object> varBuilder = new LinkedHashMap<String, Object>(); for (Entry<Integer, Collection<String>> entry : metadata.indexToName().entrySet()) { int i = entry.getKey(); Object value = argv[entry.getKey()]; if (value != null) { if (indexToExpander.containsKey(i)) { value = expandElements(indexToExpander.get(i), value); } for (String name : entry.getValue()) { varBuilder.put(name, value); } } } RequestTemplate template = resolve(argv, mutable, varBuilder); if (metadata.queryMapIndex() != null) { <START> boolean encoded = metadata.queryMapEncoded(); <END> Object value = argv[metadata.queryMapIndex()]; Map<String, Object> queryMap = toQueryMap(value); template = addQueryMapQueryParameters(queryMap, template); } if (metadata.headerMapIndex() != null) { template = addHeaderMapHeaders((Map<String, Object>) argv[metadata.headerMapIndex()], template); } return template; }</code><technical_language>correct if wrong - encoded get anywhere. - a thought style - remove parameter loosing readability following: java Map<String, Object> queryMap = toQueryMap(argv[metadata.queryMapIndex()]); template = addQueryMapQueryParameters(queryMap, template);</technical_language>

Target:
public RequestTemplate create(Object[] argv) { RequestTemplate mutable = new RequestTemplate(metadata.template()); if (metadata.urlIndex() != null) { int urlIndex = metadata.urlIndex(); checkArgument(argv[urlIndex] != null, "URI parameter %s was null", urlIndex); mutable.insert(0, String.valueOf(argv[urlIndex])); } Map<String, Object> varBuilder = new LinkedHashMap<String, Object>(); for (Entry<Integer, Collection<String>> entry : metadata.indexToName().entrySet()) { int i = entry.getKey(); Object value = argv[entry.getKey()]; if (value != null) { if (indexToExpander.containsKey(i)) { value = expandElements(indexToExpander.get(i), value); } for (String name : entry.getValue()) { varBuilder.put(name, value); } } } RequestTemplate template = resolve(argv, mutable, varBuilder); if (metadata.queryMapIndex() != null) { Object value = argv[metadata.queryMapIndex()]; Map<String, Object> queryMap = toQueryMap(value); template = addQueryMapQueryParameters(queryMap, template); } if (metadata.headerMapIndex() != null) { template = addHeaderMapHeaders((Map<String, Object>) argv[metadata.headerMapIndex()], template); } return template; }
Source:
<code>public static Map<String, String> getVariableMapByPrefix( Collection<Variable> variables, String prefix) { Map<String, String> shortlistMap = new HashMap<String, String>(); <START> if (prefix != null) { <END> for (Variable var : getVariablesByRegex(variables, "^" + prefix + ".+")) { shortlistMap .put(var.getTitle().replaceFirst(prefix, ""), var.getName()); } } return shortlistMap; }</code><technical_language>checking for variable == null ? for clarity's performance's (slightly) sake if logically correct checked in getVariablesByRegex()</technical_language>

Target:
public static Map<String, String> getVariableMapByPrefix( Collection<Variable> variables, String prefix) { Map<String, String> shortlistMap = new HashMap<String, String>(); if (variables!=null && prefix != null) { for (Variable var : getVariablesByRegex(variables, Reportal.REPORTAL_CONFIG_PREFIX_REGEX)) { shortlistMap .put(var.getTitle().replaceFirst(prefix, ""), var.getName()); } } return shortlistMap; }
Source:
<code>public void insertIntoInstanceSet(final Object keyClass, final EObject value) { Set<EObject> set = instanceMap.get(keyClass); if (set == null) { set = new HashSet<EObject>(); instanceMap.put(keyClass, set); } if (!set.add(value)) { <START> String msg = String.format("Notification received to index %s as a %s, but feature is already indexed. This indicates some errors in underlying model representation.", value, keyClass); <END> logNotificationHandlingError(msg); } isDirty = true; navigationHelper.notifyInstanceListeners(keyClass, value, true); }</code><technical_language>"feature is laready indexed" is a copy-paste bug here</technical_language>

Target:
public void insertIntoInstanceSet(final Object keyClass, final EObject value) { Set<EObject> set = instanceMap.get(keyClass); if (set == null) { set = new HashSet<EObject>(); instanceMap.put(keyClass, set); } if (!set.add(value)) { String msg = String.format("Notification received to index %s as a %s, but it already exists in the index. This indicates some errors in underlying model representation.", value, keyClass); logNotificationHandlingError(msg); } isDirty = true; navigationHelper.notifyInstanceListeners(keyClass, value, true); }
Source:
<code>public void testUrlCaching() throws Exception { if (!isHostReachable("www.random.org", 5000)) return; for (int i = 0; i < 100; i++) { Row row = new Row(2); row.setCell(0, new Cell(i < 5 ? "apple":"orange", null)); project.rows.add(row); } EngineDependentOperation op = new ColumnAdditionByFetchingURLsOperation(engine_config, "fruits", "\"<LINK_0>\"+value", OnError.StoreError, "rand", 1, 500, true); ProcessManager pm = project.getProcessManager(); Process process = op.createProcess(project, options); process.startPerforming(pm); Assert.assertTrue(process.isRunning()); try { Thread.sleep(5000); } catch (InterruptedException e) { Assert.fail("Test interrupted"); } String ref_val = (String)project.rows.get(0).getCellValue(1).toString(); if (ref_val.contains("HTTP error 403")) <START> return; <END> Assert.assertTrue(ref_val != "apple"); for (int i = 1; i < 4; i++) { System.out.println("value:" + project.rows.get(i).getCellValue(1)); Assert.assertEquals(project.rows.get(i).getCellValue(1).toString(), ref_val); } Assert.assertFalse(process.isRunning()); }</code><technical_language>skip 500 error etc, I think: if (ref_val.startsWith("HTTP error")) better</technical_language>

Target:
public void testUrlCaching() throws Exception { if (!isHostReachable("www.random.org", 5000)) return; for (int i = 0; i < 100; i++) { Row row = new Row(2); row.setCell(0, new Cell(i < 5 ? "apple":"orange", null)); project.rows.add(row); } EngineDependentOperation op = new ColumnAdditionByFetchingURLsOperation(engine_config, "fruits", "\"<LINK_0>\"+value", OnError.StoreError, "rand", 1, 500, true); ProcessManager pm = project.getProcessManager(); Process process = op.createProcess(project, options); process.startPerforming(pm); Assert.assertTrue(process.isRunning()); try { Thread.sleep(5000); } catch (InterruptedException e) { Assert.fail("Test interrupted"); } String ref_val = (String)project.rows.get(0).getCellValue(1).toString(); if (ref_val.startsWith("HTTP error")) return; Assert.assertTrue(ref_val != "apple"); for (int i = 1; i < 4; i++) { System.out.println("value:" + project.rows.get(i).getCellValue(1)); Assert.assertEquals(project.rows.get(i).getCellValue(1).toString(), ref_val); } Assert.assertFalse(process.isRunning()); }
Source:
<code>public void testConnectionSuspendedHandling() throws Exception { String leaderAddress = "localhost"; LeaderElectionService leaderElectionService = ZooKeeperUtils.createLeaderElectionService(zooKeeperClient, config); TestingContender contender = new TestingContender(leaderAddress, leaderElectionService); leaderElectionService.start(contender); <START> QueueLeaderElectionListener queueLeaderElectionListener = new QueueLeaderElectionListener(2, Duration.ofSeconds(1)); <END> ZooKeeperLeaderRetrievalService testInstance = ZooKeeperUtils.createLeaderRetrievalService(zooKeeperClient, config); testInstance.start(queueLeaderElectionListener); CompletableFuture<String> firstAddress = queueLeaderElectionListener.next(); assertThat("The first result is expected to be the initially set leader address.", firstAddress.get(), is(leaderAddress)); stopTestServer(); CompletableFuture<String> secondAddress = queueLeaderElectionListener.next(); assertThat("The next result must not be missing.", secondAddress, not(is(nullValue()))); assertThat("The next result is expected to be null.", secondAddress.get(), is(nullValue())); }</code><technical_language>A timeout of 1 for slow testing machines. I suggest a timeout expecting future delivered</technical_language>

Target:
public void testConnectionSuspendedHandling() throws Exception { String leaderAddress = "localhost"; LeaderElectionService leaderElectionService = ZooKeeperUtils.createLeaderElectionService(zooKeeperClient, config); TestingContender contender = new TestingContender(leaderAddress, leaderElectionService); leaderElectionService.start(contender); QueueLeaderElectionListener queueLeaderElectionListener = new QueueLeaderElectionListener(2); ZooKeeperLeaderRetrievalService testInstance = ZooKeeperUtils.createLeaderRetrievalService(zooKeeperClient, config); testInstance.start(queueLeaderElectionListener); CompletableFuture<String> firstAddress = queueLeaderElectionListener.next(); assertThat("The first result is expected to be the initially set leader address.", firstAddress.get(), is(leaderAddress)); stopTestServer(); CompletableFuture<String> secondAddress = queueLeaderElectionListener.next(); assertThat("The next result must not be missing.", secondAddress, is(notNullValue())); assertThat("The next result is expected to be null.", secondAddress.get(), is(nullValue())); }
Source:
<code>public ParallelDownloadManager(DownloadConfig config, Downloader downloader) { this.config = config; this.unactionedQueue = new LinkedList<>(); this.inProgressQueue = new LinkedList<>(); this.downloader = downloader; <START> pool = Executors.newFixedThreadPool(config.getPoolSize()); <END> }</code><technical_language>_this.pool_ consistent</technical_language>

Target:
public ParallelDownloadManager(DownloadConfig config, Downloader downloader) { this.config = config; this.unactionedQueue = new LinkedList<>(); this.inProgressQueue = new LinkedList<>(); this.downloader = downloader; this.pool = Executors.newFixedThreadPool(config.getPoolSize()); }
Source:
<code>private Geometry collectionClip(GeometryCollection geom) throws Exception { ArrayList<Geometry> result = new ArrayList<Geometry>(); for (int t = 0; t < geom.getNumGeometries(); t++) { Geometry g = geom.getGeometryN(0); Geometry clipped = _run(g); if ((clipped != null) && (!clipped.isEmpty())) result.add(clipped); } if (result.size() == 0) <START> return null; <END> return new GeometryCollection((Geometry[]) result.toArray(new Geometry[result.size()]), geom.getFactory()); }</code><technical_language>follow coding conventions, needs { ... }</technical_language>

Target:
private Geometry collectionClip(GeometryCollection geom) throws Exception { ArrayList<Geometry> result = new ArrayList<Geometry>(); for (int t = 0; t < geom.getNumGeometries(); t++) { Geometry g = geom.getGeometryN(0); Geometry clipped = _run(g); if ((clipped != null) && (!clipped.isEmpty())) { result.add(clipped); } } if (result.size() == 0) { return null; } return new GeometryCollection((Geometry[]) result.toArray(new Geometry[result.size()]), geom.getFactory()); }
Source:
<code>public static Integer get(final String key) { <START> if (key == null) { <END> return R.drawable.acc_none; } return map.containsKey(key.toUpperCase(Locale.getDefault())) ? map.get(key.toUpperCase()) : R.drawable.acc_none; }</code><technical_language>this key get null</technical_language>

Target:
public static Integer get(final String key) { return map.containsKey(key.toUpperCase(Locale.getDefault())) ? map.get(key.toUpperCase()) : R.drawable.acc_none; }
Source:
<code>protected List<CompletableFuture<List<ICompletionProposal>>> buildCompletionFuturesOrJobs(int invocationOffset) { Set<IContentAssistProcessor> processors = null; try { processors= fContentAssistant.getContentAssistProcessors(getTokenContentType(invocationOffset)); } catch (BadLocationException e) { } if (processors == null) { return Collections.emptyList(); } List<CompletableFuture<List<ICompletionProposal>>> futures = new ArrayList<>(processors.size()); for (IContentAssistProcessor processor : processors) { futures.add(CompletableFuture.supplyAsync(() -> { AtomicReference<List<ICompletionProposal>> result= new AtomicReference<>(); SafeRunner.run(new ISafeRunnable() { @Override public void run() throws Exception { ICompletionProposal[] proposals= processor.computeCompletionProposals(fViewer, invocationOffset); if (proposals == null) { result.set(Collections.emptyList()); } <START> result.set(Arrays.asList(proposals)); <END> } }); List<ICompletionProposal> proposals= result.get(); if (proposals == null) { return Collections.emptyList(); } return proposals; })); } return futures; }</code><technical_language>another NPE</technical_language>

Target:
protected List<CompletableFuture<List<ICompletionProposal>>> buildCompletionFuturesOrJobs(int invocationOffset) { Set<IContentAssistProcessor> processors = null; try { processors= fContentAssistant.getContentAssistProcessors(getTokenContentType(invocationOffset)); } catch (BadLocationException e) { } if (processors == null) { return Collections.emptyList(); } List<CompletableFuture<List<ICompletionProposal>>> futures = new ArrayList<>(processors.size()); for (IContentAssistProcessor processor : processors) { futures.add(CompletableFuture.supplyAsync(() -> { AtomicReference<List<ICompletionProposal>> result= new AtomicReference<>(); SafeRunner.run(new ISafeRunnable() { @Override public void run() throws Exception { ICompletionProposal[] proposals= processor.computeCompletionProposals(fViewer, invocationOffset); if (proposals == null) { result.set(Collections.emptyList()); } else { result.set(Arrays.asList(proposals)); } } }); List<ICompletionProposal> proposals= result.get(); if (proposals == null) { return Collections.emptyList(); } return proposals; })); } return futures; }
Source:
<code>private void startConsumer() { try { mqChannel.basicConsume(queueName, false, consumerName, new DefaultConsumer(mqChannel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { long deliveryTag = envelope.getDeliveryTag(); String message = new String(body); dispatch(message); log.debug("{} dispatched", message); mqChannel.basicAck(deliveryTag, false); log.debug("{} deleted", message); } @Override public void handleConsumeOk(String consumerTag) { log.info("Consumer registered: {}", consumerTag); initialized = true; } @Override public void handleCancel(String consumerTag) { <START> log.debug("Consumer has been cancelled unexpectedly: " + consumerTag); <END> } @Override public void handleCancelOk(String consumerTag) { log.info("Consumer has been cancelled successfully: " + consumerTag); } @Override public void handleShutdownSignal(String consumerTag, ShutdownSignalException sig) { log.debug("Either the channel or the underlying connection has been shut down" + " for consumer because {}", consumerTag, sig.getReason().toString()); initialized = false; } }); } catch (Exception e) { log.debug("Consumer failed to subscribe: " + e.getMessage(), e); initialized = false; } }</code><technical_language>Unexpected system behavior warrants a log.warn() message. attempt reconnect? suggestion log.warn("Consumer cancelled unexpectedly: " + consumerTag);</technical_language>

Target:
private void startConsumer() { try { mqChannel.basicConsume(queueName, false, consumerName, new DefaultConsumer(mqChannel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { long deliveryTag = envelope.getDeliveryTag(); String message = new String(body); dispatch(message); log.debug("{} dispatched", message); mqChannel.basicAck(deliveryTag, false); log.debug("{} deleted", message); } @Override public void handleConsumeOk(String consumerTag) { log.info("Consumer registered: {}", consumerTag); initialized = true; } @Override public void handleCancel(String consumerTag) { log.warn("Consumer has been cancelled unexpectedly: " + consumerTag); } @Override public void handleCancelOk(String consumerTag) { log.info("Consumer has been cancelled successfully: " + consumerTag); } @Override public void handleShutdownSignal(String consumerTag, ShutdownSignalException sig) { log.warn("Either the channel or the underlying connection has been shut down" + " for consumer because {}", consumerTag, sig.getReason().toString()); initialized = false; } }); } catch (Exception e) { log.error("Consumer failed to subscribe: " + e.getMessage(), e); initialized = false; } }
Source:
<code>public static void playSoundAtLocationExcept(Location location, Sound sound, float volume, float pitch, GlowPlayer... exclude) { if (location == null || sound == null) return; GlowWorld world = (GlowWorld) location.getWorld(); <START> double radiusSquared = Math.pow(volume * 16, 2); <END> world.getRawPlayers().stream().filter(player -> player.getLocation().distanceSquared(location) <= radiusSquared).filter(player -> !Arrays.asList(exclude).contains(player)).forEach(player -> player.playSound(location, sound, volume, pitch)); }</code><technical_language>I volume * volume * 256 more optimized</technical_language>

Target:
public static void playSoundAtLocationExcept(Location location, Sound sound, float volume, float pitch, GlowPlayer... exclude) { if (location == null || sound == null) return; GlowWorld world = (GlowWorld) location.getWorld(); double radiusSquared = volume * volume * 256; world.getRawPlayers().parallelStream().filter(player -> player.getLocation().distanceSquared(location) <= radiusSquared).filter(player -> !Arrays.asList(exclude).contains(player)).forEach(player -> player.playSound(location, sound, volume, pitch)); }
Source:
<code>private static void verifyThreadsNumberParameter(CommandLine cmdLine, List<String> result, String cliParameterName, String mustBeGreaterThanZeroMessage, String invalidNumberMessage) { if (cmdLine.hasOption(cliParameterName)) { final String checkerThreadsNumberStr = cmdLine.getOptionValue(cliParameterName); try { final int checkerThreadsNumber = Integer.parseInt(checkerThreadsNumberStr); if (checkerThreadsNumber < 1) { result.add(mustBeGreaterThanZeroMessage); } } catch (NumberFormatException ignored) { result.add(invalidNumberMessage); <START> } <END> } }</code><technical_language>I personally dislike logic is based exceptions. do performance concerns all. If mind is like: if (isInt()) { checkerThreadsNumber = Integer.parseInt(checkerThreadsNumberStr); .... } else { result.add(invalidNumberMessage); } static boolean isInt(.....) { try { Integer.parseInt(checkerThreadsNumberStr); return true; } catch (NumberFormatException ignored) { return false; } } @rnveach @sabaka , agree</technical_language>

Target:
private static void verifyThreadsNumberParameter(CommandLine cmdLine, List<String> result, String cliParameterName, String mustBeGreaterThanZeroMessage, String invalidNumberMessage) { if (cmdLine.hasOption(cliParameterName)) { final String checkerThreadsNumberStr = cmdLine.getOptionValue(cliParameterName); if (CommonUtils.isInt(checkerThreadsNumberStr)) { final int checkerThreadsNumber = Integer.parseInt(checkerThreadsNumberStr); if (checkerThreadsNumber < 1) { result.add(mustBeGreaterThanZeroMessage); } } else { result.add(invalidNumberMessage); } } }
Source:
<code><START> public void update(TableDescriptor td, boolean cacheOnly) throws IOException { <END> if (fsreadonly) { throw new UnsupportedOperationException("Cannot add a table descriptor - in read only mode"); } if (!cacheOnly) { updateTableDesciptor(td); } if (usecache) { this.cache.put(td.getTableName(), td); } }</code><technical_language>This do cacheonly is true usecache is false? is weird...... throw UnsupportedOperationException for this case too</technical_language>

Target:
public void update(TableDescriptor td, boolean cacheOnly) throws IOException { if (fsreadonly) { throw new UnsupportedOperationException("Cannot add a table descriptor - in read only mode"); } if (!cacheOnly) { updateTableDescriptor(td); } if (usecache) { this.cache.put(td.getTableName(), td); } }
Source:
<code>public String[] getConflictingIds(TaskEditorInput input) { List<String> conflictingIds = ImmutableList.of(ITasksUiConstants.ID_PAGE_PLANNING); @SuppressWarnings("restriction") String artifactFlag = input.getTask().getAttribute(ITasksCoreConstants.ATTRIBUTE_ARTIFACT); if (Boolean.parseBoolean(artifactFlag)) { final String CONTEXT_PAGE = "org.eclipse.mylyn.context.ui"; <START> conflictingIds.add(CONTEXT_PAGE); <END> } return conflictingIds.toArray(new String[conflictingIds.size()]); }</code><technical_language>This is work. add immutable list. ArrayList</technical_language>

Target:
public String[] getConflictingIds(TaskEditorInput input) { @SuppressWarnings("restriction") String isArtifact = input.getTask() .getAttribute(org.eclipse.mylyn.internal.tasks.core.ITasksCoreConstants.ATTRIBUTE_ARTIFACT); if (Boolean.parseBoolean(isArtifact)) { return new String[] { ITasksUiConstants.ID_PAGE_PLANNING, "org.eclipse.mylyn.context.ui" }; } return new String[] { ITasksUiConstants.ID_PAGE_PLANNING }; }
Source:
<code>public void copyObject(String bucketName, String objectName, String destBucketName, CopyConditions copyConditions) throws InvalidKeyException, InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, NoResponseException, ErrorResponseException, InternalException, IOException, XmlPullParserException, InvalidArgumentException { String destObjectName = objectName; <START> String sourceObjectPath = S3Escaper.encode(Paths.get(bucketName, objectName).toString()); <END> copyObjectResult(destBucketName, destObjectName, sourceObjectPath, copyConditions); }</code><technical_language>need repeat this logic in versions of copyObject(). copyObjectResult() private function do for version</technical_language>

Target:
public void copyObject(String bucketName, String objectName, String destBucketName, CopyConditions copyConditions) throws InvalidKeyException, InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, NoResponseException, ErrorResponseException, InternalException, IOException, XmlPullParserException, InvalidArgumentException { copyObject(bucketName, objectName, destBucketName, null, copyConditions); }
Source:
<code>public void get(String url) { String host = null; try { host = new URL(url).getHost(); } catch (MalformedURLException e) { <START> e.printStackTrace(); <END> } if (host != null && ("localhost" .equals(host) || "127.0.0.1" .equals(host))) { if (isSetBrowserStackLocal && !isSetBrowserStackLocalManaged) { log.info( "To test against localhost and other locations behind your firewall, you need to run a BrowserStackLocal binary. " + "You can ignore this if you have already started it, otherwise see browserstack.com/local-testing"); } } super.get(url); }</code><technical_language>i understand is printed stack trace good for. log care of propagate exception higher. line 55 checking if host != null in this case fail else ..</technical_language>

Target:
public void get(String url) { String host = null; try { host = new URL(url).getHost(); } catch (MalformedURLException e) { log.warning( "The url " + url + " has been detected as a malformed URL. The message of the exception: " + e .getMessage()); } if (host != null && (host.equals("localhost") || host.equals("127.0.0.1"))) { if (isSetBrowserStackLocal && !isSetBrowserStackLocalManaged) { log.info( "To test against localhost and other locations behind your firewall, you need to run a BrowserStackLocal binary. " + "You can ignore this if you have already started it, otherwise see browserstack.com/local-testing"); } } super.get(url); }
Source:
<code>public void verifyRead() { String feedURL2 = SimpleHttpServer.getInstance().start("foo2", HttpStatus.SC_OK, ATOM_FEED_DATA_2); when(feedRecordDataService.findByURL(feedURL)).thenReturn(new FeedRecord(feedURL, ATOM_FEED_DATA)); when(feedRecordDataService.findByURL(feedURL2)).thenReturn(new FeedRecord(feedURL2, ATOM_FEED_DATA_2)); ArgumentCaptor<MotechEvent> event = ArgumentCaptor.forClass(MotechEvent.class); atomClientService.read(feedURL, feedURL2); <START> verify(eventRelay, times(0)).sendEventMessage(event.capture()); <END> }</code><technical_language>verify if configService.readNewFeeds is invoked proper data</technical_language>

Target:
public void verifyRead() { String feedURL2 = SimpleHttpServer.getInstance().start("foo2", HttpStatus.SC_OK, ATOM_FEED_DATA_2); when(feedRecordDataService.findByURL(feedURL)).thenReturn(new FeedRecord(feedURL, ATOM_FEED_DATA)); when(feedRecordDataService.findByURL(feedURL2)).thenReturn(new FeedRecord(feedURL2, ATOM_FEED_DATA_2)); atomClientService.read(feedURL, feedURL2); verify(atomClientConfigService).readNewFeeds(35, 36, feedURL); }
Source:
<code>public static List<Map.Entry<Long, byte[]>> decode(ListIterator<ClientMessage.Frame> iterator) { <START> List<Long> listK = ListLongCodec.decode(iterator); <END> List<byte[]> listV = ListMultiFrameCodec.decode(iterator, ByteArrayCodec::decode); List<Map.Entry<Long, byte[]>> result = new ArrayList<>(listK.size()); for (int i = 0; i < listK.size(); i++) { result.add(new AbstractMap.SimpleEntry<>(listK.get(i), listV.get(i))); } return result; }</code><technical_language>order incorrect. encodes values reads keys first. this reversed</technical_language>

Target:
public static List<Map.Entry<Long, byte[]>> decode(ListIterator<ClientMessage.Frame> iterator) { List<byte[]> listV = ListMultiFrameCodec.decode(iterator, ByteArrayCodec::decode); List<Long> listK = ListLongCodec.decode(iterator); List<Map.Entry<Long, byte[]>> result = new ArrayList<>(listK.size()); for (int i = 0; i < listK.size(); i++) { result.add(new AbstractMap.SimpleEntry<>(listK.get(i), listV.get(i))); } return result; }
Source:
<code>private AbstractExpression parseAggregationExpression(VoltXMLElement exprNode) { String type = exprNode.attributes.get("optype"); <START> String user_aggregate_id = exprNode.attributes.get("user_aggregate_id"); <END> String function_name = exprNode.attributes.get("name"); ExpressionType exprType = ExpressionType.get(type); if (exprType == ExpressionType.INVALID) { throw new PlanningErrorException("Unsupported aggregation type '" + type + "'"); } assert(exprNode.children.size() <= 1); VoltXMLElement childExprNode = exprNode.children.get(0); assert(childExprNode != null); AbstractExpression childExpr = parseExpressionNode(childExprNode); if (childExpr == null) { assert(exprType == ExpressionType.AGGREGATE_COUNT); exprType = ExpressionType.AGGREGATE_COUNT_STAR; } AggregateExpression expr = new AggregateExpression(exprType, user_aggregate_id, function_name); expr.setLeft(childExpr); String node; if ((node = exprNode.attributes.get("distinct")) != null && Boolean.parseBoolean(node)) { expr.setDistinct(); } if (m_aggregationList != null) { ExpressionUtil.finalizeValueTypes(expr); m_aggregationList.add(expr); } return expr; }</code><technical_language>Fix naming</technical_language>

Target:
private AbstractExpression parseAggregationExpression(VoltXMLElement exprNode) { String type = exprNode.attributes.get("optype"); String tempId = exprNode.attributes.get("user_aggregate_id"); int userAggregateId = tempId == null ? -1 : Integer.parseInt(tempId); String functionName = exprNode.attributes.get("name"); ExpressionType exprType = ExpressionType.get(type); if (exprType == ExpressionType.INVALID) { throw new PlanningErrorException("Unsupported aggregation type '" + type + "'"); } assert(exprNode.children.size() <= 1); VoltXMLElement childExprNode = exprNode.children.get(0); assert(childExprNode != null); AbstractExpression childExpr = parseExpressionNode(childExprNode); if (childExpr == null) { assert(exprType == ExpressionType.AGGREGATE_COUNT); exprType = ExpressionType.AGGREGATE_COUNT_STAR; } AggregateExpression expr = new AggregateExpression(exprType, userAggregateId, functionName); expr.setLeft(childExpr); String node; if ((node = exprNode.attributes.get("distinct")) != null && Boolean.parseBoolean(node)) { expr.setDistinct(); } if (m_aggregationList != null) { ExpressionUtil.finalizeValueTypes(expr); m_aggregationList.add(expr); } return expr; }
Source:
<code>public void onCastStateChanged(int newState) { try { if (isInForeground()) { if (mediaRouteMenuItem != null) { googleCastDelegate.showIntroductoryOverlay(this, mediaRouteMenuItem); } invalidateOptionsMenu(); } } catch (Exception e) { <START> logger.error(e); <END> } }</code><technical_language>This log exception Crashlytics a non-fatal, call function follows: logger.error(e, true);</technical_language>

Target:
public void onCastStateChanged(int newState) { try { if (isInForeground()) { if (mediaRouteMenuItem != null) { googleCastDelegate.showIntroductoryOverlay(this, mediaRouteMenuItem); } invalidateOptionsMenu(); } } catch (Exception e) { logger.error(e, true); } }
Source:
<code>public QueryResult getInfoForPostion(String contig, int pos, String alt) throws IOException { String queryStr = contig + ":" + pos + "-" + (pos); try { TabixReader.Iterator iter = reader.query(queryStr); if(iter != null) { String str = iter.next(); while(str != null) { String[] toks = str.split("\t"); Integer qPos = Integer.parseInt(toks[1]); <START> String ALT = toks[3]; <END> String overall = toks[4]; if (qPos == pos && ALT.equals(alt) && overall.equals("overall")) { String sampleTotalStr = toks[5]; String hetsFoundStr = toks[6]; String homsFoundStr = toks[7]; double totalSamples = Double.parseDouble(sampleTotalStr); double overallHets = Double.parseDouble(hetsFoundStr); double overallHoms = Double.parseDouble(homsFoundStr); double overallAF = (overallHets + 2.0*overallHoms)/(double)(2.0*totalSamples); String details = "Samples: " + (int)totalSamples + " Hets: " + (int)overallHets + " Homs: " + (int)overallHoms; QueryResult result = new QueryResult(); result.overallFreq = overallAF; result.totHets = overallHets; result.totHoms = overallHoms; result.totSamples = totalSamples; result.details = details; return result; } if (qPos > pos) { break; } str = iter.next(); } } } catch (RuntimeException rex) { } return null; }</code><technical_language>This caps weird. caps a constant in this case this more appropriate: String alt = toks[3];</technical_language>

Target:
public QueryResult getInfoForPostion(String contig, int pos, String alt) throws IOException { String queryStr = contig + ":" + pos + "-" + (pos); try { TabixReader.Iterator iter = reader.query(queryStr); if(iter != null) { String str = iter.next(); while(str != null) { String[] toks = str.split("\t"); Integer qPos = Integer.parseInt(toks[1]); String qAlt = toks[3]; String overall = toks[4]; if (qPos == pos && qAlt.equals(alt) && overall.equals("overall")) { String sampleTotalStr = toks[5]; String hetsFoundStr = toks[6]; String homsFoundStr = toks[7]; double totalSamples = Double.parseDouble(sampleTotalStr); double overallHets = Double.parseDouble(hetsFoundStr); double overallHoms = Double.parseDouble(homsFoundStr); double overallAF = (overallHets + 2.0*overallHoms)/(double)(2.0*totalSamples); String details = "Samples: " + (int)totalSamples + " Hets: " + (int)overallHets + " Homs: " + (int)overallHoms; QueryResult result = new QueryResult(); result.overallFreq = overallAF; result.totHets = overallHets; result.totHoms = overallHoms; result.totSamples = totalSamples; result.details = details; return result; } if (qPos > pos) { break; } str = iter.next(); } } } catch (RuntimeException rex) { } return null; }
Source:
<code>public static void startSession(List<IResource> resources, final List<JID> contacts) { <START> projectAPI.saveAllDocuments(); <END> final Map<IProject, List<IResource>> newResources = acquireResources( resources, null); UIMonitoredJob sessionStartupJob = new UIMonitoredJob( "Session Startup") { @Override protected IStatus run(IProgressMonitor monitor) { monitor .beginTask("Starting session...", IProgressMonitor.UNKNOWN); try { sessionManager.startSession(newResources); Set<JID> participantsToAdd = new HashSet<JID>(contacts); monitor.worked(50); ISarosSession session = sessionManager.getSession(); if (session == null) { return Status.CANCEL_STATUS; } monitor.setTaskName("Inviting participants..."); sessionManager.invite(participantsToAdd, getShareProjectDescription(session)); monitor.done(); } catch (Exception e) { LOG.error("could not start a Saros session", e); return new Status(IStatus.ERROR, SarosComponent.PLUGIN_ID, e.getMessage(), e); } return Status.OK_STATUS; } }; sessionStartupJob.schedule(); }</code><technical_language>This necessary</technical_language>

Target:
public static void startSession(List<IResource> resources, final List<JID> contacts) { final Map<IProject, List<IResource>> newResources = acquireResources( resources, null); UIMonitoredJob sessionStartupJob = new UIMonitoredJob( "Session Startup") { @Override protected IStatus run(IProgressMonitor monitor) { monitor .beginTask("Starting session...", IProgressMonitor.UNKNOWN); try { sessionManager.startSession(newResources); Set<JID> participantsToAdd = new HashSet<JID>(contacts); monitor.worked(50); ISarosSession session = sessionManager.getSession(); if (session == null) { return Status.CANCEL_STATUS; } monitor.setTaskName("Inviting participants..."); sessionManager.invite(participantsToAdd, getShareProjectDescription(session)); monitor.done(); } catch (Exception e) { LOG.error("could not start a Saros session", e); return new Status(IStatus.ERROR, SarosComponent.PLUGIN_ID, e.getMessage(), e); } return Status.OK_STATUS; } }; sessionStartupJob.schedule(); }
Source:
<code>private Guid getTargetClusterId(Action action) { if (action.isSetCluster() && <START> (action.getCluster().isSetId() || action.getCluster().isSetName())) { <END> return getClusterId(action); } return null; }</code><technical_language>I this check more sense in "getClusterId" method. move there</technical_language>

Target:
private Guid getTargetClusterId(Action action) { if (action.isSetCluster()) { return getClusterId(action); } return null; }
Source:
<code>public List<TopicPartition> getFilteredTopicPartitions(KafkaConsumer<?, ?> consumer) { List<TopicPartition> allPartitions = new ArrayList<>(); for (String topic : topics) { <START> if(consumer.partitionsFor(topic) != null) { <END> for (PartitionInfo partitionInfo : consumer.partitionsFor(topic)) { allPartitions.add(new TopicPartition(partitionInfo.topic(), partitionInfo.partition())); } } else { LOG.warn("Topic not found, skipping addition of the topic", topic); } } return allPartitions; }</code><technical_language>I put result of partitionsFor in a variable, asking for</technical_language>

Target:
public List<TopicPartition> getFilteredTopicPartitions(KafkaConsumer<?, ?> consumer) { List<TopicPartition> allPartitions = new ArrayList<>(); for (String topic : topics) { List<PartitionInfo> partitionInfoList = consumer.partitionsFor(topic); if(partitionInfoList != null) { for (PartitionInfo partitionInfo : partitionInfoList) { allPartitions.add(new TopicPartition(partitionInfo.topic(), partitionInfo.partition())); } } else { LOG.warn("Topic not found, skipping addition of the topic", topic); } } return allPartitions; }
Source:
<code>public void testImport2BKMs() { DMNRuntime runtime = DMNRuntimeUtil.createRuntimeWithAdditionalResources("Do_say_hello_with_2_bkms.dmn", this.getClass(), "Saying_hello_2_bkms.dmn"); DMNModel importedModel = runtime.getModel("<LINK_0>", "Saying hello 2 bkms"); assertThat(importedModel, notNullValue()); <START> for (DMNMessage message : importedModel.getMessages()) { <END> LOG.debug("{}", message); } DMNModel dmnModel = runtime.getModel("<LINK_1>", "Do say hello with 2 bkms"); assertThat(dmnModel, notNullValue()); for (DMNMessage message : dmnModel.getMessages()) { LOG.debug("{}", message); } DMNContext context = runtime.newContext(); context.set("Person name", "John"); DMNResult evaluateAll = runtime.evaluateAll(dmnModel, context); for (DMNMessage message : evaluateAll.getMessages()) { LOG.debug("{}", message); } LOG.debug("{}", evaluateAll); assertThat(evaluateAll.getDecisionResultByName("Say hello decision").getResult(), is("Hello, John")); assertThat(evaluateAll.getDecisionResultByName("what about hello").getResult(), is("Hello")); }</code><technical_language>This is more places, extracted a separate method, logMessages(Messages)</technical_language>

Target:
public void testImport2BKMs() { DMNRuntime runtime = DMNRuntimeUtil.createRuntimeWithAdditionalResources("Do_say_hello_with_2_bkms.dmn", this.getClass(), "Saying_hello_2_bkms.dmn"); DMNModel importedModel = runtime.getModel("<LINK_0>", "Saying hello 2 bkms"); assertThat(importedModel, notNullValue()); assertThat(DMNRuntimeUtil.formatMessages(importedModel.getMessages()), importedModel.hasErrors(), is(false)); DMNModel dmnModel = runtime.getModel("<LINK_1>", "Do say hello with 2 bkms"); assertThat(dmnModel, notNullValue()); assertThat(DMNRuntimeUtil.formatMessages(dmnModel.getMessages()), dmnModel.hasErrors(), is(false)); DMNContext context = runtime.newContext(); context.set("Person name", "John"); DMNResult evaluateAll = runtime.evaluateAll(dmnModel, context); assertThat(DMNRuntimeUtil.formatMessages(evaluateAll.getMessages()), evaluateAll.hasErrors(), is(false)); LOG.debug("{}", evaluateAll); assertThat(evaluateAll.getDecisionResultByName("Say hello decision").getResult(), is("Hello, John")); assertThat(evaluateAll.getDecisionResultByName("what about hello").getResult(), is("Hello")); }
Source:
<code><START> private void setChargedThroughDates(final Invoice invoice, final InternalCallContext context) throws SubscriptionBaseApiException { <END> final Collection<InvoiceItem> fixedPriceItems = new LinkedList<InvoiceItem>(); final Collection<InvoiceItem> recurringItems = new LinkedList<InvoiceItem>(); for (final InvoiceItem invoiceItem : invoice.getInvoiceItems()) { switch (invoiceItem.getInvoiceItemType()) { case FIXED: fixedPriceItems.add(invoiceItem); break; case RECURRING: recurringItems.add(invoiceItem); break; default: break; } } final Map<UUID, DateTime> chargeThroughDates = new HashMap<UUID, DateTime>(); addInvoiceItemsToChargeThroughDates(chargeThroughDates, fixedPriceItems, context); addInvoiceItemsToChargeThroughDates(chargeThroughDates, recurringItems, context); for (final UUID subscriptionId : chargeThroughDates.keySet()) { if (subscriptionId != null) { final DateTime chargeThroughDate = chargeThroughDates.get(subscriptionId); subscriptionApi.setChargedThroughDate(subscriptionId, chargeThroughDate, context); } } }</code><technical_language>Independently of change, i wondering if handle USAGE types : want end a null CTD if bill for usage ? worth creating a bug track this-- understand do now, this needs fixed</technical_language>

Target:
private void setChargedThroughDates(final Invoice invoice, final InternalCallContext context) throws SubscriptionBaseApiException { final Collection<InvoiceItem> invoiceItemsToConsider = new LinkedList<InvoiceItem>(); for (final InvoiceItem invoiceItem : invoice.getInvoiceItems()) { switch (invoiceItem.getInvoiceItemType()) { case FIXED: case RECURRING: case USAGE: invoiceItemsToConsider.add(invoiceItem); break; default: break; } } final Map<UUID, DateTime> chargeThroughDates = new HashMap<UUID, DateTime>(); addInvoiceItemsToChargeThroughDates(chargeThroughDates, invoiceItemsToConsider, context); for (final UUID subscriptionId : chargeThroughDates.keySet()) { if (subscriptionId != null) { final DateTime chargeThroughDate = chargeThroughDates.get(subscriptionId); subscriptionApi.setChargedThroughDate(subscriptionId, chargeThroughDate, context); } } }
Source:
<code>protected void validate(Element element, ElementValidation validation) { super.validate(element, validation); <START> validatorHelper.param.inOrder() END> .type(CanonicalNameConstants.VIEW_PAGER).optional() .primitiveOrWrapper(TypeKind.INT).optional() .validate((ExecutableElement) element, validation); }</code><technical_language>anyOrder()</technical_language>

Target:
protected void validate(Element element, ElementValidation validation) { super.validate(element, validation); validatorHelper.param.anyOrder() .type(CanonicalNameConstants.VIEW_PAGER).optional() .primitiveOrWrapper(TypeKind.INT).optional() .validate((ExecutableElement) element, validation); }
Source:
<code>protected String run() throws Exception { <START> EntityMetadata emd = getMetadata().getEntityMetadata(entity, version); <END> CRUDController crudController = RestConfiguration.getFactory().getFactory().getCRUDController(emd); if (crudController instanceof MongoCRUDController) { MongoCRUDController mcc = (MongoCRUDController) crudController; mcc.reindex(emd); return String.format("Starting reindex of %s:%s", entity, version); } throw new UnsupportedOperationException("This command is only available on MongoDB backed instances"); }</code><technical_language>version is removed, Factory.getCRUDController(ei.getDataStore().getBackend())</technical_language>

Target:
protected String run() throws Exception { EntityInfo entityInfo = getMetadata().getEntityInfo(entity); CRUDController crudController = RestConfiguration.getFactory().getFactory().getCRUDController(entityInfo.getDataStore().getBackend()); if (crudController instanceof MongoCRUDController) { MongoCRUDController mcc = (MongoCRUDController) crudController; mcc.reindex(entityInfo); return String.format("Starting reindex of %s", entity); } throw new UnsupportedOperationException("This command is only available on MongoDB backed instances"); }
Source:
<code>private void addPlayableToQueue(Playable playable) { if (playable instanceof FeedMedia) { FeedItem feedItem = DBReader.getFeedItem(((FeedMedia) playable).getId()); <START> DBWriter.addQueueItem(this, feedItem); <END> } }</code><technical_language>for long respond. If addQueueItem(this, false, false, ((FeedMedia) playable).getId()) instead, need do database query retrieves item. way, this fixes #3277 :) :+1:</technical_language>

Target:
private void addPlayableToQueue(Playable playable) { if (playable instanceof FeedMedia) { long itemId = ((FeedMedia) playable).getId(); DBWriter.addQueueItem(this, false, false, itemId); } }