auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public String generateBodyValue(String name, Schema<?> property) { if (isArray(property)) { return generators .getArrayGenerator() .generate(name, (ArraySchema) property, "csv", false); <START> } else if (isMap(property)) { <END> return generators.getMapGenerator().generate(TYPES, property); } else { return generateValue(name, property, false); } }</code><technical_language>else is unnecessary, returns (same for else)</technical_language>

Target:
public String generateBodyValue(String name, Schema<?> property) { if (isArray(property)) { return generators .getArrayGenerator() .generate(name, (ArraySchema) property, "csv", false); } if (isMap(property)) { return generators.getMapGenerator().generate(TYPES, property); } return generateValue(name, property, false); }
Source:
<code>public void testValueOf() { StudentProfile studentProfile = new StudentProfile("id", "Joe", "joe@gmail.com", "Teammates Institute", "American", Gender.MALE, new Text("hello"), new BlobKey("key")); StudentProfileAttributes profileAttributes = StudentProfileAttributes.valueOf(studentProfile); assertEquals(studentProfile.getGoogleId(), profileAttributes.googleId); assertEquals(studentProfile.getShortName(), profileAttributes.shortName); assertEquals(studentProfile.getEmail(), profileAttributes.email); assertEquals(studentProfile.getInstitute(), profileAttributes.institute); assertEquals(studentProfile.getNationality(), profileAttributes.nationality); <START> assertEquals(studentProfile.getGender().name(), profileAttributes.gender.name()); <END> assertEquals(studentProfile.getMoreInfo().getValue(), profileAttributes.moreInfo); assertEquals(studentProfile.getPictureKey().getKeyString(), profileAttributes.pictureKey); }</code><technical_language>is this necessary</technical_language>

Target:
public void testValueOf() { StudentProfile studentProfile = new StudentProfile("id", "Joe", "joe@gmail.com", "Teammates Institute", "American", Gender.MALE, new Text("hello"), new BlobKey("key")); StudentProfileAttributes profileAttributes = StudentProfileAttributes.valueOf(studentProfile); assertEquals(studentProfile.getGoogleId(), profileAttributes.googleId); assertEquals(studentProfile.getShortName(), profileAttributes.shortName); assertEquals(studentProfile.getEmail(), profileAttributes.email); assertEquals(studentProfile.getInstitute(), profileAttributes.institute); assertEquals(studentProfile.getNationality(), profileAttributes.nationality); assertEquals(studentProfile.getGender(), profileAttributes.gender); assertEquals(studentProfile.getMoreInfo().getValue(), profileAttributes.moreInfo); assertEquals(studentProfile.getPictureKey().getKeyString(), profileAttributes.pictureKey); }
Source:
<code>public void showReflogFor(Repository repository) { String refName = Constants.R_HEADS + Constants.MASTER; try { Ref ref = repository.getRef(Constants.HEAD); if (ref != null && ref.isSymbolic()) <START> refName = ref.getTarget().getName(); <END> } catch (IOException e) { Activator.logError("Error getting HEAD reference", e); } showReflogFor(repository, refName); }</code><technical_language>no, resolve symbolic link get reflog for branch HEAD is pointing at, instead I extra reflog maintained for HEAD updates of HEAD including branch switches is case for git reflog for a branch. refName = Constants.HEAD instead of refName = ref.getTarget().getName() difference, select master difference. branch selection dialog of reflog view needs show HEAD this selected explicitly</technical_language>

Target:
public void showReflogFor(Repository repository) { showReflogFor(repository, Constants.HEAD); }
Source:
<code>private void fetchPinotData() { <START> log.debug("Fetching data from Pinot for table %s, segment %s", split.getTableName(), split.getSegment()); <END> long startTimeNanos = System.nanoTime(); int idx = 0; for (PinotColumnHandle columnHandle : columnHandles) { pinotColumnNameIndexMap.put(columnHandle.getColumnName(), idx++); } String pinotQuery = getPinotQuery(pinotConfig, columnHandles, split.getPinotFilter(), split.getTimeFilter(), split.getTableName(), split.getLimit()); Map<ServerInstance, DataTable> dataTableMap = pinotQueryClient.queryPinotServerForDataTable(pinotQuery, split.getHost(), split.getSegment()); dataTableMap.values().stream() .filter(table -> table != null && table.getNumberOfRows() > 0) .forEach(dataTable -> { int estimatedTableSizeInBytes = IntStream.rangeClosed(0, dataTable.getDataSchema().size() - 1) .map(i -> getEstimatedColumnSizeInBytes(dataTable.getDataSchema().getColumnDataType(i)) * dataTable.getNumberOfRows()) .reduce(0, Integer::sum); dataTableList.add(new PinotDataTableWithSize(dataTable, estimatedTableSizeInBytes)); estimatedMemoryUsageInBytes += estimatedTableSizeInBytes; }); ImmutableList.Builder<Type> types = ImmutableList.builder(); columnHandles .stream() .map(columnHandle -> getTypeForBlock(columnHandle)) .forEach(types::add); this.columnTypes = types.build(); readTimeNanos = System.nanoTime() - startTimeNanos; isPinotDataFetched = true; }</code><technical_language>remove</technical_language>

Target:
private void fetchPinotData() { log.debug("Fetching data from Pinot for table %s, segment %s", split.getTableName(), split.getSegment()); long startTimeNanos = System.nanoTime(); if (pinotColumnNameIndexMap.isEmpty()) { int idx = 0; for (PinotColumnHandle columnHandle : columnHandles) { pinotColumnNameIndexMap.put(columnHandle.getColumnName(), idx++); } } String pinotQuery = getPinotQuery(pinotConfig, columnHandles, split.getPinotFilter(), split.getTimeFilter(), split.getTableName(), split.getLimit()); Map<ServerInstance, DataTable> dataTableMap = pinotQueryClient.queryPinotServerForDataTable(pinotQuery, split.getHost(), split.getSegment()); dataTableMap.values().stream() .filter(table -> table != null && table.getNumberOfRows() > 0) .forEach(dataTable -> { int estimatedTableSizeInBytes = IntStream.rangeClosed(0, dataTable.getDataSchema().size() - 1) .map(i -> getEstimatedColumnSizeInBytes(dataTable.getDataSchema().getColumnDataType(i)) * dataTable.getNumberOfRows()) .reduce(0, Integer::sum); dataTableList.add(new PinotDataTableWithSize(dataTable, estimatedTableSizeInBytes)); estimatedMemoryUsageInBytes += estimatedTableSizeInBytes; }); ImmutableList.Builder<Type> types = ImmutableList.builder(); columnHandles.stream() .map(PinotPageSource::getTypeForBlock) .forEach(types::add); columnTypes = types.build(); readTimeNanos += System.nanoTime() - startTimeNanos; isPinotDataFetched = true; }
Source:
<code>public static <S, T> ForwardingObservable<T> convert(ClosableObservable<S> observable, Converter<S, T> converter) { <START> return new ForwardingObservable<>("InstUtils", new ConvertingObservable<>(observable, converter)); <END> }</code><technical_language>this debug code</technical_language>

Target:
public static <S, T> ForwardingObservable<T> convert(ClosableObservable<S> observable, Converter<S, T> converter) { return new ForwardingObservable<>(new ConvertingObservable<>(observable, converter)); }
Source:
<code>public static String checkScientificNameAtNCBI(String scientificName) throws IOException { if (!taxonomyCache.containsKey(scientificName)) { String query = ncbiEntrezUtilsURL + URLEncoder.encode(scientificName, "UTF-8"); final HttpClient httpclient = HttpClientBuilder.create().build(); HttpGet httpget = new HttpGet(query); HttpResponse response = httpclient.execute(httpget); String out = parseEntity(response.getEntity()); DocumentBuilder docBuilder; try { docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document d = docBuilder.newDocument(); <START> TransformerFactory.newInstance().newTransformer().transform(new StreamSource(new UnicodeReader(out)), new DOMResult(d)); <END> NodeList nl = d.getElementsByTagName("Id"); if (nl.getLength() > 0) { taxonomyCache.put(scientificName, nl.item(0).getTextContent()); } } catch (ParserConfigurationException | TransformerException | TransformerFactoryConfigurationError e) { throw new IOException("Taxon lookup error", e); } } return taxonomyCache.get(scientificName); }</code><technical_language>![CRITICAL](<LINK_1> 'Severity: CRITICAL') Secure this "Transformer" disabling external DTDs enabling secure processing. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
public static String checkScientificNameAtNCBI(String scientificName) throws IOException { if (!taxonomyCache.containsKey(scientificName)) { String query = NCBI_ENTREZ_UTILS_URL + URLEncoder.encode(scientificName, "UTF-8"); final HttpClient httpclient = HttpClientBuilder.create().build(); HttpGet httpget = new HttpGet(query); HttpResponse response = httpclient.execute(httpget); String out = parseEntity(response.getEntity()); DocumentBuilder docBuilder; try { docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document d = docBuilder.newDocument(); TransformerFactory.newInstance().newTransformer().transform(new StreamSource(new UnicodeReader(out)), new DOMResult(d)); NodeList nl = d.getElementsByTagName("Id"); if (nl.getLength() > 0) { taxonomyCache.put(scientificName, nl.item(0).getTextContent()); } } catch (ParserConfigurationException | TransformerException | TransformerFactoryConfigurationError e) { throw new IOException("Taxon lookup error", e); } } return taxonomyCache.get(scientificName); }
Source:
<code>public static String toString(String str, Object... triplets) { <START> assert triplets.length % 3 == 0; <END> int propCnt = triplets.length / 3; Object[] propNames = new Object[propCnt]; Object[] propVals = new Object[propCnt]; boolean[] propSens = new boolean[propCnt]; for (int i = 0; i < propCnt; i++) { Object name = triplets[i * 3]; assert name != null; propNames[i] = name; propVals[i] = triplets[i * 3 + 1]; Object sens = triplets[i * 3 + 2]; assert sens instanceof Boolean; propSens[i] = (Boolean)sens; } SBLimitedLength sb = threadLocSB.get(); boolean newStr = sb.length() == 0; try { return toStringImpl(str, sb, propNames, propVals, propSens, propCnt); } finally { if (newStr) sb.reset(); } }</code><technical_language>this exception</technical_language>

Target:
public static String toString(String str, Object... triplets) { if (triplets.length % 3 != 0) throw new IllegalArgumentException("Array length must be a multiple of 3"); int propCnt = triplets.length / 3; Object[] propNames = new Object[propCnt]; Object[] propVals = new Object[propCnt]; boolean[] propSens = new boolean[propCnt]; for (int i = 0; i < propCnt; i++) { Object name = triplets[i * 3]; assert name != null; propNames[i] = name; propVals[i] = triplets[i * 3 + 1]; Object sens = triplets[i * 3 + 2]; assert sens instanceof Boolean; propSens[i] = (Boolean)sens; } SBLimitedLength sb = threadLocSB.get(); boolean newStr = sb.length() == 0; try { return toStringImpl(str, sb, propNames, propVals, propSens, propCnt); } finally { if (newStr) sb.reset(); } }
Source:
<code>public void testWithTrace() throws IOException { String tracePath; tracePath = FileLocator.toFileURL(CtfTestTrace.ARM_64_BIT_HEADER.getTraceURL()).getPath(); SWTWorkbenchBot bot = new SWTWorkbenchBot(); SWTBotView view = bot.viewById(VIEW_ID); view.close(); bot.waitUntil(ConditionHelpers.ViewIsClosed(view)); SWTBotUtils.createProject(PROJECT_NAME); SWTBotUtils.openTrace(PROJECT_NAME, tracePath, TRACE_TYPE); SWTBotUtils.waitForJobs(); createTable(); SWTBotUtils.waitForJobs(); SWTBotTable tableBot = new SWTBotTable(fTable.getTableViewer().getTable()); assertEquals("24100", tableBot.cell(0, 2)); tableBot.header("Duration").click(); assertEquals("1000", tableBot.cell(0, 2)); tableBot.header("Duration").click(); assertEquals("5904091700", tableBot.cell(0, 2)); <START> bot.closeAllEditors(); <END> }</code><technical_language>add line clean-up. SWTBotUtils.deleteProject(PROJECT_NAME, bot);</technical_language>

Target:
public void testWithTrace() throws IOException { String tracePath; tracePath = FileLocator.toFileURL(CtfTestTrace.ARM_64_BIT_HEADER.getTraceURL()).getPath(); SWTWorkbenchBot bot = new SWTWorkbenchBot(); SWTBotView view = bot.viewById(VIEW_ID); view.close(); bot.waitUntil(ConditionHelpers.ViewIsClosed(view)); SWTBotUtils.createProject(PROJECT_NAME); SWTBotUtils.openTrace(PROJECT_NAME, tracePath, TRACE_TYPE); SWTBotUtils.waitForJobs(); createTable(); SWTBotUtils.waitForJobs(); SWTBotTable tableBot = new SWTBotTable(fTable.getTableViewer().getTable()); assertEquals("24100", tableBot.cell(0, 2)); tableBot.header("Duration").click(); assertEquals("1000", tableBot.cell(0, 2)); tableBot.header("Duration").click(); assertEquals("5904091700", tableBot.cell(0, 2)); bot.closeAllEditors(); SWTBotUtils.deleteProject(PROJECT_NAME, bot); }
Source:
<code>public static void main(String[] args) throws TException, IOException, TimeoutException { FProtocolFactory protocolFactory = new FProtocolFactory(new TBinaryProtocol.Factory()); Properties properties = new Properties(); properties.put(Options.PROP_URL, Options.DEFAULT_URL); <START> Options.Builder optionsBuilder = new Options.Builder(properties); <END> Connection conn = Nats.connect(optionsBuilder.build()); FPublisherTransportFactory publisherFactory = new FNatsPublisherTransport.Factory(conn); FSubscriberTransportFactory subscriberFactory = new FNatsSubscriberTransport.Factory(conn); FScopeProvider provider = new FScopeProvider(publisherFactory, subscriberFactory, protocolFactory); AlbumWinnersSubscriber.Iface subscriber = new AlbumWinnersSubscriber.Client(provider); subscriber.subscribeWinner((ctx, album) -> System.out.println("You won! " + album)); subscriber.subscribeContestStart((ctx, albums) -> System.out.println("Contest started, available albums: " + albums)); System.out.println("Subscriber started..."); }</code><technical_language>nit: matter examples, I more clear methods options builder instead of opaque properties object, Option.Builder optionsBuilder = new Options.Builder().server(Options.DEFAULT_URL);</technical_language>

Target:
public static void main(String[] args) throws TException, IOException, InterruptedException { FProtocolFactory protocolFactory = new FProtocolFactory(new TBinaryProtocol.Factory()); Options.Builder optionsBuilder = new Options.Builder().server(Options.DEFAULT_URL); Connection conn = Nats.connect(optionsBuilder.build()); FPublisherTransportFactory publisherFactory = new FNatsPublisherTransport.Factory(conn); FSubscriberTransportFactory subscriberFactory = new FNatsSubscriberTransport.Factory(conn); FScopeProvider provider = new FScopeProvider(publisherFactory, subscriberFactory, protocolFactory); AlbumWinnersSubscriber.Iface subscriber = new AlbumWinnersSubscriber.Client(provider); subscriber.subscribeWinner((ctx, album) -> System.out.println("You won! " + album)); subscriber.subscribeContestStart((ctx, albums) -> System.out.println("Contest started, available albums: " + albums)); System.out.println("Subscriber started..."); }
Source:
<code>public List<SourceRecord> poll() throws InterruptedException { log.trace("{} Polling for new data"); while (!stop.get()) { final TableQuerier querier = tableQueue.peek(); if (!querier.querying()) { final long nextUpdate = querier.getLastUpdate() + config.getInt(JdbcSourceTaskConfig.POLL_INTERVAL_MS_CONFIG); final long untilNext = nextUpdate - time.milliseconds(); if (untilNext > 0) { log.trace("Waiting ms to poll next", untilNext, querier.toString()); time.sleep(untilNext); continue; } } final List<SourceRecord> results = new ArrayList<>(); try { log.debug("Checking for next block of results from {}", querier.toString()); querier.maybeStartQuery(cachedConnectionProvider.getValidConnection()); int batchMaxRows = config.getInt(JdbcSourceTaskConfig.BATCH_MAX_ROWS_CONFIG); boolean hadNext = true; while (results.size() < batchMaxRows && (hadNext = querier.next())) { results.add(querier.extractRecord()); } if (!hadNext) { resetAndRequeueHead(querier); } if (results.isEmpty()) { log.trace("No updates for {}", querier.toString()); continue; } log.debug("Returning records for {}", results.size(), querier.toString()); return results; } catch (SQLException e) { log.error("Failed to run query for table {}: {}", querier.toString(), e); resetAndRequeueHead(querier); return null; <START> } catch (ConnectException e) { <END> log.error("Failed to run query for table {}: {}", querier.toString(), e); resetAndRequeueHead(querier); return null; } } return null; }</code><technical_language>I this is safe -- mask other types of errors do connectivity? do indefinitely pass ConnectExceptions along? do want tasks fail eventually, want retry for some time if can</technical_language>

Target:
public List<SourceRecord> poll() throws InterruptedException { log.trace("{} Polling for new data"); while (!stop.get()) { final TableQuerier querier = tableQueue.peek(); if (!querier.querying()) { final long nextUpdate = querier.getLastUpdate() + config.getInt(JdbcSourceTaskConfig.POLL_INTERVAL_MS_CONFIG); final long untilNext = nextUpdate - time.milliseconds(); if (untilNext > 0) { log.trace("Waiting ms to poll next", untilNext, querier.toString()); time.sleep(untilNext); continue; } } final List<SourceRecord> results = new ArrayList<>(); try { log.debug("Checking for next block of results from {}", querier.toString()); querier.maybeStartQuery(cachedConnectionProvider.getValidConnection()); int batchMaxRows = config.getInt(JdbcSourceTaskConfig.BATCH_MAX_ROWS_CONFIG); boolean hadNext = true; while (results.size() < batchMaxRows && (hadNext = querier.next())) { results.add(querier.extractRecord()); } if (!hadNext) { resetAndRequeueHead(querier); } if (results.isEmpty()) { log.trace("No updates for {}", querier.toString()); continue; } log.debug("Returning records for {}", results.size(), querier.toString()); return results; } catch (SQLException e) { log.error("Failed to run query for table {}: {}", querier.toString(), e); resetAndRequeueHead(querier); return null; } } return null; }
Source:
<code>public void deleteProject() { LOG.log(Level.INFO, "Deleting project: " + toBeDeletedProject); String sessionId = ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()) .getSession().getId(); try { projectsManagementController.deleteProject(toBeDeletedProject, sessionId); allProjects.remove(toBeDeletedProject); toBeDeletedProject = null; MessagesController.addInfoMessage("Project deleted!"); } catch (AppException ex) { LOG.log(Level.SEVERE, "Failed to delete project " + toBeDeletedProject, ex); MessagesController.addErrorMessage("Deletion failed", "Failed deleting project " + toBeDeletedProject.getName()); <START> } <END> }</code><technical_language>@kouzant This sessionId is Admin's? <LINK_0> session of project's owner? missing here</technical_language>

Target:
public void deleteProject() { LOG.log(Level.INFO, "Deleting project: " + toBeDeletedProject); Cookie[] cookies = ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()) .getCookies(); try { String sessionId = ""; for (Cookie cookie : cookies) { if (cookie.getName().equalsIgnoreCase("SESSION")) { sessionId = cookie.getValue(); break; } } projectsManagementController.deleteProject(toBeDeletedProject, sessionId); allProjects.remove(toBeDeletedProject); toBeDeletedProject = null; MessagesController.addInfoMessage("Project deleted!"); } catch (AppException ex) { LOG.log(Level.SEVERE, "Failed to delete project " + toBeDeletedProject, ex); MessagesController.addErrorMessage("Deletion failed", "Failed deleting project " + toBeDeletedProject.getName()); } }
Source:
<code>public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController(AccountUrl.AUTHENTICATION_PAGE); <START> registry.addViewController("/error/status-code"); <END> }</code><technical_language>This change is incorrect: change a URL content (view) rendered this URL is requested. is a link shed a light works now: <LINK_0></technical_language>

Target:
public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController(AccountUrl.AUTHENTICATION_PAGE); registry.addViewController(SiteUrl.FORBIDDEN_PAGE).setViewName("error/status-code"); }
Source:
<code>public void onDownloadUpdateButtonClicked() { Platform.runLater(() -> downloadUpdateButton.setOnAction(event -> { <START> })); <END> log.info("Downloading update"); updateInfoFuture .thenAccept(updateInfo -> { DownloadUpdateTask downloadUpdateTask = clientUpdateService.downloadAndInstallInBackground(updateInfo); if (downloadUpdateTask != null) { downloadUpdateButton.textProperty().bind( Bindings.createStringBinding(() -> downloadUpdateTask.getProgress() == -1 ? i18n.get("login.button.downloadPreparing") : i18n.get("login.button.downloadProgress", downloadUpdateTask.getProgress()), downloadUpdateTask.progressProperty())); } }); }</code><technical_language>callback is empty</technical_language>

Target:
public void onDownloadUpdateButtonClicked() { downloadUpdateButton.setOnAction(event -> { }); log.info("Downloading update"); updateInfoFuture .thenAccept(updateInfo -> { DownloadUpdateTask downloadUpdateTask = clientUpdateService.downloadAndInstallInBackground(updateInfo); if (downloadUpdateTask != null) { downloadUpdateButton.textProperty().bind( Bindings.createStringBinding(() -> downloadUpdateTask.getProgress() == -1 ? i18n.get("login.button.downloadPreparing") : i18n.get("login.button.downloadProgress", downloadUpdateTask.getProgress()), downloadUpdateTask.progressProperty())); } }); }
Source:
<code>private boolean checkFileExtension() { String[] sourceDirs = source.toString().split("/"); String[] destinationDirs = destination.toString().split("/"); boolean different = false; if (sourceDirs.length != destinationDirs.length) different = true; else { for (int i = 0; i < sourceDirs.length - 1; i++) { if (!sourceDirs[i].equals(destinationDirs[i])) { different = true; break; } } } String[] sourceFileNames = sourceDirs[sourceDirs.length - 1].split("\\."); String[] destinationFileNames = destinationDirs[destinationDirs.length - 1].split("\\."); boolean sameFileExt = sourceFileNames[sourceFileNames.length - 1] .equals(destinationFileNames[destinationFileNames.length - 1]); if (!different && sameFileExt) return true; <START> else <END> return false; }</code><technical_language>else return</technical_language>

Target:
private boolean checkFileExtension() { String[] sourceDirs = source.toString().split("/"); String[] destinationDirs = destination.toString().split("/"); boolean different = false; if (sourceDirs.length != destinationDirs.length) different = true; else { for (int i = 0; i < sourceDirs.length - 1; i++) { if (!sourceDirs[i].equals(destinationDirs[i])) { different = true; break; } } } String[] sourceFileNames = sourceDirs[sourceDirs.length - 1].split("\\."); String[] destinationFileNames = destinationDirs[destinationDirs.length - 1].split("\\."); boolean sameFileExt = sourceFileNames[sourceFileNames.length - 1] .equals(destinationFileNames[destinationFileNames.length - 1]); if (!different && sameFileExt) return true; return false; }
Source:
<code>public static AbstractTask getTaskByUrl(String taskUrl) { Collection<AbstractTask> tasks = TasksUiPlugin.getTaskList().getAllTasks(); for (AbstractTask task : tasks) { String currUrl = task.getUrl(); if (currUrl != null && !currUrl.equals("") && currUrl.equals(taskUrl)) { return task; <START> } else { <END> AbstractRepositoryConnector connector = TasksUi.getRepositoryManager().getRepositoryConnector( task.getConnectorKind()); TaskRepository repository = getRepository(task); if (connector != null) { URL url = connector.getBrowseableUrl(repository, task); if (url != null) { currUrl = url.toString(); if (currUrl != null && !currUrl.equals("") && currUrl.equals(taskUrl)) { return task; } } } } } return null; }</code><technical_language>Is a reason for this addition? wondering performance impact of this for task</technical_language>

Target:
public static AbstractTask getTaskByUrl(String taskUrl) { if (!Strings.isNullOrEmpty(taskUrl)) { Collection<AbstractTask> tasks = TasksUiPlugin.getTaskList().getAllTasks(); List<AbstractTask> sortedTasks = sortTasksByRepositoryUrl(tasks); String oldRepositorUrl = null; AbstractRepositoryConnector connector = null; TaskRepository repository = null; for (AbstractTask task : sortedTasks) { if (taskUrl.equals(task.getUrl())) { return task; } else { String repositoryUrl = task.getRepositoryUrl(); if (!repositoryUrl.equals(oldRepositorUrl)) { connector = TasksUi.getRepositoryManager().getRepositoryConnector(task.getConnectorKind()); repository = getRepository(task); } if (connector != null) { URL url = connector.getBrowseableUrl(repository, task); if (url != null && taskUrl.equals(url.toString())) { return task; } } oldRepositorUrl = repositoryUrl; } } } return null; }
Source:
<code>public static Drawable getCubicGradient(int baseColor, int gravity) { <START> final int numStops = 8; <END> final int cubePower = 3; PaintDrawable paintDrawable = new PaintDrawable(); paintDrawable.setShape(new RectShape()); final int[] stopColors = new int[numStops]; int red = Color.red(baseColor); int green = Color.green(baseColor); int blue = Color.blue(baseColor); int alpha = Color.alpha(baseColor); for (int i = 0; i < numStops; i++) { float x = i * 1f / (numStops - 1); float opacity = (float) Math.pow(x, cubePower); if (opacity < 0.0f) { opacity = 0.0f; } else if (opacity > 1.0f) { opacity = 1.0f; } stopColors[i] = Color.argb((int) (alpha * opacity), red, green, blue); } final float x0, x1, y0, y1; switch (gravity & Gravity.HORIZONTAL_GRAVITY_MASK) { case Gravity.LEFT: x0 = 1; x1 = 0; break; case Gravity.RIGHT: x0 = 0; x1 = 1; break; default: x0 = 0; x1 = 0; break; } switch (gravity & Gravity.VERTICAL_GRAVITY_MASK) { case Gravity.TOP: y0 = 1; y1 = 0; break; case Gravity.BOTTOM: y0 = 0; y1 = 1; break; default: y0 = 0; y1 = 0; break; } paintDrawable.setShaderFactory(new ShapeDrawable.ShaderFactory() { @Override public Shader resize(int width, int height) { return new LinearGradient(width * x0, height * y0, width * x1, height * y1, stopColors, null, Shader.TileMode.CLAMP); } }); return paintDrawable; }</code><technical_language>I recommend statics this function small</technical_language>

Target:
public static Drawable getCubicGradient(int baseColor, int gravity) { PaintDrawable paintDrawable = new PaintDrawable(); paintDrawable.setShape(new RectShape()); final int[] stopColors = new int[GRADIENT_NUM_STOPS]; int red = Color.red(baseColor); int green = Color.green(baseColor); int blue = Color.blue(baseColor); int alpha = Color.alpha(baseColor); for (int i = 0; i < GRADIENT_NUM_STOPS; i++) { float x = i * 1f / (GRADIENT_NUM_STOPS - 1); float opacity = MathUtil.constrain((float) Math.pow(x, GRADIENT_POWER), 0.0f, 1.0f); stopColors[i] = Color.argb((int) (alpha * opacity), red, green, blue); } final float x0, x1, y0, y1; switch (gravity & Gravity.HORIZONTAL_GRAVITY_MASK) { case Gravity.START: x0 = 1; x1 = 0; break; case Gravity.END: x0 = 0; x1 = 1; break; default: x0 = 0; x1 = 0; break; } switch (gravity & Gravity.VERTICAL_GRAVITY_MASK) { case Gravity.TOP: y0 = 1; y1 = 0; break; case Gravity.BOTTOM: y0 = 0; y1 = 1; break; default: y0 = 0; y1 = 0; break; } paintDrawable.setShaderFactory(new ShapeDrawable.ShaderFactory() { @Override public Shader resize(int width, int height) { return new LinearGradient(width * x0, height * y0, width * x1, height * y1, stopColors, null, Shader.TileMode.CLAMP); } }); return paintDrawable; }
Source:
<code>public void filter(final ContainerRequestContext request, final ContainerResponseContext response) throws IOException { final UUID id = UUID.randomUUID(); <START> LOGGER.info("method={} path={} request_id={} status={} bytes={}", <END> request.getMethod(), request.getUriInfo().getPath(), id, response.getStatus(), response.getLength()); response.getHeaders().add(REQUEST_ID, id); }</code><technical_language>length instead of bytes</technical_language>

Target:
public void filter(final ContainerRequestContext request, final ContainerResponseContext response) throws IOException { String id = request.getHeaderString(REQUEST_ID); if (Strings.isNullOrEmpty(id)) { id = generateRandomUuid().toString(); } LOGGER.trace("method={} path={} request_id={} status={} length={}", request.getMethod(), request.getUriInfo().getPath(), id, response.getStatus(), response.getLength()); response.getHeaders().putSingle(REQUEST_ID, id); }
Source:
<code>public static <T> List<T> loadAll(Class<T> spi) { ServiceLoader<T> serviceLoader = ServiceLoader.load(spi); List<T> implementations = new ArrayList<>(); for (T implementation : serviceLoader) { implementations.add(implementation); <START> } <END> return Collections.unmodifiableList(implementations); }</code><technical_language>if implementations is empty, this method eventually return empty (immutable) collection. throw UnavailableImplementationException instead invalid state spi class</technical_language>

Target:
public static <T> List<T> loadAll(Class<T> spi) { Assert.notNull(spi, "Parameter 'spi' must not be null."); ServiceLoader<T> serviceLoader = ServiceLoader.load(spi); List<T> implementations = new ArrayList<>(); for (T implementation : serviceLoader) { implementations.add(implementation); } if (implementations.isEmpty()) { throw new UnavailableImplementationException(spi); } return Collections.unmodifiableList(implementations); }
Source:
<code>MemberWorker(WorkerType type, String publicAddress, int agentIndex, int workerIndex, int workerPort, String hzConfigFile, boolean autoCreateHzInstance, int workerPerformanceMonitorIntervalSeconds) throws Exception { <START> this.type = type; <END> this.publicAddress = publicAddress; this.autoCreateHzInstance = autoCreateHzInstance; this.hzConfigFile = hzConfigFile; this.hazelcastInstance = getHazelcastInstance(); this.workerConnector = WorkerConnector.createInstance(agentIndex, workerIndex, workerPort, type, hazelcastInstance, this); this.workerPerformanceMonitor = initWorkerPerformanceMonitor(workerPerformanceMonitorIntervalSeconds); Runtime.getRuntime().addShutdownHook(new WorkerShutdownThread(true)); signalStartToAgent(); }</code><technical_language>please restore lines? test failures do WorkerPerformanceMonitor. please run tests branch? This takes 2.5 minutes for Simulator</technical_language>

Target:
MemberWorker(WorkerType type, String publicAddress, int agentIndex, int workerIndex, int workerPort, String hzConfigFile, boolean autoCreateHzInstance, int workerPerformanceMonitorIntervalSeconds) throws Exception { SHUTDOWN_STARTED.set(false); this.type = type; this.publicAddress = publicAddress; this.autoCreateHzInstance = autoCreateHzInstance; this.hzConfigFile = hzConfigFile; this.hazelcastInstance = getHazelcastInstance(); this.workerConnector = WorkerConnector.createInstance(agentIndex, workerIndex, workerPort, type, hazelcastInstance, this); this.workerPerformanceMonitor = initWorkerPerformanceMonitor(workerPerformanceMonitorIntervalSeconds); Runtime.getRuntime().addShutdownHook(new WorkerShutdownThread(true)); signalStartToAgent(); }
Source:
<code>public List<String> getDependencies() { <START> return Collections.singletonList(AttributesManager.NS_FACILITY_ATTR_DEF + ":googleGroupNameNamespace"); <END> }</code><technical_language>Is reason add googleGroupName-namespace:* attribute normal dependencies? replace occurrences of attributes constants</technical_language>

Target:
public List<String> getDependencies() { List<String> dependencies = new ArrayList<>(); dependencies.add(AttributesManager.NS_FACILITY_ATTR_DEF + ":googleGroupNameNamespace"); return dependencies; }
Source:
<code>public WebsocketConnection() { super(); SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); ExperimentRunManager.getInstance(); <START> this.connectionHandler = new ConnectionHandler(this, geppettoManager,geppettoManagerConfig.getAllowVolatileProjectsSimulation()); <END> }</code><technical_language>Pass geppettoManagerConfiguration</technical_language>

Target:
public WebsocketConnection() { super(); SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); ExperimentRunManager.getInstance(); this.connectionHandler = new ConnectionHandler(this, geppettoManager,geppettoManagerConfiguration); }
Source:
<code>private boolean collectProjectFilesFromDirectory( Collection<File> files, File directory, Set<String> directoriesVisited, IProgressMonitor monitor) { if (monitor.isCanceled()) { return false; } monitor.subTask(NLS.bind( <START> UIText.WizardProjectsImportPage_CheckingMessage, directory <END> .getPath())); File[] contents = directory.listFiles(); if (contents == null) return false; if (directoriesVisited == null) { directoriesVisited = new HashSet<String>(); try { directoriesVisited.add(directory.getCanonicalPath()); } catch (IOException exception) { StatusManager.getManager() .handle( new Status(IStatus.ERROR, Activator .getPluginId(), exception .getLocalizedMessage(), exception)); } } final String dotProject = IProjectDescription.DESCRIPTION_FILE_NAME; for (int i = 0; i < contents.length; i++) { File file = contents[i]; if (file.isFile() && file.getName().equals(dotProject)) { files.add(file.getParentFile()); return true; } } for (int i = 0; i < contents.length; i++) { if (contents[i].isDirectory()) { if (!contents[i].getName().equals(".metadata")) { try { String canonicalPath = contents[i] .getCanonicalPath(); if (!directoriesVisited.add(canonicalPath)) { continue; } } catch (IOException exception) { StatusManager.getManager().handle( new Status(IStatus.ERROR, Activator .getPluginId(), exception .getLocalizedMessage(), exception)); } collectProjectFilesFromDirectory(files, contents[i], directoriesVisited, monitor); } } } return true; }</code><technical_language>Reusing messages view is, I think, a good thing. name of this message clearcly states belongs anoter piece of code</technical_language>

Target:
private boolean collectProjectFilesFromDirectory( Collection<File> files, File directory, Set<String> directoriesVisited, IProgressMonitor monitor) { if (monitor.isCanceled()) { return false; } monitor.subTask(NLS.bind( RepositoryViewUITexts.RepositoriesView_Checking_Message, directory.getPath())); File[] contents = directory.listFiles(); if (contents == null) return false; final String dotProject = IProjectDescription.DESCRIPTION_FILE_NAME; for (int i = 0; i < contents.length; i++) { File file = contents[i]; if (file.isFile() && file.getName().equals(dotProject)) { files.add(file.getParentFile()); return true; } } for (int i = 0; i < contents.length; i++) { if (contents[i].isDirectory()) { if (!contents[i].getName().equals( GitProjectsImportPage.METADATA_FOLDER)) { try { String canonicalPath = contents[i] .getCanonicalPath(); if (!directoriesVisited.add(canonicalPath)) { continue; } } catch (IOException exception) { StatusManager.getManager().handle( new Status(IStatus.ERROR, Activator .getPluginId(), exception .getLocalizedMessage(), exception)); } collectProjectFilesFromDirectory(files, contents[i], directoriesVisited, monitor); } } } return true; }
Source:
<code>public TableInstance<RelationalTableDefinition> createImmutable(RelationalTableDefinition tableDefinition, TableHandle tableHandle) { TableName tableName = createImmutableTableName(tableHandle); <START> checkArgument(tableName.getSchema().isPresent(), "Cassandra requires table with schema"); <END> if (!queryExecutor.tableExists(tableName.getSchema().get(), tableName.getSchemalessNameInDatabase())) { if (!skipCreateSchema) { queryExecutor.executeQuery(format("CREATE KEYSPACE IF NOT EXISTS %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", tableName.getSchema().get())); } executeQueryIgnoreTypeError(tableDefinition.getCreateTableDDL(tableName.getNameInDatabase())); RelationalDataSource dataSource = tableDefinition.getDataSource(); insertData(tableName, dataSource); } return new CassandraTableInstance(tableName, tableDefinition); }</code><technical_language>this give default keyspace is handled elsewhere</technical_language>

Target:
public TableInstance<RelationalTableDefinition> createImmutable(RelationalTableDefinition tableDefinition, TableHandle tableHandle) { TableName tableName = createImmutableTableName(tableHandle); if (!queryExecutor.tableExists(tableName.getSchema().get(), tableName.getSchemalessNameInDatabase())) { if (!skipCreateSchema) { queryExecutor.executeQuery(format("CREATE KEYSPACE IF NOT EXISTS %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", tableName.getSchema().get())); } executeQueryIgnoreTypeError(tableDefinition.getCreateTableDDL(tableName.getNameInDatabase())); RelationalDataSource dataSource = tableDefinition.getDataSource(); insertData(tableName, dataSource); } return new CassandraTableInstance(tableName, tableDefinition); }
Source:
<code>public static boolean isHealingRequired(GlusterVolumeEntity volume) { for (GlusterBrickEntity brick : volume.getBricks()) { <START> if (brick.getUnSyncedEntries() != null && brick.getUnSyncedEntries() > 0) { <END> return true; } } return false; }</code><technical_language>Java accepted check for empty is: !brick.getUnSyncedEntries().isEmpty()</technical_language>

Target:
public static boolean isHealingRequired(GlusterVolumeEntity volume) { for (GlusterBrickEntity brick : volume.getBricks()) { if (brick.getUnSyncedEntries() > 0) { return true; } } return false; }
Source:
<code>public int hashCode() { <START> return Objects.hash(id); <END> }</code><technical_language>this change reverted well</technical_language>

Target:
public int hashCode() { return Objects.hash(id, title, description, start, end, registrationStart, registrationEnd, registrationLimit); }
Source:
<code>public Attribute getAttributeById(PerunSession sess, Host host, int id) throws InternalErrorException, AttributeNotExistsException { Attribute attributesCache = null; if(!CacheManager.isCacheDisabled()) { Attribute attr = perun.getCacheManager().getAttributeById(id, new Holder(host.getId(), Holder.HolderType.HOST), null); attributesCache = setValueOfAttribute(sess, attr, host, null); } try { Attribute attributesDB = jdbc.queryForObject("select " + getAttributeMappingSelectQuery("host_attr_values") + " from attr_names left join host_attr_values on id=attr_id and host_id=? where id=?", new SingleBeanAttributeRowMapper<>(sess, this, host), host.getId(), id); <START> String message = "The attributes do not match, attribute from cache is: " + attributesCache + " while attribute from db is: " + attributesDB + " the attribute belongs to " + host + " and its id is " + id; <END> compareAttributeFromCacheAndDB(attributesCache, attributesDB, message); return attributesDB; } catch (EmptyResultDataAccessException ex) { throw new AttributeNotExistsException("Attribute id= \"" + id + "\"", ex); } catch (RuntimeException ex) { throw new InternalErrorException(ex); } }</code><technical_language>ID of attribute in log message, is identifier, retrieve cache/DB. if results same, lease empty logged attributes attribute id</technical_language>

Target:
public Attribute getAttributeById(PerunSession sess, Host host, int id) throws InternalErrorException, AttributeNotExistsException { Attribute attributesCache = null; if(!CacheManager.isCacheDisabled()) { Attribute attr = perun.getCacheManager().getAttributeById(id, new Holder(host.getId(), Holder.HolderType.HOST), null); attributesCache = setValueOfAttribute(sess, attr, host, null); } try { Attribute attributesDB = jdbc.queryForObject("select " + getAttributeMappingSelectQuery("host_attr_values") + " from attr_names left join host_attr_values on id=attr_id and host_id=? where id=?", new SingleBeanAttributeRowMapper<>(sess, this, host), host.getId(), id); compareAttributeFromCacheAndDB(attributesCache, attributesDB, host, null); return attributesDB; } catch (EmptyResultDataAccessException ex) { throw new AttributeNotExistsException("Attribute id= \"" + id + "\"", ex); } catch (RuntimeException ex) { throw new InternalErrorException(ex); } }
Source:
<code>protected void sendStreamOpen() throws NotConnectedException, InterruptedException { CharSequence to = getXMPPServiceDomain(); CharSequence from = null; CharSequence localpart = config.getUsername(); if (localpart != null) { from = XmppStringUtils.completeJidFrom(localpart, to); } String id = getStreamId(); <START> sendNonza(new StreamOpen(to, from, id, config.getLanguage().toString().replace("_", "-"), StreamOpen.StreamContentNamespace.client)); <END> }</code><technical_language>that! Is a reason getLanguageTag return null is getLanguageTag() I worried returning null, is getLanguage(). Currently is set language null in configuration, is desirable xml:lang in stream open elements is optional. code consideration throw NPEs in that, arguably rare, case</technical_language>

Target:
protected void sendStreamOpen() throws NotConnectedException, InterruptedException { CharSequence to = getXMPPServiceDomain(); CharSequence from = null; CharSequence localpart = config.getUsername(); if (localpart != null) { from = XmppStringUtils.completeJidFrom(localpart, to); } String id = getStreamId(); sendNonza(new StreamOpen(to, from, id, config.getXmlLang(), StreamOpen.StreamContentNamespace.client)); }
Source:
<code>private void commitFile(TopicPartition topicPart) throws IOException { long offset; <START> if (offsets.containsKey(topicPart)) { <END> offset = offsets.get(topicPart) + recordCounters.get(topicPart); } else { offset = recordCounters.get(topicPart) - 1; } offsets.put(topicPart, offset); String tempFileName = FileUtils.tempFileName(url, topicsDir, topicPart); String finalFileName = FileUtils.fileName(url, topicsDir, topicPart, offset); FileUtils.renameFile(fs, tempFileName, finalFileName); }</code><technical_language>This logic works if started consuming data offset 0 available. recording latest offset for topic partition record</technical_language>

Target:
private void commitFile(TopicPartition topicPart) throws IOException { long offset; offset = offsets.get(topicPart) + recordCounters.get(topicPart); offsets.put(topicPart, offset); String tempFileName = FileUtils.tempFileName(url, topicsDir, topicPart); String finalFileName = FileUtils.committedFileName(url, topicsDir, topicPart, offset); FileUtils.renameFile(fs, tempFileName, finalFileName); }
Source:
<code>public SqlNode getCastSpec(RelDataType type) { if (type instanceof BasicSqlType) { int maxPrecision = -1; switch (type.getSqlTypeName()) { case VARCHAR: case CHAR: maxPrecision = getTypeSystem().getMaxPrecision(type.getSqlTypeName()); } if (type.getPrecision() == RelDataType.PRECISION_NOT_SPECIFIED) { type = allowTypeWithUnspecifiedPrecision(type) ? type <START> : new SqlTypeFactoryImpl(getTypeSystem()).createSqlType(type.getSqlTypeName()); <END> } String charSet = type.getCharset() != null && supportsCharSet() ? type.getCharset().name() : null; return SqlTypeUtil.convertTypeToSpec(type, charSet, maxPrecision); } return SqlTypeUtil.convertTypeToSpec(type); }</code><technical_language>Instead of create a new type, i prefer SqlTypeUtil.convertTypeToSpec(type, charSet, maxPrecision) support a explicit precision parameter</technical_language>

Target:
public SqlNode getCastSpec(RelDataType type) { if (type instanceof BasicSqlType) { int maxPrecision = -1; switch (type.getSqlTypeName()) { case VARCHAR: case CHAR: maxPrecision = getTypeSystem().getMaxPrecision(type.getSqlTypeName()); } String charSet = type.getCharset() != null && supportsCharSet() ? type.getCharset().name() : null; if (type.getPrecision() == RelDataType.PRECISION_NOT_SPECIFIED && !allowsTypeWithUnspecifiedPrecision(type)) { return SqlTypeUtil.convertTypeToSpec(type, charSet, maxPrecision, getTypeSystem().getDefaultPrecision(type.getSqlTypeName())); } return SqlTypeUtil.convertTypeToSpec(type, charSet, maxPrecision); } return SqlTypeUtil.convertTypeToSpec(type); }
Source:
<code>public Object visitCommitCommand(TxInvocationContext ctx, CommitCommand command) throws Throwable { GlobalTransaction gtx = ctx.getGlobalTransaction(); if (!ctx.isOriginLocal()) { if (txTable.isTransactionCompleted(gtx)) { log.tracef("Transaction %s already completed, skipping commit", gtx); return null; } RemoteTransaction remoteTx = (RemoteTransaction) ctx.getCacheTransaction(); if (trace) { log.tracef("Remote tx topology id %d and command topology is %d", remoteTx.lookedUpEntriesTopology(), command.getTopologyId()); } if (remoteTx.lookedUpEntriesTopology() < command.getTopologyId()) { PrepareCommand prepareCommand; if (useVersioning) { prepareCommand = commandsFactory.buildVersionedPrepareCommand(ctx.getGlobalTransaction(), ctx.getModifications(), false); } else { prepareCommand = commandsFactory.buildPrepareCommand(ctx.getGlobalTransaction(), ctx.getModifications(), false); } commandsFactory.initializeReplicableCommand(prepareCommand, true); prepareCommand.setOrigin(ctx.getOrigin()); <START> log.tracef("Replaying the transactions received as a result of state transfer %s", prepareCommand); <END> visitPrepareCommand(ctx, prepareCommand); } txTable.markTransactionCompleted(gtx); } if (this.statisticsEnabled) commits.incrementAndGet(); Object result = invokeNextInterceptor(ctx, command); if (!ctx.isOriginLocal() || isTotalOrder) { txTable.remoteTransactionCommitted(gtx, false); } return result; }</code><technical_language>if (trace)..</technical_language>

Target:
public Object visitCommitCommand(TxInvocationContext ctx, CommitCommand command) throws Throwable { GlobalTransaction gtx = ctx.getGlobalTransaction(); if (!ctx.isOriginLocal()) { if (txTable.isTransactionCompleted(gtx)) { if (trace) log.tracef("Transaction %s already completed, skipping commit", gtx); return null; } RemoteTransaction remoteTx = (RemoteTransaction) ctx.getCacheTransaction(); if (trace) { log.tracef("Remote tx topology id %d and command topology is %d", remoteTx.lookedUpEntriesTopology(), command.getTopologyId()); } if (remoteTx.lookedUpEntriesTopology() < command.getTopologyId()) { PrepareCommand prepareCommand; if (useVersioning) { prepareCommand = commandsFactory.buildVersionedPrepareCommand(ctx.getGlobalTransaction(), ctx.getModifications(), false); } else { prepareCommand = commandsFactory.buildPrepareCommand(ctx.getGlobalTransaction(), ctx.getModifications(), false); } commandsFactory.initializeReplicableCommand(prepareCommand, true); prepareCommand.setOrigin(ctx.getOrigin()); if (trace) log.tracef("Replaying the transactions received as a result of state transfer %s", prepareCommand); visitPrepareCommand(ctx, prepareCommand); } txTable.markTransactionCompleted(gtx); } if (this.statisticsEnabled) commits.incrementAndGet(); Object result = invokeNextInterceptor(ctx, command); if (!ctx.isOriginLocal() || isTotalOrder) { txTable.remoteTransactionCommitted(gtx, false); } return result; }
Source:
<code>private static void installScripts(IRemoteConnection remoteConnection) throws IOException { System.out.println("Install Scripts is being attempted"); <START> System.out.println(Scripts.INSTALL_PTP_SCRIPTS); <END> String[] installCommand = {"perl","-e",Scripts.INSTALL_PTP_SCRIPTS}; final IRemoteProcessBuilder install = remoteConnection.getProcessBuilder(installCommand); install.redirectErrorStream(); IRemoteProcess installProc = install.start(); InputStream in = installProc.getInputStream(); byte[] buf = new byte[512]; while(true) { int n = in.read(buf,0,buf.length); if(n <= 0) break; System.out.write(buf,0,n); } in.close(); }</code><technical_language>leftover debugging</technical_language>

Target:
private static void installScripts(IRemoteConnection remoteConnection) throws IOException { String[] installCommand = {"perl","-e",Scripts.INSTALL_PTP_SCRIPTS}; final IRemoteProcessBuilder install = remoteConnection.getProcessBuilder(installCommand); install.redirectErrorStream(); IRemoteProcess installProc = install.start(); InputStream in = installProc.getInputStream(); byte[] buf = new byte[512]; while(true) { int n = in.read(buf,0,buf.length); if(n <= 0) break; System.out.write(buf,0,n); } in.close(); }