auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected IStatus run(IProgressMonitor monitor) { RevCommit commit = null; try { commitOperation.execute(monitor); commit = commitOperation.getCommit(); CommitMessageComponentStateManager.deleteState(repository); RepositoryMapping mapping = RepositoryMapping .findRepositoryMapping(repository); if (mapping != null) mapping.fireRepositoryChanged(); } catch (CoreException e) { if (e.getCause() instanceof JGitInternalException) { return Activator.createErrorStatus(e.getLocalizedMessage(), e.getCause()); } if (e.getCause() instanceof AbortedByHookException) { <START> showAbortedByHook(e.getCause()); <END> } else { return Activator.createErrorStatus( UIText.CommitAction_CommittingFailed, e); } } finally { GitLightweightDecorator.refresh(); } if (commit != null) { if (openCommitEditor) openCommitEditor(commit); if (pushUpstream) pushUpstream(commit); } return Status.OK_STATUS; }</code><technical_language>return error status too? Status.CANCEL_STATUS? Returning OK_STATUS in this case wrong</technical_language>

Target:
protected IStatus run(IProgressMonitor monitor) { RevCommit commit = null; try { commitOperation.execute(monitor); commit = commitOperation.getCommit(); CommitMessageComponentStateManager.deleteState(repository); RepositoryMapping mapping = RepositoryMapping .findRepositoryMapping(repository); if (mapping != null) mapping.fireRepositoryChanged(); } catch (CoreException e) { if (e.getCause() instanceof JGitInternalException) { return Activator.createErrorStatus(e.getLocalizedMessage(), e.getCause()); } if (e.getCause() instanceof AbortedByHookException) { showAbortedByHook(e.getCause()); return Status.CANCEL_STATUS; } else { return Activator.createErrorStatus( UIText.CommitAction_CommittingFailed, e); } } finally { GitLightweightDecorator.refresh(); } if (commit != null) { if (openCommitEditor) openCommitEditor(commit); if (pushUpstream) pushUpstream(commit); } return Status.OK_STATUS; }
Source:
<code>private HttpURLConnection authorizeConnection( HttpURLConnection conn, String service, int authAttempts) throws NoRemoteRepositoryException, TransportException, IOException { <START> final int status = HttpSupport.response(conn); <END> switch (status) { case HttpURLConnection.HTTP_OK: return conn; case HttpURLConnection.HTTP_NOT_FOUND: throw new NoRemoteRepositoryException(uri, MessageFormat.format( JGitText.get().uriNotFound, conn.getURL())); case HttpURLConnection.HTTP_UNAUTHORIZED: authMethod = HttpAuthMethod.scanResponse(conn); if (authMethod == HttpAuthMethod.NONE) throw new TransportException(uri, MessageFormat.format( JGitText.get().authenticationNotSupported, uri)); if (1 < authAttempts || !authMethod.authorize(uri, getCredentialsProvider())) { throw new TransportException(uri, JGitText.get().notAuthorized); } return null; case HttpURLConnection.HTTP_FORBIDDEN: throw new TransportException(uri, MessageFormat.format( JGitText.get().serviceNotPermitted, service)); default: String err = status + " " + conn.getResponseMessage(); throw new TransportException(uri, err); } }</code><technical_language>Unnecessary final</technical_language>

Target:
private HttpURLConnection authorizeConnection( HttpURLConnection conn, String service, int authAttempts) throws NoRemoteRepositoryException, TransportException, IOException { int status = HttpSupport.response(conn); switch (status) { case HttpURLConnection.HTTP_OK: return conn; case HttpURLConnection.HTTP_NOT_FOUND: throw new NoRemoteRepositoryException(uri, MessageFormat.format( JGitText.get().uriNotFound, conn.getURL())); case HttpURLConnection.HTTP_UNAUTHORIZED: authMethod = HttpAuthMethod.scanResponse(conn); if (authMethod == HttpAuthMethod.NONE) throw new TransportException(uri, MessageFormat.format( JGitText.get().authenticationNotSupported, uri)); if (1 < authAttempts || !authMethod.authorize(uri, getCredentialsProvider())) throw new TransportException(uri, JGitText.get().notAuthorized); return null; case HttpURLConnection.HTTP_FORBIDDEN: throw new TransportException(uri, MessageFormat.format( JGitText.get().serviceNotPermitted, service)); default: String err = status + " " + conn.getResponseMessage(); throw new TransportException(uri, err); } }
Source:
<code>protected void invokeTestMethod(JupiterEngineExecutionContext context, DynamicTestExecutor dynamicTestExecutor) { TestExtensionContext testExtensionContext = (TestExtensionContext) context.getExtensionContext(); context.getThrowableCollector().execute(() -> { Object instance = testExtensionContext.getTestInstance(); Object testFactoryMethodResult = executableInvoker.invoke(getTestMethod(), instance, testExtensionContext, context.getExtensionRegistry()); <START> TestSource source = getSource().orElseThrow(AssertionError::new); <END> try (Stream<DynamicNode> dynamicNodeStream = toDynamicNodeStream(testFactoryMethodResult)) { AtomicInteger index = new AtomicInteger(); dynamicNodeStream.forEach(node -> { JupiterTestDescriptor descriptor = createDescriptor(this, node, index, source); dynamicTestExecutor.execute(descriptor); }); } catch (ClassCastException ex) { throw invalidReturnTypeException(ex); } }); }</code><technical_language>I this "cannot happen", a more comfortable JUnitException::new</technical_language>

Target:
protected void invokeTestMethod(JupiterEngineExecutionContext context, DynamicTestExecutor dynamicTestExecutor) { TestExtensionContext testExtensionContext = (TestExtensionContext) context.getExtensionContext(); context.getThrowableCollector().execute(() -> { Object instance = testExtensionContext.getTestInstance(); Object testFactoryMethodResult = executableInvoker.invoke(getTestMethod(), instance, testExtensionContext, context.getExtensionRegistry()); TestSource source = getSource().orElseThrow(() -> new JUnitException("Test source must be present")); try (Stream<DynamicNode> dynamicNodeStream = toDynamicNodeStream(testFactoryMethodResult)) { int index = 1; Iterator<DynamicNode> iterator = dynamicNodeStream.iterator(); while (iterator.hasNext()) { DynamicNode dynamicNode = iterator.next(); JupiterTestDescriptor descriptor = createDynamicDescriptor(this, dynamicNode, index++, source); dynamicTestExecutor.execute(descriptor); } } catch (ClassCastException ex) { throw invalidReturnTypeException(ex); } }); }
Source:
<code>private static void installBootBundles(Framework framework) { Enumeration<URL> resources; try { resources = Osgis.class.getClassLoader().getResources(MANIFEST_PATH); } catch (IOException e) { throw Exceptions.propagate(e); } BundleContext bundleContext = framework.getBundleContext(); Map<String, Bundle> installedBundles = getInstalledBundles(bundleContext); while(resources.hasMoreElements()) { URL url = resources.nextElement(); ReferenceWithError<Boolean> installResult = installExtensionBundle(bundleContext, url, installedBundles, getVersionedId(framework)); if (installResult.hasError()) { if (installResult.getMaskingError()) { if (LOG.isTraceEnabled()) <START> LOG.trace(installResult.getError().getMessage()); <END> } else { if (installResult.masksErrorIfPresent()) { LOG.debug(installResult.getError().getMessage()); } else { LOG.warn("Unable to install manifest from "+url+": "+installResult.getError(), installResult.getError()); } } } } }</code><technical_language>message null, exception type was? instead do toString() error? below</technical_language>

Target:
private static void installBootBundles(Framework framework) { Enumeration<URL> resources; try { resources = Osgis.class.getClassLoader().getResources(MANIFEST_PATH); } catch (IOException e) { throw Exceptions.propagate(e); } BundleContext bundleContext = framework.getBundleContext(); Map<String, Bundle> installedBundles = getInstalledBundles(bundleContext); while(resources.hasMoreElements()) { URL url = resources.nextElement(); ReferenceWithError<Boolean> installResult = installExtensionBundle(bundleContext, url, installedBundles, getVersionedId(framework)); if (installResult.hasError()) { if (installResult.getWithoutError()) { if (LOG.isTraceEnabled()) LOG.trace(installResult.getError().getMessage()); } else { if (installResult.masksErrorIfPresent()) { LOG.debug(installResult.getError().getMessage()); } else { LOG.warn("Unable to install manifest from "+url+": "+installResult.getError(), installResult.getError()); } } } } }
Source:
<code>private void createRemoteComposite() { if (fFileWidget == null) { fFileWidget = new RemoteResourceBrowserWidget(fDialogComposite, SWT.BORDER, 0); fFileWidget.setLayoutData(new GridData(GridData.FILL_BOTH)); fFileWidget.setInitialPath(LTTngControlServiceConstants.DEFAULT_PATH); fFileWidget.setConnection(fConnection); <START> getButton(IDialogConstants.OK_ID).setEnabled(true); <END> } }</code><technical_language>OK is enabled if remote file is selected</technical_language>

Target:
private void createRemoteComposite() { if (fFileWidget == null) { fFileWidget = new RemoteResourceBrowserWidget(fDialogComposite, SWT.BORDER, 0); fFileWidget.setLayoutData(new GridData(GridData.FILL_BOTH)); fFileWidget.setInitialPath(LTTngControlServiceConstants.DEFAULT_PATH); fFileWidget.setConnection(fConnection); fFileWidget.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { enableRemoteButtons(); } }); getButton(IDialogConstants.OK_ID).setEnabled(true); } }
Source:
<code>public List<RepoImage> getUserRequestForStorageDomainRepoFileList(Guid storageDomainId, ImageFileType imageType, boolean forceRefresh) { if (!isStorageDomainIdValid(storageDomainId)) { throw new EngineException(EngineError.GetIsoListError); } if (forceRefresh) { <START> if (refreshRepos(storageDomainId, imageType)) { <END> throw new EngineException(EngineError.IMAGES_NOT_SUPPORTED_ERROR); } } else { refreshReposIfIntervalPassed(storageDomainId, imageType); } return getCachedIsoListByDomainId(storageDomainId, imageType); }</code><technical_language>Missing ! operator</technical_language>

Target:
public List<RepoImage> getUserRequestForStorageDomainRepoFileList(Guid storageDomainId, ImageFileType imageType, boolean forceRefresh) { if (!isStorageDomainIdValid(storageDomainId)) { throw new EngineException(EngineError.GetIsoListError); } if (forceRefresh) { if (!refreshRepos(storageDomainId, imageType)) { throw new EngineException(EngineError.IMAGES_NOT_SUPPORTED_ERROR); } } else { refreshReposIfIntervalPassed(storageDomainId, imageType); } return getCachedIsoListByDomainId(storageDomainId, imageType); }
Source:
<code>public Optional<Response> handleWithoutObaData() { if (askState == SessionAttribute.AskState.VERIFYSTOP) { return StopUtil.handleDuplicateStopResponse(personalization.getPrincipleId(), attributesManager, true, googleMaps, obaClient, obaDao); } if (askState == SessionAttribute.AskState.COPY_PROFILE_CONFIRM && personalization.isPersonalized()) { try { Optional<ObaUserDataItem> obaUserDataItem = this.obaDao.getUserData(personalization.getUserId()); obaUserDataItem.get().setUserId(personalization.getPersonId()); obaUserDataItem.get().setPreviousResponse(StringUtils.EMPTY); ObaUserClient obaUserClient = new ObaUserClient(obaUserDataItem.get().getObaBaseUrl()); this.obaDao.saveUserData(obaUserDataItem.get()); <START> return CityUtil.tellArrivals(obaUserDataItem.get(), obaUserClient, attributesManager, obaDao); <END> } catch (Exception e) { log.error(e); throw new OneBusAwayException(promptHelper.getPrompt(Prompt.COMMUNICATION_ERROR_MESSAGE), e); } } log.error("Received yes intent without a question."); return CityUtil.askForCityResponse(); }</code><technical_language>copying profile, route filters reading arrivals user immediately copying profile settings - session attributes loaded here? Note launching skill onboarding personalization, route filters correctly recognized. Similarly, need other profile settings clock times reading arrivals immediately copy. #### Steps repro 1. Create a profile personalization 2. Set a route filter a stop 3. Turn personalization launch skill 4. "Yes" copy profile info #### I hear Alexa reads arrivals for stop, ignoring route filter #### I expect Alexa honor route filter read arrivals for routes for I filtered out arrivals</technical_language>

Target:
public Optional<Response> handleWithoutObaData() { if (askState == SessionAttribute.AskState.VERIFYSTOP) { return StopUtil.handleDuplicateStopResponse(personalization.getPrincipleId(), attributesManager, true, googleMaps, obaClient, obaDao); } if (askState == SessionAttribute.AskState.COPY_PROFILE_CONFIRM && personalization.isPersonalized()) { try { Optional<ObaUserDataItem> obaUserDataItem = this.obaDao.getUserData(personalization.getUserId()); obaUserDataItem.get().setUserId(personalization.getPersonId()); obaUserDataItem.get().setPreviousResponse(StringUtils.EMPTY); ObaUserClient obaUserClient = new ObaUserClient(obaUserDataItem.get().getObaBaseUrl()); this.obaDao.saveUserData(obaUserDataItem.get()); populateAlexaSessionAttributes(obaUserDataItem); return CityUtil.tellArrivals(obaUserDataItem.get(), obaUserClient, attributesManager, obaDao); } catch (Exception e) { log.error(e); throw new OneBusAwayException(promptHelper.getPrompt(Prompt.COMMUNICATION_ERROR_MESSAGE), e); } } log.error("Received yes intent without a question."); return CityUtil.askForCityResponse(); }
Source:
<code>public void replace(final Expression oldExpr, final Expression newExpr) { final int idx = steps.indexOf(oldExpr); if (idx < 0) { if (LOG.isTraceEnabled()) { <START> LOG.trace("Expression not found when trying to replace: " + ExpressionDumper.dump(oldExpr) + "; in: " + ExpressionDumper.dump(this)); <END> } return; } steps.set(idx, newExpr); }</code><technical_language>LOG.trace("Expression replace: {}; in: {}", ExpressionDumper.dump(oldExpr) , ExpressionDumper.dump(this));</technical_language>

Target:
public void replace(final Expression oldExpr, final Expression newExpr) { final int idx = steps.indexOf(oldExpr); if (idx < 0) { if (LOG.isTraceEnabled()) { LOG.trace("Expression not found when trying to replace: {}; in: {}", ExpressionDumper.dump(oldExpr), ExpressionDumper.dump(this)); } return; } steps.set(idx, newExpr); }
Source:
<code>private boolean validateWeightForResourceConfig(ClusterConfig clusterConfig, ResourceConfig resourceConfig, IdealState idealState) { if (resourceConfig == null) { <START> return !clusterConfig.getDefaultPartitionWeightMap().isEmpty(); <END> } Map<String, Map<String, Integer>> capacityMap; try { capacityMap = resourceConfig.getPartitionCapacityMap(); } catch (IOException ex) { logger.error("Invalid partition capacity configuration of resource: {}", idealState.getResourceName(), ex); return false; } Set<String> capacityMapSet = new HashSet<>(capacityMap.keySet()); boolean hasDefaultCapacity = capacityMapSet.contains(ResourceConfig.DEFAULT_PARTITION_KEY); capacityMapSet.remove(ResourceConfig.DEFAULT_PARTITION_KEY); if (capacityMapSet.size() != idealState.getNumPartitions() && !hasDefaultCapacity) { logger.error( "ResourceConfig for does not have all partitions defined in PartitionCapacityMap!", idealState.getResourceName()); return false; } capacityMap.keySet().forEach(partitionName -> WagedValidationUtil .validateAndGetPartitionCapacity(partitionName, resourceConfig, capacityMap, clusterConfig)); return true; }</code><technical_language>Add more check verify if default weight map contains required keys</technical_language>

Target:
private boolean validateWeightForResourceConfig(ClusterConfig clusterConfig, ResourceConfig resourceConfig, IdealState idealState) { if (resourceConfig == null) { if (clusterConfig.getDefaultPartitionWeightMap().isEmpty()) { logger.error( "ResourceConfig for is null, and there are no default weights set in ClusterConfig!", idealState.getResourceName()); return false; } if (clusterConfig.getDefaultPartitionWeightMap().keySet() .containsAll(clusterConfig.getInstanceCapacityKeys())) { return true; } logger.error( "ResourceConfig for is null, and ClusterConfig's default partition weight map doesn't have all the required keys!", idealState.getResourceName()); return false; } Map<String, Map<String, Integer>> capacityMap; try { capacityMap = resourceConfig.getPartitionCapacityMap(); } catch (IOException ex) { logger.error("Invalid partition capacity configuration of resource: {}", idealState.getResourceName(), ex); return false; } Set<String> capacityMapSet = new HashSet<>(capacityMap.keySet()); boolean hasDefaultCapacity = capacityMapSet.contains(ResourceConfig.DEFAULT_PARTITION_KEY); capacityMapSet.remove(ResourceConfig.DEFAULT_PARTITION_KEY); if (capacityMapSet.size() != idealState.getNumPartitions() && !hasDefaultCapacity) { logger.error( "ResourceConfig for does not have all partitions defined in PartitionCapacityMap!", idealState.getResourceName()); return false; } capacityMap.keySet().forEach(partitionName -> WagedValidationUtil .validateAndGetPartitionCapacity(partitionName, resourceConfig, capacityMap, clusterConfig)); return true; }
Source:
<code>public boolean equals(Object obj) { if (obj instanceof SynchronizationModel) { final SynchronizationModel other = (SynchronizationModel)obj; <START> boolean equals = leftTraversal.equals(other.leftTraversal); <END> if (equals) { equals = rightTraversal != null && rightTraversal.equals(other.rightTraversal) || other.rightTraversal == null; } if (equals) { equals = originTraversal != null && originTraversal.equals(other.originTraversal) || other.originTraversal == null; } return equals; } return false; }</code><technical_language>more readable: return Objects.equal(leftTraversal, other.leftTraversal) && Objects.equal(rightTraversal, other.rightTraversal) && Objects.equal(originTraversal, other.originTraversal)</technical_language>

Target:
public boolean equals(Object obj) { if (obj instanceof SynchronizationModel) { final SynchronizationModel other = (SynchronizationModel)obj; return Objects.equal(leftTraversal, other.leftTraversal) && Objects.equal(rightTraversal, other.rightTraversal) && Objects.equal(originTraversal, other.originTraversal); } return false; }
Source:
<code>private BacklogColumnUI() { super(WorldXViewerFactory.COLUMN_NAMESPACE + ".backlog", "Backlog", 100, XViewerAlign.Left, false, <START> SortDataType.String, true, <END> "Backlog that this item belongs to. (BL) if Agile Backlog, else Goal (which are sometimes used as backlogs)"); }</code><technical_language>fix description, showing goals anymore</technical_language>

Target:
private BacklogColumnUI() { super(WorldXViewerFactory.COLUMN_NAMESPACE + ".backlog", "Backlog", 100, XViewerAlign.Left, false, SortDataType.String, true, "Backlog that this item belongs to."); }
Source:
<code>protected static ImmutableList<Ds3EnumConstant> convertAllEnumConstants( final ImmutableList<Ds3EnumConstant> enumConstants, final NameMapper nameMapper) { if (enumConstants == null || enumConstants.isEmpty()) { return enumConstants; } <START> ImmutableList.Builder<Ds3EnumConstant> builder = ImmutableList.builder(); <END> for (final Ds3EnumConstant enumConstant : enumConstants) { final Ds3EnumConstant convertedEnumConstant = new Ds3EnumConstant( enumConstant.getName(), convertAllProperties(enumConstant.getDs3Properties(), nameMapper)); builder.add(convertedEnumConstant); } return builder.build(); }</code><technical_language>Missing final</technical_language>

Target:
protected static ImmutableList<Ds3EnumConstant> convertAllEnumConstants( final ImmutableList<Ds3EnumConstant> enumConstants, final NameMapper nameMapper) { if (enumConstants == null || enumConstants.isEmpty()) { return enumConstants; } final ImmutableList.Builder<Ds3EnumConstant> builder = ImmutableList.builder(); for (final Ds3EnumConstant enumConstant : enumConstants) { final Ds3EnumConstant convertedEnumConstant = new Ds3EnumConstant( enumConstant.getName(), convertAllProperties(enumConstant.getDs3Properties(), nameMapper)); builder.add(convertedEnumConstant); } return builder.build(); }
Source:
<code>public Event findFirstCapturedEventOrElseThrow(String event) { <START> return findFirstCapturedEvent(event).orElseThrow(() -> new AssertionError("Unable to find first Event")); <END> }</code><technical_language>suggestion return findFirstCapturedEvent(event).orElseThrow(() -> new AssertionError("Unable find Event for event: " + event));</technical_language>

Target:
public Event findFirstCapturedEventOrElseThrow(String event) { return findFirstCapturedEvent(event).orElseThrow( () -> new AssertionError("Unable to find first Event for event: " + event)); }
Source:
<code>public void testRefAltAssignmentInConstructor() { Variant variant = new Variant("1", 1, 1, "C", "T"); assertEquals("C", variant.getReference()); assertEquals("T", variant.getAlternate()); <START> variant = new Variant("1", 1, 1, "", "T"); <END> assertEquals("", variant.getReference()); assertEquals("T", variant.getAlternate()); variant = new Variant("1", 1, 1, "T", ""); assertEquals("T", variant.getReference()); assertEquals("", variant.getAlternate()); }</code><technical_language>I is enough for test assign check once</technical_language>

Target:
public void testRefAltAssignmentInConstructor() { Variant variant = new Variant("1", 1, 1, "C", "T"); assertEquals("C", variant.getReference()); assertEquals("T", variant.getAlternate()); }
Source:
<code>public void testTooManyFiles() { when(diffs.size()).thenReturn(1); when(configurable.getIntegerProperty(anyString(), anyString())).thenReturn(0); Set<LargeCommitWarning> warnings = generator.generateWarnings(commit, gitPush); verify(diffs).size(); assertFalse(warnings.isEmpty()); <START> assertEquals(1, warnings.size()); <END> assertEquals(testEquals, warnings); }</code><technical_language>basically testing Collections :wink: If warnings size 1, empty. assertion more sense me. is redundant :)</technical_language>

Target:
public void testTooManyFiles() throws IOException { List<AbstractDiffModel.DiffFile<AbstractDiffModel.DiffContext<AbstractDiffModel.DiffLine>>> diffs = Lists.newArrayList(); for (int i = 0; i < MAX_AMOUNT_OF_FILES + 2; i++) { diffs.add(diffFile); } diffModel.setDiffs(diffs); Set<LargeCommitWarning> warnings = generator.generateWarnings(commit, gitPush); assertEquals(1, warnings.size()); assertEquals(testEquals, warnings); }
Source:
<code>public Response<ResponseBody> simpleGet(String uri, Map<String, String> httpParams, Map<String, String> httpHeaders) throws IOException { HashMap<String, String> headers = getHeaders(""); <START> headers.putAll(httpHeaders); <END> ModernHttpRequester requester = CommCareApplication.instance().createGetRequester( CommCareApplication.instance(), uri, httpParams, headers, new AuthInfo.ProvidedAuth(username, password), null); Response<ResponseBody> response = requester.makeRequest(); if (response.code() == 404) { throw new FileNotFoundException("No Data available at URL " + uri); } return response; }</code><technical_language>practice treat map objects immutable ensure params leak requests [as is done here](<LINK_0></technical_language>

Target:
public Response<ResponseBody> simpleGet(String uri, Map<String, String> httpParams, Map<String, String> httpHeaders) throws IOException { HashMap<String, String> headers = new HashMap<>(getHeaders(null)); headers.putAll(httpHeaders); ModernHttpRequester requester = CommCareApplication.instance().createGetRequester( CommCareApplication.instance(), uri, httpParams, headers, new AuthInfo.ProvidedAuth(username, password), null); Response<ResponseBody> response = requester.makeRequest(); if (response.code() == 404) { throw new FileNotFoundException("No Data available at URL " + uri); } return response; }
Source:
<code>private void validateSourceWithKio(final CloudTrailEvent event, final String applicationId, final String applicationVersion, final String team, final String source, final String artifact) { if (!source.equals(artifact)) { violationSink.put( new ViolationBuilder( format("Application: %s has not a valid artifact for version: %s.", applicationId, applicationVersion)).withEventId(getCloudTrailEventId(event)).withRegion( getCloudTrailEventRegion(event)).withAccoundId(getCloudTrailEventAccountId(event)).build()); } Map<String, String> tags = Maps.newHashMap(); try { tags = this.pieroneOperations.listTags(team, applicationId); } catch (HttpClientErrorException e) { <START> LOG.error("Could not get the tags for team and applicationId {}", team, applicationId, e); <END> } if (tags.isEmpty()) { violationSink.put(new ViolationBuilder(format("Source: %s is not present in pierone.", source)).withEventId( getCloudTrailEventId(event)).withRegion(getCloudTrailEventRegion(event)).withAccoundId( getCloudTrailEventAccountId(event)).build()); } else { String value = tags.get(applicationVersion); if (value == null) { violationSink.put(new ViolationBuilder(format("Source: %s is not present in pierone.", source)) .withEventId(getCloudTrailEventId(event)).withRegion(getCloudTrailEventRegion(event)) .withAccoundId(getCloudTrailEventAccountId(event)).build()); } } }</code><technical_language>log level warn imho more appropriate, method flow is interrupted here. error means, bad happened app is able recover it</technical_language>

Target:
private void validateSourceWithKio(final CloudTrailEvent event, final String applicationId, final String applicationVersion, final String team, final String source, final String artifact) { if (!source.equals(artifact)) { violationSink.put( new ViolationBuilder( format("Application: %s has not a valid artifact for version: %s.", applicationId, applicationVersion)).withEventId(getCloudTrailEventId(event)).withRegion( getCloudTrailEventRegion(event)).withAccoundId(getCloudTrailEventAccountId(event)).build()); } Map<String, String> tags = Maps.newHashMap(); try { tags = this.pieroneOperations.listTags(team, applicationId); } catch (HttpClientErrorException e) { LOG.warn("Could not get the tags for team and applicationId {}", team, applicationId, e); } if (tags.isEmpty()) { violationSink.put(new ViolationBuilder(format("Source: %s is not present in pierone.", source)).withEventId( getCloudTrailEventId(event)).withRegion(getCloudTrailEventRegion(event)).withAccoundId( getCloudTrailEventAccountId(event)).build()); } else { String value = tags.get(applicationVersion); if (value == null) { violationSink.put(new ViolationBuilder(format("Source: %s is not present in pierone.", source)) .withEventId(getCloudTrailEventId(event)).withRegion(getCloudTrailEventRegion(event)) .withAccoundId(getCloudTrailEventAccountId(event)).build()); } } }
Source:
<code>protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { <START> final PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR)); <END> final ModelNode bufferSizeModel = BUFFER_SIZE.resolveModelAttribute(context, model); final ModelNode maxPoolSizeModel = MAX_POOL_SIZE.resolveModelAttribute(context, model); final ModelNode directModel = DIRECT.resolveModelAttribute(context, model); final int threadLocalCacheSize = THREAD_LOCAL_CACHE_SIZE.resolveModelAttribute(context, model).asInt(); final int leakDetectionPercent = LEAK_DETECTION_PERCENT.resolveModelAttribute(context, model).asInt(); final int bufferSize = bufferSizeModel.isDefined() ? bufferSizeModel.asInt() : defaultBufferSize; final int maxPoolSize = maxPoolSizeModel.isDefined() ? maxPoolSizeModel.asInt() : -1; final boolean direct = directModel.isDefined() ? directModel.asBoolean() : defaultDirectBuffers; final ByteBufferPoolService service = new ByteBufferPoolService(direct, bufferSize, maxPoolSize, threadLocalCacheSize, leakDetectionPercent); context.getCapabilityServiceTarget().addCapability(UNDERTOW_BUFFER_POOL_RUNTIME_CAPABILITY, service) .setInitialMode(ServiceController.Mode.ACTIVE) .install(); }</code><technical_language>final PathAddress address = context.getCurrentAddress();</technical_language>

Target:
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { final ModelNode bufferSizeModel = BUFFER_SIZE.resolveModelAttribute(context, model); final ModelNode maxPoolSizeModel = MAX_POOL_SIZE.resolveModelAttribute(context, model); final ModelNode directModel = DIRECT.resolveModelAttribute(context, model); final int threadLocalCacheSize = THREAD_LOCAL_CACHE_SIZE.resolveModelAttribute(context, model).asInt(); final int leakDetectionPercent = LEAK_DETECTION_PERCENT.resolveModelAttribute(context, model).asInt(); final int bufferSize = bufferSizeModel.asInt(defaultBufferSize); final int maxPoolSize = maxPoolSizeModel.asInt(-1); final boolean direct = directModel.asBoolean(defaultDirectBuffers); final ByteBufferPoolService service = new ByteBufferPoolService(direct, bufferSize, maxPoolSize, threadLocalCacheSize, leakDetectionPercent); context.getCapabilityServiceTarget().addCapability(UNDERTOW_BUFFER_POOL_RUNTIME_CAPABILITY, service) .setInitialMode(ServiceController.Mode.ACTIVE) .install(); }
Source:
<code>private void scanInstalledLibraries(UserLibraryFolder folderDesc) { File list[] = folderDesc.folder.listFiles(OnlyDirs.ONLY_DIRS); if (list == null) return; for (File subfolder : list) { String subfolderName = subfolder.getName(); if (!BaseNoGui.isSanitaryName(subfolderName)) { if (!badLibNotified.contains(subfolderName)) { badLibNotified.add(subfolderName); String mess = I18n.format(tr("The library \"{0}\" cannot be used.\n" + "Library folder names must contain only basic letters and numbers\n" <START> + "(ASCII only and no spaces), and be less than 64 characters long."), <END> subfolderName); BaseNoGui.showMessage(tr("Ignoring bad library name"), mess); } continue; } try { scanLibrary(new UserLibraryFolder(subfolder, folderDesc.location)); } catch (IOException e) { System.out.println(I18n.format(tr("Invalid library found in {0}: {1}"), subfolder, e.getMessage())); } } }</code><technical_language>constraints hold here</technical_language>

Target:
private void scanInstalledLibraries(UserLibraryFolder folderDesc) { File list[] = folderDesc.folder.listFiles(OnlyDirs.ONLY_DIRS); if (list == null) return; for (File subfolder : list) { String subfolderName = subfolder.getName(); if (!BaseNoGui.isSanitaryName(subfolderName)) { if (!badLibNotified.contains(subfolderName)) { badLibNotified.add(subfolderName); String mess = I18n.format(tr("The library \"{0}\" cannot be used.\n" + "Library folder names must start with a letter or number, followed by letters,\n" + "numbers, dashes, dots and underscores. Maximum length is 63 characters."), subfolderName); BaseNoGui.showMessage(tr("Ignoring bad library name"), mess); } continue; } try { scanLibrary(new UserLibraryFolder(subfolder, folderDesc.location)); } catch (IOException e) { System.out.println(I18n.format(tr("Invalid library found in {0}: {1}"), subfolder, e.getMessage())); } } }
Source:
<code>public <K, V> ConcurrentMap<K, V> createConcurrentMap() { <START> return new ConcurrentParallelHashMapV8<K, V>( <END> AnyEquivalence.<K>getInstance(), AnyEquivalence.<V>getInstance()); }</code><technical_language>changing return values of existing factory methods instead of adding new methods for need new logic in ConcurrentParallelHashMapV8? reason I this for EquivalentConcurrentHashMapV8 is need type of maps in order avoid issues collections call Object.equals instead of equivalence function</technical_language>

Target:
public <K, V> ConcurrentMap<K, V> createConcurrentMap() { return new EquivalentConcurrentHashMapV8<K, V>( AnyEquivalence.<K>getInstance(), AnyEquivalence.<V>getInstance()); }
Source:
<code>protected static int appendPattern(boolean[] target, int pos, int[] pattern, boolean startColor) { int numAdded = 9; for (int bit : pattern) { <START> target[pos++] = bit == 0 ? false : true; <END> } return numAdded; }</code><technical_language>= bit != 0</technical_language>

Target:
protected static int appendPattern(boolean[] target, int pos, int[] pattern, boolean startColor) { for (int bit : pattern) { target[pos++] = bit != 0; } return 9; }
Source:
<code>public void onMapReady(@NonNull MapboxMap mapboxMap) { MultipleGeometriesActivity.this.mapboxMap = mapboxMap; mapboxMap.setStyle(Style.LIGHT, new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull Style style) { createGeoJsonSource(); addPolygonLayer(); <START> addPointsLayer(); <END> } }); }</code><technical_language>add style parameter methods</technical_language>

Target:
public void onMapReady(@NonNull MapboxMap mapboxMap) { mapboxMap.setStyle(Style.LIGHT, new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull Style style) { createGeoJsonSource(style); addPolygonLayer(style); addPointsLayer(style); } }); }
Source:
<code>public void onResume() { super.onResume(); contributionsPresenter.onAttachView(this); firstLocationUpdate = true; locationManager.addLocationListener(this); <START> boolean isSettingsChanged = store.getBoolean(Prefs.IS_CONTRIBUTION_COUNT_CHANGED, false); <END> store.putBoolean(Prefs.IS_CONTRIBUTION_COUNT_CHANGED, false); if (store.getBoolean("displayNearbyCardView", true)) { checkPermissionsAndShowNearbyCardView(); if (nearbyNotificationCardView.cardViewVisibilityState == NearbyNotificationCardView.CardViewVisibilityState.READY) { nearbyNotificationCardView.setVisibility(View.VISIBLE); } } else { nearbyNotificationCardView.setVisibility(View.GONE); } fetchCampaigns(); }</code><technical_language>this deleted now, right</technical_language>

Target:
public void onResume() { super.onResume(); contributionsPresenter.onAttachView(this); firstLocationUpdate = true; locationManager.addLocationListener(this); if (store.getBoolean("displayNearbyCardView", true)) { checkPermissionsAndShowNearbyCardView(); if (nearbyNotificationCardView.cardViewVisibilityState == NearbyNotificationCardView.CardViewVisibilityState.READY) { nearbyNotificationCardView.setVisibility(View.VISIBLE); } } else { nearbyNotificationCardView.setVisibility(View.GONE); } fetchCampaigns(); }
Source:
<code>public boolean isConnected(IProgressMonitor monitor) { <START> boolean needStrategy = client.getAuthorizationStrategy() == null; <END> if(needStrategy) { client.setAuthorizationStrategy(getAuthorizationStrategy()); } try { IAuthorizationContext context = client.getContext(client.getBaseURL().toString()); return context.isAuthorized(); } catch (UnauthorizedException e) { needStrategy = false; return false; } finally { if(needStrategy) { connect(); } } }</code><technical_language>I code repeated times: boolean needStrategy = client.getAuthorizationStrategy() == null; if(needStrategy) { client.setAuthorizationStrategy(getAuthorizationStrategy()); } I if this patch solves issue (which I currently reproduce dont if helps) move a separate method called #updateAuthorizationStrategy() (or similar)</technical_language>

Target:
public boolean isConnected(IProgressMonitor monitor) { boolean needStrategy = initAuthorizationStrategy(); try { IAuthorizationContext context = client.getContext(client.getBaseURL().toString()); return context.isAuthorized(); } catch (UnauthorizedException e) { needStrategy = false; return false; } finally { if(needStrategy) { connect(); } } }
Source:
<code>public List<JudgmentEnrichmentTags> fetchEnrichmentTagsForJudgments(List<Long> judgmentIds) { List<EnrichmentTag> enrichmentTags = enrichmentTagRepository.findAllByJudgmentIds(judgmentIds); <START> List<Object[]> enrichmentTagsWithReference = fetchJudgmentsReferencingTags(judgmentIds); <END> Map<Long, JudgmentEnrichmentTags> judgmentsEnrichmentTagsMap = Maps.newHashMapWithExpectedSize(judgmentIds.size()); initializeJudgmentsEnrichmentTagsMap(judgmentsEnrichmentTagsMap, judgmentIds); collectJudgmentsEnrichmentTags(judgmentsEnrichmentTagsMap, enrichmentTags); collectJudgmentsReferencingEnrichmentTags(judgmentsEnrichmentTagsMap, enrichmentTagsWithReference); return Lists.newLinkedList(judgmentsEnrichmentTagsMap.values()); }</code><technical_language>referencingTags</technical_language>

Target:
public List<JudgmentEnrichmentTags> fetchEnrichmentTagsForJudgments(List<Long> judgmentIds) { Map<Long, JudgmentEnrichmentTags> judgmentsDirectEnrichmentTagsMap = fetchJudgmentsDirectTags(judgmentIds); Map<Long, JudgmentEnrichmentTags> judgmentsReferencingEnrichmentTags = fetchJudgmentsReferencingTags(judgmentIds); Map<Long, JudgmentEnrichmentTags> judgmentsEnrichmentTagsMap = initializeJudgmentsEnrichmentTagsMap(judgmentIds); mergeJudgmentsEnrichmentTagsMaps(judgmentsDirectEnrichmentTagsMap, judgmentsEnrichmentTagsMap); mergeJudgmentsEnrichmentTagsMaps(judgmentsReferencingEnrichmentTags, judgmentsEnrichmentTagsMap); return Lists.newLinkedList(judgmentsEnrichmentTagsMap.values()); }
Source:
<code>public String getMessage(EObject eObject, String value) { URI uri = <START> eObject.eResource().getURI(); <END> if (uri != null && uri.isPlatformPlugin() && uri.segmentCount() > 1) { Bundle bundle = Platform.getBundle(uri.segment(1)); return MessageTranslator.INSTANCE.getMessage(bundle, value); } return value; }</code><technical_language>NPE if passed EObject is part of a Resource</technical_language>

Target:
public String getMessage(EObject eObject, String value) { if (eObject.eResource() != null) { URI uri = eObject.eResource().getURI(); if (uri != null && uri.isPlatformPlugin() && uri.segmentCount() > 1) { Bundle bundle = Platform.getBundle(uri.segment(1)); return MessageTranslator.INSTANCE.getMessage(bundle, value); } } return value; }
Source:
<code>protected Buffer getBuffer(Dsn dsn) { File bufferDir; String bufferDirOpt = Lookup.lookup(BUFFER_DIR_OPTION, dsn); if (bufferDirOpt != null) { bufferDir = new File(bufferDirOpt); } else { <START> bufferDir = new File(this.ctx.getCacheDir().getAbsolutePath(), DEFAULT_BUFFER_DIR); <END> } Log.d(TAG, "Using buffer dir: " + bufferDir.getAbsolutePath()); return new DiskBuffer(bufferDir, getBufferSize(dsn)); }</code><technical_language>// nitpick-mode-on change this.ctx ctx? // nitpick-mode-off</technical_language>

Target:
protected Buffer getBuffer(Dsn dsn) { File bufferDir; String bufferDirOpt = Lookup.lookup(BUFFER_DIR_OPTION, dsn); if (bufferDirOpt != null) { bufferDir = new File(bufferDirOpt); } else { bufferDir = new File(ctx.getCacheDir().getAbsolutePath(), DEFAULT_BUFFER_DIR); } Log.d(TAG, "Using buffer dir: " + bufferDir.getAbsolutePath()); return new DiskBuffer(bufferDir, getBufferSize(dsn)); }
Source:
<code>public ProjectEditPage insertProjectData(Project project) { titleInput.sendKeys(project.getTitle()); pagesAmountInput.clear(); pagesAmountInput.sendKeys(project.getNumberOfPages().toString()); volumeAmountInput.clear(); volumeAmountInput.sendKeys(project.getNumberOfVolumes().toString()); selectTrigger.click(); WebElement option = Browser.getDriver().findElement(By.id("editForm:projectTabView:client_1")); option.click(); startDateInput.clear(); if (SystemUtils.USER_LANGUAGE.equals("en")) { <START> startDateInput.sendKeys("05/08/18"); <END> endDateInput.clear(); endDateInput.sendKeys("05/08/19"); } else { startDateInput.sendKeys("05.08.18"); endDateInput.clear(); endDateInput.sendKeys("05.08.19"); } return this; }</code><technical_language>Month day switched if want date in German English locale</technical_language>

Target:
public ProjectEditPage insertProjectData(Project project) { titleInput.sendKeys(project.getTitle()); pagesAmountInput.clear(); pagesAmountInput.sendKeys(project.getNumberOfPages().toString()); volumeAmountInput.clear(); volumeAmountInput.sendKeys(project.getNumberOfVolumes().toString()); selectTrigger.click(); WebElement option = Browser.getDriver().findElement(By.id("editForm:projectTabView:client_1")); option.click(); startDateInput.clear(); endDateInput.clear(); if (SystemUtils.USER_LANGUAGE.equals("en")) { startDateInput.sendKeys("08/05/18"); endDateInput.sendKeys("08/05/19"); } else { startDateInput.sendKeys("05.08.18"); endDateInput.sendKeys("05.08.19"); } return this; }
Source:
<code>private Enumerator<T> enumeratorBasedOnPeparedStatement() { Connection connection = null; PreparedStatement statement = null; try { connection = dataSource.getConnection(); statement = connection.prepareStatement(sql); setTimeoutIfPossible(statement); consumer.accept(statement); if (statement.execute()) { final ResultSet resultSet = statement.getResultSet(); statement = null; connection = null; return new ResultSetEnumerator<>(resultSet, rowBuilderFactory); } else { Integer updateCount = statement.getUpdateCount(); return Linq4j.singletonEnumerator((T) updateCount); } } catch (SQLException e) { <START> throw new RuntimeException("while executing SQL [" + sql + "]", e); <END> } finally { closeIfPossible(connection, statement); } }</code><technical_language>I if src/main/java/org/apache/calcite/runtime/CalciteResource.java instead</technical_language>

Target:
private Enumerator<T> enumeratorBasedOnPeparedStatement() { Connection connection = null; PreparedStatement statement = null; try { connection = dataSource.getConnection(); statement = connection.prepareStatement(sql); setTimeoutIfPossible(statement); preparedStatementEnricher.enrich(statement); if (statement.execute()) { final ResultSet resultSet = statement.getResultSet(); statement = null; connection = null; return new ResultSetEnumerator<>(resultSet, rowBuilderFactory); } else { Integer updateCount = statement.getUpdateCount(); return Linq4j.singletonEnumerator((T) updateCount); } } catch (SQLException e) { throw Static.RESOURCE.exceptionWhilePerformingQueryOnJDBSubschema(sql).ex(e); } finally { closeIfPossible(connection, statement); } }
Source:
<code>private void showResultDialog() { BranchResultDialog.show(bop.getResult(), repository, refName); <START> if (refName == null && bop.getResult().getStatus() == CheckoutResult.Status.OK) <END> showDetachedHeadWarning(); }</code><technical_language>I this is correct check. if (ObjectId.isId(repository.getFullBranch()) && bop.getResult().....) instead. This change in CheckoutCommand obsolete. point is, rely refName parameter decide head is detached operation not. For example, right now, this code, get a wrong detached head warning pop-up checkout a remote branch pointing commit currently checked out branch a consequence of bug 315166</technical_language>

Target:
private void showResultDialog() { BranchResultDialog.show(bop.getResult(), repository, refName); try { if (ObjectId.isId(repository.getFullBranch()) && bop.getResult().getStatus() == CheckoutResult.Status.OK) showDetachedHeadWarning(); } catch (IOException e) { } }
Source:
<code>protected void onCreate(Bundle arg0) { if (isLandscape()) { setTheme(android.R.style.Theme_NoTitleBar_Fullscreen); } <START> super.onCreate(arg0); <END> updateActionBarShadow(); logger.debug( "created"); }</code><technical_language>Instead of work activity lifecycle moving this super call around, overriding theme XML in a landscape-only resource</technical_language>

Target:
protected void onCreate(Bundle arg0) { super.onCreate(arg0); updateActionBarShadow(); logger.debug( "created"); }
Source:
<code>public static JsonObject beanToJson(Object bean) { if (bean == null) { throw new RuntimeException("Cannot convert null to a JSON object"); } try { return Json.parse(objectMapper.writeValueAsString(bean)); <START> } catch (JsonProcessingException e) { <END> throw new RuntimeException("Error converting bean to JSON", e); } }</code><technical_language>![MAJOR](<LINK_1> 'Severity: MAJOR') Define throw a dedicated exception instead of a generic one. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
public static JsonObject beanToJson(Object bean) { Objects.requireNonNull(bean, "Cannot convert null to a JSON object"); try { return Json.parse(objectMapper.writeValueAsString(bean)); } catch (JsonProcessingException e) { throw new RuntimeException("Error converting bean to JSON", e); } }
Source:
<code>public void doRequest( HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { ToolUser user = AuthenticationFilter.Static.getUser(request); if (user != null) { Schedule currentSchedule = Query.from(Schedule.class).where("_id = ?", request.getParameter("_scheduleId")).first(); if (currentSchedule == null) { currentSchedule = user.getCurrentSchedule(); } Date date = ObjectUtils.to(Date.class, request.getParameter("_date")); if (currentSchedule != null || date != null || PageFilter.Static.isPreview(request)) { try { PreviewDatabase pd = new PreviewDatabase(); pd.setDelegate(Database.Static.getDefault()); if (currentSchedule != null) { pd.addChanges(currentSchedule); } else if (date != null) { pd.setDate(date); } Database.Static.overrideDefault(pd); State mainState = State.getInstance(PageFilter.Static.getMainObject(request)); if (mainState != null) { mainState.setDatabase(null); mainState.setResolveInvisible(true); <START> mainState.setValues(State.getInstance(pd.applyChanges(Query <END> .fromAll() .where("_id = ?", mainState.getId()) .resolveInvisible() .noCache() .first())).getSimpleValues()); } chain.doFilter(request, response); } finally { Database.Static.restoreDefault(); } return; } } chain.doFilter(request, response); }</code><technical_language>This a 500 in preview for a new object query fail find a result</technical_language>

Target:
public void doRequest( HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { ToolUser user = AuthenticationFilter.Static.getUser(request); if (user != null) { Schedule currentSchedule = Query.from(Schedule.class).where("_id = ?", request.getParameter("_scheduleId")).first(); if (currentSchedule == null) { currentSchedule = user.getCurrentSchedule(); } Date date = ObjectUtils.to(Date.class, request.getParameter("_date")); if (currentSchedule != null || date != null || PageFilter.Static.isPreview(request)) { try { PreviewDatabase pd = new PreviewDatabase(); pd.setDelegate(Database.Static.getDefault()); if (currentSchedule != null) { pd.addChanges(currentSchedule); } else if (date != null) { pd.setDate(date); } Database.Static.overrideDefault(pd); Object mainObject = PageFilter.Static.getMainObject(request); State mainState = State.getInstance(PageFilter.Static.getMainObject(request)); if (mainState != null) { Object originalObject = Query .fromAll() .where("_id = ?", mainState.getId()) .resolveInvisible() .noCache() .first(); mainState.setDatabase(null); mainState.setResolveInvisible(true); if (originalObject != null) { mainState.setValues(State.getInstance(pd.applyChanges(originalObject)).getSimpleValues()); } else { mainState.setValues(State.getInstance(pd.applyChanges(mainObject)).getSimpleValues()); } } chain.doFilter(request, response); } finally { Database.Static.restoreDefault(); } return; } } chain.doFilter(request, response); }
Source:
<code>public void doesNotBatchRequestsIfBatchingNotEnabled() { <START> when(config.namespace()).thenReturn(Optional.of(CLIENT)); <END> setUpTimeLockBlockInRuntimeConfig(); when(runtimeConfig.timestampClient()).thenReturn(ImmutableTimestampClientConfig.of(false)); createLockAndTimestampServicesForConfig(config, runtimeConfig).timelock().getFreshTimestamp(); availableServer.verify(postRequestedFor(urlEqualTo(TIMELOCK_TIMESTAMP_PATH))); }</code><technical_language>consider putting this in setup repeating in tests</technical_language>

Target:
public void doesNotBatchRequestsIfBatchingNotEnabled() { setUpTimeLockBlockInRuntimeConfig(); when(runtimeConfig.timestampClient()).thenReturn(ImmutableTimestampClientConfig.of(false)); createLockAndTimestampServicesForConfig(config, runtimeConfig).timelock().getFreshTimestamp(); availableServer.verify(postRequestedFor(urlEqualTo(TIMELOCK_TIMESTAMP_PATH))); }