auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void buildVmWatchdog() { List<VmDevice> watchdogs = DbFacade.getInstance() .getVmDeviceDao() .getVmDeviceByVmIdAndType(vm.getId(), VmDeviceType.WATCHDOG.getName()); for(VmDevice watchdog : watchdogs) { <START> HashMap struct = new HashMap(); <END> struct.put(VdsProperties.Type, watchdog.getType()); struct.put(VdsProperties.Device, watchdog.getDevice()); Map<String, Object> specParams = watchdog.getSpecParams(); if (specParams == null) { specParams = new HashMap<String, Object>(); } struct.put(VdsProperties.SpecParams, specParams); addDevice(struct, watchdog, null); } }</code><technical_language>pick another name, I c# nightmares :)</technical_language>

Target:
protected void buildVmWatchdog() { List<VmDevice> watchdogs = DbFacade.getInstance() .getVmDeviceDao() .getVmDeviceByVmIdAndType(vm.getId(), VmDeviceType.WATCHDOG.getName()); for(VmDevice watchdog : watchdogs) { HashMap watchdogFromRpc = new HashMap(); watchdogFromRpc.put(VdsProperties.Type, watchdog.getType()); watchdogFromRpc.put(VdsProperties.Device, watchdog.getDevice()); Map<String, Object> specParams = watchdog.getSpecParams(); if (specParams == null) { specParams = new HashMap<String, Object>(); } watchdogFromRpc.put(VdsProperties.SpecParams, specParams); addDevice(watchdogFromRpc, watchdog, null); } }
Source:
<code>public <T> T build(Class<T> serviceClass, String userAgent, List<String> uris) { Preconditions.checkArgument(!uris.isEmpty()); List<String> sanitizedUris = addTrailingSlashes(uris); okhttp3.OkHttpClient client = createOkHttpClient(userAgent, sanitizedUris); Retrofit retrofit = new Retrofit.Builder() .client(client) .baseUrl(sanitizedUris.get(0)) .addConverterFactory(new CborConverterFactory( JacksonConverterFactory.create(OBJECT_MAPPER), <START> ObjectMappers.newCborClientObjectMapper())) <END> .addConverterFactory(OptionalObjectToStringConverterFactory.INSTANCE) .build(); return retrofit.create(serviceClass); }</code><technical_language>inline OBJECT_MAPPER pull out</technical_language>

Target:
public <T> T build(Class<T> serviceClass, String userAgent, List<String> uris) { Preconditions.checkArgument(!uris.isEmpty()); List<String> sanitizedUris = addTrailingSlashes(uris); okhttp3.OkHttpClient client = createOkHttpClient(userAgent, sanitizedUris); Retrofit retrofit = new Retrofit.Builder() .client(client) .baseUrl(sanitizedUris.get(0)) .addConverterFactory(new CborConverterFactory( JacksonConverterFactory.create(OBJECT_MAPPER), CBOR_OBJECT_MAPPER)) .addConverterFactory(OptionalObjectToStringConverterFactory.INSTANCE) .build(); return retrofit.create(serviceClass); }
Source:
<code>private String getDownloadedFileContent(String testFileName) throws IOException { try { <START> return downloadedFileUtil.getDownloadedFileContent( <END> seleniumWebDriver.getSessionId(), testFileName); } catch (IOException e) { WaitUtils.sleepQuietly(2); return downloadedFileUtil.getDownloadedFileContent( seleniumWebDriver.getSessionId(), testFileName); } }</code><technical_language>improve waiting download - do 5 times 1 period</technical_language>

Target:
private String getDownloadedFileContent(String testFileName) throws IOException { IOException lastException = null; for (int i = 0; i < MAX_ATTEMPTS; i++) { try { return downloadedFileUtil.getDownloadedFileContent( seleniumWebDriver.getSessionId(), testFileName); } catch (IOException e) { lastException = e; sleepQuietly(TestTimeoutsConstants.MINIMUM_SEC); } } throw lastException; }
Source:
<code>public void run() { char[] charBuffer = new char[BUF_SIZE]; try { while (true) { int readCount = mReader.read(charBuffer, 0, charBuffer.length); if (readCount < 0) { break; } <START> String newRead = new String(charBuffer, 0, readCount); int newLineLen = 0; if (newRead.endsWith("\r\n")) { newLineLen = 2; } else if (newRead.endsWith("\n")) { newLineLen = 1; } String newReadPrint = newRead.substring(0, newRead.length() - newLineLen); if (mOutputType == TYPE_STDOUT) { CLog.i(newReadPrint); } else if (mOutputType == TYPE_STDERR) { CLog.e(newReadPrint); } mBuffer.append(newRead); <END> } } catch (IOException e) { CLog.e("%s: %s", getName(), e.toString()); } }</code><technical_language>this conditional -l INFO (for stdout) -l ERROR option (for stderr) is used</technical_language>

Target:
public void run() { char[] charBuffer = new char[BUF_SIZE]; try { while (true) { int readCount = mReader.read(charBuffer, 0, charBuffer.length); if (readCount < 0) { break; } String newRead = new String(charBuffer, 0, readCount); int newLineLen = 0; if (newRead.endsWith("\r\n")) { newLineLen = 2; } else if (newRead.endsWith("\n")) { newLineLen = 1; } String newReadPrint = newRead.substring(0, newRead.length() - newLineLen); switch (mLogType) { case STDOUT: CLog.i(newReadPrint); break; case STDERR: CLog.e(newReadPrint); break; } mBuffer.append(newRead); } } catch (IOException e) { CLog.e("%s: %s", getName(), e.toString()); } }
Source:
<code>private List<String> getSchemaNames(ConnectorSession session, Optional<String> schemaName) { if (!schemaName.isPresent()) { return listSchemaNames(session); } <START> else if (schemaNameToScaleFactor(schemaName.get()) > 0) { <END> return ImmutableList.of(schemaName.get()); } return ImmutableList.of(); }</code><technical_language>else is redundant</technical_language>

Target:
private List<String> getSchemaNames(ConnectorSession session, Optional<String> schemaName) { if (!schemaName.isPresent()) { return listSchemaNames(session); } if (schemaNameToScaleFactor(schemaName.get()) > 0) { return ImmutableList.of(schemaName.get()); } return ImmutableList.of(); }
Source:
<code>private IncrementalProjectBuilder getBuilder(IBuildConfiguration buildConfiguration, ICommand command, int buildSpecIndex, MultiStatus status) throws CoreException { BuildCommand buildCommand = (BuildCommand) command; InternalBuilder result = buildCommand.getBuilder(buildConfiguration); String builderName = command.getBuilderName(); IProject project = buildConfiguration.getProject(); if (result == null) { BuilderPersistentInfo info = null; synchronized (builderInitializationLock) { BuilderPersistentInfo builderInitInProgress = getBuilderInitInfo(project, builderName); if (builderInitInProgress != null) { info = builderInitInProgress; } else { info = removePersistentBuilderInfo(builderName, buildConfiguration, buildSpecIndex); setBuilderInitInfo(project, builderName, info); } } result = buildCommand.getBuilder(buildConfiguration); if (result == null) { result = initializeBuilder(command, builderName, buildConfiguration, info, status); } synchronized (builderInitializationLock) { InternalBuilder other = buildCommand.getBuilder(buildConfiguration); if (other == null) { buildCommand.addBuilder(buildConfiguration, (IncrementalProjectBuilder) result); } else { result = other; } setBuilderInitInfo(project, builderName, null); } } if (result == null) { return null; } <START> result.setBuildConfig(buildConfiguration); if (!validateNature(result, builderName)) { result.setLastBuiltTree(null); return null; } <END> return (IncrementalProjectBuilder) result; }</code><technical_language>validateNature calls removeBuilders calls project.setDescription enters workspace locks etc. No, risky</technical_language>

Target:
private IncrementalProjectBuilder getBuilder(IBuildConfiguration buildConfiguration, ICommand command, int buildSpecIndex, MultiStatus status) throws CoreException { BuildCommand buildCommand = (BuildCommand) command; InternalBuilder result = buildCommand.getBuilder(buildConfiguration); String builderName = command.getBuilderName(); IProject project = buildConfiguration.getProject(); if (result == null) { BuilderPersistentInfo info; synchronized (builderInitializationLock) { BuilderPersistentInfo builderInitInProgress = getBuilderInitInfo(project, builderName); if (builderInitInProgress != null) { info = builderInitInProgress; } else { info = removePersistentBuilderInfo(builderName, buildConfiguration, buildSpecIndex); setBuilderInitInfo(project, builderName, info); } } result = buildCommand.getBuilder(buildConfiguration); if (result == null) { result = initializeBuilder(command, builderName, buildConfiguration, info, status); } synchronized (builderInitializationLock) { InternalBuilder other = buildCommand.getBuilder(buildConfiguration); if (other == null) { buildCommand.addBuilder(buildConfiguration, (IncrementalProjectBuilder) result); } else { result = other; } setBuilderInitInfo(project, builderName, null); } } result.setBuildConfig(buildConfiguration); if (!validateNature(result, builderName)) { result.setLastBuiltTree(null); return null; } return (IncrementalProjectBuilder) result; }
Source:
<code>public Token login(String username, String password, HttpServletRequest request) throws AuthException { String project = request.getHeader(HEADER_X_AUTH_PROJECT); if (StringUtils.isEmpty(project)) { project = this.config.tenantName(); if (StringUtils.isEmpty(project)) { throw new InvalidCredentialsException("Project missing"); } } KeystoneAuthCredentials credentials; try { <START> credentials = new KeystoneAuthCredentials( <END> username, password, project); } catch (Exception ex) { log.debug("Failed to get credentials: "+ex.getMessage()); throw new InvalidCredentialsException("Invalid credentials for user: "+username); } KeystoneAccess access = client.createToken(credentials); return getToken(access); }</code><technical_language>This throw exception</technical_language>

Target:
public Token login(String username, String password, HttpServletRequest request) throws AuthException { String project = request.getHeader(HEADER_X_AUTH_PROJECT); if (StringUtils.isEmpty(project)) { project = this.config.tenantName(); if (StringUtils.isEmpty(project)) { throw new InvalidCredentialsException("Project missing"); } } KeystoneAuthCredentials credentials = new KeystoneAuthCredentials( username, password, project); KeystoneAccess access = null; try { access = client.createToken(credentials); } catch (KeystoneConnectionException kex) { log.debug("Authentication connection failed: "+kex.getMessage()); } catch (KeystoneServerException ex) { log.debug("Failed to get credentials: "+ex.getMessage()); throw new InvalidCredentialsException("Invalid credentials for user: "+username); } return getToken(access); }
Source:
<code>public JSONObject toJSON() { JSONObject ret = new JSONObject(); String formattedDate = null; if (xmlDate == null || xmlDate.isEmpty()) { try { final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.US); formattedDate = sdf.format(date); <START> } catch (Exception e){ <END> } } JSONHelper.putValue(ret, "date", formattedDate != null ? formattedDate : xmlDate); JSONHelper.putValue(ret, "dateType", dateType != null ? dateType : ""); return ret; }</code><technical_language>SimpleDateFormat re-used</technical_language>

Target:
public JSONObject toJSON() { JSONObject ret = new JSONObject(); String formattedDate = null; if (xmlDate == null || xmlDate.isEmpty()) { try { formattedDate = date.format(DATE_FORMATTER); } catch (Exception e){ } } JSONHelper.putValue(ret, "date", formattedDate != null ? formattedDate : xmlDate); JSONHelper.putValue(ret, "dateType", dateType != null ? dateType : ""); return ret; }
Source:
<code>private void parseMemoryOffHeap(XMLExtendedStreamReader reader, ModelNode cache, Map<PathAddress, ModelNode> operations) throws XMLStreamException { PathAddress offHeapAddress = PathAddress.pathAddress(cache.get(OP_ADDR)).append(MemoryOffHeapConfigurationResource.PATH); ModelNode offHeap = Util.createAddOperation(offHeapAddress); for (int i = 0; i < reader.getAttributeCount(); i++) { String value = reader.getAttributeValue(i); Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case EVICTION: { MemoryOffHeapConfigurationResource.EVICTION.parseAndSetParameter(value, offHeap, reader); break; } case SIZE: { MemoryOffHeapConfigurationResource.SIZE.parseAndSetParameter(value, offHeap, reader); break; } case STRATEGY: { MemoryOffHeapConfigurationResource.STRATEGY.parseAndSetParameter(value, offHeap, reader); break; } case ADDRESS_COUNT: { if (namespace.since(11, 0)) { throw ParseUtils.unexpectedElement(reader); <START> } <END> break; } default: { throw ParseUtils.unexpectedAttribute(reader, i); } } } ParseUtils.requireNoContent(reader); operations.put(offHeapAddress, offHeap); }</code><technical_language>warn attribute ignoreAttribute</technical_language>

Target:
private void parseMemoryOffHeap(XMLExtendedStreamReader reader, ModelNode cache, Map<PathAddress, ModelNode> operations) throws XMLStreamException { PathAddress offHeapAddress = PathAddress.pathAddress(cache.get(OP_ADDR)).append(MemoryOffHeapConfigurationResource.PATH); ModelNode offHeap = Util.createAddOperation(offHeapAddress); for (int i = 0; i < reader.getAttributeCount(); i++) { String value = reader.getAttributeValue(i); Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case EVICTION: { MemoryOffHeapConfigurationResource.EVICTION.parseAndSetParameter(value, offHeap, reader); break; } case SIZE: { MemoryOffHeapConfigurationResource.SIZE.parseAndSetParameter(value, offHeap, reader); break; } case STRATEGY: { MemoryOffHeapConfigurationResource.STRATEGY.parseAndSetParameter(value, offHeap, reader); break; } case ADDRESS_COUNT: { if (namespace.since(11, 0)) { throw ParseUtils.unexpectedElement(reader); } ROOT_LOGGER.deprecatedAttribute(attribute.getLocalName()); break; } default: { throw ParseUtils.unexpectedAttribute(reader, i); } } } ParseUtils.requireNoContent(reader); operations.put(offHeapAddress, offHeap); }
Source:
<code><START> private long getDiskUsage(File <END> dir) throws IOException { final MutableLong size = new MutableLong(); Files.walkFileTree(dir.toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException { if (attrs.isRegularFile()) { size.add(attrs.size()); } return FileVisitResult.CONTINUE; } }); return size.longValue(); }</code><technical_language>private static long Sorry, missed one</technical_language>

Target:
private static long getDiskUsage(File dir) throws IOException { final MutableLong size = new MutableLong(); Files.walkFileTree(dir.toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException { if (attrs.isRegularFile()) { size.add(attrs.size()); } return FileVisitResult.CONTINUE; } }); return size.longValue(); }
Source:
<code>public void findByJugmentId_CommonCourtJudgment() { int judgmentId = 123; List<JudgmentCorrection> unsortedJc = Lists.newArrayList(); unsortedJc.add(createJcJudgeDelete(ccJudgment)); unsortedJc.add(createJcCommonCourtJudgment()); List<JudgmentCorrection> expectedJc = Lists.newArrayList(); expectedJc.add(createJcCommonCourtJudgment()); expectedJc.add(createJcJudgeDelete(ccJudgment)); when(judgmentCorrectionRepository.findAllByJudgmentId(judgmentId)).thenReturn(unsortedJc); <START> judgmentCorrectionService.setJudgmentCorrectionRepository(judgmentCorrectionRepository); <END> List<JudgmentCorrection> actualJc = judgmentCorrectionService.findByJugmentId(judgmentId); assertEquals(expectedJc, actualJc); }</code><technical_language>put this line method, repeat in test case</technical_language>

Target:
public void findByJugmentId_CommonCourtJudgment() { int judgmentId = 123; List<JudgmentCorrection> unsortedJc = Lists.newArrayList(); unsortedJc.add(createJcJudgeDelete(ccJudgment)); unsortedJc.add(createJcCommonCourtJudgment()); unsortedJc.add(createJcJudgeUpdate(ccJudgment)); List<JudgmentCorrection> expectedJc = Lists.newArrayList(); expectedJc.add(createJcCommonCourtJudgment()); expectedJc.add(createJcJudgeUpdate(ccJudgment)); expectedJc.add(createJcJudgeDelete(ccJudgment)); when(judgmentCorrectionRepository.findAllByJudgmentId(judgmentId)).thenReturn(unsortedJc); List<JudgmentCorrection> actualJc = judgmentCorrectionService.findAllByJudgmentIdSorted(judgmentId); assertEquals(expectedJc, actualJc); }
Source:
<code>private void addGlusterWebhook(VDS vds) { try { <START> backend.runInternalAction(ActionType.AddGlusterWebhookInternal, new VdsActionParameters(vds.getId())); <END> } catch (EngineException e) { log.error("Could not add gluster webhook for gluster host '{}'", vds.getName()); } catch (Exception e) { log.error("Could not add gluster webhook for gluster host '{}'", vds.getName()); } }</code><technical_language>iiuc, AddGlusterWebhookInternal is responsible deny request if action supported. This is blocked can-do-action recorded (maybe validation failure message log) for failure execution of AddGlusterWebhookInternal command: AddGlusterWebhookInternal command is responsible for creating events log if fails, need record in this context. result of AddGlusterWebhookInternal affect execution of initGlusterHost() ? meaning, if initGlusterPeerProcess(vds); fails, attempt execute AddGlusterWebhookInternal</technical_language>

Target:
private void addGlusterWebhook(VDS vds) { try { backend.runInternalAction(ActionType.AddGlusterWebhookInternal, new VdsActionParameters(vds.getId())); } catch (RuntimeException e) { log.error("Could not add gluster webhook for gluster host '{}'", vds.getName()); log.debug("Exception", e); } }
Source:
<code>public int getExecutionIndex() { <START> return super.getExecutionIndex() + 1; <END> }</code><technical_language>a hardcoded index</technical_language>

Target:
public int getExecutionIndex() { return 53; }
Source:
<code>public static SqlExpression create(String name, String op, Nesting value) { op = Strings.trim(op.toUpperCase()); if (value == null) { throw Lang.makeThrow("nesting sql can not be null'"); } else if ("LIKE".equals(op) || "NOT LIKE".equals(op)) { return like(name, value).setNot(op.startsWith("NOT")); } else if ("=".equals(op)) { return eq(name, value); } else if ("!=".equals(op) || "<>".equals(op)) { return notEq(name, value); } else if ("IN".equals(op) || "NOT IN".equals(op)) { return inSql(name, value).setNot(op.startsWith("NOT")); } else if ("EXISTS".equals(op) || "NOT EXISTS".equals(op)) { <START> return exusts(value).setNot(op.startsWith("NOT")); <END> } return otherSymbol(name, op, value); }</code><technical_language>suggestion return exists(value).setNot(op.startsWith("NOT"));</technical_language>

Target:
public static SqlExpression create(String name, String op, Nesting value) { op = Strings.trim(op.toUpperCase()); if (value == null) { throw Lang.makeThrow("nesting sql can not be null'"); } else if ("LIKE".equals(op) || "NOT LIKE".equals(op)) { return like(name, value).setNot(op.startsWith("NOT")); } else if ("=".equals(op)) { return eq(name, value); } else if ("!=".equals(op) || "<>".equals(op)) { return notEq(name, value); } else if ("IN".equals(op) || "NOT IN".equals(op)) { return inSql(name, value).setNot(op.startsWith("NOT")); } else if ("EXISTS".equals(op) || "NOT EXISTS".equals(op)) { return exists(value).setNot(op.startsWith("NOT")); } return otherSymbol(name, op, value); }
Source:
<code>protected void commandProcessing() { boolean longPollingActivated = false; while (connectedFlag.get()) { try { final List<CommandAndHandler> toProcess = commandBatcher.getWaitingBatches().getVal(); List<Command> commands = new ArrayList<>(); for (CommandAndHandler c : toProcess) { commands.add(c.getCommand()); } if (LOG.isDebugEnabled()) { StringBuffer buffer = new StringBuffer(); for (Command command : commands) { buffer.append(command.getClass().getSimpleName()); buffer.append(", "); } LOG.trace("Sending commands to server: {}", commands.size(), buffer.substring(0, buffer.length() - 2)); } else { LOG.trace("Sending commands to server", commands.size()); } final List<? extends Command> answers = transmit(commands); uiExecutor.execute(new Runnable() { @Override public void run() { processResults(answers, toProcess); } }); } catch (Exception e) { if (connectedFlag.get()) { handleError(e); } else { <START> LOG.debug("Remoting error based on broken connection in parallel request", e); <END> } } if(!longPollingActivated && useLongPolling.get()) { uiExecutor.execute(new Runnable() { @Override public void run() { listen(); } }); longPollingActivated = true; } } }</code><technical_language>warn ;)</technical_language>

Target:
protected void commandProcessing() { boolean longPollingActivated = false; while (connectedFlag.get()) { try { final List<CommandAndHandler> toProcess = commandBatcher.getWaitingBatches().getVal(); List<Command> commands = new ArrayList<>(); for (CommandAndHandler c : toProcess) { commands.add(c.getCommand()); } if (LOG.isDebugEnabled()) { StringBuffer buffer = new StringBuffer(); for (Command command : commands) { buffer.append(command.getClass().getSimpleName()); buffer.append(", "); } LOG.trace("Sending commands to server: {}", commands.size(), buffer.substring(0, buffer.length() - 2)); } else { LOG.trace("Sending commands to server", commands.size()); } final List<? extends Command> answers = transmit(commands); uiExecutor.execute(new Runnable() { @Override public void run() { processResults(answers, toProcess); } }); } catch (Exception e) { if (connectedFlag.get()) { handleError(e); } else { LOG.warn("Remoting error based on broken connection in parallel request", e); } } if(!longPollingActivated && useLongPolling.get()) { uiExecutor.execute(new Runnable() { @Override public void run() { listen(); } }); longPollingActivated = true; } } }
Source:
<code>public static String buildSearchUrl(String url) { <START> return UriBuilder.fromUri(url). <END> path("rest") .path("api") .path("latest") .path("search") .build().toString(); }</code><technical_language>Nitpick: trailing dot next line. Purely taste, necessary change: builder style for multiple segments benefits is mixed variables; for constants, ...fromUri(url).path("rest/api/latest/myself")... a bit more concise easy read</technical_language>

Target:
public static String buildSearchUrl(String url) { return UriBuilder.fromUri(url).path(SEARCH_URI_PATH).build().toString(); }
Source:
<code>public static List<ObjectModelResolver> getResolvers() { if (resolvers == null) { synchronized (serviceLoader) { if (resolvers == null) { List<ObjectModelResolver> foundResolvers = new ArrayList<ObjectModelResolver>(); for (ObjectModelResolver reolver : serviceLoader) { <START> foundResolvers.add(reolver); <END> } resolvers = foundResolvers; } } } return resolvers; }</code><technical_language>is typo here</technical_language>

Target:
public static List<ObjectModelResolver> getResolvers() { if (resolvers == null) { synchronized (serviceLoader) { if (resolvers == null) { List<ObjectModelResolver> foundResolvers = new ArrayList<ObjectModelResolver>(); for (ObjectModelResolver resolver : serviceLoader) { foundResolvers.add(resolver); } resolvers = foundResolvers; } } } return resolvers; }
Source:
<code>public String getLeadingImageEditLang() { <START> return isTranslation ? captionTargetPageTitle == null ? null : captionTargetPageTitle.getWikiSite().languageCode() : captionSourcePageTitle == null ? null : captionSourcePageTitle.getWikiSite().languageCode(); <END> }</code><technical_language>sourceSummary.getPageTitle() targetSummary.getPageTitle() for PageTitle</technical_language>

Target:
public String getLeadingImageEditLang() { if (isTranslation ? (targetSummary == null || sourceSummary == null) : sourceSummary == null) { return null; } return isTranslation ? targetSummary.getPageTitle().getWikiSite().languageCode() : sourceSummary.getPageTitle().getWikiSite().languageCode(); }
Source:
<code>public BasicDocumentRevision getDocument(String id, String rev) { Preconditions.checkState(this.isOpen(), "Database is closed"); Preconditions.checkArgument(!Strings.isNullOrEmpty(id), "DocumentRevisionTree id can not be empty"); Cursor cursor = null; try { String[] args = (rev == null) ? new String[]{id} : new String[]{id, rev}; String sql = (rev == null) ? GET_DOCUMENT_CURRENT_REVISION : GET_DOCUMENT_GIVEN_REVISION; cursor = this.sqlDb.rawQuery(sql, args); if (cursor.moveToFirst()) { <START> return SQLDatabaseUtils.getFullRevisionFromCurrentCursor(cursor, attachmentManager); <END> } else { return null; } } catch (SQLException e) { throw new SQLRuntimeException("Error getting document with id: " + id + "and rev" + rev, e); } finally { DatabaseUtils.closeCursorQuietly(cursor); } }</code><technical_language>SQLDatabaseUtils requiring knowledge of attachment manager class feels a bit upside down. class naming else, AttachmentManager sits MVCC knowledge layer SQLDatabaseUtils lives layer</technical_language>

Target:
public BasicDocumentRevision getDocument(String id, String rev) { Preconditions.checkState(this.isOpen(), "Database is closed"); Preconditions.checkArgument(!Strings.isNullOrEmpty(id), "DocumentRevisionTree id can not be empty"); Cursor cursor = null; try { String[] args = (rev == null) ? new String[]{id} : new String[]{id, rev}; String sql = (rev == null) ? GET_DOCUMENT_CURRENT_REVISION : GET_DOCUMENT_GIVEN_REVISION; cursor = this.sqlDb.rawQuery(sql, args); if (cursor.moveToFirst()) { long sequence = cursor.getLong(3); List<? extends Attachment> atts = attachmentManager.attachmentsForRevision(sequence); return getFullRevisionFromCurrentCursor(cursor, atts); } else { return null; } } catch (SQLException e) { throw new SQLRuntimeException("Error getting document with id: " + id + "and rev" + rev, e); } finally { DatabaseUtils.closeCursorQuietly(cursor); } }
Source:
<code><START> private static void writeTilesToBlockBuilder(OGCGeometry geometry, <END> int zoomLevel, BingTile tile, BlockBuilder blockBuilder) { int tileZoomLevel = tile.getZoomLevel(); checkArgument(tile.getZoomLevel() <= zoomLevel); OGCGeometry polygon = tileToPolygon(tile); if (tileZoomLevel == zoomLevel) { if (!geometry.disjoint(polygon)) { BIGINT.writeLong(blockBuilder, tile.encode()); } return; } if (geometry.contains(polygon)) { int subTileCount = 1 << (zoomLevel - tileZoomLevel); int minX = subTileCount * tile.getX(); int minY = subTileCount * tile.getY(); for (int x = minX; x < minX + subTileCount; x++) { for (int y = minY; y < minY + subTileCount; y++) { BIGINT.writeLong(blockBuilder, BingTile.fromCoordinates(x, y, zoomLevel).encode()); } } return; } if (geometry.disjoint(polygon)) { return; } int minX = 2 * tile.getX(); int minY = 2 * tile.getY(); int nextZoomLevel = tileZoomLevel + 1; for (int x = minX; x < minX + 2; x++) { for (int y = minY; y < minY + 2; y++) { writeTilesToBlockBuilder( geometry, zoomLevel, BingTile.fromCoordinates(x, y, nextZoomLevel), blockBuilder); } } }</code><technical_language>Is indentation for method parameters? be: private static void writeTilesToBlockBuilder(OGCGeometry geometry, int zoomLevel, BingTile tile, BlockBuilder blockBuilder)</technical_language>

Target:
private static void writeTilesToBlockBuilder( OGCGeometry geometry, int zoomLevel, BingTile tile, BlockBuilder blockBuilder) { int tileZoomLevel = tile.getZoomLevel(); checkArgument(tile.getZoomLevel() <= zoomLevel); OGCGeometry polygon = tileToPolygon(tile); if (tileZoomLevel == zoomLevel) { if (!geometry.disjoint(polygon)) { BIGINT.writeLong(blockBuilder, tile.encode()); } return; } if (geometry.contains(polygon)) { int subTileCount = 1 << (zoomLevel - tileZoomLevel); int minX = subTileCount * tile.getX(); int minY = subTileCount * tile.getY(); for (int x = minX; x < minX + subTileCount; x++) { for (int y = minY; y < minY + subTileCount; y++) { BIGINT.writeLong(blockBuilder, BingTile.fromCoordinates(x, y, zoomLevel).encode()); } } return; } if (geometry.disjoint(polygon)) { return; } int minX = 2 * tile.getX(); int minY = 2 * tile.getY(); int nextZoomLevel = tileZoomLevel + 1; Verify.verify(nextZoomLevel <= MAX_ZOOM_LEVEL); for (int x = minX; x < minX + 2; x++) { for (int y = minY; y < minY + 2; y++) { writeTilesToBlockBuilder( geometry, zoomLevel, BingTile.fromCoordinates(x, y, nextZoomLevel), blockBuilder); } } }
Source:
<code>private void initValidEmails() { if (validEmails == null) { <START> validEmails = state().getEmailAddresses(); <END> } }</code><technical_language>reading this code I idea AccountState's list of email addresses differs Realm's. AccountState.getEmailAddresses query realm? this double layer of email address listing belong in IdentifiedUser all</technical_language>

Target:
private void initValidEmails() { if (validEmails == null) { validEmails = Sets.newHashSetWithExpectedSize(4); } }
Source:
<code>public UserIdentity getUserIdentityByToken(String token) throws AuthException { log.debug("KeystoneService: entered getUserIdentityByToken. Token={}", token); if (StringUtils.isEmpty(token)) { throw new InvalidCredentialsException("No token was passed in."); } KeystoneAccess access = null; try { access = client.getToken(token); } catch (KeystoneConnectionException kex) { <START> log.debug("Authentication connection failed: "+kex.getMessage()); <END> } catch (KeystoneServerException ex) { log.debug("Authentication failed: "+ex.getMessage()); throw new InvalidCredentialsException("Invalid token"); } return (access == null) ? null : getUserIdentity(access); }</code><technical_language>squash exception here? If do, instead log "warn" here</technical_language>

Target:
public UserIdentity getUserIdentityByToken(String token) throws AuthException { log.debug("KeystoneService: entered getUserIdentityByToken. Token={}", token); if (StringUtils.isEmpty(token)) { throw new InvalidCredentialsException("No token was passed in."); } KeystoneAccess access = null; try { access = client.getToken(token); } catch (KeystoneConnectionException kex) { log.warn("Authentication connection failed: "+ kex.getMessage()); } catch (KeystoneServerException ex) { log.debug("Authentication failed: " + ex.getMessage()); throw new InvalidCredentialsException("Problems with the token: " + ex.getMessage()); } return (access == null) ? null : getUserIdentity(access); }
Source:
<code>public Path getResourceManagerRootPath() { <START> return Paths.get(getResourceManagerRoot().getAbsolutePath()); <END> }</code><technical_language>getResourceManagerRoot().toPath();</technical_language>

Target:
public Path getResourceManagerRootPath() { return getResourceManagerRoot().toPath(); }
Source:
<code>private XceiverClientSpi getClient(Pipeline pipeline, boolean forRead) throws IOException { HddsProtos.ReplicationType type = pipeline.getType(); try { <START> String key = pipeline.getId().getId().toString() + type; <END> if (topologyAwareRead && forRead) { key += pipeline.getClosestNode().getHostName(); } key = isSecurityEnabled ? key + UserGroupInformation.getCurrentUser().getShortUserName() : key; return clientCache.get(key, new Callable<XceiverClientSpi>() { @Override public XceiverClientSpi call() throws Exception { XceiverClientSpi client = null; switch (type) { case RATIS: client = XceiverClientRatis.newXceiverClientRatis(pipeline, conf); client.connect(); break; case STAND_ALONE: client = new XceiverClientGrpc(pipeline, conf); break; case CHAINED: default: throw new IOException("not implemented" + pipeline.getType()); } return client; } }); } catch (Exception e) { throw new IOException( "Exception getting XceiverClient: " + e.toString(), e); } }</code><technical_language>wrap this logic in a function getPipelineKey()</technical_language>

Target:
private XceiverClientSpi getClient(Pipeline pipeline, boolean forRead) throws IOException { HddsProtos.ReplicationType type = pipeline.getType(); try { String key = getPipelineCacheKey(pipeline, forRead); key = isSecurityEnabled ? key + UserGroupInformation.getCurrentUser().getShortUserName() : key; return clientCache.get(key, new Callable<XceiverClientSpi>() { @Override public XceiverClientSpi call() throws Exception { XceiverClientSpi client = null; switch (type) { case RATIS: client = XceiverClientRatis.newXceiverClientRatis(pipeline, conf); client.connect(); break; case STAND_ALONE: client = new XceiverClientGrpc(pipeline, conf); break; case CHAINED: default: throw new IOException("not implemented" + pipeline.getType()); } return client; } }); } catch (Exception e) { throw new IOException( "Exception getting XceiverClient: " + e.toString(), e); } }
Source:
<code>public void cancel() { <START> final PublishSubject<Integer> pp = PublishSubject.create(); <END> final CompletableSubject cs = CompletableSubject.create(); TestObserver<Integer> ts = pp.mergeWith(cs).test(); assertTrue(pp.hasObservers()); assertTrue(cs.hasObservers()); ts.cancel(); assertFalse(pp.hasObservers()); assertFalse(cs.hasObservers()); }</code><technical_language>nit: ps pp</technical_language>

Target:
public void cancel() { final PublishSubject<Integer> ps = PublishSubject.create(); final CompletableSubject cs = CompletableSubject.create(); TestObserver<Integer> to = ps.mergeWith(cs).test(); assertTrue(ps.hasObservers()); assertTrue(cs.hasObservers()); to.cancel(); assertFalse(ps.hasObservers()); assertFalse(cs.hasObservers()); }
Source:
<code>public String rewriteURL( @Nullable RuntimeIdentity identity, @Nullable String machineName, @Nullable String serverName, String url) throws InfrastructureException { final String host = hostnameBuilder.build(serverName, machineName, identity.getWorkspaceId()); try { <START> URI uri = UriBuilder.fromUri(url).host(host).build(); <END> url = uri.toString(); } catch (UriBuilderException | IllegalArgumentException e) { throw new InternalInfrastructureException( format( "Rewriting of host '%s' in URL '%s' failed. Error: %s", host, url, e.getMessage())); } return url; }</code><technical_language>I in this case port is rewritten, this code changes a hostname only</technical_language>

Target:
public String rewriteURL( @Nullable RuntimeIdentity identity, @Nullable String machineName, @Nullable String serverName, String url) throws InfrastructureException { final String host = hostnameBuilder.build(serverName, machineName, identity.getWorkspaceId()); try { int port = wildcartPort != null ? Integer.parseInt(wildcartPort) : chePort; URI uri = UriBuilder.fromUri(url).host(host).port(port).build(); url = uri.toString(); } catch (UriBuilderException | IllegalArgumentException e) { throw new InternalInfrastructureException( format( "Rewriting of host '%s' in URL '%s' failed. Error: %s", host, url, e.getMessage())); } return url; }
Source:
<code>public void appendString(Blackhole bh, AppenderState appenderState) throws IOException { <START> bh.consume(appenderState.appender.append("A small string")); <END> }</code><technical_language>afraid this is wrong. In fact want compare benchmarks a steady state. more append slower becomes. want add @Param int numAppends; compare perf for string of a length. Alternative option is call RelLiteral#toJavaString run Calcite versions in classpath</technical_language>

Target:
public void appendString(Blackhole bh, AppenderState appenderState) throws IOException { bh.consume(appenderState.getOrCreateAppender().append("placeholder")); }
Source:
<code>public void handleResponse(final String methodName, final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType deviceResult, final OsgpException exception) { LOGGER.debug("{} for MessageType: {}", methodName, deviceMessageMetadata.getMessageType()); ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error("Device Response not ok. Unexpected Exception", exception); result = ResponseMessageResultType.NOT_OK; } <START> this.webServiceResponseMessageSender.send(ResponseMessage.newResponseMessageBuilder() <END> .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception).withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(), deviceMessageMetadata.getMessageType()); }</code><technical_language>Extract building of ResponseMessage variable (in eclipse, select text, right-click > refactor > extract local variable / select code + shift+alt+L). This code a bit more readable, especially passing in other besides ResponseMessage</technical_language>

Target:
public void handleResponse(final String methodName, final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType deviceResult, final OsgpException exception) { LOGGER.debug("{} for MessageType: {}", methodName, deviceMessageMetadata.getMessageType()); ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error("Device Response not ok. Unexpected Exception", exception); result = ResponseMessageResultType.NOT_OK; } ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception).withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(); this.webServiceResponseMessageSender.send(responseMessage, deviceMessageMetadata.getMessageType()); }
Source:
<code>T getNextHandle() { try { while (xmlStreamReader.hasNext()) { int event = xmlStreamReader.next(); if (event == XMLStreamReader.START_ELEMENT) { StartElementReaderImpl startElementReader = new StartElementReaderImpl(xmlStreamReader); NodeOperation nodeOperation = visitor.startElement(startElementReader); if (nodeOperation == null) { throw new IllegalStateException("No NodeOperation returned."); } switch (nodeOperation) { case DESCEND: break; case PROCESS: T handle = visitor.makeBufferedHandle(xmlStreamReader); if (handle != null) { return handle; } break; case SKIP: <START> int count = 0; <END> while (xmlStreamReader.hasNext()) { int next = xmlStreamReader.next(); if (next == XMLStreamReader.START_ELEMENT) { count++; } if (next == XMLStreamReader.END_ELEMENT) { if (count == 0) { break; } count--; } } break; default: throw new IllegalStateException("Unknown state"); } }else if (event == XMLStreamReader.END_ELEMENT) { visitor.endElement( xmlStreamReader.getNamespaceURI(), xmlStreamReader.getLocalName()); } } return null; } catch (XMLStreamException e) { throw new RuntimeException("Failed to traverse document", e); } }</code><technical_language>counting depth in tree, code easier for new read if variable renamed "depth"</technical_language>

Target:
T getNextHandle() { try { while (xmlStreamReader.hasNext()) { int event = xmlStreamReader.next(); checkForHandle: switch (event) { case XMLStreamReader.START_ELEMENT: StartElementReaderImpl startElementReader = new StartElementReaderImpl(xmlStreamReader); NodeOperation nodeOperation = visitor.startElement(startElementReader); if (nodeOperation == null) { throw new IllegalStateException("No NodeOperation returned."); } switch (nodeOperation) { case DESCEND: break checkForHandle; case PROCESS: T handle = visitor.makeBufferedHandle(new XMLBranchStreamReader(xmlStreamReader)); if (handle != null) { return handle; } break checkForHandle; case SKIP: int depth = 0; while (xmlStreamReader.hasNext()) { int next = xmlStreamReader.next(); skipCheck: switch (next) { case XMLStreamReader.START_ELEMENT: depth++; break skipCheck; case XMLStreamReader.END_ELEMENT: if (depth == 0) { break checkForHandle; } depth--; break skipCheck; default: break skipCheck; } } break checkForHandle; default: throw new IllegalStateException("Unknown state"); } case XMLStreamReader.END_ELEMENT: visitor.endElement( xmlStreamReader.getNamespaceURI(), xmlStreamReader.getLocalName()); break checkForHandle; default: break checkForHandle; } } return null; } catch (XMLStreamException e) { throw new RuntimeException("Failed to traverse document", e); } }
Source:
<code>public ContentEvent nextEvent() { InstanceContentEvent contentEvent = null; <START> if (isReachedEndOfStream()) { <END> contentEvent = new InstanceContentEvent(-1, firstInstance, false, true); contentEvent.setLast(true); finished = true; } else if (hasNext()) { numInstanceSent++; contentEvent = new InstanceContentEvent(numInstanceSent, nextInstance(), true, true); if (schedule == null && delay > 0) { schedule = timer.scheduleWithFixedDelay(new DelayTimeoutHandler(this), delay, delay, TimeUnit.MILLISECONDS); } } return contentEvent; }</code><technical_language>I Java conventions, read hasReached...</technical_language>

Target:
public ContentEvent nextEvent() { InstanceContentEvent contentEvent = null; if (hasReachedEndOfStream()) { contentEvent = new InstanceContentEvent(-1, firstInstance, false, true); contentEvent.setLast(true); finished = true; } else if (hasNext()) { numInstanceSent++; contentEvent = new InstanceContentEvent(numInstanceSent, nextInstance(), true, true); if (schedule == null && delay > 0) { schedule = timer.scheduleWithFixedDelay(new DelayTimeoutHandler(this), delay, delay, TimeUnit.MICROSECONDS); } } return contentEvent; }
Source:
<code>public final CompletionStage<Void> commit(int segment, InternalDataContainer container) { if (segment < 0) { throw new IllegalArgumentException("Segment must be 0 or greater"); } if (shouldCommit()) { if (isEvicted()) { CompletionStage<Void> evict = container.evict(segment, key); setCommitted(); return evict; } else if (isRemoved()) { container.remove(segment, key); setCommitted(); } else if (value != null) { container.put(segment, key, value, metadata, internalMetadata, created, lastUsed); setCommitted(); <START> } <END> } return CompletableFutures.completedNull(); }</code><technical_language>call setCommitted() immediately shouldCommit()</technical_language>

Target:
public final CompletionStage<Void> commit(int segment, InternalDataContainer container) { if (segment < 0) { throw new IllegalArgumentException("Segment must be 0 or greater"); } if (shouldCommit()) { setCommitted(); if (isEvicted()) { return container.evict(segment, key); } else if (isRemoved()) { container.remove(segment, key); } else if (value != null) { container.put(segment, key, value, metadata, internalMetadata, created, lastUsed); } } return CompletableFutures.completedNull(); }
Source:
<code>private void doForm(List<String> parameters) { form = new FormStyleLayout(); form.setType(FormType.HORIZONTAL); Anchor link = new Anchor(); link.setText(referenceLink); link.setHref(referenceLink); link.setTarget("_blank"); form.addAttribute("Reference Link", link); for (String param : parameters) { TextBox paramField = GWT.create(TextBox.class); form.addAttribute(param, paramField); fields.add(paramField); } this.setBody(form); <START> this.add(new ModalFooter() {{ <END> Button installButton = new Button(Constants.INSTANCE.InstallServiceTask()) {{ addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { List<String> parameters = fields.stream().map(textbox -> textbox.getValue()).collect(Collectors.toList()); presenter.installWithParameters(serviceTaskId, target, parameters); hide(); } }); }}; installButton.setType( ButtonType.PRIMARY ); add(installButton); add(new Button(Constants.INSTANCE.Cancel()) {{ addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { hide(); } }); }}); }}); }</code><technical_language>here, class code style</technical_language>

Target:
private void doForm(List<String> parameters) { form = new FormStyleLayout(); form.setType(FormType.HORIZONTAL); Anchor link = new Anchor(); link.setText(referenceLink); link.setHref(referenceLink); link.setTarget("_blank"); form.addAttribute("Reference Link", link); for (String param : parameters) { TextBox paramField = GWT.create(TextBox.class); form.addAttribute(param, paramField); fields.add(paramField); } this.setBody(form); Button installButton = new Button(Constants.INSTANCE.InstallServiceTask()); installButton.setType(ButtonType.PRIMARY); installButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { List<String> parameters = fields.stream().map(textbox -> textbox.getValue()).collect(Collectors.toList()); presenter.installWithParameters(serviceTaskId, target, parameters); hide(); } }); ModalFooter footer = new ModalFooter(); Button cancelButton = new Button(Constants.INSTANCE.Cancel()); cancelButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { hide(); } }); footer.add(installButton); footer.add(cancelButton); this.add(footer); }
Source:
<code>public static boolean extractFileFromZip(String filePath, String file, String name) throws Exception { ZipInputStream inZip = new ZipInputStream( new BufferedInputStream( new FileInputStream(filePath))); byte data[] = new byte[BUFFER_SIZE]; boolean found = false; ZipEntry ze; while((ze = inZip.getNextEntry()) != null) { if(ze.getName().equals(name)) { found = true; File oldFile = new File(file); if(oldFile.exists()) { if(!oldFile.delete()) { throw new Exception("Could not delete " + file); } } FileOutputStream outFile = new FileOutputStream(file); <START> int count; <END> while((count = inZip.read(data)) != -1) { outFile.write(data, 0, count); } outFile.close(); inZip.closeEntry(); } } return found; }</code><technical_language>count = 0; stay for visibility</technical_language>

Target:
public static boolean extractFileFromZip(String filePath, String file, String name) throws Exception { ZipInputStream inZip = new ZipInputStream( new BufferedInputStream( new FileInputStream(filePath))); byte data[] = new byte[BUFFER_SIZE]; boolean found = false; ZipEntry ze; while((ze = inZip.getNextEntry()) != null) { if(ze.getName().equals(name)) { found = true; File oldFile = new File(file); if(oldFile.exists()) { if(!oldFile.delete()) { throw new Exception("Could not delete " + file); } } FileOutputStream outFile = new FileOutputStream(file); int count = 0; while((count = inZip.read(data)) != -1) { outFile.write(data, 0, count); } outFile.close(); inZip.closeEntry(); } } return found; }
Source:
<code>public void testArrayRefToLiteralCharArraySameLengths() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); try (Connection conn = DriverManager.getConnection(getUrl(), props)) { PreparedStatement stmt = conn.prepareStatement("select ?[2] from " <START> + "\"SYSTEM\".\"CATALOG\" limit 1"); <END> Array array = conn.createArrayOf("CHAR", new String[] {"a","b","c"}); stmt.setArray(1, array); ResultSet rs = stmt.executeQuery(); assertTrue(rs.next()); assertEquals("b", rs.getString(1)); assertFalse(rs.next()); } }</code><technical_language>define static final String TEST_STATEMENT = "select ?[2] \"SYSTEM\".\"CATALOG\" limit 1"</technical_language>

Target:
public void testArrayRefToLiteralCharArraySameLengths() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); try (Connection conn = DriverManager.getConnection(getUrl(), props)) { PreparedStatement stmt = conn.prepareStatement(TEST_QUERY); Array array = conn.createArrayOf("CHAR", new String[] {"a","b","c"}); stmt.setArray(1, array); ResultSet rs = stmt.executeQuery(); assertTrue(rs.next()); assertEquals("b", rs.getString(1)); assertFalse(rs.next()); } }