auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public QueryControlResult create(final Tuple<String, AvroDag> tuple) { final QueryControlResult queryControlResult = new QueryControlResult(); queryControlResult.setQueryId(tuple.getKey()); try { planStore.saveAvroDag(tuple); final String queryId = tuple.getKey(); final String appId = tuple.getValue().getAppId(); if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "Create Query [aid: {0}, qid: {2}]", new Object[]{appId, queryId}); } if (!applicationMap.containsKey(appId)) { <START> createApplication(appId, tuple.getValue().getJarPaths()); <END> } final ApplicationInfo applicationInfo = applicationMap.get(appId); final DAG<ConfigVertex, MISTEdge> configDag = configDagGenerator.generate(tuple.getValue()); final Query query = createAndStartQuery(queryId, applicationInfo, configDag); queryControlResult.setIsSuccess(true); queryControlResult.setMsg(ResultMessage.submitSuccess(tuple.getKey())); return queryControlResult; } catch (final Exception e) { e.printStackTrace(); LOG.log(Level.SEVERE, "An exception occurred while starting {0} query: {1}", new Object[] {tuple.getKey(), e.toString()}); queryControlResult.setIsSuccess(false); queryControlResult.setMsg(e.getMessage()); return queryControlResult; } }</code><technical_language>I is a concurrency issue multiple queries appId submitted time. need fix it</technical_language>

Target:
public QueryControlResult create(final Tuple<String, AvroDag> tuple) { final QueryControlResult queryControlResult = new QueryControlResult(); queryControlResult.setQueryId(tuple.getKey()); try { planStore.saveAvroDag(tuple); final String queryId = tuple.getKey(); final String appId = tuple.getValue().getAppId(); if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "Create Query [aid: {0}, qid: {2}]", new Object[]{appId, queryId}); } if (!applicationMap.containsKey(appId)) { createApplication(appId, tuple.getValue().getJarPaths()); } final ApplicationInfo applicationInfo = applicationMap.get(appId); final DAG<ConfigVertex, MISTEdge> configDag = configDagGenerator.generate(tuple.getValue()); while (applicationInfo.getGroups().isEmpty()) { Thread.sleep(100); } final Query query = createAndStartQuery(queryId, applicationInfo, configDag); queryControlResult.setIsSuccess(true); queryControlResult.setMsg(ResultMessage.submitSuccess(tuple.getKey())); return queryControlResult; } catch (final Exception e) { e.printStackTrace(); LOG.log(Level.SEVERE, "An exception occurred while starting {0} query: {1}", new Object[] {tuple.getKey(), e.toString()}); queryControlResult.setIsSuccess(false); queryControlResult.setMsg(e.getMessage()); return queryControlResult; } }
Source:
<code>public void addPage(BenchmarkData data) { int pageCount = data.getPageCount(); <START> Page page = data.getDataPage(); <END> PartitionedOutputOperator operator = data.createPartitionedOutputOperator(); for (int i = 0; i < pageCount; i++) { operator.addInput(page); } operator.finish(); }</code><technical_language>inline vars</technical_language>

Target:
public void addPage(BenchmarkData data) { PartitionedOutputOperator operator = data.createPartitionedOutputOperator(); for (int i = 0; i < data.getPageCount(); i++) { operator.addInput(data.getDataPage()); } operator.finish(); }
Source:
<code>void readContainerLogsInSeparateThread( String container, String workspaceId, String machineId, MessageProcessor<LogMessage> logsProcessor) { executor.execute( () -> { boolean test = false; if (test) { <START> throw new RuntimeException("test test 123"); <END> } long lastProcessedLogDate = 0; boolean isContainerRunning = true; int errorsCounter = 0; long lastErrorTime = 0; while (isContainerRunning) { try { docker.getContainerLogs( GetContainerLogsParams.create(container) .withFollow(true) .withSince(lastProcessedLogDate), logsProcessor); isContainerRunning = false; } catch (SocketTimeoutException ste) { lastProcessedLogDate = System.currentTimeMillis() / 1000L; } catch (ContainerNotFoundException e) { isContainerRunning = false; } catch (IOException e) { long errorTime = System.currentTimeMillis(); lastProcessedLogDate = errorTime / 1000L; LOG.warn( "Failed to get logs from machine of workspace backed by container {}, because: {}.", machineId, workspaceId, container, e.getMessage(), e); if (errorTime - lastErrorTime < 20_000L) { if (++errorsCounter == 5) { LOG.error( "Too many errors while streaming logs from machine of workspace backed by container {}. " + "Logs streaming is closed. Last error: {}.", machineId, workspaceId, container, e.getMessage(), e); break; } } else { errorsCounter = 1; } lastErrorTime = errorTime; try { sleep(1_000); } catch (InterruptedException ie) { return; } } } }); }</code><technical_language>is remove it,</technical_language>

Target:
void readContainerLogsInSeparateThread( String container, String workspaceId, String machineId, MessageProcessor<LogMessage> logsProcessor) { executor.execute( () -> { long lastProcessedLogDate = 0; boolean isContainerRunning = true; int errorsCounter = 0; long lastErrorTime = 0; while (isContainerRunning) { try { docker.getContainerLogs( GetContainerLogsParams.create(container) .withFollow(true) .withSince(lastProcessedLogDate), logsProcessor); isContainerRunning = false; } catch (SocketTimeoutException ste) { lastProcessedLogDate = System.currentTimeMillis() / 1000L; } catch (ContainerNotFoundException e) { isContainerRunning = false; } catch (IOException e) { long errorTime = System.currentTimeMillis(); lastProcessedLogDate = errorTime / 1000L; LOG.warn( "Failed to get logs from machine of workspace backed by container {}, because: {}.", machineId, workspaceId, container, e.getMessage(), e); if (errorTime - lastErrorTime < 20_000L) { if (++errorsCounter == 5) { LOG.error( "Too many errors while streaming logs from machine of workspace backed by container {}. " + "Logs streaming is closed. Last error: {}.", machineId, workspaceId, container, e.getMessage(), e); break; } } else { errorsCounter = 1; } lastErrorTime = errorTime; try { sleep(1_000); } catch (InterruptedException ie) { return; } } } }); }
Source:
<code>public Object getSparkObject() throws StandardException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = null; try { out = new ObjectOutputStream(bos); out.writeObject(value); out.flush(); return bos.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); } finally { try { bos.close(); } catch (IOException ex) { } } <START> } <END></code><technical_language>making of a try-with-resources block simplify a bit? java @Override public Object getSparkObject() throws StandardException { try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { ObjectOutput out = new ObjectOutputStream(bos); out.writeObject(value); out.flush(); return bos.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); } } Also, throwing RuntimeException instead of StandardException</technical_language>

Target:
public Object getSparkObject() throws StandardException { if (value instanceof Serializable) { return SerializationUtils.serialize((Serializable) value); } else { return super.getSparkObject(); } }
Source:
<code>public Object execute(ExecutionEvent event) throws ExecutionException { IStructuredSelection selection = (IStructuredSelection) HandlerUtil .getCurrentSelection(event); final Repository repository = SelectionUtils.getRepository(selection); final GitFlowRepository gfRepo = new GitFlowRepository(repository); <START> Job job = new Job(UIText.FeatureFinishHandler_finishingFeature) { <END> @Override protected IStatus run(IProgressMonitor monitor) { try { new FeatureFinishOperation(gfRepo).execute(monitor); } catch (WrongGitFlowStateException e) { return error(e.getMessage(), e); } catch (CoreException e) { return error(e.getMessage(), e); } catch (IOException e) { return error(e.getMessage(), e); } return Status.OK_STATUS; } }; job.setUser(true); job.schedule(); return null; }</code><technical_language>WorkspaceJob prevent refresh is triggered prematurely (see commit 786698088)</technical_language>

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { IStructuredSelection selection = (IStructuredSelection) HandlerUtil .getCurrentSelection(event); final Repository repository = SelectionUtils.getRepository(selection); final GitFlowRepository gfRepo = new GitFlowRepository(repository); WorkspaceJob job = new WorkspaceJob( UIText.FeatureFinishHandler_finishingFeature) { @Override public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException { try { new FeatureFinishOperation(gfRepo).execute(monitor); } catch (WrongGitFlowStateException e) { return error(e.getMessage(), e); } catch (CoreException e) { return error(e.getMessage(), e); } catch (IOException e) { return error(e.getMessage(), e); } return Status.OK_STATUS; } }; job.setUser(true); job.schedule(); return null; }
Source:
<code>public Mappings.TargetMapping getPartialMapping(int inputFieldCount) { Mappings.TargetMapping mapping = Mappings.create(MappingType.INVERSE_FUNCTION, inputFieldCount, projects.size()); for (Ord<RexLocalRef> exp : Ord.zip(projects)) { <START> RexInputRef inputRef = (RexInputRef) exprs.get(exp.e.index); <END> mapping.set(inputRef.getIndex(), exp.i); } return mapping; }</code><technical_language>call RexProgram#expandLocalRef for expansion</technical_language>

Target:
public Mappings.TargetMapping getPartialMapping(int inputFieldCount) { Mappings.TargetMapping mapping = Mappings.create(MappingType.INVERSE_FUNCTION, inputFieldCount, projects.size()); for (Ord<RexLocalRef> exp : Ord.zip(projects)) { RexNode rexNode = expandLocalRef(exp.e); if (rexNode instanceof RexInputRef) { mapping.set(((RexInputRef) rexNode).getIndex(), exp.i); } } return mapping; }
Source:
<code>public void validate(ValidationContext validationContext) { <START> if(name == null || StringUtil.isBlank(CaseInsensitiveString.str(name))) <END> addError("User cannot be blank."); }</code><technical_language>a CaseInsensitiveString#isBlank instead of pulling out raw string</technical_language>

Target:
public void validate(ValidationContext validationContext) { if(name == null || name.isBlank()) addError("User cannot be blank."); }
Source:
<code>public void addInput(Page page) { <START> checkState(pendingInput == null); <END> requireNonNull(page, "page is null"); processInput(page); updateMemoryUsage(); }</code><technical_language>Add a message checkState easier debug if hit it</technical_language>

Target:
public void addInput(Page page) { checkState(!finishing, "Operator is already finishing"); requireNonNull(page, "page is null"); processInput(page); updateMemoryUsage(); }
Source:
<code><START> public static LiveVariablesAnalysis analyze(ControlFlowGraph cfg, SymbolTable symbols) { <END> return new LiveVariablesAnalysis(cfg, symbols); }</code><technical_language>this static layer</technical_language>

Target:
public static LiveVariablesAnalysis analyze(ControlFlowGraph cfg, SymbolTable symbols) { LiveVariablesAnalysis instance = new LiveVariablesAnalysis(); instance.compute(cfg, symbols); return instance; }
Source:
<code>private void updateTscFrequency() { if (getSelectedCluster() == null || getVmType() == null || getMigrationMode() == null) { return; } boolean isChangeable = ArchitectureType.x86.equals(getSelectedCluster().getArchitecture().getFamily()) && VmType.HighPerformance.equals(getVmType().getSelectedItem()) && <START> MigrationSupport.MIGRATABLE.equals(getMigrationMode().getSelectedItem()); <END> tscFrequency.setIsChangeable(isChangeable); tscFrequency.setEntity(isChangeable); }</code><technical_language>This condition enables checkbox if VM is automatically migratable. enabled if VM is manually migratable (MigrationSupport.IMPLICITLY_NON_MIGRATABLE)</technical_language>

Target:
private void updateTscFrequency() { if (getSelectedCluster() == null || getVmType() == null || getMigrationMode() == null) { return; } boolean isChangeable = ArchitectureType.x86.equals(getSelectedCluster().getArchitecture().getFamily()) && VmType.HighPerformance.equals(getVmType().getSelectedItem()) && (MigrationSupport.MIGRATABLE.equals(getMigrationMode().getSelectedItem()) || MigrationSupport.IMPLICITLY_NON_MIGRATABLE.equals(getMigrationMode().getSelectedItem())); tscFrequency.setIsChangeable(isChangeable); tscFrequency.setEntity(isChangeable); }
Source:
<code>public void badResponseHandlerAndRestRequestTest() throws Exception { RestRequest restRequest = new BadRestRequest(); MockRestResponseChannel restResponseChannel = new MockRestResponseChannel(); responseHandler.shutdown(); ambryBlobStorageService.handleGet(restRequest, restResponseChannel); assertEquals("Unexpected exception", IllegalStateException.class, restResponseChannel.getException().getClass()); responseHandler.reset(); restResponseChannel = new MockRestResponseChannel(); ambryBlobStorageService.handlePost(restRequest, restResponseChannel); Exception e = restResponseChannel.getException(); assertTrue("Unexpected exception", e instanceof IllegalStateException || e instanceof NullPointerException); responseHandler.reset(); restResponseChannel = new MockRestResponseChannel(); <START> ambryBlobStorageService.handlePut(restRequest, restResponseChannel); <END> e = restResponseChannel.getException(); assertTrue("Unexpected exception", e instanceof RestServiceException); responseHandler.reset(); restResponseChannel = new MockRestResponseChannel(); ambryBlobStorageService.handleDelete(restRequest, restResponseChannel); e = restResponseChannel.getException(); assertTrue("Unexpected exception", e instanceof IllegalStateException || e instanceof NullPointerException); responseHandler.reset(); restResponseChannel = new MockRestResponseChannel(); ambryBlobStorageService.handleHead(restRequest, restResponseChannel); e = restResponseChannel.getException(); assertTrue("Unexpected exception", e instanceof IllegalStateException || e instanceof NullPointerException); }</code><technical_language>this belong in badResponseHandlerAndRestRequestTest() - a test AdminBlobStorageServiceTest::putFailureTest()</technical_language>

Target:
public void badResponseHandlerAndRestRequestTest() throws Exception { RestRequest restRequest = new BadRestRequest(); MockRestResponseChannel restResponseChannel = new MockRestResponseChannel(); responseHandler.shutdown(); ambryBlobStorageService.handleGet(restRequest, restResponseChannel); assertEquals("Unexpected exception", IllegalStateException.class, restResponseChannel.getException().getClass()); responseHandler.reset(); restResponseChannel = new MockRestResponseChannel(); ambryBlobStorageService.handlePost(restRequest, restResponseChannel); Exception e = restResponseChannel.getException(); assertTrue("Unexpected exception", e instanceof IllegalStateException || e instanceof NullPointerException); responseHandler.reset(); restResponseChannel = new MockRestResponseChannel(); ambryBlobStorageService.handleDelete(restRequest, restResponseChannel); e = restResponseChannel.getException(); assertTrue("Unexpected exception", e instanceof IllegalStateException || e instanceof NullPointerException); responseHandler.reset(); restResponseChannel = new MockRestResponseChannel(); ambryBlobStorageService.handleHead(restRequest, restResponseChannel); e = restResponseChannel.getException(); assertTrue("Unexpected exception", e instanceof IllegalStateException || e instanceof NullPointerException); }
Source:
<code>public static void launchArrangeCommand(DiagramEditPart diagramEditPart, <START> boolean isAfterDiagramEditorInstantiation) { <END> TransactionalEditingDomain editingDomain = diagramEditPart.getEditingDomain(); Map<IGraphicalEditPart, List<IAdaptable>> createdViewsToLayoutMap = getCreatedViewsToLayoutMap(diagramEditPart); Map<IGraphicalEditPart, List<IAdaptable>> createdViewsWithSpecialLayoutMap = getCreatedViewsWithSpecialLayoutMap(diagramEditPart); DiagramDescription diagDesc = new EditPartQuery(diagramEditPart).getDiagramDescription(); if (isAfterDiagramEditorInstantiation && diagDesc != null && diagDesc.getLayout() instanceof CustomLayoutConfiguration) { List<IAdaptable> createdViews = createdViewsToLayoutMap.get(diagramEditPart); createdViewsToLayoutMap.clear(); if (createdViews != null && !createdViews.isEmpty()) { createdViewsToLayoutMap.put(diagramEditPart, createdViews); } } Command layoutCommand = getLayoutCommand(createdViewsToLayoutMap, createdViewsWithSpecialLayoutMap, editingDomain); if (layoutCommand.canExecute()) { editingDomain.getCommandStack().execute(layoutCommand); } }</code><technical_language>Boolean parameters code hard understand. obivous I read launchArrangeCommand(diag, true) launchArrangeCommand(diag, false) "true" of "false" mean. is method names difference explicit. launchArrangeOnOpening() launchRearrange()</technical_language>

Target:
private static void launchArrangeCommand(DiagramEditPart diagramEditPart, boolean isAfterDiagramEditorInstantiation) { TransactionalEditingDomain editingDomain = diagramEditPart.getEditingDomain(); Map<IGraphicalEditPart, List<IAdaptable>> createdViewsToLayoutMap = getCreatedViewsToLayoutMap(diagramEditPart); Map<IGraphicalEditPart, List<IAdaptable>> createdViewsWithSpecialLayoutMap = getCreatedViewsWithSpecialLayoutMap(diagramEditPart); DiagramDescription diagDesc = new EditPartQuery(diagramEditPart).getDiagramDescription(); if (isAfterDiagramEditorInstantiation && diagDesc != null && diagDesc.getLayout() instanceof CustomLayoutConfiguration) { List<IAdaptable> createdViews = createdViewsToLayoutMap.get(diagramEditPart); createdViewsToLayoutMap.clear(); if (createdViews != null && !createdViews.isEmpty()) { createdViewsToLayoutMap.put(diagramEditPart, createdViews); } } Command layoutCommand = getLayoutCommand(createdViewsToLayoutMap, createdViewsWithSpecialLayoutMap, editingDomain); if (layoutCommand.canExecute()) { editingDomain.getCommandStack().execute(layoutCommand); } }
Source:
<code>public void register(final Collection<String> componentIds) { final Map<String, SctId> sctIds = Maps.newHashMap(); final Set<String> registeredComponentIds = newHashSet(); LOGGER.debug(String.format("Registering %d component IDs.", componentIds.size())); try { <START> final Collection<String> existingIds = getSctIds(componentIds).stream().filter(id -> id.matches(IdentifierStatus.AVAILABLE, IdentifierStatus.RESERVED)).map(SctId::getSctid).collect(Collectors.toSet()); <END> for (final String componentId : componentIds) { if (!existingIds.contains(componentId)) { final SctId sctId = buildSctId(componentId, IdentifierStatus.ASSIGNED); sctIds.put(componentId, sctId); registeredComponentIds.add(componentId); } else { LOGGER.warn("Cannot register ID as it is already taken.", componentId); } } putSctIds(sctIds); } catch (Exception e) { removeSctIds(registeredComponentIds); throw e; } }</code><technical_language>change foreach block warning message display non-registrable status again? Java 8 fancy of this to: * getSctIds(componentIds) retrieve SctId instances for incoming IDs; * Collectors.partitioningBy(sctIds, id -> id.matches(IdentifierStatus.AVAILABLE, IdentifierStatus.RESERVED)) get a Map<Boolean, List<SctId>> holds SctIds pass fail predicate, depending key; * Iterate key true (IDs in state Reserved Available) do registration; * Iterate key false log identifier status prevented registration</technical_language>

Target:
public void register(final Collection<String> componentIds) { final Map<String, SctId> sctIds = Maps.newHashMap(); final Set<String> registeredComponentIds = newHashSet(); LOGGER.debug(String.format("Registering %d component IDs.", componentIds.size())); try { for (final SctId sctId : getSctIds(componentIds)) { if (!sctId.matches(IdentifierStatus.AVAILABLE, IdentifierStatus.RESERVED)) { LOGGER.warn("Cannot register ID as it is already present with status {}.", sctId.getSctid(), sctId.getStatus()); } else { sctId.setStatus(IdentifierStatus.ASSIGNED.getSerializedName()); } } putSctIds(sctIds); } catch (Exception e) { removeSctIds(registeredComponentIds); throw e; } }
Source:
<code>public Object perform(InvocationContext ctx) throws Throwable { <START> ((DefaultCacheManager) cacheManager).removeCacheLocally(cacheName); <END> return null; }</code><technical_language>This blow running Wildfly Wildfly DefaulCacheManager implementation AFAIK. implement a delegating cache manager AFAIK. I need for a removeCacheLocally method all. create a private method in this command, get component registry cache manager, injected, in private method do do in removeCacheLocally? If method needs accessible multiple places, add a util class static method passing in parameters needed</technical_language>

Target:
public Object perform(InvocationContext ctx) throws Throwable { GlobalComponentRegistry globalComponentRegistry = cacheManager.getGlobalComponentRegistry(); ComponentRegistry cacheComponentRegistry = globalComponentRegistry.getNamedComponentRegistry(cacheName); if (cacheComponentRegistry != null) { cacheComponentRegistry.getComponent(PersistenceManager.class).setClearOnStop(true); cacheComponentRegistry.getComponent(CacheJmxRegistration.class).setUnregisterCacheMBean(true); cacheComponentRegistry.getComponent(PassivationManager.class).skipPassivationOnStop(true); Cache<?, ?> cache = cacheManager.getCache(cacheName, false); if (cache != null) { cache.stop(); } } globalComponentRegistry.removeCache(cacheName); globalComponentRegistry.getComponent(ConfigurationManager.class).removeConfiguration(cacheName); globalComponentRegistry.getComponent(DependencyGraph.class, CACHE_DEPENDENCY_GRAPH).remove(cacheName); return null; }
Source:
<code>FileState(BufferedWriter writer) { this.writer = writer; this.stream = null; <START> this.lastFlush = System.currentTimeMillis(); <END> }</code><technical_language>lastFlush is updated. I missing something? I if update MessageFlushPredicate.shouldFlush() for this new lastFlush argument well</technical_language>

Target:
FileState(BufferedWriter writer) { this.writer = writer; this.stream = null; }
Source:
<code>public void initialise() { <START> sceneOpaqueFbo = displayResolutionDependentFBOs.get(SCENE_OPAQUE); <END> playerCamera = worldRenderer.getActiveCamera(); wireframeStateChange = new SetWireframe(true); renderingDebugConfig = config.getRendering().getDebug(); new WireframeTrigger(renderingDebugConfig, this); addDesiredStateChange(new LookThrough(playerCamera)); addDesiredStateChange(new SetViewportToSizeOf(SCENE_OPAQUE, displayResolutionDependentFBOs)); }</code><technical_language>Please move line after... =)</technical_language>

Target:
public void initialise() { wireframeStateChange = new SetWireframe(true); renderingDebugConfig = config.getRendering().getDebug(); new WireframeTrigger(renderingDebugConfig, this); playerCamera = worldRenderer.getActiveCamera(); addDesiredStateChange(new LookThrough(playerCamera)); addDesiredStateChange(new SetViewportToSizeOf(READONLY_GBUFFER, displayResolutionDependentFBOs)); sceneOpaqueFbo = displayResolutionDependentFBOs.get(READONLY_GBUFFER); }
Source:
<code>public void shouldAcquireSchemaWriteLockBeforeCreatingUniquenessConstraint() throws Exception { when( constraintIndexCreator.createUniquenessConstraintIndex( transaction, descriptor ) ).thenReturn( 42L ); when( storeReadLayer.constraintsGetForSchema( descriptor.schema() ) ).thenReturn( Collections.emptyIterator() ); operations.uniquePropertyConstraintCreate( descriptor ); <START> verify( locks ).acquireExclusive( LockTracer.NONE, ResourceTypes.LABEL, descriptor.getLabelId() ); <END> }</code><technical_language>order.verify lock is creation, similar i done w. drops</technical_language>

Target:
public void shouldAcquireSchemaWriteLockBeforeCreatingUniquenessConstraint() throws Exception { when( constraintIndexCreator.createUniquenessConstraintIndex( transaction, descriptor ) ).thenReturn( 42L ); when( storeReadLayer.constraintsGetForSchema( descriptor.schema() ) ).thenReturn( Collections.emptyIterator() ); operations.uniquePropertyConstraintCreate( descriptor ); order.verify( locks ).acquireExclusive( LockTracer.NONE, ResourceTypes.LABEL, descriptor.getLabelId() ); order.verify( txState ).constraintDoAdd( ConstraintDescriptorFactory.uniqueForSchema( descriptor ), 42L ); }
Source:
<code><START> public static void damageItem(GlowPlayer player, ItemStack holding) { <END> if (player != null && player.getGameMode() == GameMode.CREATIVE) { return; } int durability = holding.getEnchantmentLevel(Enchantment.DURABILITY); if (durability > 0 && ThreadLocalRandom.current().nextDouble() < 1 / (durability + 1)) { return; } holding.setDurability((short) (holding.getDurability() + 1)); if (holding.getDurability() == holding.getType().getMaxDurability() + 1) { if (player != null) { EventFactory.callEvent(new PlayerItemBreakEvent(player, holding)); } holding.setAmount(0); } }</code><technical_language>I do, is a method ItemStack, returns ItemStack. ItemStack get updated in player's inventory inventory.setItem(slot, stack); slot information of ItemStack object, this current implementation work. Also, in case, return InventoryUtil.createEmptyStack() if item is removed (max damage)</technical_language>

Target:
public static ItemStack damageItem(GlowPlayer player, ItemStack holding) { if (player != null && player.getGameMode() == GameMode.CREATIVE) { return holding; } int durability = holding.getEnchantmentLevel(Enchantment.DURABILITY); if (durability > 0 && ThreadLocalRandom.current().nextDouble() < 1 / (durability + 1)) { return holding; } holding.setDurability((short) (holding.getDurability() + 1)); if (holding.getDurability() == holding.getType().getMaxDurability() + 1) { if (player != null) { EventFactory.callEvent(new PlayerItemBreakEvent(player, holding)); } return createEmptyStack(); } return holding; }
Source:
<code>public Optional<Layout> getCurrentLayout() { if(!serverMap.containsKey(LayoutServer.class)){ throw new IllegalStateException("Layout server is not in a server map."); } <START> LayoutServer layoutServer = (LayoutServer) serverMap.get(LayoutServer.class); <END> return Optional.ofNullable(layoutServer.getCurrentLayout()); }</code><technical_language>router depend LayoutServer , cleaner serverContext</technical_language>

Target:
public Optional<Layout> getCurrentLayout() { return Optional.ofNullable(serverContext.getCurrentLayout()); }
Source:
<code>private static Customer getSampleCustomer() { return Customer.newBuilder() .setId(CustomerId.newBuilder() .setNumber((int) UUID.randomUUID() .getLeastSignificantBits())) .setName(PersonName.newBuilder() <START> .setGivenName("Socrates") <END> .build()) .addNicknames(PersonName.newBuilder() .setGivenName("Philosopher")) .addNicknames(PersonName.newBuilder() .setGivenName("Wise guy")) .build(); }</code><technical_language>Please of other test names</technical_language>

Target:
private static Customer getSampleCustomer() { return Customer.newBuilder() .setId(CustomerId.newBuilder() .setNumber((int) UUID.randomUUID() .getLeastSignificantBits())) .setName(PersonName.newBuilder() .setGivenName("John") .build()) .addNicknames(PersonName.newBuilder() .setGivenName("Johnny")) .addNicknames(PersonName.newBuilder() .setGivenName("Big Guy")) .build(); }
Source:
<code>public Response getCredentials() { String user = authenticationService.getPrincipal(); <START> LOGGER.info("getCredentials credentials for user ", user); <END> UserCredentials uc; try { uc = credentials.getUserCredentials(user); return new JsonResponse<>(Status.OK, uc).build(); } catch (IOException e) { LOGGER.error(e.getMessage(), e); return new JsonResponse<>(Status.INTERNAL_SERVER_ERROR).build(); } }</code><technical_language>> getCredentials for user {}</technical_language>

Target:
public Response getCredentials() { String user = authenticationService.getPrincipal(); LOGGER.info("getCredentials for user ", user); UserCredentials uc; try { uc = credentials.getUserCredentials(user); return new JsonResponse<>(Status.OK, uc).build(); } catch (IOException e) { LOGGER.error(e.getMessage(), e); return new JsonResponse<>(Status.INTERNAL_SERVER_ERROR).build(); } }
Source:
<code>public String toString() { final StringBuilder builder = new StringBuilder("{"); final Iterator<Map.Entry<String, JsonValue>> it = unmodifieableBackingMap.entrySet().iterator(); boolean hasNext = it.hasNext(); while (hasNext) { final Map.Entry<String, JsonValue> entry = it.next(); <START> builder.append('"').append(Strings.escape(entry.getKey())).append("\":"); <END> final JsonValue value = entry.getValue(); if (JsonString.class.isInstance(value)) { builder.append(value.toString()); } else { builder.append(value != JsonValue.NULL ? value.toString() : JsonChars.NULL); } hasNext = it.hasNext(); if (hasNext) { builder.append(","); } } return builder.append('}').toString(); }</code><technical_language>This relies a global buffer cache, want builder - object builder parser factory - buffer factory global is for compatibility IIRC. slows default case - escaped - is a concern toString is a serialization solution for jsonobject for jsonb some other cases. memory, caching efficient lock free hash free. Alternatively Strings a method a builder buffer logic call if key contains characters convert in unicode escapable, in this case check fast conversion surely done buffer is needs done. Needs a small benchmark sounds simplest fastest assuming escaping is rare (from experience is for keys). iterating char[] instead of String chartAt faster. Wdyt? try this escape call a bit impacting</technical_language>

Target:
public String toString() { final StringBuilder builder = new StringBuilder("{"); final Iterator<Map.Entry<String, JsonValue>> it = unmodifieableBackingMap.entrySet().iterator(); boolean hasNext = it.hasNext(); while (hasNext) { final Map.Entry<String, JsonValue> entry = it.next(); builder.append('"'); Strings.appendEscaped(entry.getKey(), builder); builder.append("\":"); final JsonValue value = entry.getValue(); if (JsonString.class.isInstance(value)) { builder.append(value.toString()); } else { builder.append(value != JsonValue.NULL ? value.toString() : JsonChars.NULL); } hasNext = it.hasNext(); if (hasNext) { builder.append(","); } } return builder.append('}').toString(); }
Source:
<code>public static Field copyField(final Field field, final int newSortOrder) { JsonFieldTransformer jsonFieldTransformer = new JsonFieldTransformer(field); final JSONObject jsonObject = jsonFieldTransformer.jsonObject(); try { jsonObject.put("sortOrder", newSortOrder); } catch (JSONException e) { <START> throw new DotRuntimeException(e); <END> } jsonFieldTransformer = new JsonFieldTransformer(jsonObject.toString()); return jsonFieldTransformer.from(); }</code><technical_language>Log Identifier name of Field in error</technical_language>

Target:
public static Field copyField(final Field field, final int newSortOrder) { JsonFieldTransformer jsonFieldTransformer = new JsonFieldTransformer(field); final JSONObject jsonObject = jsonFieldTransformer.jsonObject(); try { jsonObject.put("sortOrder", newSortOrder); } catch (JSONException e) { Logger.error(FieldUtil.class, String.format("Eror witg fiels %s: %s", field.name(), e.getMessage())); throw new DotRuntimeException(e); } jsonFieldTransformer = new JsonFieldTransformer(jsonObject.toString()); return jsonFieldTransformer.from(); }
Source:
<code>public void deselectByValue(String value) { List<WebElement> options = element.findElements(By.xpath( ". boolean matched = false; for (WebElement option : options) { setSelected(option, false); <START> if (!isMultiple()) { <END> return; } matched = true; } if (!matched) { throw new NoSuchElementException("Cannot locate option with value: " + value); } }</code><technical_language>deselecting a non-multiple select sense. deselect in a normal select? A user do it. adding this check (same for deselectByVisibleText), check start of method throw exception if is multiple</technical_language>

Target:
public void deselectByValue(String value) { if (!isMultiple()) { throw new UnsupportedOperationException( "You may only deselect options of a multi-select"); } List<WebElement> options = element.findElements(By.xpath( ". boolean matched = false; for (WebElement option : options) { setSelected(option, false); matched = true; } if (!matched) { throw new NoSuchElementException("Cannot locate option with value: " + value); } }
Source:
<code>private static boolean isProtectedOrOverriding(MethodTreeImpl member) { <START> return ModifiersUtils.hasModifier(member.modifiers(), Modifier.PROTECTED) || member.isOverriding(); <END> }</code><technical_language>member.isOverriding return null... a NPE waiting for right here. problem is a bit deeper in fact introduced <LINK_0></technical_language>

Target:
private static boolean isProtectedOrOverriding(MethodTreeImpl member) { return ModifiersUtils.hasModifier(member.modifiers(), Modifier.PROTECTED) || !Boolean.FALSE.equals(member.isOverriding()); }
Source:
<code>public void setUp() { assumeTrue(CameraUtil.deviceHasCamera()); Context context = ApplicationProvider.getApplicationContext(); AppConfig appConfig = Camera2AppConfig.create(context); CameraFactory cameraFactory = appConfig.getCameraFactory( null); try { mCameraId = cameraFactory.cameraIdForLensFacing(LensFacing.BACK); } catch (Exception e) { throw new IllegalArgumentException( "Unable to attach to camera with LensFacing " + LensFacing.BACK, e); } CameraX.initialize(context, appConfig); mCameraInternal = cameraFactory.getCamera(mCameraId); mDefaultConfig = Preview.DEFAULT_CONFIG.getConfig(LensFacing.BACK); mSurfaceFutureSemaphore = new Semaphore( 0); mSaveToReleaseSemaphore = new Semaphore( 0); <START> mCameraSelector = new CameraSelector.Builder().requireLensFacing(LensFacing.BACK).build(); <END> }</code><technical_language>is mCameraSelector used? I bind call in tests</technical_language>

Target:
public void setUp() { assumeTrue(CameraUtil.deviceHasCamera()); Context context = ApplicationProvider.getApplicationContext(); AppConfig appConfig = Camera2AppConfig.create(context); CameraFactory cameraFactory = appConfig.getCameraFactory( null); try { mCameraId = cameraFactory.cameraIdForLensFacing(LensFacing.BACK); } catch (Exception e) { throw new IllegalArgumentException( "Unable to attach to camera with LensFacing " + LensFacing.BACK, e); } CameraX.initialize(context, appConfig); mCameraInternal = cameraFactory.getCamera(mCameraId); mDefaultConfig = Preview.DEFAULT_CONFIG.getConfig(LensFacing.BACK); mSurfaceFutureSemaphore = new Semaphore( 0); mSaveToReleaseSemaphore = new Semaphore( 0); }
Source:
<code>public static int getCurrentCounterValue() { return COUNTER.intValue(); <START> } <END></code><technical_language>Default access (no modifier) suffices</technical_language>

Target:
static int getCurrentCounterValue() { return COUNTER.intValue(); }
Source:
<code>public void testUpdateKeyWithVersion() { List<Key> keys = api().getKeyVersions(vaultUri, KEY_NAME); assertNotNull(keys); assertTrue(keys.size() > 1); Key key = keys.get(1); assertNotNull(key); String version = key.kid().substring(key.kid().lastIndexOf("/") + 1).trim(); Map<String, String> tags = new HashMap<String, String>(); tags.put("purpose", "testing again"); KeyBundle updatedKey = api().updateKey(vaultUri, KEY_NAME, "/" + version, null, null, tags); assertNotNull(updatedKey); keys = api().getKeyVersions(vaultUri, KEY_NAME); assertNotNull(keys); boolean found = false; for (Key k : keys) { if (k.kid().contains(version)) { key = k; found = true; break; } <START> } <END> assertTrue(found); assertEquals(tags, key.tags()); }</code><technical_language>style minor: java assertTrue(Iterables.anyMatch(keys, new Predicate<Key>() { @Override boolean apply(Key input) { return input.kid().contains(version); } }));</technical_language>

Target:
public void testUpdateKeyWithVersion() { List<Key> keys = api().getKeyVersions(vaultUri, KEY_NAME); assertNotNull(keys); assertTrue(keys.size() > 1); Key key = keys.get(1); assertNotNull(key); final String version = key.kid().substring(key.kid().lastIndexOf("/") + 1).trim(); Map<String, String> tags = new HashMap<String, String>(); tags.put("purpose", "testing again"); KeyBundle updatedKey = api().updateKey(vaultUri, KEY_NAME, version, null, null, tags); assertNotNull(updatedKey); FluentIterable<Key> iKeys = FluentIterable.from(api().getKeyVersions(vaultUri, KEY_NAME)); assertTrue(iKeys.anyMatch(new Predicate<Key>() { @Override public boolean apply(Key input) { return input.kid().contains(version); } })); assertEquals(tags, updatedKey.tags()); }
Source:
<code>public void testThreadNameWithoutNumberDemon() { Thread daemonThread = ThreadUtils.createThreadFactory(THREAD_NAME, true).newThread(EMPTY_RUNNABLE); try { Assert.assertEquals(daemonThread.getName(), THREAD_NAME); Assert.assertTrue(daemonThread.isDaemon()); } finally { try { daemonThread.join(); } catch (InterruptedException e) { <START> e.printStackTrace(); <END> } } }</code><technical_language>need print stack trace if ignore</technical_language>

Target:
public void testThreadNameWithoutNumberDemon() { Thread daemonThread = ThreadUtils.createThreadFactory(THREAD_NAME, true).newThread(EMPTY_RUNNABLE); try { assertEquals(THREAD_NAME, daemonThread.getName()); assertTrue(daemonThread.isDaemon()); } finally { try { daemonThread.join(); } catch (InterruptedException e) { } } }
Source:
<code>private static List<String> getScopesFromExpression(QueryContext queryContext) { <START> ArrayList<String> scopes = new ArrayList<>(); <END> Queue<QueryContext> bfsQueue = new LinkedList<QueryContext>(); if(queryContext != null) { bfsQueue.add(queryContext); } while(!bfsQueue.isEmpty()) { QueryContext currContext = bfsQueue.poll(); if(currContext.getChildExpressions()!=null) { for(TSDBQueryExpression expression : currContext.getChildExpressions()) { scopes.add(expression.getScope()); } if(currContext.getChildContexts()!=null) { bfsQueue.addAll(currContext.getChildContexts()); } } } return scopes; }</code><technical_language>this a set, duplicates get filtered out</technical_language>

Target:
private static List<String> getScopesFromExpression(QueryContext queryContext) { Set<String> scopes = new HashSet<>(); Queue<QueryContext> bfsQueue = new LinkedList<QueryContext>(); if(queryContext != null) { bfsQueue.add(queryContext); } while(!bfsQueue.isEmpty()) { QueryContext currContext = bfsQueue.poll(); if(currContext.getChildExpressions()!=null) { for(TSDBQueryExpression expression : currContext.getChildExpressions()) { scopes.add(expression.getScope()); } if(currContext.getChildContexts()!=null) { bfsQueue.addAll(currContext.getChildContexts()); } } } return new ArrayList<>(scopes); }
Source:
<code>public static int parseIntegerToShort(String value) { BigInteger result = DatatypeConverter.parseInteger(value); if (result.longValue() > Short.MAX_VALUE) { <START> throw new InvalidValueException("Value " +value+ " greater than Short.MAX_VALUE"); <END> } return result.intValue(); }</code><technical_language>display this user, I is if Java concepts, Short.MAX_VALUE. this? "Value " + + " greater maximum " + Short.MAX_VALUE + "</technical_language>

Target:
public static int parseIntegerToShort(String value) { BigInteger result = DatatypeConverter.parseInteger(value); if (result.longValue() > Short.MAX_VALUE) { throw new InvalidValueException("Value " +value+ " greater than maximum " + Short.MAX_VALUE); } return result.intValue(); }
Source:
<code>private void updateJobStatus( final JobEntity jobEntity, final JobStatus newStatus, @Nullable final String statusMsg ) { final JobStatus currentStatus = jobEntity.getStatus(); if (currentStatus.isActive()) { jobEntity.setStatus(newStatus); jobEntity.setStatusMsg(statusMsg); if (newStatus.equals(JobStatus.RUNNING)) { jobEntity.setStarted(Instant.now()); } else if (jobEntity.getStarted().isPresent() && newStatus.isFinished()) { jobEntity.setFinished(Instant.now()); } } if (currentStatus != newStatus) { synchronized (this.observers) { <START> this.observers.forEach(o -> o.notifyJobStateChange(jobEntity.getUniqueId(), currentStatus, newStatus)); <END> } } }</code><technical_language>Slight concern is notifying observers persist state database (which happen completion of persistence method/transaction) is a chance this notifications database reflect changes. calling observers in current thread delay database update long of observers takes do work. Do fire asynchronous event instead</technical_language>

Target:
private void updateJobStatus( final JobEntity jobEntity, final JobStatus newStatus, @Nullable final String statusMsg ) { final JobStatus currentStatus = jobEntity.getStatus(); if (currentStatus.isActive()) { jobEntity.setStatus(newStatus); jobEntity.setStatusMsg(statusMsg); if (newStatus.equals(JobStatus.RUNNING)) { jobEntity.setStarted(Instant.now()); } else if (jobEntity.getStarted().isPresent() && newStatus.isFinished()) { jobEntity.setFinished(Instant.now()); } } }
Source:
<code>public void run() { m_taskQueue.offer(this); SiteTasker task = m_taskQueue.peek(); long currentTime = System.nanoTime(); long headOfQueueOfferTime; String taskInfo = ""; if (task != null) { headOfQueueOfferTime = task.getQueueOfferTime(); taskInfo = " Task Info: " + task.getTaskInfo(); } else { headOfQueueOfferTime = currentTime; } if (headOfQueueOfferTime != m_previousTaskTimestamp) { m_previousTaskTimestamp = headOfQueueOfferTime; m_previousTaskPeekTime = currentTime; } else if (currentTime - m_previousTaskPeekTime >= m_procedureLogThreshold) { long waitTime = (currentTime - m_previousTaskPeekTime)/1_000_000_000L; <START> if (m_logger.isDebugEnabled()) { <END> m_logger.rateLimitedLog(SUPPRESS_INTERVAL, Level.DEBUG, null, TICK_MESSAGE + taskInfo, waitTime, m_partitionId); } else { m_logger.rateLimitedLog(SUPPRESS_INTERVAL, Level.INFO, null, TICK_MESSAGE, waitTime, m_partitionId); } } }</code><technical_language>move line 83 here, in cases create new strings</technical_language>

Target:
public void run() { m_taskQueue.offer(this); SiteTasker task = m_taskQueue.peek(); long currentTime = System.nanoTime(); long headOfQueueOfferTime; if (task != null) { headOfQueueOfferTime = task.getQueueOfferTime(); } else { headOfQueueOfferTime = currentTime; } if (headOfQueueOfferTime != m_previousTaskTimestamp) { m_previousTaskTimestamp = headOfQueueOfferTime; m_previousTaskPeekTime = currentTime; } else if (currentTime - m_previousTaskPeekTime >= m_procedureLogThreshold) { long waitTime = (currentTime - m_previousTaskPeekTime)/1_000_000_000L; if (m_logger.isDebugEnabled()) { String taskInfo = (task == null) ? "" : " Task Info: " + task.getTaskInfo(); m_logger.rateLimitedLog(SUPPRESS_INTERVAL, Level.DEBUG, null, TICK_MESSAGE + taskInfo, waitTime, m_partitionId); } else { m_logger.rateLimitedLog(SUPPRESS_INTERVAL, Level.INFO, null, TICK_MESSAGE, waitTime, m_partitionId); } } }
Source:
<code>MetricsInterceptor(Registry registry) { this.registry = registry; <START> this.log = LoggerFactory.getLogger(getClass()); <END> this.packageName = this.getClass().getPackage().getName().split("\\.")[1]; }</code><technical_language>give results a blind com.netflix.spinnaker package prefix</technical_language>

Target:
MetricsInterceptor(Registry registry) { this.registry = registry; this.log = LoggerFactory.getLogger(getClass()); }
Source:
<code>public String buildPatternTableau() { StringBuilder builder = new StringBuilder(); TreeSet<ColumnIdentifier> patternTableauHead = condition.getContainedColumns(); builder.append(patternTableauHead); List<Map<ColumnIdentifier, String>> conditions = condition.getPatternConditions(); for (Map<ColumnIdentifier, String> condition : conditions) { <START> builder.append("\r\n"); <END> for (ColumnIdentifier column : patternTableauHead) { if (condition.containsKey(column)) { String value = condition.get(column); if (value.length() < column.toString().length()) { StringBuilder whitespaceBuilder = new StringBuilder(); for (int i = 0; i < (column.toString().length() - value.length()) / 2; i++) { whitespaceBuilder.append(" "); } builder.append(whitespaceBuilder); builder.append(value); builder.append(whitespaceBuilder); } else { builder.append(value); builder.append(" "); } } else { StringBuilder whitespaceBuilder = new StringBuilder(); for (int i = 0; i < column.toString().length() / 2; i++) { whitespaceBuilder.append(" "); } builder.append(whitespaceBuilder); builder.append("-"); builder.append(whitespaceBuilder); } } } return builder.toString(); }</code><technical_language>this is platform independent</technical_language>

Target:
public String buildPatternTableau() { StringBuilder builder = new StringBuilder(); TreeSet<ColumnIdentifier> patternTableauHead = condition.getContainedColumns(); builder.append(patternTableauHead); List<Map<ColumnIdentifier, String>> conditions = condition.getPatternConditions(); for (Map<ColumnIdentifier, String> condition : conditions) { builder.append(LINESEPARATOR); for (ColumnIdentifier column : patternTableauHead) { if (condition.containsKey(column)) { String value = condition.get(column); if (value.length() < column.toString().length()) { StringBuilder whitespaceBuilder = new StringBuilder(); for (int i = 0; i < (column.toString().length() - value.length()) / 2; i++) { whitespaceBuilder.append(" "); } builder.append(whitespaceBuilder); builder.append(value); builder.append(whitespaceBuilder); } else { builder.append(value); builder.append(" "); } } else { StringBuilder whitespaceBuilder = new StringBuilder(); for (int i = 0; i < column.toString().length() / 2; i++) { whitespaceBuilder.append(" "); } builder.append(whitespaceBuilder); builder.append("-"); builder.append(whitespaceBuilder); } } } return builder.toString(); }
Source:
<code>Rgb24ImageRepresentationHandler(final Map<Integer, Integer> bandMap, final int actualBitsPerPixelPerBand) { this.bandMapping = bandMap; <START> this.numOfReadsPerBand = (int) Math.ceil(actualBitsPerPixelPerBand / ((double) Byte.SIZE)); <END> if (actualBitsPerPixelPerBand - Byte.SIZE < 0) { this.bitsToDiscard = 0; } else { this.bitsToDiscard = actualBitsPerPixelPerBand - Byte.SIZE; } }</code><technical_language>This right logic for NBPP==12. test data cover case, 8 16</technical_language>

Target:
Rgb24ImageRepresentationHandler(final Map<Integer, Integer> bandMap, final int actualBitsPerPixelPerBand) { super(bandMap, actualBitsPerPixelPerBand); }
Source:
<code>public void unsuspend(Collection<TabletLocationState> tablets) { <START> for (TabletLocationState tls : tablets) { if (tls.suspend != null) { continue; } TabletMutator tabletMutator = ample.mutateTablet(tls.extent); tabletMutator.deleteSuspension(); tabletMutator.mutate(); } <END> }</code><technical_language>Mutating tablets a time slow remote RPCs. Ample a mechanism for mutating multiple tablets is more efficient, current codes of a batchwriter. able do following. suggestion try(var tabletsMutator = ample.mutateTablets()){ for (TabletLocationState tls : tablets) { if (tls.suspend != null) { continue; } TabletMutator tabletMutator = tabletsMutator.mutateTablet(tls.extent); tabletMutator.deleteSuspension(); tabletMutator.mutate(); } }</technical_language>

Target:
public void unsuspend(Collection<TabletLocationState> tablets) { try (var tabletsMutator = ample.mutateTablets()) { for (TabletLocationState tls : tablets) { if (tls.suspend != null) { continue; } TabletMutator tabletMutator = tabletsMutator.mutateTablet(tls.extent); tabletMutator.deleteSuspension(); tabletMutator.mutate(); } } }