auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public CommonProtos.Priority serialize(Priority source) { CommonProtos.Priority.Builder builder = CommonProtos.Priority.newBuilder(); if(source.getReasons() != null) { <START> if (source.getReasons().getPositive() != null) { <END> for (String reason : source.getReasons().getPositive()) { builder.addPositiveReasons(reason); } } if (source.getReasons().getNegative() != null) { for (String reason : source.getReasons().getNegative()) { builder.addNegativeReasons(reason); } } } if(source.getPriority() != null) { builder.setPriority(source.getPriority()); } return builder.build(); }</code><technical_language>above, extract var</technical_language>

Target:
public CommonProtos.Priority serialize(Priority source) { CommonProtos.Priority.Builder builder = CommonProtos.Priority.newBuilder(); PriorityScoreReasons scoreReasons = source.getReasons(); if(scoreReasons != null) { if (scoreReasons.getPositive() != null) { for (String reason : scoreReasons.getPositive()) { builder.addPositiveReasons(reason); } } if (scoreReasons.getNegative() != null) { for (String reason : scoreReasons.getNegative()) { builder.addNegativeReasons(reason); } } } if(source.getPriority() != null) { builder.setPriority(source.getPriority()); } return builder.build(); }
Source:
<code>static void addToWarsByContext(Entity entity, String url, String targetName) { targetName = filenameToWebContextMapper.convertDeploymentTargetNameToContext(targetName); <START> synchronized (entity) { <END> Map<String,String> newWarsMap = MutableMap.copyOf(entity.getConfig(WARS_BY_CONTEXT)); newWarsMap.put(targetName, url); ((EntityInternal)entity).setConfig(WARS_BY_CONTEXT, newWarsMap); } }</code><technical_language>I worry this - i.e. synchronizing entity. Other code synchronize entity for completely reasons, lead deadlock, depending else caller done. If a simple effector call fine kicks in a new thread</technical_language>

Target:
static void addToWarsByContext(Entity entity, String url, String targetName) { targetName = FILENAME_TO_WEB_CONTEXT_MAPPER.convertDeploymentTargetNameToContext(targetName); synchronized (entity) { Map<String,String> newWarsMap = MutableMap.copyOf(entity.getConfig(WARS_BY_CONTEXT)); newWarsMap.put(targetName, url); ((EntityInternal)entity).setConfig(WARS_BY_CONTEXT, newWarsMap); } }
Source:
<code>public void addHead(final MessageReference ref, boolean scheduling) { enterCritical(CRITICAL_PATH_ADD_HEAD); synchronized (this) { try { <START> enforceRing(ref, scheduling); <END> if (!ref.isAlreadyAcked()) { if (!scheduling && scheduledDeliveryHandler.checkAndSchedule(ref, false)) { return; } internalAddHead(ref); directDeliver = false; } } finally { leaveCritical(CRITICAL_PATH_ADD_HEAD); } } }</code><technical_language>a if check wrapped this, avoid method (which method is large unlikly inlined) call ringsize is disabled (-1)</technical_language>

Target:
public void addHead(final MessageReference ref, boolean scheduling) { enterCritical(CRITICAL_PATH_ADD_HEAD); synchronized (this) { try { if (ringSize != -1) { enforceRing(ref, scheduling); } if (!ref.isAlreadyAcked()) { if (!scheduling && scheduledDeliveryHandler.checkAndSchedule(ref, false)) { return; } internalAddHead(ref); directDeliver = false; } } finally { leaveCritical(CRITICAL_PATH_ADD_HEAD); } } }
Source:
<code>protected void doStart() { Assert.state(this.outputChannel != null || StringUtils.hasText(this.outputChannelName), "'outputChannel' or 'outputChannelName' is required"); if (this.outputChannelName != null) { <START> synchronized (this) { <END> if (this.outputChannelName != null) { this.outputChannel = getChannelResolver().resolveDestination(this.outputChannelName); this.outputChannelName = null; } } } }</code><technical_language>This is redundant. protected lifecycleLock in AbstractEndpoint.start()</technical_language>

Target:
protected void doStart() { Assert.state(this.outputChannel != null || StringUtils.hasText(this.outputChannelName), "'outputChannel' or 'outputChannelName' is required"); if (this.outputChannelName != null) { this.outputChannel = getChannelResolver().resolveDestination(this.outputChannelName); } }
Source:
<code>public boolean tryLock(String... names) throws InterruptedException { <START> return tryLock(jgroupsLockingService.getLockTimeoutMillis(), TimeUnit.MILLISECONDS, names); <END> }</code><technical_language>lock timeout length JGroups locking service</technical_language>

Target:
public boolean tryLock(String... names) throws InterruptedException { return tryLock(lockTimeoutMillis, TimeUnit.MILLISECONDS, names); }
Source:
<code>public ChannelOutput receive() throws IOException { ByteBuf responseByteBuf; try { responseByteBuf = responsePromise.get(http2ClientConfig.http2BlockingChannelReceiveTimeoutMs, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { throw new IOException("Failed to receive response from " + getRemoteHost() + ":" + getRemotePort(), e); } DataInputStream dataInputStream = new NettyByteBufDataInputStream(responseByteBuf); <START> return new ChannelOutput(dataInputStream, dataInputStream.readLong() - 8); <END> }</code><technical_language>replace 8 Long.BYTES</technical_language>

Target:
public ChannelOutput receive() throws IOException { logger.error("Http2 doesn't support send() receive(). Please use sendAndReceive()"); throw new UnsupportedOperationException(); }
Source:
<code>private void markAsDeleted(StoreKey id, FileSpan fileSpan, MessageInfo info) throws StoreException { validateFileSpan(fileSpan, true); IndexValue value = findKey(id); if (value == null && info == null) { throw new StoreException("Id " + id + " not present in index " + dataDir, StoreErrorCodes.ID_Not_Found); } else if (value != null && value.isFlagSet(IndexValue.Flags.Delete_Index)) { throw new StoreException("Id " + id + " already deleted in index " + dataDir, StoreErrorCodes.ID_Deleted); } long size = fileSpan.getEndOffset().getOffset() - fileSpan.getStartOffset().getOffset(); IndexValue newValue; if (value == null) { <START> newValue = new IndexValue(size, fileSpan.getStartOffset(), info.getExpirationTimeInMs(), Utils.Infinite_Time, <END> IndexValue.SERVICE_CONTAINER_ID_DEFAULT_VALUE, IndexValue.SERVICE_CONTAINER_ID_DEFAULT_VALUE); newValue.clearOriginalMessageOffset(); } else { newValue = new IndexValue(value.getSize(), value.getOffset(), value.getExpiresAtMs(), Utils.Infinite_Time, value.getServiceId(), value.getContainerId()); newValue.setNewOffset(fileSpan.getStartOffset()); newValue.setNewSize(size); } newValue.setFlag(IndexValue.Flags.Delete_Index); addToIndex(new IndexEntry(id, newValue, null), fileSpan); }</code><technical_language>java newValue = new IndexValue(size, fileSpan.getStartOffset(), info.getExpirationTimeInMs()) suffice, no</technical_language>

Target:
private void markAsDeleted(StoreKey id, FileSpan fileSpan, MessageInfo info) throws StoreException { validateFileSpan(fileSpan, true); IndexValue value = findKey(id); if (value == null && info == null) { throw new StoreException("Id " + id + " not present in index " + dataDir, StoreErrorCodes.ID_Not_Found); } else if (value != null && value.isFlagSet(IndexValue.Flags.Delete_Index)) { throw new StoreException("Id " + id + " already deleted in index " + dataDir, StoreErrorCodes.ID_Deleted); } long size = fileSpan.getEndOffset().getOffset() - fileSpan.getStartOffset().getOffset(); IndexValue newValue; if (value == null) { newValue = new IndexValue(size, fileSpan.getStartOffset(), info.getExpirationTimeInMs()); newValue.clearOriginalMessageOffset(); } else { newValue = new IndexValue(value.getSize(), value.getOffset(), value.getExpiresAtMs(), Utils.Infinite_Time, value.getServiceId(), value.getContainerId()); newValue.setNewOffset(fileSpan.getStartOffset()); newValue.setNewSize(size); } newValue.setFlag(IndexValue.Flags.Delete_Index); addToIndex(new IndexEntry(id, newValue, null), fileSpan); }
Source:
<code>protected void runQuery(String key, QueryResultCallback callback) throws DashboardDataException { if (!sqlQueries.containsKey(key)) { throw new DashboardDataException("SQL query not found: " + key); } try (Connection con = dataSource.getConnection(); PreparedStatement ps = con.prepareStatement(sqlQueries.getProperty(key)); <START> ResultSet rs = ps.executeQuery()) { <END> callback.onResult(rs); } catch (SQLException e) { throw new DashboardDataException("Error while running SQL query", e); } }</code><technical_language>a thought -- similar is done in Spring JdbcTemplate, call per-row. I looked DAOs, do call rs.next() in a while loop. So, while loop moved in if wanted to. change interface remove ability execute other a straight query. But, this executing straight queries</technical_language>

Target:
protected void runQuery(String key, QueryResultCallback callback) throws DashboardDataException { if (!sqlQueries.containsKey(key)) { throw new DashboardDataException("SQL query not found: " + key); } try (Connection con = dataSource.getConnection(); PreparedStatement ps = con.prepareStatement(sqlQueries.getProperty(key)); ResultSet rs = ps.executeQuery()) { while (rs.next()) { callback.onResult(rs); } } catch (SQLException e) { throw new DashboardDataException("Error while running SQL query", e); } }
Source:
<code>protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { <START> request.setCharacterEncoding("UTF-8"); <END> String contentType = request.getParameter("contenttype"); String fileName = request.getParameter("filename"); Boolean cache = Boolean.parseBoolean(request.getParameter("cache")); String encodingType = request.getParameter("encodingtype"); String content = request.getParameter("content"); if (contentType != null) { response.setContentType(contentType); } if (fileName == null) { fileName = "attachment"; } response.setHeader("Content-Disposition", "attachment; filename*='UTF-8'" + URLEncoder.encode(StringEscapeUtils.unescapeHtml(fileName), "UTF-8")); if (!cache) { response.setHeader("Cache-Control", "max-age=0, must-revalidate"); response.setHeader("Expires", "Sat, 26 Jul 1997 05:00:00 GMT"); } if (content == null) { return; } if ("binary".equals(encodingType)) { response.getOutputStream().write(Base64.decodeBase64(content)); } else if ("plain".equals(encodingType)) { content = StringEscapeUtils.unescapeHtml(content); response.getWriter().write(content); if (response.getWriter().checkError()) { throw new IOException("Error when writing to response stream"); } } else { throw new ServletException(String.format("Unsupported encoding type %s", encodingType)); } }</code><technical_language>Do some browsers set is null</technical_language>

Target:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String contentType = request.getParameter("contenttype"); Boolean cache = Boolean.parseBoolean(request.getParameter("cache")); String encodingType = request.getParameter("encodingtype"); String content = request.getParameter("content"); if (StringUtils.isNotBlank(contentType)) { response.setContentType(contentType); } if (!cache) { response.setHeader("Cache-Control", "max-age=0, must-revalidate"); response.setHeader("Expires", "Sat, 26 Jul 1997 05:00:00 GMT"); } if (content == null) { return; } if (ENCODINGTYPE_BINARY.equals(encodingType)) { response.getOutputStream().write(Base64.decodeBase64(content)); } else if (ENCODINGTYPE_PLAIN.equals(encodingType)) { content = StringEscapeUtils.unescapeHtml(content); response.getWriter().write(content); if (response.getWriter().checkError()) { throw new IOException("Error when writing to response stream"); } } else { throw new ServletException(String.format("Unsupported encoding type %s", encodingType)); } }
Source:
<code>private <T> boolean hasApparentlyEqualsAndWarn(Collection<? extends T> items, T newItem) { T oldItem = findApparentlyEquals(items, newItem); if (oldItem!=null) { <START> LOG.warn("Adding to "+this+", "+newItem+" appears identical to existing "+oldItem+"; will remove after adding"); <END> return true; } else { return false; } }</code><technical_language>in message need for user fix - this behaviour relied in next future releases</technical_language>

Target:
private <T> boolean hasApparentlyEqualsAndWarn(Collection<? extends T> items, T newItem) { T oldItem = findApparentlyEquals(items, newItem); if (oldItem!=null) { if (isRebinding()) { LOG.warn("Adding to "+this+", "+newItem+" appears identical to existing "+oldItem+"; will remove after adding. " + "Underlying addition should be checked as this behavior will likely be removed without further notice."); return true; } else { LOG.warn("Adding to "+this+", "+newItem+" appears identical to existing "+oldItem+"; may get removed on rebind. " + "If unintended, addition should be removed. If intended, enricher should be modified so difference is apparent."); return false; } } else { return false; } }
Source:
<code>public void setupRoutes() { path(controllerBasePath(), () -> { before("", mimeType, this::setContentType); before("", mimeType, authHelper::checkUserAnd403); before("", mimeType, this::verifyContentType); before("/*", mimeType, this::setContentType); before("/*", mimeType, this::verifyContentType); get(ConfigRepos.INDEX_PATH, mimeType, this::listRepos); <START> before(ConfigRepos.REPO_PATH, mimeType, (request, response) -> { authHelper.checkUserHasPermissions(currentUsername(), getAction(request), CONFIG_REPO, request.params(":id")); }); <END> get(ConfigRepos.REPO_PATH, mimeType, this::showRepo); before(ConfigRepos.STATUS_PATH, mimeType, (request, response) -> { authHelper.checkUserHasPermissions(currentUsername(), getAction(request), CONFIG_REPO, request.params(":id")); }); get(ConfigRepos.STATUS_PATH, mimeType, this::inProgress); before(ConfigRepos.TRIGGER_UPDATE_PATH, mimeType, (request, response) -> { authHelper.checkUserHasPermissions(currentUsername(), getAction(request), CONFIG_REPO, request.params(":id")); }); post(ConfigRepos.TRIGGER_UPDATE_PATH, mimeType, this::triggerUpdate); before(ConfigRepos.DEFINITIONS_PATH, mimeType, (request, response) -> { authHelper.checkUserHasPermissions(currentUsername(), getAction(request), CONFIG_REPO, request.params(":id")); }); get(ConfigRepos.DEFINITIONS_PATH, mimeType, this::definedConfigs); }); }</code><technical_language>extract lambda a separate function reuse</technical_language>

Target:
public void setupRoutes() { path(controllerBasePath(), () -> { before("", mimeType, this::setContentType); before("", mimeType, authHelper::checkUserAnd403); before("", mimeType, this::verifyContentType); before("/*", mimeType, this::setContentType); before("/*", mimeType, this::verifyContentType); before(ConfigRepos.REPO_PATH, mimeType, this::authorize); before(ConfigRepos.STATUS_PATH, mimeType, this::authorize); before(ConfigRepos.TRIGGER_UPDATE_PATH, mimeType, this::authorize); before(ConfigRepos.DEFINITIONS_PATH, mimeType, this::authorize); get(ConfigRepos.INDEX_PATH, mimeType, this::listRepos); get(ConfigRepos.REPO_PATH, mimeType, this::showRepo); get(ConfigRepos.STATUS_PATH, mimeType, this::inProgress); post(ConfigRepos.TRIGGER_UPDATE_PATH, mimeType, this::triggerUpdate); get(ConfigRepos.DEFINITIONS_PATH, mimeType, this::definedConfigs); }); }
Source:
<code>private Drawable getDefaultAppDrawable(ComponentName componentName, UserHandle userHandle) { try { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { LauncherApps launcher = (LauncherApps) ctx.getSystemService(Context.LAUNCHER_APPS_SERVICE); List<LauncherActivityInfo> icons = launcher.getActivityList(componentName.getPackageName(), userHandle.getRealHandle()); for (LauncherActivityInfo info : icons) { if (info.getComponentName().equals(componentName)) { Drawable icon = info.getBadgedIcon(0); <START> if(iconsPackPackageName.equalsIgnoreCase("squircle") || iconsPackPackageName.equalsIgnoreCase("square") || iconsPackPackageName.equalsIgnoreCase("circle")) { <END> return DrawableUtils.handleAdaptiveIcons(ctx, icon); } else { return icon; } } } return icons.get(0).getBadgedIcon(0); } else { return pm.getActivityIcon(componentName); } } catch (NameNotFoundException | IndexOutOfBoundsException e) { Log.e(TAG, "Unable to found component " + componentName.toString() + e); return null; } }</code><technical_language>a method</technical_language>

Target:
private Drawable getDefaultAppDrawable(ComponentName componentName, UserHandle userHandle) { try { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { LauncherApps launcher = (LauncherApps) ctx.getSystemService(Context.LAUNCHER_APPS_SERVICE); List<LauncherActivityInfo> icons = launcher.getActivityList(componentName.getPackageName(), userHandle.getRealHandle()); for (LauncherActivityInfo info : icons) { if (info.getComponentName().equals(componentName)) { Drawable icon = info.getBadgedIcon(0); if(DrawableUtils.isIconsPackAdaptive(iconsPackPackageName)) { return DrawableUtils.handleAdaptiveIcons(ctx, icon); } else { return icon; } } } return icons.get(0).getBadgedIcon(0); } else { return pm.getActivityIcon(componentName); } } catch (NameNotFoundException | IndexOutOfBoundsException e) { Log.e(TAG, "Unable to found component " + componentName.toString() + e); return null; } }
Source:
<code>public <T> CompletableFuture<T> runScript(ScriptingManagerImpl scriptManager, ScriptMetadata metadata, CacheScriptBindings binding) { Cache<?, ?> masterCacheNode = (Cache<?, ?>) binding.get(SystemBindings.CACHE.toString()); if (masterCacheNode == null) { throw log.distributedTaskNeedCacheInBinding(metadata.name()); } DefaultExecutorService des = new DefaultExecutorService(masterCacheNode); try { List<Future<T>> tasks = des.submitEverywhere(new DistributedScript<T>(metadata)); <START> List<CompletableFuture<T>> all = new ArrayList<>(tasks.size()); <END> for(Future<T> task : tasks) { all.add(CompletableFutures.connect((NotifyingFuture<T>) task)); } return (CompletableFuture<T>) CompletableFutures.combine(all); } finally { des.shutdown(); } }</code><technical_language>do this more succinctly tasks.stream().map(CompletableFutures::connect). if work :: need cast... Also, CompletableFutures.connect, asCompletableFuture, Future instead of NotifyingFuture users need do casting. converter method check real type..</technical_language>

Target:
public <T> CompletableFuture<T> runScript(ScriptingManagerImpl scriptManager, ScriptMetadata metadata, CacheScriptBindings binding) { Cache<?, ?> masterCacheNode = (Cache<?, ?>) binding.get(SystemBindings.CACHE.toString()); if (masterCacheNode == null) { throw log.distributedTaskNeedCacheInBinding(metadata.name()); } DefaultExecutorService des = new DefaultExecutorService(masterCacheNode); try { List<Future<T>> tasks = des.submitEverywhere(new DistributedScript<T>(metadata)); List<CompletableFuture<T>> all = new ArrayList<>(tasks.size()); tasks.forEach(task -> all.add(CompletableFutures.toCompletableFuture((NotifyingFuture<T>) task))); return (CompletableFuture<T>) CompletableFutures.sequence(all); } finally { des.shutdown(); } }
Source:
<code>public String toString() { ToStringHelper helper = toStringHelper(this) .add("name", name) .add("ordinalPosition", ordinalPosition) .add("type", type); <START> return helper.toString(); <END> }</code><technical_language>please inline helper</technical_language>

Target:
public String toString() { return toStringHelper(this) .add("name", name) .add("ordinalPosition", ordinalPosition) .add("type", type) .toString(); }
Source:
<code>public void testFailingScheduleOrUpdateConsumers() throws Exception { final SchedulerBase scheduler = SchedulerTestingUtils.newSchedulerBuilder(new JobGraph()).build(); scheduler.start(ComponentMainThreadExecutorServiceAdapter.forMainThread()); scheduler.startScheduling(); final ExecutionGraph eg = scheduler.getExecutionGraph(); <START> assertEquals(JobStatus.RUNNING, eg.getState()); <END> ExecutionGraphTestUtils.switchAllVerticesToRunning(eg); IntermediateResultPartitionID intermediateResultPartitionId = new IntermediateResultPartitionID(); ExecutionAttemptID producerId = new ExecutionAttemptID(); ResultPartitionID resultPartitionId = new ResultPartitionID(intermediateResultPartitionId, producerId); try { eg.scheduleOrUpdateConsumers(resultPartitionId); fail("Expected ExecutionGraphException."); } catch (ExecutionGraphException e) { } assertEquals(JobStatus.RUNNING, eg.getState()); }</code><technical_language>do need test eg.scheduleOrUpdateConsumers here</technical_language>

Target:
public void testFailingScheduleOrUpdateConsumers() throws Exception { final SchedulerBase scheduler = SchedulerTestingUtils.newSchedulerBuilder(new JobGraph()).build(); scheduler.initialize(ComponentMainThreadExecutorServiceAdapter.forMainThread()); scheduler.startScheduling(); final ExecutionGraph eg = scheduler.getExecutionGraph(); assertEquals(JobStatus.RUNNING, eg.getState()); ExecutionGraphTestUtils.switchAllVerticesToRunning(eg); IntermediateResultPartitionID intermediateResultPartitionId = new IntermediateResultPartitionID(); ExecutionAttemptID producerId = new ExecutionAttemptID(); ResultPartitionID resultPartitionId = new ResultPartitionID(intermediateResultPartitionId, producerId); try { scheduler.scheduleOrUpdateConsumers(resultPartitionId); fail("Expected ExecutionGraphException."); } catch (RuntimeException e) { assertThat(e.getCause(), instanceOf(ExecutionGraphException.class)); } assertEquals(JobStatus.RUNNING, eg.getState()); }
Source:
<code>public final int asInt() { if (value == null) { <START> assert NullHandling.replaceWithDefault(); <END> return 0; } final Integer theInt = Ints.tryParse(value); return theInt == null ? 0 : theInt; }</code><technical_language>need check in line 257</technical_language>

Target:
public final int asInt() { if (value == null) { assert NullHandling.replaceWithDefault(); return 0; } final Integer theInt = Ints.tryParse(value); assert NullHandling.replaceWithDefault() || theInt != null; return theInt == null ? 0 : theInt; }
Source:
<code>public <T extends AppPage> T goToPreviousPage(Class<T> typeOfPreviousPage) { browser.driver.navigate().back(); waitForPageToLoad(); <START> switchToNewWindow(); <END> return changePageType(typeOfPreviousPage); }</code><technical_language>Is this change required? goToPreviousPage function called elsewhere, this statement change behavior</technical_language>

Target:
public <T extends AppPage> T goToPreviousPage(Class<T> typeOfPreviousPage) { browser.driver.navigate().back(); waitForPageToLoad(); return changePageType(typeOfPreviousPage); }
Source:
<code>private static boolean[] readBooleanArray(BytesObjectInput in) throws IOException { byte type = in.readByte(); <START> int len; <END> switch (type) { case ID_ARRAY_EMPTY: return new boolean[]{}; case ID_ARRAY_SMALL: return readBooleans(mkBooleanArray(in.readUnsignedByte(), ID_SMALL), in); case ID_ARRAY_MEDIUM: return readBooleans(mkBooleanArray(in.readUnsignedShort(), ID_MEDIUM), in); case ID_ARRAY_LARGE: return readBooleans(new boolean[in.readInt()], in); default: throw new IOException("Unknown array type: " + Integer.toHexString(type)); } }</code><technical_language>Unused variable</technical_language>

Target:
private static boolean[] readBooleanArray(BytesObjectInput in) throws IOException { byte type = in.readByte(); switch (type) { case ID_ARRAY_EMPTY: return new boolean[]{}; case ID_ARRAY_SMALL: return readBooleans(mkBooleanArray(in.readUnsignedByte() + 1), in); case ID_ARRAY_MEDIUM: return readBooleans(mkBooleanArray(in.readUnsignedShort() + 1), in); case ID_ARRAY_LARGE: return readBooleans(new boolean[in.readInt()], in); default: throw new IOException("Unknown array type: " + Integer.toHexString(type)); } }
Source:
<code>public boolean chkAuthorization(String userName, Object accessObj, String[] userRoles) throws QuadrigaStorageException, QuadrigaAccessException { boolean haveAccess; String projectOwner; String collaboratorName; String collaboratorRoleId; List<IQuadrigaRole> collaboratorRoles; ArrayList<String> roles; <START> haveAccess = false; <END> IProject project; String projectId = null; if (accessObj.getClass().equals(String.class)) { projectId = (String) accessObj; project = projectManager.getProjectDetails(projectId); } else { project = (IProject) accessObj; } projectOwner = project.getOwner().getUserName(); if (userName.equals(projectOwner)) { haveAccess = true; } if (!haveAccess) { if (userRoles.length > 0) { roles = getAccessRoleList(userRoles); List<IProjectCollaborator> projectCollaborators = project.getProjectCollaborators(); if (projectCollaborators != null) { for (IProjectCollaborator projectCollaborator : projectCollaborators) { ICollaborator collaborator = projectCollaborator.getCollaborator(); collaboratorName = collaborator.getUserObj().getUserName(); if (userName.equals(collaboratorName)) { collaboratorRoles = collaborator.getCollaboratorRoles(); for (IQuadrigaRole collabRole : collaboratorRoles) { collaboratorRoleId = collabRole.getId(); if (roles.contains(collaboratorRoleId)) { haveAccess = true; return haveAccess; } } } } } } } return haveAccess; }</code><technical_language>define of</technical_language>

Target:
public boolean chkAuthorization(String userName, Object accessObj, String[] userRoles) throws QuadrigaStorageException, QuadrigaAccessException { IProject project; if (accessObj instanceof String) { String projectId = (String) accessObj; project = projectManager.getProjectDetails(projectId); } else { try { project = (IProject) accessObj; } catch (ClassCastException cce) { throw new IllegalObjectException(cce); } } String projectOwner = project.getOwner().getUserName(); if (userName.equals(projectOwner)) { return true; } else { if (userRoles.length > 0) { List<String> roles = Arrays.asList(userRoles); List<IProjectCollaborator> projectCollaborators = project.getProjectCollaborators(); if (projectCollaborators != null) { for (IProjectCollaborator projectCollaborator : projectCollaborators) { ICollaborator collaborator = projectCollaborator.getCollaborator(); String collaboratorName = collaborator.getUserObj().getUserName(); if (userName.equals(collaboratorName)) { List<IQuadrigaRole> collaboratorRoles = collaborator.getCollaboratorRoles(); for (IQuadrigaRole collabRole : collaboratorRoles) { if (roles.contains(collabRole.getId())) { return true; } } } } } } } return false; }
Source:
<code>public void registerRequest(final Request request) { requests.add(request); request.addMessageObserver(new MessageObserverAdapter() { @Override public void onCancel() { requests.remove(request); <START> System.out.println(request + " cancelled"); <END> } @Override public void onReject() { requests.remove(request); System.out.println(request + " rejected"); } @Override public void onResponse(Response response) { requests.remove(request); System.out.println(request + " answered"); } @Override public void onSendError(Throwable error) { requests.remove(request); System.out.println(request + " can not be sent"); } @Override public void onTimeout() { requests.remove(request); System.out.println(request + " timed-out"); } }); }</code><technical_language>I know, test frequently System.out err. this change logger</technical_language>

Target:
public void registerRequest(final Request request) { requests.add(request); request.addMessageObserver(new MessageObserverAdapter() { @Override public void onCancel() { requests.remove(request); } @Override public void onReject() { requests.remove(request); } @Override public void onResponse(Response response) { requests.remove(request); } @Override public void onSendError(Throwable error) { requests.remove(request); } @Override public void onTimeout() { requests.remove(request); } }); }
Source:
<code>public static GlueDatabase create(UdbContext udbContext, UdbConfiguration configuration) { String glueDbName = udbContext.getUdbDbName(); if (glueDbName == null || glueDbName.isEmpty()) { throw new IllegalArgumentException( "Glue database name cannot be empty: " + glueDbName); <START> } else if (configuration.get(Property.GLUE_REGION) == null) { <END> throw new IllegalArgumentException("GlueUdb Error: AWS region cannot be empty."); } return new GlueDatabase(udbContext, configuration, glueDbName); }</code><technical_language>is ok if is empty string</technical_language>

Target:
public static GlueDatabase create(UdbContext udbContext, UdbConfiguration configuration) { String glueDbName = udbContext.getUdbDbName(); if (glueDbName == null || glueDbName.isEmpty()) { throw new IllegalArgumentException( "Glue database name cannot be empty: " + glueDbName); } else if (configuration.get(Property.GLUE_REGION) == null) { throw new IllegalArgumentException("GlueUdb Error: Please setup aws region."); } return new GlueDatabase(udbContext, configuration, glueDbName); }
Source:
<code>public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == EditHandler.RESULT_REFRESH_PAGE) { <START> section = data.getParcelableExtra(EditSectionActivity.EXTRA_SECTION); <END> ViewAnimations.crossFade(webView, loadProgress); setState(STATE_NO_FETCH); performActionForState(state); } }</code><technical_language>send 'id' back, that, sending entire 'section' object back. In general, prefer send primitive objects (strings, ints, etc) Activity boundaries entire objects, simpler for reasons: 1. section object a copy of section object have, unnecessary copy (performance implications, confusing actions object coming Intent effect elsewhere). apply in this case (we try objects immuatble perform actions 'Section' objects), is good practice 2. expose information needed interfaces! 3. is a performance penalty for passing full objects back. small, avoid it</technical_language>

Target:
public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == EditHandler.RESULT_REFRESH_PAGE) { int sectionId = data.getIntExtra(EditSectionActivity.EXTRA_SECTION,-1); section = page.getSections().get(sectionId); ViewAnimations.crossFade(webView, loadProgress); setState(STATE_NO_FETCH); performActionForState(state); } }
Source:
<code>public void flushCache() throws IOException { RestResponse r = adminSession.get("/config/server/caches/groups"); <START> CacheInfo result = newGson().fromJson(r.getReader(), new TypeToken<CacheInfo>() {}.getType()); <END> assertTrue(result.entries.mem.longValue() > 0); r = adminSession.post("/config/server/caches/groups/flush"); assertEquals(HttpStatus.SC_OK, r.getStatusCode()); r.consume(); r = adminSession.get("/config/server/caches/groups"); result = newGson().fromJson(r.getReader(), new TypeToken<CacheInfo>() {}.getType()); assertNull(result.entries.mem); }</code><technical_language>Simplify this</technical_language>

Target:
public void flushCache() throws IOException { RestResponse r = adminSession.get("/config/server/caches/groups"); CacheInfo result = newGson().fromJson(r.getReader(), CacheInfo.class); assertTrue(result.entries.mem.longValue() > 0); r = adminSession.post("/config/server/caches/groups/flush"); assertEquals(HttpStatus.SC_OK, r.getStatusCode()); r.consume(); r = adminSession.get("/config/server/caches/groups"); result = newGson().fromJson(r.getReader(), CacheInfo.class); assertNull(result.entries.mem); }
Source:
<code>SweepBatch getBatchForPartition(ShardAndStrategy shardStrategy, long partitionFine, long minTsExclusive, long maxTsExclusive) { if (inconsistentBounds(minTsExclusive, maxTsExclusive)) { return SweepBatch.of(ImmutableList.of(), minTsExclusive); } SweepableCellsTable.SweepableCellsRow row = computeRow(partitionFine, shardStrategy); RowColumnRangeIterator resultIterator = getRowColumnRange(row, partitionFine, minTsExclusive, maxTsExclusive); Multimap<Long, WriteInfo> startTsWrites = HashMultimap.create(); long lastSweptTs = 0L; while (resultIterator.hasNext() && startTsWrites.size() < SWEEP_BATCH_SIZE) { Map.Entry<Cell, Value> entry = resultIterator.next(); SweepableCellsTable.SweepableCellsColumn col = computeColumn(entry); lastSweptTs = getTimestamp(row, col); startTsWrites.putAll(lastSweptTs, getWrites(row, col, entry.getValue())); } List<Long> committedTs = getCommittedTimestampsAndCleanupAborted(startTsWrites); <START> committedTs.sort(Comparator.reverseOrder()); <END> if (exhaustedAllColumns(resultIterator)) { lastSweptTs = lastGuaranteedSwept(partitionFine, maxTsExclusive); } Map<CellReference, WriteInfo> writesToSweepFor = new HashMap<>(); committedTs.stream() .map(startTsWrites::get) .flatMap(Collection::stream) .forEach(write -> writesToSweepFor .putIfAbsent(write.writeRef().cellReference(), write)); return SweepBatch.of(writesToSweepFor.values(), lastSweptTs); }</code><technical_language>get this for free carefully choosing data structure for committedTs? Also, I here, streaming commit timestamps below, streaming start timestamps commited. scope is small, variable name long: startTimestampsThatWereCommitted</technical_language>

Target:
SweepBatch getBatchForPartition(ShardAndStrategy shardStrategy, long partitionFine, long minTsExclusive, long maxTsExclusive) { if (inconsistentBounds(minTsExclusive, maxTsExclusive)) { return SweepBatch.of(ImmutableList.of(), minTsExclusive); } SweepableCellsTable.SweepableCellsRow row = computeRow(partitionFine, shardStrategy); RowColumnRangeIterator resultIterator = getRowColumnRange(row, partitionFine, minTsExclusive, maxTsExclusive); Multimap<Long, WriteInfo> writesByStartTs = getBatchOfWrites(row, resultIterator); List<Long> startTimestampsForCommitted = getCommittedTimestampsDescendingAndCleanupAborted(writesByStartTs); Collection<WriteInfo> writes = getWritesToSweep(writesByStartTs, startTimestampsForCommitted); long lastSweptTs = getLastSweptTs(writesByStartTs, resultIterator, partitionFine, maxTsExclusive); return SweepBatch.of(writes, lastSweptTs); }
Source:
<code>public String toString() { StringBuilder sb = new StringBuilder(); sb.append("BlobProperties["); sb.append("BlobSize=").append(getBlobSize()); if (getContentType() != null) { sb.append(", ").append("ContentType=").append(getContentType()); } else { sb.append(", ").append("ContentType=Null"); } if (getOwnerId() != null) { sb.append(", ").append("OwnerId=").append(getOwnerId()); } else { sb.append(", ").append("OwnerId=Null"); } if (getServiceId() != null) { sb.append(", ").append("ServiceId=").append(getServiceId()); } else { sb.append(", ").append("ServiceId=Null"); } sb.append(", ").append("IsPrivate=").append(isPrivate()); sb.append(", ").append("CreationTimeInMs=").append(getCreationTimeInMs()); if (getTimeToLiveInSeconds() != Utils.Infinite_Time) { sb.append(", ").append("TimeToLiveInSeconds=").append(getTimeToLiveInSeconds()); } else { sb.append(", ").append("TimeToLiveInSeconds=Infinite"); } sb.append(", ").append("AccountId=").append(getAccountId()); sb.append(", ").append("ContainerId=").append(getContainerId()); sb.append(", ").append("IsEncrypted=").append(isEncrypted()); sb.append(", ").append("externalAssetTag=").append(getExternalAssetTag()); if (getContentEncoding() != null) { sb.append(", ").append("ContentEncoding=").append(getContentEncoding()); } else { <START> sb.append(", ").append("ContentEncoding=Null"); <END> } if (getFilename() != null) { sb.append(", ").append("Filename=").append(getFilename()); } else { sb.append(", ").append("Filename=Null"); } sb.append("]"); return sb.toString(); }</code><technical_language>I this null handling case is required, I this pattern in this method. sb.append("ContentEncoding=").append(null) work return "ContentEncoding=null"</technical_language>

Target:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("BlobProperties["); sb.append("BlobSize=").append(getBlobSize()); sb.append(", ").append("ContentType=").append(getContentType()); sb.append(", ").append("OwnerId=").append(getOwnerId()); sb.append(", ").append("ServiceId=").append(getServiceId()); sb.append(", ").append("IsPrivate=").append(isPrivate()); sb.append(", ").append("CreationTimeInMs=").append(getCreationTimeInMs()); if (getTimeToLiveInSeconds() != Utils.Infinite_Time) { sb.append(", ").append("TimeToLiveInSeconds=").append(getTimeToLiveInSeconds()); } else { sb.append(", ").append("TimeToLiveInSeconds=Infinite"); } sb.append(", ").append("AccountId=").append(getAccountId()); sb.append(", ").append("ContainerId=").append(getContainerId()); sb.append(", ").append("IsEncrypted=").append(isEncrypted()); sb.append(", ").append("externalAssetTag=").append(getExternalAssetTag()); sb.append(", ").append("ContentEncoding=").append(getContentEncoding()); sb.append(", ").append("Filename=").append(getFilename()); sb.append("]"); return sb.toString(); }
Source:
<code>public OAuth2IntrospectionAuthenticationToken(OAuth2AccessToken token, Map<String, Object> attributes, Collection<? extends GrantedAuthority> authorities) { this(token, attributes, authorities, null); <START> setAuthenticated(true); <END> }</code><technical_language>setAuthenticated(true) get pushed 4 arg constructor</technical_language>

Target:
public OAuth2IntrospectionAuthenticationToken(OAuth2AccessToken token, Map<String, Object> attributes, Collection<? extends GrantedAuthority> authorities) { this(token, attributes, authorities, null); }
Source:
<code>public ResponseEntity<?> getSubscription(@PathVariable("id") final String subscriptionId, <START> final NativeWebRequest request) { <END> return status(OK).body(subscriptionService.getSubscription(subscriptionId)); }</code><technical_language>declare throws please</technical_language>

Target:
public ResponseEntity<?> getSubscription(@PathVariable("id") final String subscriptionId, final NativeWebRequest request) throws NoSuchSubscriptionException, ServiceTemporarilyUnavailableException { return status(OK).body(subscriptionService.getSubscription(subscriptionId)); }
Source:
<code>private List<CcJudgmentKeyword> extractKeywords(SourceCcJudgment sourceJudgment) { List<CcJudgmentKeyword> keywords = Lists.newArrayList(); if (CollectionUtils.isEmpty(sourceJudgment.getThemePhrases())) { return keywords; } for (String themePhrase : sourceJudgment.getThemePhrases()) { <START> themePhrase = themePhrase.toLowerCase(); <END> CcJudgmentKeyword keyword = ccJudgmentKeywordCreator.getOrCreateCcJudgmentKeyword(themePhrase); keywords.add(keyword); } return keywords; }</code><technical_language>J) locale independent version themePhrase.toLowerCase(Locale.ROOT);</technical_language>

Target:
private List<CcJudgmentKeyword> extractKeywords(SourceCcJudgment sourceJudgment) { List<CcJudgmentKeyword> keywords = Lists.newArrayList(); if (CollectionUtils.isEmpty(sourceJudgment.getThemePhrases())) { return keywords; } for (String themePhrase : sourceJudgment.getThemePhrases()) { themePhrase = themePhrase.toLowerCase(Locale.ROOT); CcJudgmentKeyword keyword = ccJudgmentKeywordCreator.getOrCreateCcJudgmentKeyword(themePhrase); keywords.add(keyword); } return keywords; }
Source:
<code>public void testBelatedTransactionDoesntLeak() throws Throwable { final ControlledCommandFactory ccf = ControlledCommandFactory.registerControlledCommandFactory(advancedCache(1), VersionedPrepareCommand.class); ccf.gate.close(); Cache receiver = cache(1); BlockingPrepareInterceptor interceptor = new BlockingPrepareInterceptor(); advancedCache(1).addInterceptor(interceptor, 1); final Object key = getKeyForCache(1); fork(() -> { try { cache(0).put(key, "v"); } catch (Throwable e) { } }); <START> eventually(() -> ccf.blockTypeCommandsReceived.get() == 1); <END> killMember(0); Thread.sleep(5000); ccf.gate.open(); interceptor.prepareExecuted.await(); log.trace("Finished waiting for belated prepare to complete"); final TransactionTable transactionTable = TestingUtil.getTransactionTable(receiver); assertEquals(0, transactionTable.getRemoteTxCount()); assertEquals(0, transactionTable.getLocalTxCount()); assertFalse(receiver.getAdvancedCache().getLockManager().isLocked(key)); }</code><technical_language>eventuallyEquals</technical_language>

Target:
public void testBelatedTransactionDoesntLeak() throws Throwable { final ControlledCommandFactory ccf = ControlledCommandFactory.registerControlledCommandFactory(advancedCache(1), VersionedPrepareCommand.class); ccf.gate.close(); Cache receiver = cache(1); BlockingPrepareInterceptor interceptor = new BlockingPrepareInterceptor(); advancedCache(1).addInterceptor(interceptor, 1); final Object key = getKeyForCache(1); fork(() -> { try { cache(0).put(key, "v"); } catch (Throwable e) { } }); eventuallyEquals(1, ccf.blockTypeCommandsReceived::get); killMember(0); Thread.sleep(5000); ccf.gate.open(); interceptor.prepareExecuted.await(); log.trace("Finished waiting for belated prepare to complete"); final TransactionTable transactionTable = TestingUtil.getTransactionTable(receiver); assertEquals(0, transactionTable.getRemoteTxCount()); assertEquals(0, transactionTable.getLocalTxCount()); assertFalse(receiver.getAdvancedCache().getLockManager().isLocked(key)); }
Source:
<code>private static void sendToLoggers(LogLevel level, String tag, String msg) { boolean fileSucceeded = false; boolean consoleSucceeded = false; try { LogDomain domain = LogDomain.valueOf(tag); Database.getLog().getFile().log(level, domain, msg); fileSucceeded = true; Database.getLog().getConsole().log(level, domain, msg); <START> consoleSucceeded = false; <END> Logger custom = Database.getLog().getCustom(); if(custom != null) { custom.log(level, domain, msg); } } catch(Exception e) { if(fileSucceeded) { Database.getLog().getFile().log(LogLevel.ERROR, LogDomain.DATABASE, e.toString()); } if(consoleSucceeded) { Database.getLog().getConsole().log(LogLevel.ERROR, LogDomain.DATABASE, e.toString()); } } }</code><technical_language>set true</technical_language>

Target:
private static void sendToLoggers(LogLevel level, String tag, String msg) { boolean fileSucceeded = false; boolean consoleSucceeded = false; try { LogDomain domain = LogDomain.valueOf(tag); Database.getLog().getFile().log(level, domain, msg); fileSucceeded = true; Database.getLog().getConsole().log(level, domain, msg); consoleSucceeded = true; Logger custom = Database.getLog().getCustom(); if(custom != null) { custom.log(level, domain, msg); } } catch(Exception e) { if(fileSucceeded) { Database.getLog().getFile().log(LogLevel.ERROR, LogDomain.DATABASE, e.toString()); } if(consoleSucceeded) { Database.getLog().getConsole().log(LogLevel.ERROR, LogDomain.DATABASE, e.toString()); } } }
Source:
<code>public void doRequireBundle(String bundle, String installLocation) { String version = null; try { Manifest manifestSource; InputStream srcStream; if (installLocation.endsWith(".jar")) { ZipFile zip = new ZipFile(installLocation); srcStream = zip.getInputStream(zip.getEntry("META-INF/MANIFEST.MF")); manifestSource = new Manifest(srcStream); zip.close(); } else { <START> srcStream = new URL("file://" + installLocation + "/META-INF/MANIFEST.MF").openStream(); END> manifestSource = new Manifest(srcStream); } version = manifestSource.getMainAttributes().getValue("Bundle-Version"); } catch (Exception e) { e.printStackTrace(); return; } IFile fileManifest = project.getFile("META-INF/MANIFEST.MF"); Manifest manifest; try { manifest = new Manifest(fileManifest.getContents()); String value = manifest.getMainAttributes().getValue("Require-Bundle"); if (value == null) { manifest.getMainAttributes().putValue("Require-Bundle", bundle); } else { value += "," + bundle; if (version != null) { value += ";bundle-version=" + version; } manifest.getMainAttributes().putValue("Require-Bundle", value); } ByteArrayOutputStream bos = new ByteArrayOutputStream(); manifest.write(bos); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); fileManifest.setContents(bis, true, true, null); result = file; } catch (IOException e1) { e1.printStackTrace(); } catch (CoreException e1) { e1.printStackTrace(); } }</code><technical_language>Error: Replace with: srcStream = new BufferedInputStream(new FileInputStream(installLocation + "/META-INF/MANIFEST.MF")); //$NON-NLS-1$</technical_language>

Target:
public void doRequireBundle(String bundle, String installLocation) { String version = null; InputStream srcStream = null; try { Manifest manifestSource; if (installLocation.endsWith(".jar")) { ZipFile zip = new ZipFile(installLocation); srcStream = zip.getInputStream(zip.getEntry("META-INF/MANIFEST.MF")); manifestSource = new Manifest(srcStream); zip.close(); } else { srcStream = new BufferedInputStream(new FileInputStream(installLocation + "/META-INF/MANIFEST.MF")); manifestSource = new Manifest(srcStream); } version = manifestSource.getMainAttributes().getValue("Bundle-Version"); if (version != null) { version = version.replaceFirst("\\.qualifier", ""); } } catch (Exception e) { e.printStackTrace(); return; } finally { try { srcStream.close(); } catch (Exception e) { } } IFile fileManifest = project.getFile("META-INF/MANIFEST.MF"); Manifest manifest; try { manifest = new Manifest(fileManifest.getContents()); String value = manifest.getMainAttributes().getValue("Require-Bundle"); if (value == null) { manifest.getMainAttributes().putValue("Require-Bundle", bundle); } else { value += "," + bundle; if (version != null) { value += ";bundle-version=" + version; } manifest.getMainAttributes().putValue("Require-Bundle", value); } ByteArrayOutputStream bos = new ByteArrayOutputStream(); manifest.write(bos); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); fileManifest.setContents(bis, true, true, null); result = file; } catch (IOException e1) { e1.printStackTrace(); } catch (CoreException e1) { e1.printStackTrace(); } }
Source:
<code>private MemorySegment requestMemorySegment(int targetChannel) { MemorySegment segment; synchronized (availableMemorySegments) { if (isDestroyed) { throw new IllegalStateException("Buffer pool is destroyed."); } if (targetChannel != UNKNOWN_CHANNEL && subpartitionBuffersCount[targetChannel] >= maxBuffersPerChannel) { return null; } segment = availableMemorySegments.poll(); if (segment == null) { return null; } if (targetChannel != UNKNOWN_CHANNEL) { if (++subpartitionBuffersCount[targetChannel] == maxBuffersPerChannel) { unavailableSubpartitionsCount++; } } if (!checkAvailability()) { availabilityHelper.resetUnavailable(); <START> } <END> assert hasConsistentAvailability(); } return segment; }</code><technical_language>subpartitionBuffersCount[targetChannel]++ ++subpartitionBuffersCount[targetChannel], changing semantic a bit</technical_language>

Target:
private MemorySegment requestMemorySegment(int targetChannel) { MemorySegment segment; synchronized (availableMemorySegments) { if (isDestroyed) { throw new IllegalStateException("Buffer pool is destroyed."); } if (targetChannel != UNKNOWN_CHANNEL && subpartitionBuffersCount[targetChannel] >= maxBuffersPerChannel) { return null; } segment = availableMemorySegments.poll(); if (segment == null) { return null; } if (targetChannel != UNKNOWN_CHANNEL) { if (++subpartitionBuffersCount[targetChannel] == maxBuffersPerChannel) { unavailableSubpartitionsCount++; } } if (!checkAvailability()) { availabilityHelper.resetUnavailable(); } checkConsistentAvailability(); } return segment; }