auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public String setLabel(String entityId, String type, String label, String language) throws RetryableException { String datatype = type.equals("property") ? "string" : null; EditRequest data = new EditRequest( datatype, ImmutableMap.of( <START> "en", <END> new Label( language, label + System.currentTimeMillis()))); try { URI uri = uris.edit(entityId, type, mapper.writeValueAsString(data)); log.debug("Editing entity using {}", uri); EditResponse result = checkApi(getJson(postWithToken(uri), EditResponse.class)); return result.getEntity().getId(); } catch (IOException e) { throw new RetryableException("Error adding page", e); } }</code><technical_language>I "en" is a bug here, "language"</technical_language>

Target:
public String setLabel(String entityId, String type, String label, String language) throws RetryableException { String datatype = type.equals("property") ? "string" : null; EditRequest data = new EditRequest( datatype, ImmutableMap.of( language, new Label(language, label))); try { URI uri = uris.edit(entityId, type, mapper.writeValueAsString(data)); log.debug("Editing entity using {}", uri); EditResponse result = checkApi(getJson(postWithToken(uri), EditResponse.class)); return result.getEntity().getId(); } catch (IOException e) { throw new RetryableException("Error adding page", e); } }
Source:
<code>private Optional<JavaFileScannerContext.Location> flowFromCaughtException(ExplodedGraph.Edge edge) { ProgramPoint programPoint = edge.parent.programPoint; if (((CFG.Block) programPoint.block).isCatchBlock() && programPoint.i == 0) { VariableTree catchVariable = ((VariableTree) programPoint.syntaxTree()); SymbolicValue.CaughtExceptionSymbolicValue caughtSv = ((SymbolicValue.CaughtExceptionSymbolicValue) edge.child.programState.getValue(catchVariable.symbol())); Type exceptionType = caughtSv.exception().exceptionType(); <START> return Optional.of(location(edge.parent, String.format("%s is caught.", exceptionName(exceptionType)))); <END> } return Optional.empty(); }</code><technical_language>I add a Precondition enforce non-null is expected</technical_language>

Target:
private Optional<JavaFileScannerContext.Location> flowFromCaughtException(ExplodedGraph.Edge edge) { ProgramPoint programPoint = edge.parent.programPoint; if (((CFG.Block) programPoint.block).isCatchBlock() && programPoint.i == 0) { VariableTree catchVariable = ((VariableTree) programPoint.syntaxTree()); SymbolicValue.CaughtExceptionSymbolicValue caughtSv = ((SymbolicValue.CaughtExceptionSymbolicValue) edge.child.programState.getValue(catchVariable.symbol())); Preconditions.checkNotNull(caughtSv, "Caught exception not found in program state"); Type exceptionType = caughtSv.exception().exceptionType(); return Optional.of(location(edge.parent, String.format("%s is caught.", exceptionName(exceptionType)))); } return Optional.empty(); }
Source:
<code><START> Graphics() { <END> init0(Font.getDefaultFont()); }</code><technical_language>I constructor "nativized" (see for example, string.js)</technical_language>

Target:
Graphics() { }
Source:
<code>public Object[] deserialize(InputStream inputStream, ResourceMethod method) { <START> Method jMethod = getJMethod(method); <END> Class<?>[] types = getTypes(method); if (types.length == 0) { throw new IllegalArgumentException( "Methods that consumes representations must receive just one argument"); } Gson gson = getGson(); Object[] params = new Object[types.length]; String[] parameterNames = paramNameProvider.parameterNamesFor(jMethod); try { String content = getContentOfStream(inputStream); logger.debug("json retrieved: {}", content); JsonParser parser = new JsonParser(); JsonObject root = (JsonObject) parser.parse(content); for (int i = 0; i < types.length; i++) { String name = parameterNames[i]; JsonElement node = root.get(name); if (isWithoutRoot(types, node)) { params[i] = gson.fromJson(root, types[i]); logger.info("json without root deserialized"); } else if(node != null){ params[i] = gson.fromJson(node, types[i]); } logger.debug("json deserialized: {}", params[i]); } } catch (Exception e) { throw new ResultException("Unable to deserialize data", e); } return params; }</code><technical_language>method.getMethod() is clear. need extract this method. Please get method.getMethod()</technical_language>

Target:
public Object[] deserialize(InputStream inputStream, ResourceMethod method) { Method jMethod = method.getMethod(); Class<?>[] types = getTypes(method); if (types.length == 0) { throw new IllegalArgumentException( "Methods that consumes representations must receive just one argument"); } Gson gson = getGson(); Object[] params = new Object[types.length]; String[] parameterNames = paramNameProvider.parameterNamesFor(jMethod); try { String content = getContentOfStream(inputStream); logger.debug("json retrieved: {}", content); JsonParser parser = new JsonParser(); JsonObject root = (JsonObject) parser.parse(content); for (int i = 0; i < types.length; i++) { String name = parameterNames[i]; JsonElement node = root.get(name); if (isWithoutRoot(types, node)) { params[i] = gson.fromJson(root, types[i]); logger.info("json without root deserialized"); } else if(node != null){ params[i] = gson.fromJson(node, types[i]); } logger.debug("json deserialized: {}", params[i]); } } catch (Exception e) { throw new ResultException("Unable to deserialize data", e); } return params; }
Source:
<code>public void testMigrationIsNeededOnData() { Version <START> diagramSplitVersion = <END> DRepresentationContainerToDViewMigrationParticipant.MIGRATION_VERSION; URI uri = URI.createPlatformPluginURI(SiriusTestsPlugin.PLUGIN_ID + PATH + SESSION_RESOURCE_NAME, true); Version loadedVersion = checkRepresentationFileMigrationStatus(uri, true); assertTrue("The list migration must be required on test data.", diagramSplitVersion.compareTo(loadedVersion) > 0); checkFileContainsDRepresentationContainer(uri, true, "Test data should contain a DRepresentationContainer."); }</code><technical_language>Is this name a copy/pasted test diagram split work</technical_language>

Target:
public void testMigrationIsNeededOnData() { Version dRepresentationContainerRemovalVersion = DRepresentationContainerToDViewMigrationParticipant.MIGRATION_VERSION; URI uri = URI.createPlatformPluginURI(SiriusTestsPlugin.PLUGIN_ID + PATH + SESSION_RESOURCE_NAME, true); Version loadedVersion = checkRepresentationFileMigrationStatus(uri, true); assertTrue("The DRepresentationContainer removal migration must be required on test data.", dRepresentationContainerRemovalVersion.compareTo(loadedVersion) > 0); checkFileContainsDRepresentationContainer(uri, true, "Test data should contain a DRepresentationContainer."); }
Source:
<code>public Map<Long, ILogData> read(Iterable<Long> addresses, @NonNull ReadOptions options) { if (!options.isClientCacheable()) { <START> return fetchAll(addresses, options); <END> } final Map<Long, ILogData> cachedData = readCache.getAllPresent(addresses); final Set<Long> addressesToFetch = Sets.difference( Sets.newHashSet(addresses), cachedData.keySet()); final Map<Long, ILogData> uncachedData = fetchAll(addressesToFetch, options); final List<Long> trimmedAddresses = filterTrimmedAddresses(uncachedData, options); trimmedAddresses.forEach(uncachedData::remove); final Map<Long, ILogData> result = uncachedData.entrySet().stream() .collect(Collectors.toMap(Entry::getKey, entry -> cacheLoadAndGet(readCache, entry.getKey(), entry.getValue(), options))); result.putAll(cachedData); if (!trimmedAddresses.isEmpty()) { if (!options.isIgnoreTrim()) { throw new TrimmedException(trimmedAddresses); } log.warn("read: ignoring trimmed addresses {}", trimmedAddresses); } return result; }</code><technical_language>In refactoring lost check for trimmed addresses, meaning that, in event of cache disable throw trimmed exceptions if address trimmed</technical_language>

Target:
public Map<Long, ILogData> read(Iterable<Long> addresses, @NonNull ReadOptions options) { final Map<Long, ILogData> cachedData = readCache.getAllPresent(addresses); final Set<Long> addressesToFetch = Sets.difference( Sets.newHashSet(addresses), cachedData.keySet()); final Map<Long, ILogData> uncachedData = fetchAll(addressesToFetch, options); final List<Long> trimmedAddresses = filterTrimmedAddresses(uncachedData); trimmedAddresses.forEach(uncachedData::remove); final Map<Long, ILogData> result = uncachedData.entrySet().stream() .collect(Collectors.toMap(Entry::getKey, entry -> cacheLoadAndGet(readCache, entry.getKey(), entry.getValue(), options))); result.putAll(cachedData); if (!trimmedAddresses.isEmpty()) { if (!options.isIgnoreTrim()) { throw new TrimmedException(trimmedAddresses); } log.warn("read: ignoring trimmed addresses {}", trimmedAddresses); } return result; }
Source:
<code>public void setBeginShark() { this.setShark(new LaserShark(Position.middlePosition(), START_SIZE, START_SPEED, START_DIRECTION)); <START> System.out.println("begin shark"); <END> }</code><technical_language>Please remove Syso's</technical_language>

Target:
public void setBeginShark() { this.setShark(new LaserShark(Position.middlePosition(), START_SIZE, START_SPEED, START_DIRECTION)); }
Source:
<code>public void visit(PolygonSymbolizer poly) { super.visit(poly); PolygonSymbolizer copy = (PolygonSymbolizer) pages.peek(); Unit<Length> uom = copy.getUnitOfMeasure(); rescaleStroke(copy.getStroke(), uom); rescaleFill(copy.getFill(), uom); <START> scaleIntArrayOption(copy.getOptions(), TextSymbolizer.GRAPHIC_MARGIN_KEY, uom); <END> copy.setUnitOfMeasure(NonSI.PIXEL); }</code><technical_language>While value, confusing TextSymbolizer referenced here, PolygonSymbolizer right constant in this pull request</technical_language>

Target:
public void visit(PolygonSymbolizer poly) { super.visit(poly); PolygonSymbolizer copy = (PolygonSymbolizer) pages.peek(); Unit<Length> uom = copy.getUnitOfMeasure(); rescaleStroke(copy.getStroke(), uom); rescaleFill(copy.getFill(), uom); scaleIntArrayOption(copy.getOptions(), PolygonSymbolizer.GRAPHIC_MARGIN_KEY, uom); copy.setUnitOfMeasure(NonSI.PIXEL); }
Source:
<code>private Collection<IInstallableUnit> findUpdates(IInstallableUnit iu, IProgressMonitor monitor) { SubMonitor subMonitor = SubMonitor.convert(monitor, 1); Collection<IInstallableUnit> availableUpdates = new HashSet<>(); IQueryResult<IInstallableUnit> updatesAvailable = planner.updatesFor(iu, provisioningContext, subMonitor.split(1)); for (IInstallableUnit <START> iuu : <END> updatesAvailable) { availableUpdates.add(iuu); } return availableUpdates; }</code><technical_language>rename iu</technical_language>

Target:
private Collection<IInstallableUnit> findUpdates(IInstallableUnit iu, IProgressMonitor monitor) { SubMonitor subMonitor = SubMonitor.convert(monitor, 1); Collection<IInstallableUnit> availableUpdates = new HashSet<>(); IQueryResult<IInstallableUnit> updatesAvailable = planner.updatesFor(iu, provisioningContext, subMonitor.split(1)); for (IInstallableUnit unit : updatesAvailable) { availableUpdates.add(unit); } return availableUpdates; }
Source:
<code>public void testRangeCountWithRangeMerge() <START> { <END> List<Token> tokens = updateTokens(Arrays.asList(100, 200, 300, 400)); Keyspace keyspace = Keyspace.open(KEYSPACE1); List<ReplicaPlan.ForRangeRead> ranges = new ArrayList<>(); for (int i = 0; i + 1 < tokens.size(); i++) { Range<PartitionPosition> range = Range.makeRowRange(tokens.get(i), tokens.get(i + 1)); ranges.add(ReplicaPlans.forRangeRead(keyspace, ConsistencyLevel.ONE, range, 1)); } StorageProxy.RangeMerger merge = new StorageProxy.RangeMerger(ranges.iterator(), keyspace, ConsistencyLevel.ONE); ReplicaPlan.ForRangeRead mergedRange = Iterators.getOnlyElement(merge); assertEquals(tokens.size() - 1, mergedRange.vnodeCount()); }</code><technical_language>nit: This resident of a new RangeMergerTest</technical_language>

Target:
public void testRangeCountWithRangeMerge() { List<Token> tokens = setTokens(Arrays.asList(100, 200, 300, 400)); int vnodeCount = 0; Keyspace keyspace = Keyspace.open(KEYSPACE1); List<ReplicaPlan.ForRangeRead> ranges = new ArrayList<>(); for (int i = 0; i + 1 < tokens.size(); i++) { Range<PartitionPosition> range = Range.makeRowRange(tokens.get(i), tokens.get(i + 1)); ranges.add(ReplicaPlans.forRangeRead(keyspace, ConsistencyLevel.ONE, range, 1)); vnodeCount++; } StorageProxy.RangeMerger merge = new StorageProxy.RangeMerger(ranges.iterator(), keyspace, ConsistencyLevel.ONE); ReplicaPlan.ForRangeRead mergedRange = Iterators.getOnlyElement(merge); assertEquals(vnodeCount, mergedRange.vnodeCount()); }
Source:
<code>private void createPaintListener(final Table rawTable) { rawTable.addListener(SWT.EraseItem, new Listener() { @Override public void handleEvent(final Event event) { if <START> (0 <= event.index && event.index <= 5) <END> event.detail &= ~SWT.FOREGROUND; } }); rawTable.addListener(SWT.PaintItem, new Listener() { @Override public void handleEvent(final Event event) { doPaint(event); } }); }</code><technical_language>heck painting columns ourselves? need draw column 1 graphical commit tree. This suggests a nice two-liner fix this: replace event.index == 1 and..</technical_language>

Target:
private void createPaintListener(final Table rawTable) { rawTable.addListener(SWT.EraseItem, new Listener() { @Override public void handleEvent(final Event event) { if (event.index == 1) { event.detail &= ~SWT.FOREGROUND; } } }); rawTable.addListener(SWT.PaintItem, new Listener() { @Override public void handleEvent(final Event event) { if (event.index == 1) { doPaint(event); } } }); }
Source:
<code>private void rotate(final File file) throws IOException { if (suffix == null) { String filePath = file.getAbsolutePath(); File _file = new File(filePath + "." + maxBackupIndex); if (_file.exists()) <START> _file.delete(); <END> for (int i = maxBackupIndex - 1; i >= 1; i--) { final File src = new File(filePath + "." + i); if (src.exists()) { final File target = new File(filePath + "." + (i + 1)); FileMove.move(src, target); } } FileMove.move(file, new File(filePath + ".1")); } else { final String suffix = new SimpleDateFormat(this.suffix).format(new Date()); final String newBaseFilename = file.getAbsolutePath() + suffix; File newBaseFile = new File(newBaseFilename + "." + maxBackupIndex); if (newBaseFile.exists()) newBaseFile.delete(); for (int i = maxBackupIndex - 1; i >= 1; i--) { final File src = new File(newBaseFilename + "." + i); if (src.exists()) { final File target = new File(newBaseFilename + "." + (i + 1)); FileMove.move(src, target); } } FileMove.move(file, new File(newBaseFilename + ".1")); } }</code><technical_language>do new File(filePath + "." + maxBackupIndex).delete() here. fail. I _ prefix :)</technical_language>

Target:
private void rotate(final File file) throws IOException { if (suffix == null) { String filePath = file.getAbsolutePath(); new File(filePath + "." + maxBackupIndex).delete(); for (int i = maxBackupIndex - 1; i >= 1; i--) { final File src = new File(filePath + "." + i); if (src.exists()) { final File target = new File(filePath + "." + (i + 1)); FileMove.move(src, target); } } FileMove.move(file, new File(filePath + ".1")); } else { final String suffix = new SimpleDateFormat(this.suffix).format(new Date()); final String newBaseFilename = file.getAbsolutePath() + suffix; File newBaseFile = new File(newBaseFilename + "." + maxBackupIndex); if (newBaseFile.exists()) newBaseFile.delete(); for (int i = maxBackupIndex - 1; i >= 1; i--) { final File src = new File(newBaseFilename + "." + i); if (src.exists()) { final File target = new File(newBaseFilename + "." + (i + 1)); FileMove.move(src, target); } } FileMove.move(file, new File(newBaseFilename + ".1")); } }
Source:
<code><START> public static PublicSuffixMatcher load(final InputStream in) throws IOException { <END> Args.notNull(in, "InputStream"); final List<PublicSuffixList> lists = new PublicSuffixListParser().parseByType( new InputStreamReader(in, StandardCharsets.UTF_8)); return new PublicSuffixMatcher(lists); }</code><technical_language>@nielsbasjes Is making this method public necessary? Do need expose this method in public APIs? package private</technical_language>

Target:
private static PublicSuffixMatcher load(final InputStream in) throws IOException { final List<PublicSuffixList> lists = new PublicSuffixListParser().parseByType( new InputStreamReader(in, StandardCharsets.UTF_8)); return new PublicSuffixMatcher(lists); }
Source:
<code>private void paintColumnHeaderFooter(final WTable table, final WebXmlRenderContext renderContext, final boolean renderHeaders) { XmlStringBuilder xml = renderContext.getWriter(); int[] columnOrder = table.getColumnOrder(); TableModel model = table.getTableModel(); final int columnCount = columnOrder == null ? table.getColumnCount() : columnOrder.length; if (renderHeaders) { xml.appendTagOpen("ui:thead"); xml.appendOptionalAttribute("hidden", !table.isShowColumnHeaders(), "true"); xml.appendClose(); } else { xml.appendTag("tfoot"); xml.appendTag("tr"); <START> if (table.getExpandMode() != ExpandMode.NONE) { xml.append("<td/>"); } if (table.getSelectMode() != SelectMode.NONE) { xml.append("<td/>"); <END> } } for (int i = 0; i < columnCount; i++) { int colIndex = columnOrder == null ? i : columnOrder[i]; WTableColumn col = table.getColumn(colIndex); if (col.isVisible()) { if (renderHeaders) { boolean sortable = model.isSortable(colIndex); paintColumnHeading(col, sortable, renderContext); } else { paintColumnFooting(col, renderContext); } } } if (renderHeaders) { xml.appendEndTag("ui:thead"); } else { xml.appendEndTag("tr"); xml.appendEndTag("tfoot"); } }</code><technical_language>problem rendering a HTML tfoot elements is in correct form td element is self-closing output <td></td> <td/>. work self-closing element right</technical_language>

Target:
private void paintColumnHeaderFooter(final WTable table, final WebXmlRenderContext renderContext, final boolean renderHeaders) { XmlStringBuilder xml = renderContext.getWriter(); int[] columnOrder = table.getColumnOrder(); TableModel model = table.getTableModel(); final int columnCount = columnOrder == null ? table.getColumnCount() : columnOrder.length; if (renderHeaders) { xml.appendTagOpen("ui:thead"); xml.appendOptionalAttribute("hidden", !table.isShowColumnHeaders(), "true"); xml.appendClose(); } else { xml.appendTag("tfoot"); xml.appendTag("tr"); if (table.getExpandMode() != ExpandMode.NONE) { xml.appendTag("td"); xml.appendEndTag("td"); } if (table.getSelectMode() != SelectMode.NONE) { xml.appendTag("td"); xml.appendEndTag("td"); } } for (int i = 0; i < columnCount; i++) { int colIndex = columnOrder == null ? i : columnOrder[i]; WTableColumn col = table.getColumn(colIndex); if (col.isVisible()) { if (renderHeaders) { boolean sortable = model.isSortable(colIndex); paintColumnHeading(col, sortable, renderContext); } else { paintColumnFooting(col, renderContext); } } } if (renderHeaders) { xml.appendEndTag("ui:thead"); } else { xml.appendEndTag("tr"); xml.appendEndTag("tfoot"); } }
Source:
<code>private boolean comparer(IDeclaration <START> obj,IFieldCompareHelper <END> comparer ) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof StructDeclaration)) { return false; } StructDeclaration other = (StructDeclaration) obj; if (fFieldMap.size() != other.fFieldMap.size()) { return false; } List<String> localFieldNames = new ArrayList<>(); localFieldNames.addAll(fFieldMap.keySet()); List<IDeclaration> localDecs = new ArrayList<>(); localDecs.addAll(fFieldMap.values()); List<String> otherFieldNames = new ArrayList<>(); otherFieldNames.addAll(other.fFieldMap.keySet()); List<IDeclaration> otherDecs = new ArrayList<>(); otherDecs.addAll(other.fFieldMap.values()); for (int i = 0; i < fFieldMap.size(); i++) { if (!comparer.compareField(otherDecs.get(i),localDecs.get(i))|| (!localFieldNames.get(i).equals(otherFieldNames.get(i))) ) { return false; } } if (fMaxAlign != other.fMaxAlign) { return false; } return true; }</code><technical_language>space</technical_language>

Target:
private boolean comparer(IDeclaration obj, IFieldCompareHelper comparer) { if (this == obj) { return true; } if (!(obj instanceof StructDeclaration)) { return false; } StructDeclaration other = (StructDeclaration) obj; if (fFieldMap.size() != other.fFieldMap.size()) { return false; } List<String> localFieldNames = new ArrayList<>(); localFieldNames.addAll(fFieldMap.keySet()); List<IDeclaration> localDecs = new ArrayList<>(); localDecs.addAll(fFieldMap.values()); List<String> otherFieldNames = new ArrayList<>(); otherFieldNames.addAll(other.fFieldMap.keySet()); List<IDeclaration> otherDecs = new ArrayList<>(); otherDecs.addAll(other.fFieldMap.values()); for (int i = 0; i < fFieldMap.size(); i++) { if (!comparer.compareField(otherDecs.get(i), localDecs.get(i)) || (!localFieldNames.get(i).equals(otherFieldNames.get(i)))) { return false; } } if (fMaxAlign != other.fMaxAlign) { return false; } return true; }
Source:
<code>public void handleMessage(Message message) { if (!isRequestor(message) && message.get(SseInterceptor.class) == null) { message.put(SseInterceptor.class, this); <START> final Exchange exchange = message.getExchange(); <END> OperationResourceInfo ori = (OperationResourceInfo)exchange.get(OperationResourceInfo.class.getName()); if (ori != null) { final ServerProviderFactory providerFactory = ServerProviderFactory.getInstance(message); final ResponseImpl response = (ResponseImpl)Response.ok().build(); try { JAXRSUtils.runContainerResponseFilters(providerFactory, response, message, ori, ori.getAnnotatedMethod()); } catch (Throwable ex) { if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, ex.getMessage(), ex); } } } } }</code><technical_language>Is this put check if get is equal null responsible is called twice</technical_language>

Target:
public void handleMessage(Message message) { if (!isRequestor(message) && message.get(SseInterceptor.class) == null) { message.put(SseInterceptor.class, this); final Exchange exchange = message.getExchange(); OperationResourceInfo ori = (OperationResourceInfo)exchange.get(OperationResourceInfo.class.getName()); if (ori != null) { Response.ResponseBuilder builder = Response.ok(); final ServerProviderFactory providerFactory = ServerProviderFactory.getInstance(message); final Object response = message.get(AbstractHTTPDestination.HTTP_RESPONSE); if (response instanceof HttpServletResponse) { final HttpServletResponse servletResponse = (HttpServletResponse)response; builder = Response.status(servletResponse.getStatus()); for (final String header: servletResponse.getHeaderNames()) { builder.header(header, servletResponse.getHeaders(header)); } } try { final ResponseImpl responseImpl = (ResponseImpl)builder.build(); JAXRSUtils.runContainerResponseFilters(providerFactory, responseImpl, message, ori, ori.getAnnotatedMethod()); } catch (Throwable ex) { if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, ex.getMessage(), ex); } } } } }
Source:
<code><START> private String getValueForOptionalKey(JSONObject object, String key) { <END> return object.has(key) ? object.optJSONObject(key).optString("value") : ""; }</code><technical_language>This nice! adding a throws JSONException signature of getValueForOptionalKey() parseImageLicenseMetadata() needed try / catch in place for processPage()</technical_language>

Target:
private String getValueForOptionalKey(JSONObject object, String key) throws JSONException { return object.has(key) ? object.getJSONObject(key).getString("value") : ""; }
Source:
<code>public void addCallable( World w, IWorldCallable<?> c ) { if( w == null ) { this.serverQueue.add( c ); } else { Queue<IWorldCallable<?>> queue = this.callQueue.get( w ); if( queue == null ) { <START> this.callQueue.put( w, queue = new LinkedList<IWorldCallable<?>>() ); <END> } queue.add( c ); } }</code><technical_language>split in lines</technical_language>

Target:
public void addCallable( World w, IWorldCallable<?> c ) { if( w == null ) { this.serverQueue.add( c ); } else { Queue<IWorldCallable<?>> queue = this.callQueue.get( w ); if( queue == null ) { queue = new LinkedList<IWorldCallable<?>>(); this.callQueue.put( w, queue ); } queue.add( c ); } }
Source:
<code>public abstract void init(String url, String user, String pwd) throws SchedulerException, LoginException; public abstract void disconnect() throws PermissionException, NotConnectedException; @Override public boolean isConnected() { if (!initialized) { return false; } if (terminated) { <START> return true; <END> } return getScheduler().isConnected(); }</code><technical_language>returning true if terminated</technical_language>

Target:
public abstract void init(String url, String user, String pwd) throws SchedulerException, LoginException; public abstract void disconnect() throws PermissionException, NotConnectedException; @Override public boolean isConnected() { if (!initialized) { return false; } if (terminated) { return false; } return getScheduler().isConnected(); }
Source:
<code>public void multipleIteratorsNestedInterleavedExists() throws Exception { try ( Transaction tx = db.beginTx(); Statement statement = db.statement() ) { ReadOperations readOperations = statement.readOperations(); PrimitiveLongIterator iter1 = indexCoordinator.queryExists( readOperations ); List<Long> actual1 = new ArrayList<>(); PrimitiveLongIterator iter2 = indexCoordinator.queryExists( readOperations ); List<Long> actual2 = new ArrayList<>(); <START> while ( iter1.hasNext() && iter2.hasNext() ) <END> { if ( rnd.nextBoolean() ) { actual1.add( iter1.next() ); } else { actual2.add( iter2.next() ); } } while ( iter1.hasNext() ) { actual1.add( iter1.next() ); } while ( iter2.hasNext() ) { actual2.add( iter2.next() ); } indexCoordinator.assertExistsResult( actual1 ); indexCoordinator.assertExistsResult( actual2 ); tx.success(); } }</code><technical_language>I extract random order exhaustion a method, line 298-318</technical_language>

Target:
public void multipleIteratorsNestedInterleavedExists() throws Exception { try ( Transaction tx = db.beginTx(); Statement statement = db.statement() ) { ReadOperations readOperations = statement.readOperations(); PrimitiveLongIterator iter1 = indexCoordinator.queryExists( readOperations ); List<Long> actual1 = new ArrayList<>(); PrimitiveLongIterator iter2 = indexCoordinator.queryExists( readOperations ); List<Long> actual2 = new ArrayList<>(); exhaustInterleaved( iter1, actual1, iter2, actual2 ); indexCoordinator.assertExistsResult( actual1 ); indexCoordinator.assertExistsResult( actual2 ); tx.success(); } }
Source:
<code>public List<VDS> filter(List<VDS> hosts, VM vm, Map<String, String> parameters, List<String> messages) { <START> if (vm.getRunOnVds() == null && vm.getDedicatedVmForVds() == null) { <END> return hosts; } if (vm.getMigrationSupport() == MigrationSupport.PINNED_TO_HOST) { for (VDS host : hosts) { if (host.getId().equals(vm.getDedicatedVmForVds())) { return Arrays.asList(host); } } messages.add(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_PINNED_TO_HOST.toString()); return new ArrayList<>(); } return hosts; }</code><technical_language>If testing vm.getMigrationSupport() here, skip pin host functionality</technical_language>

Target:
public List<VDS> filter(List<VDS> hosts, VM vm, Map<String, String> parameters, List<String> messages) { if (vm.getMigrationSupport() == MigrationSupport.PINNED_TO_HOST) { if(vm.getDedicatedVmForVds() != null) { for (VDS host : hosts) { if (host.getId().equals(vm.getDedicatedVmForVds())) { return Arrays.asList(host); } } } else { if (vm.getRunOnVds() == null) { return hosts; } } return new ArrayList<>(); } return hosts; }
Source:
<code><START> public String execGesture(String gesture) { <END> lastGestureExecuted = gesture; String ret; if (python == null) { log.warn("execGesture : No jython engine..."); return null; } subscribe(python.getName(), "publishStatus", this.getName(), "onGestureStatus"); startedGesture(lastGestureExecuted); ret = Utils.execPy(gesture); return ret; }</code><technical_language>big a change for nixie. stuff this inmoov2 in ogre</technical_language>

Target:
public String execGesture(String gesture) { lastGestureExecuted = gesture; String ret; if (python == null) { log.warn("execGesture : No jython engine..."); return null; } subscribe(python.getName(), "publishStatus", this.getName(), "onGestureStatus"); startedGesture(lastGestureExecuted); return python.evalAndWait(gesture); }
Source:
<code>private SearchResult parseToSearchResult(@Nonnull final IMAPResponse[] ir) throws ImapAsyncClientException { if (ir.length < 1) { throw new ImapAsyncClientException(FailureType.INVALID_INPUT); } final Response taggedResponse = ir[ir.length - 1]; if (!taggedResponse.isOK()) { throw new ImapAsyncClientException(FailureType.INVALID_INPUT); } final List<Long> v = new ArrayList<Long>(); long num; for (final IMAPResponse sr : ir) { if (sr.keyEquals("SEARCH")) { while ((num = sr.readLong()) != -1) { <START> v.add(num); <END> } } } return new SearchResult(v); }</code><technical_language>revert it, I for a reason</technical_language>

Target:
private SearchResult parseToSearchResult(@Nonnull final IMAPResponse[] ir) throws ImapAsyncClientException { if (ir.length < 1) { throw new ImapAsyncClientException(FailureType.INVALID_INPUT); } final Response taggedResponse = ir[ir.length - 1]; if (!taggedResponse.isOK()) { throw new ImapAsyncClientException(FailureType.INVALID_INPUT); } final List<Long> v = new ArrayList<Long>(); long num; for (final IMAPResponse sr : ir) { if (sr.keyEquals("SEARCH")) { while ((num = sr.readLong()) != -1) { v.add(Long.valueOf(num)); } } } return new SearchResult(v); }
Source:
<code>private String getReleaseNotesFromScm(AbstractBuild build) { StringBuilder notes = new StringBuilder(); AbstractProject project = build.getProject(); AbstractBuild lastSuccessfulBuild = (AbstractBuild)project.getLastSuccessfulBuild(); AbstractBuild currentBuild = null; if (lastSuccessfulBuild == null) { AbstractBuild lastBuild = (AbstractBuild)project.getLastBuild(); currentBuild = lastBuild; } else { currentBuild = lastSuccessfulBuild.getNextBuild(); } if (currentBuild != null) { while (currentBuild != build) { String currBuildNotes = convertChangeSetToString(currentBuild); <START> if (!currBuildNotes.isEmpty()) <END> notes.append(currBuildNotes); currentBuild = currentBuild.getNextBuild(); } String currBuildNotes = convertChangeSetToString(build); if (!currBuildNotes.isEmpty()) notes.append(currBuildNotes); } return notes.toString(); }</code><technical_language>for sake of consistency readability, please include curly brackets liners</technical_language>

Target:
private String getReleaseNotesFromScm(AbstractBuild build) { StringBuilder notes = new StringBuilder(); AbstractProject project = build.getProject(); AbstractBuild lastSuccessfulBuild = (AbstractBuild)project.getLastSuccessfulBuild(); AbstractBuild currentBuild = null; if (lastSuccessfulBuild == null) { AbstractBuild lastBuild = (AbstractBuild)project.getLastBuild(); currentBuild = lastBuild; } else { currentBuild = lastSuccessfulBuild.getNextBuild(); } if (currentBuild != null) { while (currentBuild != build) { String currBuildNotes = convertChangeSetToString(currentBuild); if (!currBuildNotes.isEmpty()) { notes.append(currBuildNotes); } currentBuild = currentBuild.getNextBuild(); } String currBuildNotes = convertChangeSetToString(build); if (!currBuildNotes.isEmpty()) { notes.append(currBuildNotes); } } return notes.toString(); }
Source:
<code>public void newSubnet() { if (getWindow() != null) { return; } NewExternalSubnetModel model = new NewExternalSubnetModel(this); setWindow(model); <START> initNetworkInModel(model); <END> }</code><technical_language>Is reason do encapsulate logic in constructor of NewExternalSubnetModel? Especially I see, called dialog is instantiated</technical_language>

Target:
public void newSubnet() { if (getWindow() != null) { return; } NewExternalSubnetModel model = new NewExternalSubnetModel(getEntity(), this); setWindow(model); }
Source:
<code>private void checkIfDDLStatementandMutationState(final CompilableStatement stmt, MutationState state) throws SQLException { boolean throwUncommittedMutation = connection.getQueryServices().getProps().getBoolean( QueryServices.PENDING_MUTATIONS_DDL_THROW_ATTRIB, QueryServicesOptions.DEFAULT_PENDING_MUTATIONS_DDL_THROW); if (stmt instanceof MutableStatement && !(stmt instanceof DMLStatement) && state.getNumRows() > 0) { if (throwUncommittedMutation) { throw new SQLExceptionInfo.Builder( SQLExceptionCode.CANNOT_PERFORM_DDL_WITH_PENDING_MUTATIONS).build() .buildException(); } else { <START> LOGGER.info( <END> "There are Uncommitted mutations, which will be dropped on the execution of this DDL statement."); } } }</code><technical_language>change this warn level</technical_language>

Target:
private void checkIfDDLStatementandMutationState(final CompilableStatement stmt, MutationState state) throws SQLException { boolean throwUncommittedMutation = connection.getQueryServices().getProps().getBoolean( QueryServices.PENDING_MUTATIONS_DDL_THROW_ATTRIB, QueryServicesOptions.DEFAULT_PENDING_MUTATIONS_DDL_THROW); if (stmt instanceof MutableStatement && !(stmt instanceof DMLStatement) && state.getNumRows() > 0) { if (throwUncommittedMutation) { throw new SQLExceptionInfo.Builder( SQLExceptionCode.CANNOT_PERFORM_DDL_WITH_PENDING_MUTATIONS).build() .buildException(); } else { LOGGER.warn( "There are Uncommitted mutations, which will be dropped on the execution of this DDL statement."); } } }
Source:
<code>private static PropertySource<?> loadPropertySource() { Properties properties = new Properties(); try (InputStream is = LdapAuthenticationProviderTest.class.getResourceAsStream("lapt.properties")) { properties.load(is); } catch (Exception ex) { throw new UndeclaredThrowableException(ex); } <START> properties.put(BASE64_ENCODING_KEY, true); <END> return new PropertiesPropertySource(STRONGBOX_AUTHENTICATION_PROVIDERS, properties); }</code><technical_language>@madhukarbharti do this well. Please another properties file for this test instead. labet.properties strongbox.authentication.ldap.base64EncodedPassword=true</technical_language>

Target:
private static PropertySource<?> loadPropertySource() { Properties properties = new Properties(); try (InputStream is = LdapAuthenticationProviderTest.class.getResourceAsStream("labet.properties")) { properties.load(is); } catch (Exception ex) { throw new UndeclaredThrowableException(ex); } return new PropertiesPropertySource(STRONGBOX_AUTHENTICATION_PROVIDERS, properties); }
Source:
<code>public static String waitForFileContents(String file, String desiredContent, Duration timeout, boolean failOnAbsent) { long secs = Math.max(timeout.toSeconds(), 1); List<String> commands = ImmutableList.of( "for i in {1.."+secs+"}", <START> "do", <END> " grep '"+desiredContent+"' "+file+" && result=0 || result=$?", " [ \"$result\" == 0 ] && break", " sleep 1", "done", "if test \"$result\" -ne 0; then", " "+ (failOnAbsent ? "echo \"Couldn't find "+desiredContent+" in "+file+"; aborting\" && exit 1" : "echo \"Couldn't find "+desiredContent+" in "+file+"; continuing\""), "fi"); return Joiner.on("\n").join(commands); }</code><technical_language>Neater line, if below? for i in {1..x}; do</technical_language>

Target:
public static String waitForFileContents(String file, String desiredContent, Duration timeout, boolean failOnAbsent) { long secs = Math.max(timeout.toSeconds(), 1); List<String> commands = ImmutableList.of( "for i in {1.."+secs+"}; do", " grep '"+desiredContent+"' "+file+" && result=0 || result=$?", " [ \"$result\" == 0 ] && break", " sleep 1", "done", "if test \"$result\" -ne 0; then", " "+ (failOnAbsent ? "echo \"Couldn't find "+desiredContent+" in "+file+"; aborting\" && exit 1" : "echo \"Couldn't find "+desiredContent+" in "+file+"; continuing\""), "fi"); return Joiner.on("\n").join(commands); }
Source:
<code>public void saveScreenshot() { final ByteBuffer buffer = buffersManager.getSceneFinalRawData(); if (buffer == null) { logger.error("No screenshot data available. No screenshot will be saved."); return; } int width = buffersManager.getFBO("ocUndistorted").width(); <START> int height = buffersManager.getFBO("sceneFinal").height(); <END> Runnable task = () -> { SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss"); final String format = renderingConfig.getScreenshotFormat(); final String fileName = "Terasology-" + sdf.format(new Date()) + "-" + width + "x" + height + "." + format; Path path = PathManager.getInstance().getScreenshotPath().resolve(fileName); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { int i = (x + width * y) * 4; int r = buffer.get(i) & 0xFF; int g = buffer.get(i + 1) & 0xFF; int b = buffer.get(i + 2) & 0xFF; image.setRGB(x, height - (y + 1), (0xFF << 24) | (r << 16) | (g << 8) | b); } } try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(path))) { ImageIO.write(image, format, out); logger.info("Screenshot '" + fileName + "' saved! "); } catch (IOException e) { logger.warn("Failed to save screenshot!", e); } }; threadManager.submitTask("Write screenshot", task); isTakingScreenshot = false; }</code><technical_language>This odd. width FBO height other</technical_language>

Target:
public void saveScreenshot() { final ByteBuffer buffer = buffersManager.getSceneFinalRawData(); if (buffer == null) { logger.error("No screenshot data available. No screenshot will be saved."); return; } FBO sceneFinal = buffersManager.getFBO("sceneFinal"); int width = sceneFinal.width(); int height = sceneFinal.height(); Runnable task = () -> { SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss"); final String format = renderingConfig.getScreenshotFormat(); final String fileName = "Terasology-" + sdf.format(new Date()) + "-" + width + "x" + height + "." + format; Path path = PathManager.getInstance().getScreenshotPath().resolve(fileName); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { int i = (x + width * y) * 4; int r = buffer.get(i) & 0xFF; int g = buffer.get(i + 1) & 0xFF; int b = buffer.get(i + 2) & 0xFF; image.setRGB(x, height - (y + 1), (0xFF << 24) | (r << 16) | (g << 8) | b); } } try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(path))) { ImageIO.write(image, format, out); logger.info("Screenshot '" + fileName + "' saved! "); } catch (IOException e) { logger.warn("Failed to save screenshot!", e); } }; threadManager.submitTask("Write screenshot", task); isTakingScreenshot = false; }
Source:
<code>private void createBranch(final String textForBranch, boolean doCheckout, RevCommit commit, IProgressMonitor monitor) throws CoreException, GitAPIException { monitor.setTaskName(UIText.FetchGerritChangePage_CreatingBranchTaskName); CreateLocalBranchOperation bop = new CreateLocalBranchOperation( repository, textForBranch, commit); bop.execute(monitor); if (doCheckout) { final CheckoutResult result = checkout(textForBranch); if (result.getStatus() == Status.CONFLICTS) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(); CleanupUncomittedChangesDialog cleanupUncomittedChangesDialog = new CleanupUncomittedChangesDialog( shell, UIText.BranchResultDialog_CheckoutConflictsTitle, UIText.AbstractRebaseCommandHandler_cleanupDialog_text, repository, result.getConflictList()); cleanupUncomittedChangesDialog.open(); <START> if (cleanupUncomittedChangesDialog.shouldContinue()) { <END> try { checkout(textForBranch); } catch (GitAPIException e) { Activator.logError(e.getMessage(), e); } } }); } } monitor.worked(1); }</code><technical_language>a race condition here. CleanupUncommittedChangesDialog creates, depending user's choice, a CommitJob, a JobFamilies.RESET JobFamilies.STASH job. means dialog, do operations repo synchronously. need in job get queued (if scheduling rule, should). in worst case join COMMIT, RESET, STASH, hate that. this needs a larger refactoring of this FetchGerritChangePage. I internalDoFetch(...) method boolean flags (some of [or all?] mutually exclusive) "sequence" of steps highly confusing</technical_language>

Target:
private void createBranch(final String textForBranch, boolean doCheckout, RevCommit commit, IProgressMonitor monitor) throws CoreException { monitor.setTaskName(UIText.FetchGerritChangePage_CreatingBranchTaskName); CreateLocalBranchOperation bop = new CreateLocalBranchOperation( repository, textForBranch, commit); bop.execute(monitor); if (doCheckout) { CheckoutResult result; try { result = checkout(textForBranch, monitor); } catch (OperationCanceledException | InterruptedException e1) { return; } if (result.getStatus() == Status.CONFLICTS) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(); CleanupUncomittedChangesDialog cleanupUncomittedChangesDialog = new CleanupUncomittedChangesDialog( shell, UIText.BranchResultDialog_CheckoutConflictsTitle, UIText.AbstractRebaseCommandHandler_cleanupDialog_text, repository, result.getConflictList()); cleanupUncomittedChangesDialog.open(); if (cleanupUncomittedChangesDialog.shouldContinue()) { try { checkout(textForBranch, monitor); } catch (InterruptedException e) { Activator.logError(e.getMessage(), e); } } }); } } monitor.worked(1); }
Source:
<code>public AppConfig() { register(StatusController.class); register(MachineController.class); register(TextController.class); register(MacrosController.class); register(SettingsController.class); register(FilesController.class); <START> register(MultiPartFeature.class); <END> BackendAPI backendAPI = BackendAPIFactory.getInstance().getBackendAPI(); JogService jogService = new JogService(backendAPI); register(new AbstractBinder() { @Override protected void configure() { bind(backendAPI).to(BackendAPI.class); bind(jogService).to(JogService.class); } }); }</code><technical_language>nitpick: convention familiar (using Jersey dropwizard) classes end in Resource instead of Controller</technical_language>

Target:
public AppConfig() { register(ExceptionMapper.class); register(StatusResource.class); register(MachineResource.class); register(TextResource.class); register(MacrosResource.class); register(SettingsResource.class); register(FilesResource.class); register(MultiPartFeature.class); BackendAPI backendAPI = BackendAPIFactory.getInstance().getBackendAPI(); JogService jogService = new JogService(backendAPI); register(new AbstractBinder() { @Override protected void configure() { bind(backendAPI).to(BackendAPI.class); bind(jogService).to(JogService.class); } }); }
Source:
<code>@Override public Connection getConnection() throws JMSException { <START> return getConnection(null, null); <END> }</code><technical_language>connection = super.createConnection() instead? do pass null parameters</technical_language>

Target:
public Connection getConnection() throws JMSException { return getConnection(null, null); }
Source:
<code>private boolean satisfiesUpdatedHours(TurboIssue issue, UpdatedKind updatedKind) { NumberRange updatedRange; if (numberRange.isPresent()) { updatedRange = numberRange.get(); } else if (number.isPresent()) { updatedRange = new NumberRange(null, number.get(), true); } else { return false; } int hoursSinceUpdate = Integer.MIN_VALUE; LocalDateTime dateOfUpdate = LocalDateTime.ofEpochSecond(0, 0, ZoneOffset.ofHours(0)); <START> if (hoursSinceUpdate == Integer.MIN_VALUE) { <END> dateOfUpdate = issue.getUpdatedAt(); } switch (updatedKind){ case SELF_UPDATED: if (issue.getMetadata().isUpdatedBySelf()) { dateOfUpdate = issue.getMetadata().getSelfUpdatedAt(); } break; case OTHER_UPDATED: if (issue.getMetadata().isUpdatedByOthers()) { dateOfUpdate = issue.getMetadata().getNonSelfUpdatedAt(); } break; case ALL_UPDATED: if (issue.getMetadata().isUpdated()) { dateOfUpdate = issue.getUpdatedAt(); } } hoursSinceUpdate = Utility.safeLongToInt(dateOfUpdate.until(getCurrentTime(), ChronoUnit.HOURS)); return updatedRange.encloses(hoursSinceUpdate); }</code><technical_language>Moving this caused a bug -- this is true. intended return early</technical_language>

Target:
private boolean satisfiesUpdatedHours(TurboIssue issue, UpdatedKind updatedKind) { NumberRange updatedRange; if (numberRange.isPresent()) { updatedRange = numberRange.get(); } else if (number.isPresent()) { updatedRange = new NumberRange(null, number.get(), true); } else { return false; } LocalDateTime dateOfUpdate = null; switch (updatedKind){ case SELF_UPDATED: if (issue.getMetadata().isUpdatedBySelf()) { dateOfUpdate = issue.getMetadata().getSelfUpdatedAt(); } break; case OTHER_UPDATED: if (issue.getMetadata().isUpdatedByOthers()) { dateOfUpdate = issue.getMetadata().getNonSelfUpdatedAt(); } break; case ALL_UPDATED: dateOfUpdate = issue.getUpdatedAt(); } if (dateOfUpdate == null) { return false; } else { int hoursSinceUpdate = Utility.safeLongToInt(dateOfUpdate.until(getCurrentTime(), ChronoUnit.HOURS)); return updatedRange.encloses(hoursSinceUpdate); } }
Source:
<code>private void trackNodeError(Node node, Throwable error, long nodeResponseTimeNanos) { if (requestTracker instanceof NoopRequestTracker) { return; } <START> if (nodeResponseTimeNanos < 0) { <END> nodeResponseTimeNanos = System.nanoTime(); } long latencyNanos = nodeResponseTimeNanos - this.nodeStartTimeNanos; requestTracker.onNodeError(statement, error, latencyNanos, executionProfile, node); }</code><technical_language>this check more explicit if( nodeResponseTimeNanos == NO_MEASURMENT) { ... }</technical_language>

Target:
private void trackNodeError(Node node, Throwable error, long nodeResponseTimeNanos) { if (requestTracker instanceof NoopRequestTracker) { return; } if (nodeResponseTimeNanos == NANOTIME_NOT_MEASURED_YET) { nodeResponseTimeNanos = System.nanoTime(); } long latencyNanos = nodeResponseTimeNanos - this.nodeStartTimeNanos; requestTracker.onNodeError(statement, error, latencyNanos, executionProfile, node); }