auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void deleteCommand(@ApiParam("The id of the workspace") @PathParam("id") String id, @ApiParam("The name of the command to remove") @PathParam("name") String commandName) throws ServerException, BadRequestException, NotFoundException, ConflictException, ForbiddenException { final WorkspaceImpl workspace = workspaceManager.getWorkspace(id); if (workspace.getConfig().getCommands().removeIf(command -> command.getName().equals(commandName))) { workspaceManager.updateWorkspace(id, workspace); } else { <START> throw new NotFoundException(String.format("Failed to delete command '%s'", commandName)); <END> } }</code><technical_language>Command name '%s' in workspace id '%s'? I this message for NotFoundException add swagger annotation for this case of 404 response code</technical_language>

Target:
public void deleteCommand(@ApiParam("The id of the workspace") @PathParam("id") String id, @ApiParam("The name of the command to remove") @PathParam("name") String commandName) throws ServerException, BadRequestException, NotFoundException, ConflictException, ForbiddenException { final WorkspaceImpl workspace = workspaceManager.getWorkspace(id); if (workspace.getConfig().getCommands().removeIf(command -> command.getName().equals(commandName))) { workspaceManager.updateWorkspace(id, workspace); } else { throw new NotFoundException(String.format("Command with name '%s' was not found in workspace with id %s", commandName, id)); } }
Source:
<code>protected void doExecute() { Collection<EObject> impactedEObjects = new ArrayList<EObject>(); DslCommonPlugin.PROFILER.startWork(SiriusTasksKey.CLEANING_REMOVEDANGLING_KEY); final ECrossReferenceAdapter xReferencer = session.getSemanticCrossReferencer(); ModelAccessor modelAccessor = session.getModelAccessor(); for (EObject eObject : toRemoveXRefFrom) { ECrossReferenceAdapter filteredCrossReferencer = new ECrossReferenceAdapter() { @Override public Collection<Setting> getInverseReferences(EObject eObject, boolean resolve) { Collection<Setting> settings = xReferencer.getInverseReferences(eObject, resolve); Collection<Setting> settingsToTryToUnset = Lists.newArrayList(); for (Setting s : settings) { if (!toRemoveXRefFrom.contains(s.getEObject())) { settingsToTryToUnset.add(s); } } return settingsToTryToUnset; } }; impactedEObjects.addAll(modelAccessor.eRemoveInverseCrossReferences(eObject, filteredCrossReferencer, isReferenceToIgnorePredicate)); } for (EObject impactedEObject : impactedEObjects) { Resource resource = impactedEObject.eResource(); if <START> (session.getSemanticResources().contains(resource)) <END> { session.getRefreshEditorsListener().disable(); break; } } DslCommonPlugin.PROFILER.stopWork(SiriusTasksKey.CLEANING_REMOVEDANGLING_KEY); toRemoveXRefFrom.clear(); session = null; }</code><technical_language>session.getSemanticResources() called loop</technical_language>

Target:
protected void doExecute() { Collection<EObject> impactedEObjects = new ArrayList<EObject>(); DslCommonPlugin.PROFILER.startWork(SiriusTasksKey.CLEANING_REMOVEDANGLING_KEY); for (EObject eObject : toRemoveXRefFrom) { ECrossReferenceAdapter filteredCrossReferencer = new ECrossReferenceAdapter() { @Override public Collection<Setting> getInverseReferences(EObject eObject, boolean resolve) { Collection<Setting> settings = xReferencer.getInverseReferences(eObject, resolve); Collection<Setting> settingsToTryToUnset = Lists.newArrayList(); for (Setting s : settings) { if (!toRemoveXRefFrom.contains(s.getEObject())) { settingsToTryToUnset.add(s); } } return settingsToTryToUnset; } }; impactedEObjects.addAll(modelAccessor.eRemoveInverseCrossReferences(eObject, filteredCrossReferencer, isReferenceToIgnorePredicate)); } for (EObject impactedEObject : impactedEObjects) { Resource resource = impactedEObject.eResource(); if (semanticResources.contains(resource)) { refreshEditorsPrecommitListener.disable(); break; } } DslCommonPlugin.PROFILER.stopWork(SiriusTasksKey.CLEANING_REMOVEDANGLING_KEY); toRemoveXRefFrom.clear(); modelAccessor = null; xReferencer = null; semanticResources = null; refreshEditorsPrecommitListener = null; }
Source:
<code>public VDS getServer(Guid clusterId, String hostnameOrIp) { List<VDS> servers = getVdsDao().getAllForHostname(hostnameOrIp); if (servers.size() > 0) { return getServerOfCluster(clusterId, servers); } List<VdsNetworkInterface> ifaces; try { ifaces = getInterfaceDao().getAllInterfacesWithIpAddress(clusterId, InetAddress.getByName(hostnameOrIp).getHostAddress()); switch (ifaces.size()) { case 0: return null; case 1: VDS server = getVdsDao().get(ifaces.get(0).getVdsId()); <START> if (server != null && server.getVdsGroupId().equals(clusterId)) { <END> return server; } return null; default: throw new RuntimeException(String.format("There are multiple servers in DB having same IP address %1$s! " + "Cannot arrive at correct server id for bricks related to this ip address in cluster %2$s", hostnameOrIp, clusterId)); } } catch (UnknownHostException e) { throw new RuntimeException(e); } }</code><technical_language>Is this check needed? Interfaces for cluster id, server cluster</technical_language>

Target:
public VdsStatic getServer(Guid clusterId, String hostnameOrIp) { VdsStatic server = getVdsStaticDao().getByHostName(hostnameOrIp); if (server != null) { return server.getVdsGroupId().equals(clusterId) ? server : null; } List<VdsNetworkInterface> ifaces; try { ifaces = getInterfaceDao().getAllInterfacesWithIpAddress(clusterId, InetAddress.getByName(hostnameOrIp).getHostAddress()); switch (ifaces.size()) { case 0: return null; case 1: return getVdsStaticDao().get(ifaces.get(0).getVdsId().getValue()); default: throw new RuntimeException(String.format("There are multiple servers in DB having same IP address %1$s!", hostnameOrIp, clusterId)); } } catch (UnknownHostException e) { throw new RuntimeException(e); } }
Source:
<code>public Optional<Duration> nextBackoff() { return numTimesRetried.getAndIncrement() < maxNumRetries <START> ? Optional.of(Duration.ofMinutes(0)) <END> : Optional.empty(); }</code><technical_language>Duration.ZERO</technical_language>

Target:
public Optional<Duration> nextBackoff() { numTimesRetried += 1; return numTimesRetried <= maxNumRetries ? Optional.of(Duration.ZERO) : Optional.empty(); }
Source:
<code>public Block getBlock(int[] positions, int positionCount) { checkState(outputType != null, "This stream reader produces null block "); <START> return RunLengthEncodedBlock.create(outputType, null, positionCount); <END> }</code><technical_language>return createNullBlock(outputType, positionCount);</technical_language>

Target:
public Block getBlock(int[] positions, int positionCount) { return createNullBlock(outputType, positionCount); }
Source:
<code>public static XARecoveryModule getRegisteredXARecoveryModule () { if (registeredXARecoveryModule == null) { RecoveryManager recMan = RecoveryManager.manager(); Vector recoveryModules = recMan.getModules(); if (recoveryModules != null) { Enumeration modules = recoveryModules.elements(); while (modules.hasMoreElements()) { RecoveryModule m = (RecoveryModule) modules.nextElement(); if (m instanceof XARecoveryModule) { <START> registeredXARecoveryModule = (XARecoveryModule) m; <END> } } } } return registeredXARecoveryModule; }</code><technical_language>break out of loop early finding target module</technical_language>

Target:
public static XARecoveryModule getRegisteredXARecoveryModule () { if (registeredXARecoveryModule == null) { RecoveryManager recMan = RecoveryManager.manager(); Vector recoveryModules = recMan.getModules(); if (recoveryModules != null) { Enumeration modules = recoveryModules.elements(); while (modules.hasMoreElements()) { RecoveryModule m = (RecoveryModule) modules.nextElement(); if (m instanceof XARecoveryModule) { registeredXARecoveryModule = (XARecoveryModule) m; break; } } } } return registeredXARecoveryModule; }
Source:
<code>private String getHelp() { StringBuilder sb = new StringBuilder(); sb.append(help.get("usage") + "\n\n"); sb.append("Actions:\n"); for(Map.Entry<String, Map<String, ParserArgument>> usage : usages.entrySet()) { sb.append("\t" + usage.getKey() + "\n"); <START> sb.append("\t\t" + "Options:\n"); <END> for(Map.Entry<String, ParserArgument> entry : usage.getValue().entrySet()) { sb.append( String.format( "\t\t\t--%-30s%-60s\n", entry.getKey() + (entry.getValue().getType() != ArgumentType.no_argument ? "=[" + entry.getValue().getMetavar() + "]" : ""), entry.getValue().getHelp() ) ); } sb.append("\n"); } sb.append("\n" + help.get("underlinetext") + "\n"); return sb.toString(); }</code><technical_language>please do tabs in output, please String.format. also, please avoid multiple additions... sb.append( String.format( ( "line1\n" "line2\n" ), format1, ... ) )</technical_language>

Target:
private String getHelp() { StringBuilder args = new StringBuilder(); for(Map.Entry<String, Map<String, ParserArgument>> usage : usages.entrySet()) { args.append( String.format( "%1$soptional arguments:%n", usage.getKey().contains("__single__") ? "" : usage.getKey() + " " ) ); for(Map.Entry<String, ParserArgument> entry : usage.getValue().entrySet()) { args.append( String.format( " --%-30s%-60s\n", entry.getKey() + (entry.getValue().getType() != ArgumentType.no_argument ? "=[" + entry.getValue().getMetavar() + "]" : ""), entry.getValue().getHelp() ) ); } args.append("\n"); } StringBuilder sb = new StringBuilder(); sb.append( String.format( "%s%n%n%s%n%n%s%n", help.get("usage"), help.get("underlinetext"), args.toString() ) ); return sb.toString(); }
Source:
<code>private void deleteDataSource(Long dsObjId) { String dataSourceId = Long.toString(dsObjId); String deleteQuery = "image_id:" + dataSourceId; try { UpdateResponse updateResponse = solrCore.deleteByQuery(deleteQuery); } catch (SolrServerException | IOException ex) { <START> logger.log(Level.SEVERE, "Error deleting content from Solr. Solr image id " + dataSourceId, ex); END> } }</code><technical_language>for DeleteDataSourceAction, level classes propagate exceptions for handling top level classes. E.g., here, Server performAction needs do in context of a menu selection in UI a user? exceptions propagate public deleteDataSource method above, propagate errors, on, chain. exceptions wrapped in other exceptions needed</technical_language>

Target:
private void deleteDataSource(Long dsObjId) throws IOException, SolrServerException { String dataSourceId = Long.toString(dsObjId); String deleteQuery = "image_id:" + dataSourceId; solrCore.deleteByQuery(deleteQuery); }
Source:
<code>public Optional<String> checkValue(String value) { if (StringUtil.isNullOrEmpty(value)) { return Optional.of(Localization.lang("empty BibTeX key")); } <START> String cleaned = BibtexKeyGenerator.cleanKey(value, Globals.prefs.getUnwantedCharacters()); <END> if (cleaned.equals(value)) { return Optional.empty(); } else { return Optional.of(Localization.lang("Invalid BibTeX key")); } }</code><technical_language>Luckily, simply pass empty string integrity check warn unwanted characters. (This is I meant cryptic text other day)</technical_language>

Target:
public Optional<String> checkValue(String value) { if (StringUtil.isNullOrEmpty(value)) { return Optional.of(Localization.lang("empty BibTeX key")); } String cleaned = BibtexKeyGenerator.cleanKey(value, ""); if (cleaned.equals(value)) { return Optional.empty(); } else { return Optional.of(Localization.lang("Invalid BibTeX key")); } }
Source:
<code>private StreamLoader(long position) throws IOException { if (packOut == null) throw new IllegalStateException(DfsText.get().unexpectedEofInPack); in = packOut.out.openInputStream(position); int c = in.read(); if (c < 0) throw new IllegalStateException(DfsText.get().unexpectedEofInPack); type = (c >> 4) & 7; <START> if (type == Constants.OBJ_OFS_DELTA || type == Constants.OBJ_REF_DELTA) <END> throw new IllegalStateException(MessageFormat.format( DfsText.get().readBackDelta, Integer.toString(type))); long sz = c & 15; int shift = 4; while ((c & 0x80) != 0) { c = in.read(); if (c < 0) throw new IllegalStateException(DfsText.get().unexpectedEofInPack); sz += ((long) (c & 0x7f)) << shift; shift += 7; } size = sz; }</code><technical_language>Import a static import</technical_language>

Target:
private StreamLoader(long position) throws IOException { if (packOut == null) throw new IllegalStateException(DfsText.get().unexpectedEofInPack); in = packOut.out.openInputStream(position); int c = in.read(); if (c < 0) throw new IllegalStateException(DfsText.get().unexpectedEofInPack); type = (c >> 4) & 7; if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) throw new IllegalStateException(MessageFormat.format( DfsText.get().readBackDelta, Integer.toString(type))); long sz = c & 0x0f; int shift = 4; while ((c & 0x80) != 0) { c = in.read(); if (c < 0) throw new IllegalStateException(DfsText.get().unexpectedEofInPack); sz += ((long) (c & 0x7f)) << shift; shift += 7; } size = sz; }
Source:
<code>void _checkShrink () { if (keys == null) { if (!ignoreShrink) { int count = (int) OS.SendMessage (handle, OS.LVM_GETITEMCOUNT, 0, 0); if (count == 0 && items.length > 4) { <START> for (;count<items.length && items[count] != null && !items[count].isDisposed();count++); <END> } if (items.length > 4 && items.length - count > 3) { int length = Math.max (4, (count + 3) / 4 * 4); TableItem newItems = new TableItem [length]; System.arraycopy (items, 0, newItems, 0, count); items = newItems; } } } else { if (!ignoreShrink) { if (keys.length > 4 && keys.length - keyCount > 3) { int length = Math.max (4, (keyCount + 3) / 4 * 4); int newKeys = new int [length]; System.arraycopy (keys, 0, newKeys, 0, keyCount); keys = newKeys; TableItem newItems = new TableItem [length]; System.arraycopy (items, 0, newItems, 0, keyCount); items = newItems; } } } }</code><technical_language>logic a bit more readable of while loop below: while (count<items.length && items[count] != null && !items[count].isDisposed()) { count++; }</technical_language>

Target:
void _checkShrink () { if (keys == null) { if (!ignoreShrink) { int count = (int) OS.SendMessage (handle, OS.LVM_GETITEMCOUNT, 0, 0); if (count == 0 && items.length > 4) { while (count<items.length && items[count] != null && !items[count].isDisposed()) { count++; } } if (items.length > 4 && items.length - count > 3) { int length = Math.max (4, (count + 3) / 4 * 4); TableItem newItems = new TableItem [length]; System.arraycopy (items, 0, newItems, 0, count); items = newItems; } } } else { if (!ignoreShrink) { if (keys.length > 4 && keys.length - keyCount > 3) { int length = Math.max (4, (keyCount + 3) / 4 * 4); int newKeys = new int [length]; System.arraycopy (keys, 0, newKeys, 0, keyCount); keys = newKeys; TableItem newItems = new TableItem [length]; System.arraycopy (items, 0, newItems, 0, keyCount); items = newItems; } } } }
Source:
<code>public MergingPageOutput(Iterable<? extends Type> types, long minPageSizeInBytes, int minRowCount, int maxPageSizeInBytes) { this.types = ImmutableList.copyOf(requireNonNull(types, "types is null")); checkArgument(minPageSizeInBytes >= 0, "minPageSizeInBytes must be greater or equal than zero"); checkArgument(minRowCount >= 0, "minRowCount must be greater or equal than zero"); checkArgument(maxPageSizeInBytes > 0, "maxPageSizeInBytes must be greater than zero"); checkArgument(maxPageSizeInBytes >= minPageSizeInBytes, "maxPageSizeInBytes must be greater or equal than minPageSizeInBytes"); <START> checkArgument(minPageSizeInBytes <= 1024 * 1024, "minPageSizeInBytes must be less or equal than 1048576"); <END> this.minPageSizeInBytes = minPageSizeInBytes; this.minRowCount = minRowCount; pageBuilder = PageBuilder.withMaxPageSize(maxPageSizeInBytes, this.types); }</code><technical_language>this validates maxPageSizeInBytes >= 0, check is required</technical_language>

Target:
public MergingPageOutput(Iterable<? extends Type> types, long minPageSizeInBytes, int minRowCount, int maxPageSizeInBytes) { this.types = ImmutableList.copyOf(requireNonNull(types, "types is null")); checkArgument(minPageSizeInBytes >= 0, "minPageSizeInBytes must be greater or equal than zero"); checkArgument(minRowCount >= 0, "minRowCount must be greater or equal than zero"); checkArgument(maxPageSizeInBytes > 0, "maxPageSizeInBytes must be greater than zero"); checkArgument(maxPageSizeInBytes >= minPageSizeInBytes, "maxPageSizeInBytes must be greater or equal than minPageSizeInBytes"); checkArgument(minPageSizeInBytes <= MAX_MIN_PAGE_SIZE, "minPageSizeInBytes must be less or equal than %d", MAX_MIN_PAGE_SIZE); this.minPageSizeInBytes = minPageSizeInBytes; this.minRowCount = minRowCount; pageBuilder = PageBuilder.withMaxPageSize(maxPageSizeInBytes, this.types); }
Source:
<code>private String getWktFromGeometry(String geometry) { String wkt = getWktFromGml3(geometry); if (StringUtils.isNotBlank(wkt)) { return wkt; } <START> LOGGER.debug("Error converting gml to wkt using gml3 configuration. Trying gml2.", geometry); <END> return getWktFromGml2(geometry); }</code><technical_language>missing for parameter</technical_language>

Target:
private String getWktFromGeometry(String geometry) { String wkt = getWktFromGml3(geometry); if (StringUtils.isNotBlank(wkt)) { return wkt; } LOGGER.debug("Error converting gml to wkt using gml3 configuration. Trying gml2."); return getWktFromGml2(geometry); }
Source:
<code>private static long getUnsignedLongValue(String bits){ long value = 0; int i = 0; for (int j = bits.length() - 1; j >= 0; j--, i++) { if (bits.charAt(j) == '1') { <START> value += (long) Math.pow(2.0, (double) i); <END> } } return value; }</code><technical_language>here, please 1 << i</technical_language>

Target:
private static long getUnsignedLongValue(String bits){ long value = 0; int i = 0; for (int j = bits.length() - 1; j >= 0; j--, i++) { if (bits.charAt(j) == '1') { value += 1L << i; } } return value; }
Source:
<code>public int read(byte[] dest, int off, int siz) throws IOException { checkClosed(); if (siz == 0) { return 0; } int bytesRead = 0; while (bytesRead < siz && isBufAvailable()) { final int toCopy = Math.min(siz - bytesRead, len - curPosition); <START> System.arraycopy(this.bytes, curPosition, bytes, off + bytesRead, toCopy); <END> bytesRead += toCopy; curPosition += toCopy; } return bytesRead > 0 ? bytesRead : -1; }</code><technical_language>System.arraycopy(this.bytes, curPosition, **dest,** + bytesRead, toCopy)</technical_language>

Target:
public int read(byte[] dest, int off, int siz) throws IOException { checkClosed(); if (siz == 0) { return 0; } int bytesRead = 0; while (bytesRead < siz && isBufAvailable()) { final int toCopy = Math.min(siz - bytesRead, len - curPosition); System.arraycopy(this.bytes, curPosition, dest, off + bytesRead, toCopy); bytesRead += toCopy; curPosition += toCopy; } return bytesRead > 0 ? bytesRead : -1; }
Source:
<code>public void testDefaultNormalizerTwice() { String[] testSentence = new String[] {"a", "b", "c", "d", "e", "f", "g", "h"}; <START> TokenNormalizerFeatureGenerator featureGenerator = <END> new TokenNormalizerFeatureGenerator(new IdentityFeatureGenerator()); for (int i = 0; i < testSentence.length; i++) { featureGenerator.createFeatures(features, testSentence, i, null); Assert.assertEquals(features.get(i), testSentence[i]); } testSentence = new String[] {"i", "j", "l", "m", "n", "o", "p", "q"}; features = new ArrayList<>(); for (int i = 0; i < testSentence.length; i++) { featureGenerator.createFeatures(features, testSentence, i, null); Assert.assertEquals(features.get(i), testSentence[i]); } }</code><technical_language>Indentation issue - minor nitpick</technical_language>

Target:
public void testDefaultNormalizerTwice() { String[] testSentence = new String[] {"a", "b", "c", "d", "e", "f", "g", "h"}; TokenNormalizerFeatureGenerator featureGenerator = new TokenNormalizerFeatureGenerator(new IdentityFeatureGenerator()); List<String> features = new ArrayList<>(); for (int i = 0; i < testSentence.length; i++) { featureGenerator.createFeatures(features, testSentence, i, null); Assert.assertEquals(features.get(i), testSentence[i]); } testSentence = new String[] {"i", "j", "l", "m", "n", "o", "p", "q"}; features = new ArrayList<>(); for (int i = 0; i < testSentence.length; i++) { featureGenerator.createFeatures(features, testSentence, i, null); Assert.assertEquals(features.get(i), testSentence[i]); } }
Source:
<code>public void testNoNotifyOnSavepoint() throws IOException { TestBufferReceivedListener listener = new TestBufferReceivedListener(); <START> LocalInputChannel channel = new LocalInputChannel( new SingleInputGateBuilder().build(), 0, new ResultPartitionID(), new ResultPartitionManager(), new TaskEventDispatcher(), new TestCounter(), new TestCounter()); <END> CheckpointBarrier barrier = new CheckpointBarrier(123L, 123L, new CheckpointOptions(SAVEPOINT, CheckpointStorageLocationReference.getDefault())); channel.notifyPriorityEvent(new BufferConsumer(toBuffer(barrier).getMemorySegment(), FreeingBufferRecycler.INSTANCE, getDataType(barrier))); channel.checkError(); assertTrue(listener.notifiedOnBarriers.isEmpty()); }</code><technical_language>nit: InputChannelBuilder .newBuilder() .buildLocalChannel(new SingleInputGateBuilder().build())</technical_language>

Target:
public void testNoNotifyOnSavepoint() throws IOException { TestBufferReceivedListener listener = new TestBufferReceivedListener(); SingleInputGate inputGate = new SingleInputGateBuilder().build(); inputGate.registerBufferReceivedListener(listener); LocalInputChannel channel = InputChannelBuilder.newBuilder().buildLocalChannel(inputGate); CheckpointBarrier barrier = new CheckpointBarrier(123L, 123L, new CheckpointOptions(SAVEPOINT, CheckpointStorageLocationReference.getDefault())); channel.notifyPriorityEvent(new BufferConsumer(toBuffer(barrier).getMemorySegment(), FreeingBufferRecycler.INSTANCE, getDataType(barrier))); channel.checkError(); assertTrue(listener.notifiedOnBarriers.isEmpty()); }
Source:
<code>public void authenticate(String username, final String password, final AsyncCallback<LoginResult> callback) { LoginResult result = new LoginResult(); if (username == null || "".equals(username) || password == null || "".equals(password)) { result.success = false; callback.onSuccess(result); return; } <START> username = username.trim().toLowerCase(); <END> final AuthRequest req = AuthRequest.forUser(username); req.setPassword(password); final AuthResult res; try { res = accountManager.authenticate(req); } catch (AccountException e) { result.success = false; callback.onSuccess(result); return; } result.success = true; result.isNew = res.isNew(); webSession.get().login(res, false); callback.onSuccess(result); }</code><technical_language>do this test for empty string, in case input username foolishly " ". Also, do want lowercase everything? Some existing databases lowercased lowercasing users create new duplicate accounts. need a schema upgrade force records lowercase, need a configuration flag enables lowercasing behavior</technical_language>

Target:
public void authenticate(String username, final String password, final AsyncCallback<LoginResult> callback) { LoginResult result = new LoginResult(); if (username == null || "".equals(username.trim()) || password == null || "".equals(password)) { result.success = false; callback.onSuccess(result); return; } username = username.trim(); final AuthRequest req = AuthRequest.forUser(username); req.setPassword(password); final AuthResult res; try { res = accountManager.authenticate(req); } catch (AccountException e) { result.success = false; callback.onSuccess(result); return; } result.success = true; result.isNew = res.isNew(); webSession.get().login(res, false); callback.onSuccess(result); }
Source:
<code>public int compareTo(final AESharedItemStack b) { Preconditions.checkState(this.itemStack.getCount() == 1, "ItemStack#getCount() has to be 1"); Preconditions.checkArgument(b.getDefinition().getCount() == 1, "ItemStack#getCount() has to be 1"); if (this.itemStack == b.getDefinition()) { return 0; } final int id = this.itemId - b.itemId; if (id != 0) { return id; } final int damageValue = this.itemDamage - b.itemDamage; if (damageValue != 0) { return damageValue; } <START> return this.hashCode - b.hashCode; <END> }</code><technical_language>This is intended a stopgap I presume hashCode is _guaranteed_ unique, right</technical_language>

Target:
public int compareTo(final AESharedItemStack b) { Preconditions.checkState(this.itemStack.getCount() == 1, "ItemStack#getCount() has to be 1"); Preconditions.checkArgument(b.getDefinition().getCount() == 1, "ItemStack#getCount() has to be 1"); if (this.itemStack == b.getDefinition()) { return 0; } final int id = this.itemId - b.itemId; if (id != 0) { return id; } final int damageValue = this.itemDamage - b.itemDamage; if (damageValue != 0) { return damageValue; } return System.identityHashCode(this.getDefinition().getTag()) - System.identityHashCode(b.getDefinition().getTag()); }
Source:
<code>public void updateOrderFulfillerStatus_shouldEditFulfillerStatusWithAccessioNumberInOrder() { Order originalOrder = orderService.getOrder(111); String commentText = "We got the new order"; String accessionNumber = "12345"; <START> assertNotEquals(originalOrder.getAccessionNumber(), 0); <END> orderService.updateOrderFulfillerStatus(originalOrder, Order.FulfillerStatus.IN_PROGRESS, commentText, accessionNumber); Order updatedOrder = orderService.getOrder(111); assertEquals(updatedOrder.getAccessionNumber(), accessionNumber); }</code><technical_language>Minor point, testing accession number is "12345"</technical_language>

Target:
public void updateOrderFulfillerStatus_shouldEditFulfillerStatusWithAccessioNumberInOrder() { Order originalOrder = orderService.getOrder(111); String commentText = "We got the new order"; String accessionNumber = "12345"; assertNotEquals(originalOrder.getAccessionNumber(), accessionNumber); orderService.updateOrderFulfillerStatus(originalOrder, Order.FulfillerStatus.IN_PROGRESS, commentText, accessionNumber); Order updatedOrder = orderService.getOrder(111); assertEquals(updatedOrder.getAccessionNumber(), accessionNumber); }
Source:
<code>public boolean selectionExists(ISelector selector) { <START> return (Boolean) <END> this.browser.syncRun(String.format("return %s.length > 0;", selector.getStatement())); }</code><technical_language>returned Java this.browser.syncRun(String.format("return %s.length > 0;", selector.getStatement())) null? If this is case, need a nullcheck returning implicit unboxing needed convert returned Boolean a boolean (which is actual return type of method) throw a NPE if is null</technical_language>

Target:
public boolean selectionExists(ISelector selector) { Boolean result = (Boolean) this.browser.syncRun(String.format("return %s.length > 0;", selector.getStatement())); return result != null && result; }
Source:
<code>public String toString() { if (type == TransitionType.RULE) { Attributes a = rule.getAttributes(); <START> UnparserFilter unparser = new UnparserFilter(true, context.colorOptions.color(context.krunOptions.experimental.outputFile != null), context.krunOptions.output, context); <END> unparser.visitNode(a); return "\nRule tagged " + unparser.getResult() + " "; } else if (type == TransitionType.LABEL) { return "\nRule labelled " + label + " "; } else if (type == TransitionType.REDUCE) { return "\nMaude 'reduce' command "; } else if (type == TransitionType.UNLABELLED) { return "\nUnlabelled rule "; } else if (type == TransitionType.DEADLOCK) { return "\nDeadlock "; } else { return "\nRead " + StringBuiltin.of(readString).value(); } }</code><technical_language>a bit confused this part. Jansi handle output stream's color support. Do need pass redirection info color class? Also, this work in general. Currently --output-file argument if output is redirected pipes etc. ? Jansi handles too</technical_language>

Target:
public String toString() { if (type == TransitionType.RULE) { Attributes a = rule.getAttributes(); UnparserFilter unparser = new UnparserFilter(true, context.colorOptions.color(), context.krunOptions.output, context); unparser.visitNode(a); return "\nRule tagged " + unparser.getResult() + " "; } else if (type == TransitionType.LABEL) { return "\nRule labelled " + label + " "; } else if (type == TransitionType.REDUCE) { return "\nMaude 'reduce' command "; } else if (type == TransitionType.UNLABELLED) { return "\nUnlabelled rule "; } else if (type == TransitionType.DEADLOCK) { return "\nDeadlock "; } else { return "\nRead " + StringBuiltin.of(readString).value(); } }
Source:
<code>public void deactivateUser(HttpServletRequest request, HttpServletResponse response, @PathVariable String uid) throws IOException { <START> ResponseWriter writer = null; <END> try { User editingUser = userFetcher.userFor(request).get(); if (!editingUser.is(Role.ADMIN)) { throw new ResourceForbiddenException(); } Id userId = Id.valueOf(idCodec.decode(uid)); Optional<User> user = userStore.userForId(userId); if (user.isPresent()) { UserRef userRef = user.get().getUserRef(); Credentials credentialsMaybe = credentialsStore.find(userRef).requireValue(); Credentials credentials = credentialsMaybe; credentialsStore.expired(credentials.authToken()); } else { throw new NotFoundException(userId); } } catch (Exception e) { log.error("Request exception " + request.getRequestURI(), e); ErrorSummary summary = ErrorSummary.forException(e); new ErrorResultWriter().write(summary, writer, request, response); } }</code><technical_language>This is unused, it</technical_language>

Target:
public void deactivateUser(HttpServletRequest request, HttpServletResponse response, @PathVariable String uid) throws IOException { ResponseWriter writer = null; try { User editingUser = userFetcher.userFor(request).get(); if (!editingUser.is(Role.ADMIN)) { throw new ResourceForbiddenException(); } Id userId = Id.valueOf(idCodec.decode(uid)); Optional<User> user = userStore.userForId(userId); if (user.isPresent()) { UserRef userRef = user.get().getUserRef(); Credentials credentials = credentialsStore.find(userRef).requireValue(); credentialsStore.expired(credentials.authToken()); } else { throw new NotFoundException(userId); } } catch (Exception e) { log.error("Request exception " + request.getRequestURI(), e); ErrorSummary summary = ErrorSummary.forException(e); new ErrorResultWriter().write(summary, writer, request, response); } }
Source:
<code>public void subscribe(@Context SseEventSink sink) throws IOException { synchronized (outputLock) { if (sink == null) { throw new IllegalStateException("No client connected."); <START> } <END> } eventSink = sink; if (sseBroadcaster == null) { sseBroadcaster = sse.newBroadcaster(); } sseBroadcaster.register(sink); }</code><technical_language>So, line (eventSink = sink;) is a bug fix, stores a reference sink in resource, allowing close() method do something. Nice catch</technical_language>

Target:
public void subscribe(@Context SseEventSink sink) throws IOException { if (sink == null) { throw new IllegalStateException("No client connected."); } eventSink = sink; if (sseBroadcaster == null) { sseBroadcaster = sse.newBroadcaster(); } sseBroadcaster.register(sink); }
Source:
<code>public boolean same() { boolean same; final String mine = Manifests.read("Rultor-Revision"); try { final String base; try { base = new JdkRequest( <START> URI.create("<LINK_0>") <END> ) .method(Request.GET) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .body(); } catch (IOException ex) { throw new IllegalStateException(ex); } if (mine.equals(base) || !base.matches("[a-f0-9]+")) { same = true; } else { same = false; Logger.info( Main.class, "#same(): we're in %s while %s is the newest one", mine, base ); } } catch (AssertionError ex) { Logger.warn(Main.class, "#same(): %s", ex); same = true; } return same; }</code><technical_language>need convert URI, String is enough for JdkRequest</technical_language>

Target:
public boolean same() { boolean same; final String mine = Manifests.read("Rultor-Revision"); try { final String base; try { base = new JdkRequest("<LINK_0>") .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .body(); } catch (IOException ex) { throw new IllegalStateException(ex); } if (mine.equals(base) || !base.matches("[a-f0-9]+")) { same = true; } else { same = false; Logger.info( Main.class, "#same(): we're in %s while %s is the newest one", mine, base ); } } catch (AssertionError ex) { Logger.warn(Main.class, "#same(): %s", ex); same = true; } return same; }
Source:
<code>private String decodeAlarm(String event) { if (event.equals('Z')) { return Position.ALARM_LOW_BATTERY; } else if (event.equals('X')) { return Position.ALARM_GEOFENCE_ENTER; } else if (event.equals('T')) { return Position.ALARM_TAMPERING; } else if (event.equals("H")) { return Position.ALARM_POWER_OFF; } else if (event.equals('X')) { return Position.ALARM_GEOFENCE_ENTER; } else if (event.equals('8')) { return Position.ALARM_SHOCK; <START> } else if (event.equals('7') && event.equals('4')) { <END> return Position.ALARM_GEOFENCE_EXIT; } else if (event.equals('6')) { return Position.ALARM_OVERSPEED; } else if (event.equals('3')) { return Position.ALARM_SOS; } return null; }</code><technical_language>This false? mean</technical_language>

Target:
private String decodeAlarm(String event) { switch (event) { case "Z": return Position.ALARM_LOW_BATTERY; case "X": return Position.ALARM_GEOFENCE_ENTER; case "T": return Position.ALARM_TAMPERING; case "H": return Position.ALARM_POWER_OFF; case "8": return Position.ALARM_SHOCK; case "7": case "4": return Position.ALARM_GEOFENCE_EXIT; case "6": return Position.ALARM_OVERSPEED; case "3": return Position.ALARM_SOS; default: return null; } }
Source:
<code>private void validateModel(BpmnModel model) throws Exception { FlowElement flowElement = model.getMainProcess().getFlowElement("Task_17unmd8"); <START> assertNotNull(flowElement); <END> assertTrue(flowElement instanceof Task); checkXml(model); }</code><technical_language>User AssertJ assertions</technical_language>

Target:
private void validateModel(BpmnModel model) throws Exception { FlowElement flowElement = model.getMainProcess().getFlowElement("Task_17unmd8"); assertThat(flowElement).isNotNull(); assertThat(flowElement instanceof Task).isTrue(); checkXml(model); }
Source:
<code>public void run() { switch (filterManager.getCurrentSynchronizationBehavior()) { case ASK_EACH_TIME: SynchronizerDialog dialog = new SynchronizerDialog(shell, EMFCompareRCPUIMessages .getString("FilterAction.SYNCHRONIZATION_DIALOG_TITLE"), EMFCompareRCPUIMessages.getString("FilterAction.SYNCHRONIZATION_DIALOG_MESSAGE"), EMFCompareRCPUIMessages .getString("FilterAction.SYNCHRONIZATION_DIALOG_TOGGLE_MESSAGE")); dialog.open(); <START> if (dialog.synchronize()) { <END> setSelectedGroupAsDefault(isChecked()); } SynchronizationBehavior synchronizationBehavior = dialog.getSynchronizationBehavior(); filterManager.setCurrentSynchronizationBehavior(synchronizationBehavior); break; case ALWAYS: setSelectedGroupAsDefault(isChecked()); break; case NEVER: break; default: EMFCompareRCPUIPlugin.getDefault().log(IStatus.WARNING, "Unhandle case for syncrhonization filter behavior preference value"); break; } }</code><technical_language>replace "dialog.synchronize()" "dialog.getReturnCode() == IDialogConstants.OK_ID"</technical_language>

Target:
public void run() { MessageDialogWithToggle dialog = new SynchronizerDialog(shell, EMFCompareRCPUIMessages .getString("FilterAction.synchronization.dialog.title"), EMFCompareRCPUIMessages.getString("FilterAction.synchronization.dialog.message"), EMFCompareRCPUIMessages.getString("FilterAction.synchronization.dialog.toggle.message")); dialog.setPrefKey(FiltersPreferencePage.SYNCHRONIZATION_BEHAVIOR); dialog.setPrefStore(new ScopedPreferenceStore(new InstanceScope(), EMFCompareRCPUIPlugin.PLUGIN_ID)); if (dialog.open() == IDialogConstants.YES_ID) { setSelectedGroupAsDefault(isChecked()); } }
Source:
<code>private boolean isChannelPubSub(String channelName) { <START> return channelName != null <END> && (channelName.startsWith(TAP_CHANNEL_PREFIX) || channelName.startsWith(TOPIC_CHANNEL_PREFIX)); }</code><technical_language>null check done caller (if all). Currently, a null trigger else() branch of if()</technical_language>

Target:
private boolean isChannelPubSub(String channelName) { Assert.isTrue(StringUtils.hasText(channelName), "Channel name should not be empty/null."); return (channelName.startsWith(TAP_CHANNEL_PREFIX) || channelName.startsWith(TOPIC_CHANNEL_PREFIX)); }
Source:
<code>public void writeTo(WritableByteChannel channel) throws IOException { if (bufferToSend == null) { bufferToSend = ByteBuffer.allocate((int) sizeInBytes()); writeHeader(); bufferToSend.putShort((short) flags.ordinal()); bufferToSend.putLong(partition); bufferToSend.putInt(ids.size()); for (BlobId id : ids) { ByteBuffer buf = id.toBytes(); <START> bufferToSend.putShort((short)id.sizeInBytes()); <END> bufferToSend.put(buf.array()); } bufferToSend.flip(); } if (bufferToSend.remaining() > 0) { int written = channel.write(bufferToSend); sizeSent += written; } }</code><technical_language>checked casts. need implement verifies range casting, Guava: bufferToSend.putShort(Shorts.checkedCast(id.sizeInBytes())); Guava is Java Boost is C++ in mind silly advantage of utilities Guava offers do cleaner, safer Java code</technical_language>

Target:
public void writeTo(WritableByteChannel channel) throws IOException { if (bufferToSend == null) { bufferToSend = ByteBuffer.allocate((int) sizeInBytes()); writeHeader(); bufferToSend.putShort((short) flags.ordinal()); bufferToSend.putLong(partitionId); bufferToSend.putInt(ids.size()); for (BlobId id : ids) { ByteBuffer buf = id.toBytes(); bufferToSend.putShort(id.sizeInBytes()); bufferToSend.put(buf.array()); } bufferToSend.flip(); } if (bufferToSend.remaining() > 0) { int written = channel.write(bufferToSend); sizeSent += written; } }
Source:
<code>private static String toHex(byte[] digest) { <START> return DatatypeConverter.printHexBinary(digest); <END> }</code><technical_language>javax.xml.bind disappear JDK soon enough :-)</technical_language>

Target:
protected static String toHex(byte[] digest) { char[] result = new char[digest.length * 2]; for (int i = 0; i < digest.length; i++) { toChars(digest[i], result, i * 2); } return new String(result); }
Source:
<code>public String getMimeType() { switch (imageProfileInt) { case GIF_LRG_INT: return "image/gif"; case JPEG_LRG_INT: case JPEG_MED_INT: case JPEG_RES_H_V_INT: case JPEG_SM_INT: case JPEG_TN_INT: return "image/jpeg"; case PNG_LRG_INT: case PNG_TN_INT: return "image/png"; } <START> return "image/unknown"; <END> }</code><technical_language>@Sami32 I "made up" supposed happen. values listed above, possibility code get is if a new profile is added this switch updated. Ideally fail if happens, easily detected. I put first, Java compiler requires a return for "all potential paths" I error it. I added it, thinking used. Thinking now, throw exception if code there, easier pick fill in correct mime type for profile</technical_language>

Target:
public String getMimeType() { switch (getFormat()) { case GIF: return "image/gif"; case JPEG: return "image/jpeg"; case PNG: return "image/png"; default: throw new IllegalStateException("Format is missing from switch statement"); } }
Source:
<code>public void processTimer(ComputationContext context, String key, long timestamp) { if (!TIMER_BATCH.equals(key) || batchRecords.isEmpty()) { <START> return; <END> } processBatch(context); context.setTimer(TIMER_BATCH, System.currentTimeMillis() + thresholdMillis); }</code><technical_language>need set timer if batchRecords is empty</technical_language>

Target:
public void processTimer(ComputationContext context, String key, long timestamp) { if (!TIMER_BATCH.equals(key)) { return; } if (! batchRecords.isEmpty()) { processBatch(context); } context.setTimer(TIMER_BATCH, System.currentTimeMillis() + thresholdMillis); }
Source:
<code>public void onCreate() { super.onCreate(); Thread.setDefaultUncaughtExceptionHandler(new CrashReportWriter()); if(BuildConfig.DEBUG) { StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .penaltyLog() .penaltyDropBox(); if (Build.VERSION.SDK_INT >= 11) { builder.detectActivityLeaks(); builder.detectLeakedClosableObjects(); } if(Build.VERSION.SDK_INT >= 16) { builder.detectLeakedRegistrationObjects(); } StrictMode.setVmPolicy(builder.build()); } singleton = this; PodDBAdapter.init(this); UpdateManager.init(this); UserPreferences.init(this); PlaybackPreferences.init(this); NetworkUtils.init(this); EventDistributor.getInstance(); Iconify.with(new FontAwesomeModule()); SPAUtil.sendSPAppsQueryFeedsIntent(this); <START> throw new NullPointerException(); <END> }</code><technical_language>pretty want this in here..</technical_language>

Target:
public void onCreate() { super.onCreate(); Thread.setDefaultUncaughtExceptionHandler(new CrashReportWriter()); if(BuildConfig.DEBUG) { StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .penaltyLog() .penaltyDropBox(); if (Build.VERSION.SDK_INT >= 11) { builder.detectActivityLeaks(); builder.detectLeakedClosableObjects(); } if(Build.VERSION.SDK_INT >= 16) { builder.detectLeakedRegistrationObjects(); } StrictMode.setVmPolicy(builder.build()); } singleton = this; PodDBAdapter.init(this); UpdateManager.init(this); UserPreferences.init(this); PlaybackPreferences.init(this); NetworkUtils.init(this); EventDistributor.getInstance(); Iconify.with(new FontAwesomeModule()); SPAUtil.sendSPAppsQueryFeedsIntent(this); }
Source:
<code>protected void acquire(TransactionLocks locks) throws IOException { setLockMode(lockType); Set<String> hldrs = new HashSet<>(); if (leaseHolder != null && singleFileLock == null) { hldrs.add(leaseHolder); } else if (leaseHolder != null && singleFileLock != null) { <START> Lease lease = acquireLock(lockType, Lease.Finder.ByHolder, leaseHolder, Lease.getHolderId(leaseHolder)); <END> if (lease != null) { singleFileLease = lease; } } if (locks.containsLock(Type.INode)) { BaseINodeLock inodeLock = (BaseINodeLock) locks.getLock(Type.INode); for (INode f : inodeLock.getAllResolvedINodes()) { if ((f instanceof INodeFile) && f.isUnderConstruction()) { hldrs.add(((INodeFile) f).getFileUnderConstructionFeature().getClientName()); } } } List<String> holders = new ArrayList<>(hldrs); Collections.sort(holders); if(holders.isEmpty() && !locks.containsLock(Type.INode)){ Collection<Lease> allLeases = acquireLockList(lockType, Lease.Finder.All); if (leases != null) { leases.addAll(allLeases); } } for (String h : holders) { Lease lease = acquireLock(lockType, Lease.Finder.ByHolder, h, Lease.getHolderId(h)); if (lease != null) { leases.add(lease); } } }</code><technical_language>explain problem this is solving? jira tel leases</technical_language>

Target:
protected void acquire(TransactionLocks locks) throws IOException { setLockMode(lockType); Set<String> hldrs = new HashSet<>(); if (leaseHolder != null) { hldrs.add(leaseHolder); } if (locks.containsLock(Type.INode)) { BaseINodeLock inodeLock = (BaseINodeLock) locks.getLock(Type.INode); for (INode f : inodeLock.getAllResolvedINodes()) { if ((f instanceof INodeFile) && f.isUnderConstruction()) { hldrs.add(((INodeFile) f).getFileUnderConstructionFeature().getClientName()); } } } List<String> holders = new ArrayList<>(hldrs); Collections.sort(holders); if (holders.isEmpty() && !locks.containsLock(Type.INode)) { Collection<Lease> allLeases = acquireLockList(lockType, Lease.Finder.All); if (leases != null) { leases.addAll(allLeases); } } for (String h : holders) { Lease lease = acquireLock(lockType, Lease.Finder.ByHolder, h, Lease.getHolderId(h)); if (lease != null) { leases.add(lease); } } }
Source:
<code>public void should_replace_classpath_in_arquillian_xml() throws Exception { final String xml = desc.get().exportAsString(); <START> System.out.println(xml); <END> AssertXPath.assertXPath(xml, "/arquillian/container/@qualifier", VALUE_EL_OVERRIDE); final URL resource = Thread.currentThread().getContextClassLoader().getResource("arquillian_sysprop.xml"); assertXPath(xml, "/arquillian/container/configuration/property", String.format("-Djavax.net.ssl.trustStore=%s", resource.toString())); }</code><technical_language>is system out necessary</technical_language>

Target:
public void should_replace_classpath_in_arquillian_xml() throws Exception { final String xml = desc.get().exportAsString(); AssertXPath.assertXPath(xml, "/arquillian/container/@qualifier", VALUE_EL_OVERRIDE); final URL resource = Thread.currentThread().getContextClassLoader().getResource("arquillian_sysprop.xml"); assertXPath(xml, "/arquillian/container/configuration/property", String.format("-Djavax.net.ssl.trustStore=%s", resource.toString())); }
Source:
<code>public void run() { <START> DateTime fiveMinutesAgo = DateTime.now().minusSeconds(DEAD_CONNECTION_INTERVAL_SECONDS); <END> if (lastHeartbeat.isBefore(fiveMinutesAgo) && es.getState() == ReadyState.OPEN) { try { logger.info("Stream stopped receiving heartbeats- reconnecting."); es.close(); start(); } catch (IOException e) { logger.warn("Encountered exception closing stream connection: " + e.getMessage()); } } }</code><technical_language>rename fiveMinutesAgo reconnectThresholdTime else tied of constant</technical_language>

Target:
public void run() { DateTime reconnectThresholdTime = DateTime.now().minusSeconds(DEAD_CONNECTION_INTERVAL_SECONDS); if (lastHeartbeat.isBefore(reconnectThresholdTime) && es.getState() == ReadyState.OPEN) { try { logger.info("Stream stopped receiving heartbeats- reconnecting."); es.close(); } catch (IOException e) { logger.error("Encountered exception closing stream connection: " + e.getMessage()); } finally { if (es.getState() == ReadyState.SHUTDOWN) { start(); } else { logger.error("Expected ES to be in state SHUTDOWN, but it's currently in state " + es.getState().toString()); } } } }
Source:
<code>public static <E> boolean isEqualCollection(final Collection<? extends E> a, final Collection<? extends E> b, final Equator<? super E> equator) { <START> if(a == null && b == null) { <END> return true; } if(a == null || b == null) { return false; } if (equator == null) { throw new NullPointerException("Equator must not be null."); } if(a.size() != b.size()) { return false; } @SuppressWarnings({ "unchecked", "rawtypes" }) final Transformer<E, ?> transformer = new Transformer() { @Override public EquatorWrapper<?> transform(final Object input) { return new EquatorWrapper(equator, input); } }; return isEqualCollection(collect(a, transformer), collect(b, transformer)); }</code><technical_language>instead of repeating checks here, remove .size() checks, leaving checked call overloaded isEqualCollection</technical_language>

Target:
public static <E> boolean isEqualCollection(final Collection<? extends E> a, final Collection<? extends E> b, final Equator<? super E> equator) { if (equator == null) { throw new NullPointerException("Equator must not be null."); } @SuppressWarnings({ "unchecked", "rawtypes" }) final Transformer<E, ?> transformer = new Transformer() { @Override public EquatorWrapper<?> transform(final Object input) { return new EquatorWrapper(equator, input); } }; return isEqualCollection(collect(a, transformer), collect(b, transformer)); }
Source:
<code>public LzoProtobufBlockScheme(Class protoClass) { <START> super(protoClass); <END> }</code><technical_language>I confused. deprecated top.</technical_language>

Target:
public LzoProtobufBlockScheme(Class protoClass) { super(protoClass); LOG.warn("LzoProtobufBlockScheme is deprecated, please use LzoProtobufScheme"); }