auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private BoBManager(XMPPConnection connection) { <START> super(connection); <END> }</code><technical_language>announce support here, XEP-0231 3</technical_language>

Target:
private BoBManager(XMPPConnection connection) { super(connection); ServiceDiscoveryManager serviceDiscoveryManager = ServiceDiscoveryManager.getInstanceFor(connection); serviceDiscoveryManager.addFeature(NAMESPACE); connection.registerIQRequestHandler( new AbstractIqRequestHandler(BoBIQ.ELEMENT, BoBIQ.NAMESPACE, Type.get, Mode.sync) { @Override public IQ handleIQRequest(IQ iqRequest) { BoBIQ getBoBIQ = (BoBIQ) iqRequest; BoBData bobData = bobSaverManager.getBoB(getBoBIQ.getBoBHash()); BoBIQ responseBoBIQ = null; try { responseBoBIQ = responseBoB(getBoBIQ, bobData); } catch (NotConnectedException | NotLoggedInException | InterruptedException e) { } return responseBoBIQ; } }); connection.registerIQRequestHandler( new AbstractIqRequestHandler(BoBIQ.ELEMENT, BoBIQ.NAMESPACE, Type.result, Mode.sync) { @Override public IQ handleIQRequest(IQ iqRequest) { BoBIQ resultBoBIQ = (BoBIQ) iqRequest; bobSaverManager.addBoB(resultBoBIQ.getBoBHash(), resultBoBIQ.getBoBData()); return null; } }); }
Source:
<code>public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); <START> ((WordPress) getActivity().getApplication()).component().inject(this); <END> setHasOptionsMenu(true); }</code><technical_language>suggestion ((WordPress) requireActivity().getApplication()).component().inject(this); This getActivity() requireActivity()</technical_language>

Target:
public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((WordPress) requireActivity().getApplication()).component().inject(this); setHasOptionsMenu(true); }
Source:
<code>private boolean computeIsConstantExpression() { <START> if (getConstructor() == null) { <END> ICPPEvaluation conversionEval = maybeApplyConversion(fArguments[0], fInputType, false, false); if (!conversionEval.isConstantExpression()) return false; } return !fRepresentsNewExpression && areAllConstantExpressions(fArguments) && isNullOrConstexprFunc(getConstructor()); }</code><technical_language>Do I understand correctly, added code is intended handle cases this: struct S { constexpr operator int() { return 42; } }; constexpr int val = int(S()); ? If so, I handling oversight. add support for this getValue() well. (We do in a separate patch.)</technical_language>

Target:
private boolean computeIsConstantExpression() { if (getConstructor() == null && fArguments.length == 1) { ICPPEvaluation conversionEval = maybeApplyConversion(fArguments[0], fInputType, false, false); if (!conversionEval.isConstantExpression()) return false; } return !fRepresentsNewExpression && areAllConstantExpressions(fArguments) && isNullOrConstexprFunc(getConstructor()); }
Source:
<code>public void findInPage(String s) { textView.setFindListener((activeMatchOrdinal, numberOfMatches, textPosition, findingNext) -> { if (numberOfMatches > 0) { findInPageMatch.setText(textView.getContext().getString(R.string.find_in_page_result, activeMatchOrdinal + 1, numberOfMatches)); findInPageMatch.setTextColor(ResourceUtil.getThemedColor(textView.getContext(), R.attr.material_theme_de_emphasised_color)); setFindInPageChevronsEnabled(true); textView.setSelection(textPosition, textPosition + s.length()); Rect r = new Rect(); <START> textView.getFocusedRect(r); <END> final int scrollTopOffset = 32; scrollView.scrollTo(0, r.top - DimenUtil.roundedDpToPx(scrollTopOffset)); } else { findInPageMatch.setText("0/0"); findInPageMatch.setTextColor(ResourceUtil.getThemedColor(textView.getContext(), R.attr.colorError)); setFindInPageChevronsEnabled(false); } findInPageMatch.setVisibility(View.VISIBLE); }); textView.findInEditor(s, syntaxHighlighter); }</code><technical_language>if adds textView.requestFocus() tapping "find next/previous" button, span color of currently selected text changed</technical_language>

Target:
public void findInPage(String s) { textView.setFindListener((activeMatchOrdinal, numberOfMatches, textPosition, findingNext) -> { if (numberOfMatches > 0) { findInPageMatch.setText(textView.getContext().getString(R.string.find_in_page_result, activeMatchOrdinal + 1, numberOfMatches)); findInPageMatch.setTextColor(ResourceUtil.getThemedColor(textView.getContext(), R.attr.material_theme_de_emphasised_color)); setFindInPageChevronsEnabled(true); textView.setSelection(textPosition, textPosition + s.length()); Rect r = new Rect(); textView.getFocusedRect(r); final int scrollTopOffset = 32; scrollView.scrollTo(0, r.top - DimenUtil.roundedDpToPx(scrollTopOffset)); if (findingNext) { textView.requestFocus(); } } else { findInPageMatch.setText("0/0"); findInPageMatch.setTextColor(ResourceUtil.getThemedColor(textView.getContext(), R.attr.colorError)); setFindInPageChevronsEnabled(false); } findInPageMatch.setVisibility(View.VISIBLE); }); textView.findInEditor(s, syntaxHighlighter); }
Source:
<code><START> public void should_save_a_project() throws Exception { <END> DynamicProjectRepository repo = new DynamicProjectRepository(); GHRepository ghRepository = setupMockGHRepository(); DynamicProject project = repo.createNewProject(ghRepository); assert(repo.getDatastore().getCount(DynamicProject.class) > 0); assert(repo.getDatastore().createQuery(DynamicProject.class).get() instanceof DynamicProject); }</code><technical_language>Is saving a project saving a build sufficient exercise this change? other db operations queries worth verifying</technical_language>

Target:
public void should_save_a_project() throws Exception { DynamicProjectRepository repo = new DynamicProjectRepository(); GHRepository ghRepository = setupMockGHRepository(); DynamicProject project = repo.createNewProject(ghRepository); assert(repo.getDatastore().getCount(DynamicProject.class) > 0); DynamicProject restoredProject = repo.getDatastore().createQuery(DynamicProject.class).get(); assert("repo_name".equals(restoredProject.getName())); }
Source:
<code>public void load(Collection<Properties> configurations) { if (configurations == null) { return; <START> } <END> for (Properties configuration : configurations) { ExtensionEntry entry = new ExtensionEntry(configuration); ExtensionEntry alreadyLoaded = loadedEntries.get(entry.getName()); if (alreadyLoaded != null) { throw new ConfigurationException(String.format("Could not load the configuration '%1$s'. %2%s", entry.getName(), alreadyLoaded.file != null ? String.format("The already loaded file %1$s contains a configuration with the same name", alreadyLoaded.file.getAbsolutePath()) : "")); } loadedEntries.put(entry.getName(), entry); } }</code><technical_language>hmmm... call it? wait for null pointer exceptions..</technical_language>

Target:
public void load(Collection<Properties> configurations) { for (Properties configuration : configurations) { ExtensionEntry entry = new ExtensionEntry(configuration); load(entry); } activate(); }
Source:
<code>public void toggleApplicationDetailsTest() throws Exception { <START> List<ApplicationsPage.ClientRepresentation> applications = applicationsPage.toggleApplicationsDetails(); <END> assertFalse(applications.isEmpty()); Map<String, ApplicationsPage.ClientRepresentation> apps = applications.stream().collect(Collectors.toMap(x -> x.getClientId(), x -> x)); assertThat(apps.keySet(), containsInAnyOrder("always-display-client", "account-console")); assertClientRep(apps.get("account-console"), "Account Console", false, true, "/realms/test/account/", true); assertClientRep(apps.get("always-display-client"), "Always Display Client", false, false, "https://localhost:8543/auth/realms/master/app/always-display-client", true); applications = applicationsPage.toggleApplicationsDetails(); assertFalse(applications.isEmpty()); apps = applications.stream().collect(Collectors.toMap(x -> x.getClientId(), x -> x)); assertThat(apps.keySet(), containsInAnyOrder("always-display-client", "account-console")); assertClientRep(apps.get("account-console"), "Account Console", false, true, "/realms/test/account/", false); assertClientRep(apps.get("always-display-client"), "Always Display Client", false, false, "https://localhost:8543/auth/realms/master/app/always-display-client", false); }</code><technical_language>want try toggling app. if button is broken toggles apps instead of one? :)</technical_language>

Target:
public void toggleApplicationDetailsTest() throws Exception { applicationsPage.toggleApplicationDetails("account-console"); List<ApplicationsPage.ClientRepresentation> applications = applicationsPage.getApplications(); assertFalse(applications.isEmpty()); Map<String, ApplicationsPage.ClientRepresentation> apps = applications.stream().collect(Collectors.toMap(x -> x.getClientId(), x -> x)); assertThat(apps.keySet(), containsInAnyOrder("always-display-client", "account-console")); assertClientRep(apps.get("account-console"), "Account Console", false, true, "/realms/test/account/", true); assertClientRep(apps.get("always-display-client"), "Always Display Client", false, false, "https://localhost:8543/auth/realms/master/app/always-display-client", false); applicationsPage.toggleApplicationDetails("account-console"); applications = applicationsPage.getApplications(); assertFalse(applications.isEmpty()); apps = applications.stream().collect(Collectors.toMap(x -> x.getClientId(), x -> x)); assertThat(apps.keySet(), containsInAnyOrder("always-display-client", "account-console")); assertClientRep(apps.get("account-console"), "Account Console", false, true, "/realms/test/account/", false); assertClientRep(apps.get("always-display-client"), "Always Display Client", false, false, "https://localhost:8543/auth/realms/master/app/always-display-client", false); }
Source:
<code>public Preview.PreviewSurfaceCallback getPreviewSurfaceCallback() { return new Preview.PreviewSurfaceCallback() { @NonNull @Override public ListenableFuture<Surface> createSurfaceFuture(@NonNull Size resolution, int imageFormat) { final SurfaceTexture surfaceTexture = <START> mTextureView.getSurfaceTexture(); <END> surfaceTexture.setDefaultBufferSize(resolution.getWidth(), resolution.getHeight()); return Futures.immediateFuture(new Surface(surfaceTexture)); } @Override public void onSafeToRelease(@NonNull ListenableFuture<Surface> surfaceFuture) { try { surfaceFuture.get().release(); } catch (ExecutionException | InterruptedException e) { e.printStackTrace(); } } }; }</code><technical_language>If want SurfaceTexture TextureView, wait in a SurfaceTextureListener. But, want CameraX decide destroy is for TextureView create a new one. a TextureView, please PreviewUtil. check CameraXActivity for examples</technical_language>

Target:
public Preview.PreviewSurfaceCallback getPreviewSurfaceCallback() { return new Preview.PreviewSurfaceCallback() { final Map<Surface, SurfaceTexture> mSurfaceTextureMap = new HashMap<>(); @NonNull @Override public ListenableFuture<Surface> createSurfaceFuture(@NonNull Size resolution, int imageFormat) { final SurfaceTexture surfaceTexture = new SurfaceTexture(0); surfaceTexture.setDefaultBufferSize(resolution.getWidth(), resolution.getHeight()); surfaceTexture.detachFromGLContext(); final ViewGroup parent = (ViewGroup) mTextureView.getParent(); parent.removeView(mTextureView); parent.addView(mTextureView); mTextureView.setSurfaceTexture(surfaceTexture); final Surface surface = new Surface(surfaceTexture); mSurfaceTextureMap.put(surface, surfaceTexture); return Futures.immediateFuture(surface); } @Override public void onSafeToRelease(@NonNull ListenableFuture<Surface> surfaceFuture) { try { final Surface surface = surfaceFuture.get(); final SurfaceTexture surfaceTexture = mSurfaceTextureMap.get(surface); if (surfaceTexture != null) { surfaceTexture.release(); mSurfaceTextureMap.remove(surface); } surface.release(); } catch (ExecutionException | InterruptedException e) { e.printStackTrace(); } } }; }
Source:
<code>public String countConsumers( @PathParam("owner_key") @Verify(value = Owner.class, subResource = SubResource.CONSUMERS) String ownerKey, @QueryParam("type") Set<String> typeLabels, @QueryParam("sku") List<String> skus, @QueryParam("subscription_id") List<String> subscriptionIds, @QueryParam("contract") List<String> contracts) { findOwner(ownerKey); findAndValidateTypeLabels(typeLabels); int count = consumerCurator.countConsumers(ownerKey, typeLabels, skus, subscriptionIds, contracts); <START> return "{ \"consumersCount\" : " + count + "}"; <END> }</code><technical_language>This odd for a couple reasons: returning a map/dict/object for a single value, building JSON ourselves. some time I looked pinhead docs, in this case, logical return count method. If absolutely need some kind of wrapper it, a cleaner do a singleton map Tomcat/Jackson do serialization for us: public Map<String, Object> countConsumers( ... return Collections.<String, Object>singletonMap("consumer_count", count);</technical_language>

Target:
public int countConsumers( @PathParam("owner_key") @Verify(value = Owner.class, subResource = SubResource.CONSUMERS) String ownerKey, @QueryParam("type") Set<String> typeLabels, @QueryParam("sku") List<String> skus, @QueryParam("subscription_id") List<String> subscriptionIds, @QueryParam("contract") List<String> contracts) { findOwner(ownerKey); consumerTypeValidator.findAndValidateTypeLabels(typeLabels); return consumerCurator.countConsumers(ownerKey, typeLabels, skus, subscriptionIds, contracts); }
Source:
<code>public PieChart(PlotSheet plotSheet, double[] vals){ this.mPlotSheet = plotSheet; mValues = vals; mPercent = new double[mValues.length]; for(double v: mValues) mSum +=v; <START> double denominator; <END> if(mSum == 0) denominator = 1; else denominator = mSum; mPercent[0]= mValues[0]/ denominator; for(int i=1; i< mValues.length; i++){ mPercent[i]= mPercent[i-1]+ mValues[i]/ denominator; } mColorHelper = mColors.length; if((mValues.length-1)%(mColors.length)==0) mColorHelper = mColors.length-1; }</code><technical_language>I missed this in review, in AnkiDroid if / else curly braces; prefer line form: double denominator = (mSum == 0) ? 1 : mSum;</technical_language>

Target:
public PieChart(PlotSheet plotSheet, double[] vals){ this.mPlotSheet = plotSheet; mValues = vals; mPercent = new double[mValues.length]; for(double v: mValues) mSum +=v; double denominator = (mSum == 0) ? 1 : mSum; mPercent[0]= mValues[0]/ denominator; for(int i=1; i< mValues.length; i++){ mPercent[i]= mPercent[i-1]+ mValues[i]/ denominator; } mColorHelper = mColors.length; if((mValues.length-1)%(mColors.length)==0) mColorHelper = mColors.length-1; }
Source:
<code>private OAuth2AuthorizationRequest authorizationRequest(ServerWebExchange exchange, ClientRegistration clientRegistration) { String redirectUriStr = this .expandRedirectUri(exchange.getRequest(), clientRegistration); Map<String, Object> additionalParameters = new HashMap<>(); additionalParameters.put(OAuth2ParameterNames.REGISTRATION_ID, clientRegistration.getRegistrationId()); OAuth2AuthorizationRequest.Builder builder; if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(clientRegistration.getAuthorizationGrantType())) { builder = OAuth2AuthorizationRequest.authorizationCode(); <START> if (isEmpty(clientRegistration.getClientSecret())) { <END> builder.codeVerifier(this.pkceCodeVerifierStringKeyGenerator.generateKey()); } } else if (AuthorizationGrantType.IMPLICIT.equals(clientRegistration.getAuthorizationGrantType())) { builder = OAuth2AuthorizationRequest.implicit(); } else { throw new IllegalArgumentException( "Invalid Authorization Grant Type (" + clientRegistration.getAuthorizationGrantType().getValue() + ") for Client Registration with Id: " + clientRegistration.getRegistrationId()); } return builder .clientId(clientRegistration.getClientId()) .authorizationUri(clientRegistration.getProviderDetails().getAuthorizationUri()) .redirectUri(redirectUriStr).scopes(clientRegistration.getScopes()) .state(this.stateGenerator.generateKey()) .additionalParameters(additionalParameters) .build(); }</code><technical_language>is determine if PKCE used</technical_language>

Target:
private OAuth2AuthorizationRequest authorizationRequest(ServerWebExchange exchange, ClientRegistration clientRegistration) { String redirectUriStr = this .expandRedirectUri(exchange.getRequest(), clientRegistration); Map<String, Object> attributes = new HashMap<>(); attributes.put(OAuth2ParameterNames.REGISTRATION_ID, clientRegistration.getRegistrationId()); OAuth2AuthorizationRequest.Builder builder; if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(clientRegistration.getAuthorizationGrantType())) { builder = OAuth2AuthorizationRequest.authorizationCode(); if (ClientAuthenticationMethod.NONE.equals(clientRegistration.getClientAuthenticationMethod())) { Map<String, Object> additionalParameters = new HashMap<>(); addPkceParameters(attributes, additionalParameters); builder.additionalParameters(additionalParameters); } } else if (AuthorizationGrantType.IMPLICIT.equals(clientRegistration.getAuthorizationGrantType())) { builder = OAuth2AuthorizationRequest.implicit(); } else { throw new IllegalArgumentException( "Invalid Authorization Grant Type (" + clientRegistration.getAuthorizationGrantType().getValue() + ") for Client Registration with Id: " + clientRegistration.getRegistrationId()); } return builder .clientId(clientRegistration.getClientId()) .authorizationUri(clientRegistration.getProviderDetails().getAuthorizationUri()) .redirectUri(redirectUriStr).scopes(clientRegistration.getScopes()) .state(this.stateGenerator.generateKey()) .attributes(attributes) .build(); }
Source:
<code>private void parseECState(final ECC ecc) throws TypeImportException, XMLStreamException { ECState state = LibraryElementFactory.eINSTANCE.createECState(); readNameCommentAttributes(state); getXandY(state); processChildren(LibraryElementTags.ECSTATE_ELEMENT, name -> { if <START> (name.equals(LibraryElementTags.ECACTION_ELEMENT)) <END> { parseECAction(state); return true; } return false; }); if (ecc.getECState().isEmpty()) { ecc.setStart(state); } ecc.getECState().add(state); ecStates.put(state.getName(), state); }</code><technical_language>call equals constant</technical_language>

Target:
private void parseECState(final ECC ecc) throws TypeImportException, XMLStreamException { ECState state = LibraryElementFactory.eINSTANCE.createECState(); readNameCommentAttributes(state); getXandY(state); processChildren(LibraryElementTags.ECSTATE_ELEMENT, name -> { if (LibraryElementTags.ECACTION_ELEMENT.equals(name)) { parseECAction(state); return true; } return false; }); if (ecc.getECState().isEmpty()) { ecc.setStart(state); } ecc.getECState().add(state); ecStates.put(state.getName(), state); }
Source:
<code>private void setType() { try { final Field typeField; if (option.getClass().getSimpleName().equals("SequenceOption")) { typeField = option.getClass().getDeclaredField("elementType"); } else { typeField = option.getClass().getDeclaredField("type"); } typeField.setAccessible(true); optionType = (Class<?>) typeField.get(option); if (optionType.isAssignableFrom(Integer.class)) { type = ModelType.INT; } else if (optionType.isAssignableFrom(Long.class)) { type = ModelType.LONG; } else if (optionType.isAssignableFrom(BigInteger.class)) { type = ModelType.BIG_INTEGER; } else if (optionType.isAssignableFrom(Double.class)) { type = ModelType.DOUBLE; } else if (optionType.isAssignableFrom(BigDecimal.class)) { type = ModelType.BIG_DECIMAL; } else if (optionType.isEnum() || optionType.isAssignableFrom(String.class)) { type = ModelType.STRING; } else if (optionType.isAssignableFrom(Boolean.class)) { type = ModelType.BOOLEAN; } else { type = ModelType.UNDEFINED; } } catch (Exception e) { <START> IOLogger.ROOT_LOGGER.error(e.getLocalizedMessage(), e); <END> } }</code><technical_language>This catch specific checked exceptions code throw, wrap in RuntimeException rethrow. swallowing problems here</technical_language>

Target:
private void setType() { try { final Field typeField; if (option.getClass().getSimpleName().equals("SequenceOption")) { typeField = option.getClass().getDeclaredField("elementType"); } else { typeField = option.getClass().getDeclaredField("type"); } typeField.setAccessible(true); optionType = (Class<?>) typeField.get(option); if (optionType.isAssignableFrom(Integer.class)) { type = ModelType.INT; } else if (optionType.isAssignableFrom(Long.class)) { type = ModelType.LONG; } else if (optionType.isAssignableFrom(BigInteger.class)) { type = ModelType.BIG_INTEGER; } else if (optionType.isAssignableFrom(Double.class)) { type = ModelType.DOUBLE; } else if (optionType.isAssignableFrom(BigDecimal.class)) { type = ModelType.BIG_DECIMAL; } else if (optionType.isEnum() || optionType.isAssignableFrom(String.class)) { type = ModelType.STRING; } else if (optionType.isAssignableFrom(Boolean.class)) { type = ModelType.BOOLEAN; } else { type = ModelType.UNDEFINED; } } catch (Exception e) { throw new IllegalArgumentException(e); } }
Source:
<code>public VEvent() { mProperties = new HashMap<String, String>(); mAttendees = new LinkedList<Attendee>(); <START> addProperty(UID , UUID.randomUUID().toString() + "@cyanogenmod.com"); <END> addTimeStamp(); }</code><technical_language>this, change @android.local</technical_language>

Target:
public VEvent() { mProperties = new HashMap<String, String>(); mAttendees = new LinkedList<Attendee>(); addProperty(UID , UUID.randomUUID().toString() + "@ws.xsoh.etar"); addTimeStamp(); }
Source:
<code>public void setArch(String arch) { incrementSequenceNumber(); fArch = arch; if (fRoot != null && arch != null && <START> arch.length() > 0) { <END> Element archNode = TargetDefinitionDocumentTools.getChildElement(fRoot, TargetDefinitionPersistenceHelper.ENVIRONMENT, TargetDefinitionPersistenceHelper.ARCH); archNode.setTextContent(arch); } else { removeElement(TargetDefinitionPersistenceHelper.ENVIRONMENT, TargetDefinitionPersistenceHelper.ARCH); } }</code><technical_language>Please !string.isEmpty()</technical_language>

Target:
public void setArch(String arch) { incrementSequenceNumber(); fArch = arch; if (fRoot != null && arch != null && !arch.isEmpty()) { Element archNode = TargetDefinitionDocumentTools.getChildElement(fRoot, TargetDefinitionPersistenceHelper.ENVIRONMENT, TargetDefinitionPersistenceHelper.ARCH); archNode.setTextContent(arch); } else { removeElement(TargetDefinitionPersistenceHelper.ENVIRONMENT, TargetDefinitionPersistenceHelper.ARCH); } }
Source:
<code>public static User login(final HttpServletRequest request, final HttpServletResponse response, final User user, final String authenticationMethod) { if (user == null || user.isLoginExpired()) { throw AuthorizationException.authenticationFailed(); } final AuthenticationContext authenticationContext = loggedUserContext.get(); if (authenticationContext == null) { loggedUserContext.set(new AuthenticationContext(user, authenticationMethod)); storeInSession(request, authenticationContext); final Locale preferredLocale = user.getProfile().getPreferredLocale(); if (preferredLocale != null) { <START> I18NFilter.updateLocale(preferredLocale, request, response); <END> } fireLoginListeners(request, response, user); logger.debug("Logged in user: " + user.getUsername()); } else if (authenticationContext.getUser() != user) { throw AuthorizationException.authenticationFailed(); } else { authenticationContext.addAuthenticationMethodEvent(authenticationMethod); } return user; }</code><technical_language>this store null. Is expected behaviour</technical_language>

Target:
public static User login(final HttpServletRequest request, final HttpServletResponse response, final User user, final String authenticationMethod) { if (user == null || user.isLoginExpired()) { throw AuthorizationException.authenticationFailed(); } AuthenticationContext authenticationContext = loggedUserContext.get(); if (authenticationContext == null) { authenticationContext = new AuthenticationContext(user, authenticationMethod); loggedUserContext.set(authenticationContext); storeInSession(request, authenticationContext); final Locale preferredLocale = user.getProfile().getPreferredLocale(); if (preferredLocale != null) { I18NFilter.updateLocale(preferredLocale, request, response); } fireLoginListeners(request, response, authenticationContext); logger.debug("Logged in user: " + user.getUsername()); } else if (authenticationContext.getUser() != user) { throw AuthorizationException.authenticationFailed(); } else { authenticationContext.addAuthenticationMethodEvent(authenticationMethod); } return user; }
Source:
<code>private List<String> determineAccessStatus(DocumentIndexingPackage dip) throws IndexingException { ContentObject obj = dip.getContentObject(); PID pid = obj.getPid(); List<String> status = new ArrayList<>(); PatronAccess inheritedAccess = inheritedAclFactory.getPatronAccess(pid); PatronAccess objAccess = objAclFactory.getPatronAccess(pid); if (inheritedAclFactory.isMarkedForDeletion(pid)) { status.add(FacetConstants.MARKED_FOR_DELETION); } if (inheritedAclFactory.getEmbargoUntil(pid) != null) { <START> status.add(FacetConstants.EMBARGOED); <END> } if (inheritedAccess.equals(PatronAccess.none)) { status.add(FacetConstants.STAFF_ONLY_ACCESS); } else if (inheritedAclFactory.getPrincipalRoles(pid).containsKey(AccessPrincipalConstants.PUBLIC_PRINC)) { status.add(FacetConstants.PUBLIC_ACCESS); } if (inheritedAccess.equals(PatronAccess.none) && !objAccess.equals(PatronAccess.none)) { status.add(FacetConstants.PARENT_HAS_STAFF_ONLY_ACCESS); } return status; }</code><technical_language>check julie if want this facet if is embargoed, include embargoed parent is embargoed? wondering marked for delete, I feel sense inherited value</technical_language>

Target:
private List<String> determineAccessStatus(DocumentIndexingPackage dip) throws IndexingException { PID pid = dip.getPid(); List<String> status = new ArrayList<>(); PatronAccess inheritedAccess = inheritedAclFactory.getPatronAccess(pid); PatronAccess objAccess = objAclFactory.getPatronAccess(pid); if (inheritedAclFactory.isMarkedForDeletion(pid)) { status.add(FacetConstants.MARKED_FOR_DELETION); } Date objEmbargo = objAclFactory.getEmbargoUntil(pid); Date parentEmbargo = inheritedAclFactory.getEmbargoUntil(pid); if (objEmbargo != null) { status.add(FacetConstants.EMBARGOED); } else if (parentEmbargo != null) { status.add(FacetConstants.EMBARGOED_PARENT); } if (objAccess.equals(PatronAccess.none)) { status.add(FacetConstants.STAFF_ONLY_ACCESS); } else if (inheritedAclFactory.getPrincipalRoles(pid).containsKey(AccessPrincipalConstants.PUBLIC_PRINC)) { status.add(FacetConstants.PUBLIC_ACCESS); } if (inheritedAccess.equals(PatronAccess.none) && !objAccess.equals(PatronAccess.none)) { status.add(FacetConstants.PARENT_HAS_STAFF_ONLY_ACCESS); } return status; }
Source:
<code>protected Scope visitCreateFunction(CreateFunction node, Optional<Scope> scope) { analysis.setUpdateType("CREATE FUNCTION"); Type returnType = metadata.getType(parseTypeSignature(node.getReturnType())); List<Field> fields = node.getParameters().stream() .map(parameter -> Field.newUnqualified(parameter.getName().getValue(), metadata.getType(parseTypeSignature(parameter.getType())))) .collect(toImmutableList()); Scope functionScope = Scope.builder() .withRelationType(RelationId.anonymous(), new RelationType(fields)) .build(); Type bodyType = analyzeExpression(node.getBody(), functionScope).getExpressionTypes().get(NodeRef.of(node.getBody())); <START> metadata.getTypeManager().canCoerce(bodyType, returnType); <END> Analyzer.verifyNoAggregateWindowOrGroupingFunctions(analysis.getFunctionHandles(), metadata.getFunctionManager(), node.getBody(), "CREATE FUNCTION body"); return createAndAssignScope(node, scope); }</code><technical_language>implications run time if return type of body is returnType. Is valid reasons want allow coercion? require return type exact</technical_language>

Target:
protected Scope visitCreateFunction(CreateFunction node, Optional<Scope> scope) { analysis.setUpdateType("CREATE FUNCTION"); List<String> duplicateParameters = node.getParameters().stream() .map(SqlParameterDeclaration::getName) .map(Identifier::getValue) .collect(groupingBy(Function.identity(), counting())) .entrySet() .stream() .filter(entry -> entry.getValue() > 1) .map(Entry::getKey) .collect(toImmutableList()); if (!duplicateParameters.isEmpty()) { throw new SemanticException(DUPLICATE_PARAMETER_NAME, node, "Duplicate function parameter name: %s", Joiner.on(", ").join(duplicateParameters)); } Type returnType = metadata.getType(parseTypeSignature(node.getReturnType())); List<Field> fields = node.getParameters().stream() .map(parameter -> Field.newUnqualified(parameter.getName().getValue(), metadata.getType(parseTypeSignature(parameter.getType())))) .collect(toImmutableList()); Scope functionScope = Scope.builder() .withRelationType(RelationId.anonymous(), new RelationType(fields)) .build(); Type bodyType = analyzeExpression(node.getBody(), functionScope).getExpressionTypes().get(NodeRef.of(node.getBody())); if (!bodyType.equals(returnType)) { throw new SemanticException(TYPE_MISMATCH, node, "Function implementation type '%s' does not match declared return type '%s'", bodyType, returnType); } Analyzer.verifyNoAggregateWindowOrGroupingFunctions(analysis.getFunctionHandles(), metadata.getFunctionManager(), node.getBody(), "CREATE FUNCTION body"); return createAndAssignScope(node, scope); }
Source:
<code>public void testNoAuth() throws Exception { serverKeystore = null; serverTruststore = null; clientKeystore = null; clientTruststore = null; Properties p = saveStoresAndGetConnectorProperties(); p.put(JmxmpAgent.USE_SSL_PROPERTY, "false"); p.put(JmxmpAgent.AUTHENTICATE_CLIENTS_PROPERTY, "false"); server = new JmxmpAgent().startJmxmpConnector(p); <START> new JmxmpClient().connect("service:jmx:jmxmp://almacretin.local:11099", new LinkedHashMap()); <END> }</code><technical_language>this "localhost", instead of "almacretin.local"</technical_language>

Target:
public void testNoAuth() throws Exception { serverKeystore = null; serverTruststore = null; clientKeystore = null; clientTruststore = null; Properties p = saveStoresAndGetConnectorProperties(); p.put(JmxmpAgent.USE_SSL_PROPERTY, "false"); p.put(JmxmpAgent.AUTHENTICATE_CLIENTS_PROPERTY, "false"); server = new JmxmpAgent().startJmxmpConnector(p); new JmxmpClient().connect("service:jmx:jmxmp://localhost:11099", new LinkedHashMap()); }
Source:
<code>public void sendAdvertisedRefs(final RefAdvertiser adv) throws IOException, ServiceMayNotContinueException { try { advertiseRefsHook.advertiseRefs(this); } catch (ServiceMayNotContinueException fail) { if (fail.getMessage() != null) { adv.writeOne("ERR " + fail.getMessage()); fail.setOutput(); } throw fail; } adv.init(db); adv.advertiseCapability(OPTION_INCLUDE_TAG); adv.advertiseCapability(OPTION_MULTI_ACK_DETAILED); adv.advertiseCapability(OPTION_MULTI_ACK); adv.advertiseCapability(OPTION_OFS_DELTA); adv.advertiseCapability(OPTION_SIDE_BAND); adv.advertiseCapability(OPTION_SIDE_BAND_64K); adv.advertiseCapability(OPTION_THIN_PACK); adv.advertiseCapability(OPTION_NO_PROGRESS); adv.advertiseCapability(OPTION_SHALLOW); if (!biDirectionalPipe) adv.advertiseCapability(OPTION_NO_DONE); RequestPolicy policy = getRequestPolicy(); if (policy == RequestPolicy.TIP || policy == RequestPolicy.REACHABLE_COMMIT_TIP || policy == null) adv.advertiseCapability(OPTION_ALLOW_TIP_SHA1_IN_WANT); adv.setDerefTags(true); findSymrefs(adv); advertised = <START> adv.send(getAdvertisedOrDefaultRefs()); <END> if (adv.isEmpty()) adv.advertiseId(ObjectId.zeroId(), "capabilities^{}"); adv.end(); }</code><technical_language>need HEAD this collection. like: Map<String, Ref> refs = getAdvertisedOrDefaultRefs(); addSymrefs(adv, refs); advertised = adv.send(refs);</technical_language>

Target:
public void sendAdvertisedRefs(final RefAdvertiser adv) throws IOException, ServiceMayNotContinueException { try { advertiseRefsHook.advertiseRefs(this); } catch (ServiceMayNotContinueException fail) { if (fail.getMessage() != null) { adv.writeOne("ERR " + fail.getMessage()); fail.setOutput(); } throw fail; } adv.init(db); adv.advertiseCapability(OPTION_INCLUDE_TAG); adv.advertiseCapability(OPTION_MULTI_ACK_DETAILED); adv.advertiseCapability(OPTION_MULTI_ACK); adv.advertiseCapability(OPTION_OFS_DELTA); adv.advertiseCapability(OPTION_SIDE_BAND); adv.advertiseCapability(OPTION_SIDE_BAND_64K); adv.advertiseCapability(OPTION_THIN_PACK); adv.advertiseCapability(OPTION_NO_PROGRESS); adv.advertiseCapability(OPTION_SHALLOW); if (!biDirectionalPipe) adv.advertiseCapability(OPTION_NO_DONE); RequestPolicy policy = getRequestPolicy(); if (policy == RequestPolicy.TIP || policy == RequestPolicy.REACHABLE_COMMIT_TIP || policy == null) adv.advertiseCapability(OPTION_ALLOW_TIP_SHA1_IN_WANT); adv.setDerefTags(true); Map<String, Ref> refs = getAdvertisedOrDefaultRefs(); findSymrefs(adv, refs); advertised = adv.send(refs); if (adv.isEmpty()) adv.advertiseId(ObjectId.zeroId(), "capabilities^{}"); adv.end(); }
Source:
<code>private static <TSource, TInner, TResult> Enumerable<TResult> nestedLoopJoinAsList( final Enumerable<TSource> outer, final Enumerable<TInner> inner, final Predicate2<TSource, TInner> predicate, Function2<TSource, TInner, TResult> resultSelector, <START> final JoinType joinType) { <END> final boolean generateNullsOnLeft = joinType.generatesNullsOnLeft(); final boolean generateNullsOnRight = joinType.generatesNullsOnRight(); final List<TResult> result = new ArrayList<>(); final Enumerator<TSource> lefts = outer.enumerator(); final List<TInner> rightList = inner.toList(); final Set<TInner> rightUnmatched; if (generateNullsOnLeft) { rightUnmatched = Sets.newIdentityHashSet(); rightUnmatched.addAll(rightList); } else { rightUnmatched = null; } while (lefts.moveNext()) { int leftMatchCount = 0; final TSource left = lefts.current(); final Enumerator<TInner> rights = Linq4j.iterableEnumerator(rightList); while (rights.moveNext()) { TInner right = rights.current(); if (predicate.apply(left, right)) { ++leftMatchCount; if (joinType == JoinType.ANTI) { break; } else { if (rightUnmatched != null) { rightUnmatched.remove(right); } result.add(resultSelector.apply(left, right)); if (joinType == JoinType.SEMI) { break; } } } } if (leftMatchCount == 0 && (generateNullsOnRight || joinType == JoinType.ANTI)) { result.add(resultSelector.apply(left, null)); } } if (rightUnmatched != null) { final Enumerator<TInner> rights = Linq4j.iterableEnumerator(rightUnmatched); while (rights.moveNext()) { TInner right = rights.current(); result.add(resultSelector.apply(null, right)); } } return Linq4j.asEnumerable(result); }</code><technical_language>generateNullsOnLeft true,</technical_language>

Target:
private static <TSource, TInner, TResult> Enumerable<TResult> nestedLoopJoinAsList( final Enumerable<TSource> outer, final Enumerable<TInner> inner, final Predicate2<TSource, TInner> predicate, Function2<TSource, TInner, TResult> resultSelector, final JoinType joinType) { final boolean generateNullsOnLeft = joinType.generatesNullsOnLeft(); final boolean generateNullsOnRight = joinType.generatesNullsOnRight(); final List<TResult> result = new ArrayList<>(); final List<TInner> rightList = inner.toList(); final Set<TInner> rightUnmatched; if (generateNullsOnLeft) { rightUnmatched = Sets.newIdentityHashSet(); rightUnmatched.addAll(rightList); } else { rightUnmatched = null; } try (Enumerator<TSource> lefts = outer.enumerator()) { while (lefts.moveNext()) { int leftMatchCount = 0; final TSource left = lefts.current(); for (TInner right : rightList) { if (predicate.apply(left, right)) { ++leftMatchCount; if (joinType == JoinType.ANTI) { break; } else { if (rightUnmatched != null) { rightUnmatched.remove(right); } result.add(resultSelector.apply(left, right)); if (joinType == JoinType.SEMI) { break; } } } } if (leftMatchCount == 0 && (generateNullsOnRight || joinType == JoinType.ANTI)) { result.add(resultSelector.apply(left, null)); } } if (rightUnmatched != null) { for (TInner right : rightUnmatched) { result.add(resultSelector.apply(null, right)); } } return Linq4j.asEnumerable(result); } }
Source:
<code>private String getCertificateUrlParams(String secret, String path, String cn, String name, String alt, String organizationName) throws UnsupportedEncodingException { String pathAux = path != null ? path.replaceAll("/", "%2F") + secret : "%2Fuserland%2Fcertificates%2F" + secret; String cnAux = cn != null ? cn : secret; String nameAux = name != null ? name : secret; <START> String urlParams = "?path=" + URLEncoder.encode(pathAux, "UTF-8") + "&cn=" + URLEncoder.encode(cnAux, "UTF-8") + "&name=" + URLEncoder.encode(nameAux, "UTF-8"); <END> if (alt != null) { urlParams = urlParams + "&alt=" + alt; } if (organizationName != null) { urlParams = urlParams + "&organizationName=" + organizationName; } return urlParams; }</code><technical_language>review params alt organizationName</technical_language>

Target:
private String getCertificateUrlParams(String secret, String path, String cn, String name, String alt, String organizationName) { String pathAux = path != null ? path.replaceAll("/", "%2F") + secret : "%2Fuserland%2Fcertificates%2F" + secret; String cnAux = cn != null ? cn : secret; String nameAux = name != null ? name : secret; String urlParams = "?path=" + pathAux + "&cn=" + cnAux + "&name=" + nameAux; if (alt != null) { urlParams = urlParams + "&alt=" + alt; } if (organizationName != null) { urlParams = urlParams + "&organizationName=" + organizationName; } return urlParams; }
Source:
<code>public Map<String, List<Integer>> parse(File... files) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db; Map<NodeList, List<String>> coverageData = new HashMap<NodeList, List<String>>(); for (File file : files) { InputStream is = null; try { is = new FileInputStream(file); db = dbf.newDocumentBuilder(); <START> db.setEntityResolver(new EntityResolver() { <END> @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { String res = dtdMap.get(systemId); if (res != null) { return new InputSource(this.getClass().getResourceAsStream(res)); } else { LOGGER.log(Level.WARNING, "Unknown DTD systemID \"" + systemId + "\", skipping download by returning empty DTD"); return new InputSource(new StringReader(EMPTY_XML)); } } }); Document doc = db.parse(is); NodeList classes = doc.getElementsByTagName(TAG_NAME_CLASS); List<String> sourceDirs = getSourceDirs(doc); coverageData.put(classes, sourceDirs); } finally { if (is != null) { is.close(); } } } return parse(coverageData); }</code><technical_language>Remove anonymous class. EntityResolver a private static final constant is initialized beginning</technical_language>

Target:
public Map<String, List<Integer>> parse(File... files) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db; Map<NodeList, List<String>> coverageData = new HashMap<NodeList, List<String>>(); for (File file : files) { InputStream is = null; try { is = new FileInputStream(file); db = dbf.newDocumentBuilder(); db.setEntityResolver(entityResolver); Document doc = db.parse(is); NodeList classes = doc.getElementsByTagName(TAG_NAME_CLASS); List<String> sourceDirs = getSourceDirs(doc); coverageData.put(classes, sourceDirs); } finally { if (is != null) { is.close(); } } } return parse(coverageData); }
Source:
<code>public void registerTaskManager(final TaskExecutorConnection taskExecutorConnection, SlotReport initialSlotReport) { checkInit(); LOG.debug("Registering TaskManager under at the SlotManager.", taskExecutorConnection.getResourceID(), taskExecutorConnection.getInstanceID()); if (taskManagerRegistrations.containsKey(taskExecutorConnection.getInstanceID())) { reportSlotStatus(taskExecutorConnection.getInstanceID(), initialSlotReport); } else { <START> if (getNumberRegisteredSlots() + Math.max(getNumberPendingTaskManagerSlots(), numSlotsPerWorker) > maxSlotNum) { <END> LOG.warn("The total number of slots exceeds the max limitation, release the excess resource."); resourceActions.releaseResource(taskExecutorConnection.getInstanceID(), new FlinkException("The total number of slots exceeds the max limitation.")); return; } ArrayList<SlotID> reportedSlots = new ArrayList<>(); for (SlotStatus slotStatus : initialSlotReport) { reportedSlots.add(slotStatus.getSlotID()); } TaskManagerRegistration taskManagerRegistration = new TaskManagerRegistration( taskExecutorConnection, reportedSlots); taskManagerRegistrations.put(taskExecutorConnection.getInstanceID(), taskManagerRegistration); for (SlotStatus slotStatus : initialSlotReport) { registerSlot( slotStatus.getSlotID(), slotStatus.getAllocationID(), slotStatus.getJobID(), slotStatus.getResourceProfile(), taskExecutorConnection); } } }</code><technical_language>I this if condition assumes pending slots consumed new registered slots. In other words, resource profiles of registered slots matches pending slots exactly. I this is a strong assumption. true moment, weaken generality of SlotManagerImpl. I suggest check registered slots matched pending slots here, decide release registered task executor based checkin gresult</technical_language>

Target:
public void registerTaskManager(final TaskExecutorConnection taskExecutorConnection, SlotReport initialSlotReport) { checkInit(); LOG.debug("Registering TaskManager under at the SlotManager.", taskExecutorConnection.getResourceID(), taskExecutorConnection.getInstanceID()); if (taskManagerRegistrations.containsKey(taskExecutorConnection.getInstanceID())) { reportSlotStatus(taskExecutorConnection.getInstanceID(), initialSlotReport); } else { if (isMaxSlotNumExceededAfterRegistration(initialSlotReport)) { LOG.info("The total number of slots exceeds the max limitation {}, release the excess resource.", maxSlotNum); resourceActions.releaseResource(taskExecutorConnection.getInstanceID(), new FlinkException("The total number of slots exceeds the max limitation.")); return; } ArrayList<SlotID> reportedSlots = new ArrayList<>(); for (SlotStatus slotStatus : initialSlotReport) { reportedSlots.add(slotStatus.getSlotID()); } TaskManagerRegistration taskManagerRegistration = new TaskManagerRegistration( taskExecutorConnection, reportedSlots); taskManagerRegistrations.put(taskExecutorConnection.getInstanceID(), taskManagerRegistration); for (SlotStatus slotStatus : initialSlotReport) { registerSlot( slotStatus.getSlotID(), slotStatus.getAllocationID(), slotStatus.getJobID(), slotStatus.getResourceProfile(), taskExecutorConnection); } } }
Source:
<code>public void skipWindowsThatDontCleanTempFolder() { <START> org.junit.Assume.assumeFalse(IS_WIN); <END> }</code><technical_language>ConditionalIgnoreRule.IgnoreWindows class, I check if depend nuxeo-runtime-test. Otherwise, SystemUtils.IS_OS_WINDOWS commons-lang3</technical_language>

Target:
public void skipWindowsThatDontCleanTempFolder() { assumeFalse(IS_WIN); }
Source:
<code>public void convertCcDivisions_Same() { long idOne = 111; long idTwo = 222; CommonCourtDivision ccDivisionOne = new CommonCourtDivision(); ccDivisionOne.setName(ccDivisionNames[0]); Whitebox.setInternalState(ccDivisionOne, "id", idOne); CommonCourtDivision ccDivisionTwo = new CommonCourtDivision(); ccDivisionTwo.setName(ccDivisionNames[1]); Whitebox.setInternalState(ccDivisionTwo, "id", idTwo); List<CommonCourtDivision> ccDivisions = Arrays.asList(ccDivisionOne, ccDivisionTwo); List<SimpleEntity> convertedSimpleEntities = simpleEntityConverter.convertCcDivisions(ccDivisions); <START> assertEquals(ccDivisionNames.length, convertedSimpleEntities.size()); <END> assertEquals(idOne, convertedSimpleEntities.get(0).getId()); assertEquals(idTwo, convertedSimpleEntities.get(1).getId()); assertEquals(ccDivisionNames[0], convertedSimpleEntities.get(0).getName()); assertEquals(ccDivisionNames[1], convertedSimpleEntities.get(1).getName()); }</code><technical_language>ccDivisions.size() more accurate for other test cases in this class</technical_language>

Target:
public void convertCcDivisions_Same() { long idOne = 111; long idTwo = 222; CommonCourtDivision ccDivisionOne = new CommonCourtDivision(); ccDivisionOne.setName(ccDivisionNames[0]); Whitebox.setInternalState(ccDivisionOne, "id", idOne); CommonCourtDivision ccDivisionTwo = new CommonCourtDivision(); ccDivisionTwo.setName(ccDivisionNames[1]); Whitebox.setInternalState(ccDivisionTwo, "id", idTwo); List<CommonCourtDivision> ccDivisions = Arrays.asList(ccDivisionOne, ccDivisionTwo); List<SimpleEntity> convertedSimpleEntities = simpleEntityConverter.convertCcDivisions(ccDivisions); assertEquals(ccDivisions.size(), convertedSimpleEntities.size()); assertEquals(idOne, convertedSimpleEntities.get(0).getId()); assertEquals(idTwo, convertedSimpleEntities.get(1).getId()); assertEquals(ccDivisionNames[0], convertedSimpleEntities.get(0).getName()); assertEquals(ccDivisionNames[1], convertedSimpleEntities.get(1).getName()); }
Source:
<code>public void shouldNotBeAllowedToAttachTwoRules() { <START> RetentionRule rr = createManualImmediateRuleMillis(100L); <END> file = service.attachRule(file, rr, session); try { service.attachRule(file, rr, session); fail("Should not be abe to attach rule twice"); } catch (NuxeoException e) { } }</code><technical_language>literal L is needed method createManualImmediateRuleMillis takes a primitif type</technical_language>

Target:
public void shouldNotBeAllowedToAttachTwoRules() { RetentionRule rr = createManualImmediateRuleMillis(100); file = service.attachRule(file, rr, session); try { service.attachRule(file, rr, session); fail("Should not be abe to attach rule twice"); } catch (NuxeoException e) { assertEquals("Document is already a record", e.getMessage()); } }
Source:
<code>public void releaseStore(Store<?, ?> resource) { <START> CacheStore cacheStore = (CacheStore) resource; <END> Map.Entry<CachingTier.Provider, AuthoritativeTier.Provider> entry = providersMap.remove(resource); if (entry == null) { throw new IllegalArgumentException("Given store is not managed by this provider : " + resource); } entry.getKey().releaseCachingTier(cacheStore.cachingTier); entry.getValue().releaseAuthoritativeTier(cacheStore.authoritativeTier); }</code><technical_language>cast done if (entry == null) check avoid a potential ClassCastException. mistake</technical_language>

Target:
public void releaseStore(Store<?, ?> resource) { Map.Entry<CachingTier.Provider, AuthoritativeTier.Provider> entry = providersMap.get(resource); if (entry == null) { throw new IllegalArgumentException("Given store is not managed by this provider : " + resource); } CacheStore cacheStore = (CacheStore) resource; entry.getKey().releaseCachingTier(cacheStore.cachingTier); entry.getValue().releaseAuthoritativeTier(cacheStore.authoritativeTier); }