auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private AdalAuthorizatonGrant processPasswordGrant( AdalAuthorizatonGrant authGrant) throws Exception { if (!(authGrant.getAuthorizationGrant() instanceof ResourceOwnerPasswordCredentialsGrant)) { return authGrant; } ResourceOwnerPasswordCredentialsGrant grant = (ResourceOwnerPasswordCredentialsGrant) authGrant .getAuthorizationGrant(); UserDiscoveryResponse discoveryResponse = UserDiscoveryRequest .execute(this.authenticationAuthority .getUserRealmEndpoint(grant.getUsername())); <START> if (discoveryResponse.isAccountFederated()) { <END> WSTrustResponse response = WSTrustRequest.execute(MexParser .getWsTrustEndpointFromMexEndpoint(discoveryResponse .getFederationMetadataUrl()), grant.getUsername(), grant.getPassword().getValue()); AuthorizationGrant updatedGrant = null; if (response.isTokenSaml2()) { updatedGrant = new SAML2BearerGrant(new Base64URL( Base64.encodeBase64String(response.getToken() .getBytes()))); } else { updatedGrant = new SAML11BearerGrant(new Base64URL( Base64.encodeBase64String(response.getToken() .getBytes()))); } authGrant = new AdalAuthorizatonGrant(updatedGrant, authGrant.getCustomParameters()); } return authGrant; }</code><technical_language>if discovery response fails invalid, log here</technical_language>

Target:
private AdalAuthorizatonGrant processPasswordGrant( AdalAuthorizatonGrant authGrant) throws Exception { if (!(authGrant.getAuthorizationGrant() instanceof ResourceOwnerPasswordCredentialsGrant)) { return authGrant; } ResourceOwnerPasswordCredentialsGrant grant = (ResourceOwnerPasswordCredentialsGrant) authGrant .getAuthorizationGrant(); UserDiscoveryResponse discoveryResponse = UserDiscoveryRequest .execute(this.authenticationAuthority .getUserRealmEndpoint(grant.getUsername())); if (discoveryResponse.isAccountFederated()) { WSTrustResponse response = WSTrustRequest.execute(MexParser .getWsTrustEndpointFromMexEndpoint(discoveryResponse .getFederationMetadataUrl()), grant.getUsername(), grant.getPassword().getValue()); AuthorizationGrant updatedGrant = null; if (response.isTokenSaml2()) { updatedGrant = new SAML2BearerGrant(new Base64URL( Base64.encodeBase64String(response.getToken().getBytes( "UTF-8")))); } else { updatedGrant = new SAML11BearerGrant(new Base64URL( Base64.encodeBase64String(response.getToken() .getBytes()))); } authGrant = new AdalAuthorizatonGrant(updatedGrant, authGrant.getCustomParameters()); } return authGrant; }
Source:
<code>private void populateSubAttributeList(Object attributeValue) { String attributeType = getAttribute().getType(); if ("javax.management.openmbean.CompositeData".equals(attributeType)) { CompositeData data = (CompositeData) attributeValue; for (String key : data.getCompositeType().keySet()) { this.subAttributeList.put(key, new HashMap<String, Object>()); } } else if (("java.util.HashMap".equals(attributeType)) || ("java.util.Map".equals(attributeType))){ <START> HashMap<String, Double> data = (HashMap<String, Double>) attributeValue; <END> for (String key : data.keySet()) { this.subAttributeList.put(key, new HashMap<String, Object>()); } } }</code><technical_language>I this cast work in general case underlying attributeValue object is a HashMap. tested this a non-HashMap Map</technical_language>

Target:
private void populateSubAttributeList(Object attributeValue) { String attributeType = getAttribute().getType(); if ("javax.management.openmbean.CompositeData".equals(attributeType)) { CompositeData data = (CompositeData) attributeValue; for (String key : data.getCompositeType().keySet()) { this.subAttributeList.put(key, new HashMap<String, Object>()); } } else if (("java.util.HashMap".equals(attributeType)) || ("java.util.Map".equals(attributeType))){ Map<String, Double> data = (Map<String, Double>) attributeValue; for (String key : data.keySet()) { this.subAttributeList.put(key, new HashMap<String, Object>()); } } }
Source:
<code>public void setup() throws Exception { VerifiableProperties verProps = new VerifiableProperties(System.getProperties()); <START> azureDest = new AzureCloudDestination(new AzureCloudConfig(verProps), new MetricRegistry()); <END> cosmosCollectionLink = verProps.getString(AzureCloudConfig.COSMOS_COLLECTION_LINK); }</code><technical_language>AzureCloudDestinationFactory for more coverage</technical_language>

Target:
public void setup() throws Exception { VerifiableProperties verProps = new VerifiableProperties(System.getProperties()); azureDest = (AzureCloudDestination) new AzureCloudDestinationFactory(verProps, new MetricRegistry()).getCloudDestination(); cosmosCollectionLink = verProps.getString(AzureCloudConfig.COSMOS_COLLECTION_LINK); }
Source:
<code>private void checkArchiveAttributesAllowed() { if (getProject() == null || (isReference() <START> && getRefid().getReferencedObject(getProject()) instanceof ArchiveFileSet)) { <END> checkAttributesAllowed(); } }</code><technical_language>please whitespace changes separate PRs (or create all)</technical_language>

Target:
private void checkArchiveAttributesAllowed() { if (getProject() == null || (isReference() && (getRefid().getReferencedObject( getProject()) instanceof ArchiveFileSet))) { checkAttributesAllowed(); } }
Source:
<code>public void setUp() throws IOException { tmpFile = File.createTempFile("storage-debug", ".json"); tmpFile.deleteOnExit(); objectStorage = new JsonStorage<>(tmpFile, this.getClass().getClassLoader(), 0, 0, 0); <START> objectStorage.put("DummyObject", new DummyObject()); <END> }</code><technical_language>this done for test cases imho this part of single test. In testIntegerScale_fromCache testIntegerScale_fromDisk call</technical_language>

Target:
public void setUp() throws IOException { tmpFile = File.createTempFile("storage-debug", ".json"); tmpFile.deleteOnExit(); objectStorage = new JsonStorage<>(tmpFile, this.getClass().getClassLoader(), 0, 0, 0); }
Source:
<code>public WorkflowItemRest fromModel(XmlWorkflowItem obj) { WorkflowItemRest witem = new WorkflowItemRest(); Collection collection = obj.getCollection(); Item item = obj.getItem(); EPerson submitter = null; try { submitter = obj.getSubmitter(); <START> } catch (SQLException e) { <END> throw new RuntimeException(e.getMessage(), e); } witem.setId(obj.getID()); witem.setCollection(collection != null ? collectionConverter.convert(collection) : null); witem.setItem(itemConverter.convert(item)); witem.setSubmitter(epersonConverter.convert(submitter)); if (collection != null) { witem.setStatus(true); SubmissionDefinitionRest def = submissionDefinitionConverter .convert(submissionConfigReader.getSubmissionConfigByCollection(collection.getHandle())); witem.setSubmissionDefinition(def); for (SubmissionSectionRest sections : def.getPanels()) { SubmissionStepConfig stepConfig = submissionSectionConverter.toModel(sections); ClassLoader loader = this.getClass().getClassLoader(); Class stepClass; try { stepClass = loader.loadClass(stepConfig.getProcessingClassName()); Object stepInstance = stepClass.newInstance(); if (stepInstance instanceof AbstractRestProcessingStep) { AbstractRestProcessingStep stepProcessing = (AbstractRestProcessingStep) stepClass.newInstance(); for (ErrorRest error : stepProcessing.validate(submissionService, obj, stepConfig)) { addError(witem.getErrors(), error); witem.setStatus(false); } witem.getSections() .put(sections.getId(), stepProcessing.getData(submissionService, obj, stepConfig)); } else { log.warn("The submission step class specified by '" + stepConfig.getProcessingClassName() + "' does not extend the class org.dspace.app.rest.submit.AbstractRestProcessingStep!" + " Therefore it cannot be used by the Configurable Submission as the " + "<processing-class>!"); } } catch (Exception e) { log.error(e.getMessage(), e); } } } return witem; }</code><technical_language>I drop exception catching here, SQLException thrown method thrown there. Remove & here</technical_language>

Target:
public WorkflowItemRest fromModel(XmlWorkflowItem obj) { WorkflowItemRest witem = new WorkflowItemRest(); fillFromModel(obj, witem); return witem; }
Source:
<code>private ModuleType determineType(List<ModuleDeploymentRequest> modules) { Collections.sort(modules); Assert.isTrue(modules != null && modules.size() > 0, "at least one module required"); if (modules.size() == 1) { return modules.get(0).getType(); } ModuleType firstType = modules.get(0).getType(); ModuleType lastType = modules.get(modules.size() - 1).getType(); <START> boolean hasInput = (!firstType.equals(ModuleType.source)); <END> boolean hasOutput = (!lastType.equals(ModuleType.sink)); if (hasInput && hasOutput) { return ModuleType.processor; } if (hasInput) { return ModuleType.sink; } if (hasOutput) { return ModuleType.source; } throw new IllegalArgumentException("invalid module composition; must expose input and/or output channel"); }</code><technical_language>!= instead of equals()</technical_language>

Target:
private ModuleType determineType(List<ModuleDeploymentRequest> modules) { Collections.sort(modules); Assert.isTrue(modules != null && modules.size() > 0, "at least one module required"); if (modules.size() == 1) { return modules.get(0).getType(); } ModuleType firstType = modules.get(0).getType(); ModuleType lastType = modules.get(modules.size() - 1).getType(); boolean hasInput = firstType != ModuleType.source; boolean hasOutput = lastType != ModuleType.sink; if (hasInput && hasOutput) { return ModuleType.processor; } if (hasInput) { return ModuleType.sink; } if (hasOutput) { return ModuleType.source; } throw new IllegalArgumentException("invalid module composition; must expose input and/or output channel"); }
Source:
<code>public Set<ClusterComponent> getParcelComponentsByBlueprint(Stack stack) { Cluster cluster = stack.getCluster(); Set<ClusterComponent> components = getParcelComponents(cluster); <START> if (stack.isDatalake()) { <END> ClusterComponent stackComponent = components.stream() .filter(clusterComponent -> clusterComponent.getName().equals(StackType.CDH.name())) .findFirst().orElse(null); if (Objects.isNull(stackComponent)) { throw new NotFoundException("Runtime component not found!"); } return Set.of(stackComponent); } else { Map<String, ClusterComponent> cmProductMap = new HashMap<>(); Set<ClouderaManagerProduct> cmProducts = new HashSet<>(); for (ClusterComponent clusterComponent : components) { ClouderaManagerProduct product = clusterComponent.getAttributes().getSilent(ClouderaManagerProduct.class); cmProductMap.put(product.getName(), clusterComponent); cmProducts.add(product); } cmProducts = filterParcelsByBlueprint(cmProducts, cluster.getBlueprint()); return cmProducts.stream().map(cmp -> cmProductMap.get(cmp.getName())).collect(Collectors.toSet()); } }</code><technical_language>Add logs</technical_language>

Target:
public Set<ClusterComponent> getParcelComponentsByBlueprint(Stack stack) { Cluster cluster = stack.getCluster(); Set<ClusterComponent> components = getParcelComponents(cluster); if (stack.isDatalake()) { ClusterComponent stackComponent = components.stream() .filter(clusterComponent -> clusterComponent.getName().equals(StackType.CDH.name())) .findFirst().orElseThrow(() -> new NotFoundException("Runtime component not found!")); LOGGER.debug("For datalake clusters only the CDH parcel is used in CM: {}", stackComponent); return Set.of(stackComponent); } else { Map<String, ClusterComponent> cmProductMap = new HashMap<>(); Set<ClouderaManagerProduct> cmProducts = new HashSet<>(); for (ClusterComponent clusterComponent : components) { ClouderaManagerProduct product = clusterComponent.getAttributes().getSilent(ClouderaManagerProduct.class); cmProductMap.put(product.getName(), clusterComponent); cmProducts.add(product); } cmProducts = filterParcelsByBlueprint(cmProducts, cluster.getBlueprint(), false); LOGGER.debug("The following parcels are used in CM based on blueprint: {}", cmProducts); return cmProducts.stream().map(cmp -> cmProductMap.get(cmp.getName())).collect(Collectors.toSet()); } }
Source:
<code>public Function<A, Object> getLeftMapping(int joinerIndex) { <START> throw new UnsupportedOperationException(); <END> }</code><technical_language>change this to: throw new UnsupportedOperationException("Impossible state: getLeftMapping is called a NoneBiJoiner."); "Impossible state" is of saying: theoretically a 100% code do this, if do this, a bug fault, user</technical_language>

Target:
public Function<A, Object> getLeftMapping(int joinerIndex) { throw new UnsupportedOperationException("Impossible state: getLeftMapping() is never called on a NoneBiJoiner."); }
Source:
<code>public static <T> Iterable<T> latest(final Observable<? extends T> source) { return new Iterable<T>() { @Override public Iterator<T> iterator() { LatestObserverIterator<T> lio = new LatestObserverIterator<T>(); <START> lio.subscription = source.materialize().subscribe(lio); <END> return lio; } }; }</code><technical_language>This set races dereference of L101 NPE. Besides, set lio essentially (plus a transparent SafeSubscriber layer), need this field. call this.unsubscribe() L101</technical_language>

Target:
public static <T> Iterable<T> latest(final Observable<? extends T> source) { return new Iterable<T>() { @Override public Iterator<T> iterator() { LatestObserverIterator<T> lio = new LatestObserverIterator<T>(); source.materialize().subscribe(lio); return lio; } }; }
Source:
<code>public Set<String> listViews(String catalogName, String databaseName) { Catalog currentCatalog = catalogs.get(getCurrentCatalog()); try { return Stream.concat( currentCatalog.listViews(getCurrentDatabase()).stream(), <START> listTemporaryTablesInternal(catalogName, databaseName) .filter(e -> e.getValue() instanceof CatalogView) .map(e -> e.getKey().getObjectName()) ).collect(Collectors.toSet()); <END> } catch (DatabaseNotExistException e) { throw new ValidationException("Current database does not exist", e); } }</code><technical_language>add a method listTemporaryViews(String catalogName, String databaseName), listTemporaryViews() method this method</technical_language>

Target:
public Set<String> listViews(String catalogName, String databaseName) { Catalog currentCatalog = catalogs.get(getCurrentCatalog()); try { return Stream.concat( currentCatalog.listViews(getCurrentDatabase()).stream(), listTemporaryViewsInternal(catalogName, databaseName) .map(e -> e.getKey().getObjectName()) ).collect(Collectors.toSet()); } catch (DatabaseNotExistException e) { throw new ValidationException("Current database does not exist", e); } }
Source:
<code>public WebElement displayedToStudentCheckBox(int instrNum) { return browser.driver.findElement(By.cssSelector("#instructorTable" + instrNum <START> + " input[name=\"instructorisdisplayed\"]")); <END> }</code><technical_language>single quotes avoid escape enclosed double quotes (applies rest too)</technical_language>

Target:
public WebElement displayedToStudentCheckBox(int instrNum) { return browser.driver.findElement(By.cssSelector("#instructorTable" + instrNum + " input[name='" + Const.ParamsNames.INSTRUCTOR_IS_DISPLAYED_TO_STUDENT + "']")); }
Source:
<code>protected void sortByDateAdded() { <START> if (sortByAdded.isChecked()) { <END> return; } sortByAdded.setChecked(true); applicationSettings.setLastUsedSearchSortOrder(SearchSortOrder.Combined); refreshSearch(); }</code><technical_language>For this logic check applicationSettings.getLastUsedSearchSortOrder()</technical_language>

Target:
protected void sortByDateAdded() { if (applicationSettings.getLastUsedSearchSortOrder() == SearchSortOrder.Combined) { return; } invalidateOptionsMenu(); applicationSettings.setLastUsedSearchSortOrder(SearchSortOrder.Combined); refreshSearch(); }
Source:
<code>public static void initAuth(ConfigProvider configuration) { AuthScheme scheme = AuthScheme.BASIC; String username = configuration.getProperty(scheme, "username"); String password = configuration.getProperty(scheme, "password"); <START> if (username != null) { <END> LOG.info("Setting scheme: user: {}", scheme, username); registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory()); AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthSchemes.BASIC); Credentials credentials = new UsernamePasswordCredentials(username, password); credentialsProvider.setCredentials(authScope, credentials); } registryBuilder.register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()); credentialsProvider.setCredentials(AuthScope.ANY, DEFAULT_TOKEN_CREDENTIALS); authRegistry = registryBuilder.build(); }</code><technical_language>Is null/empty password valid? If not, check for username password null (or empty)? If username password is null/empty, logged (WARN)</technical_language>

Target:
public static void initAuth(ConfigProvider configuration) { AuthScheme scheme = AuthScheme.BASIC; String username = configuration.getProperty(scheme, "username"); String password = configuration.getProperty(scheme, "password"); if ((username != null) && (password != null)) { LOG.info("Setting up scheme {}", scheme); registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory()); AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthSchemes.BASIC); Credentials credentials = new UsernamePasswordCredentials(username, password); credentialsProvider.setCredentials(authScope, credentials); } else if ((username != null) || (password != null)) { LOG.warn("Not setting up scheme {}, missing credentials {}", scheme, (username == null) ? "username" : "password"); } registryBuilder.register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()); credentialsProvider.setCredentials(AuthScope.ANY, DEFAULT_TOKEN_CREDENTIALS); authRegistry = registryBuilder.build(); }
Source:
<code>private GetBlockLocationsResult getBlockLocationsInt(final String srcArg, final String src, final long offset, final long length, final boolean needBlockToken, final boolean checkSafeMode) throws IOException { if (offset < 0) { throw new HadoopIllegalArgumentException( "Negative offset is not supported. File: " + src); } if (length < 0) { throw new HadoopIllegalArgumentException( "Negative length is not supported. File: " + src); } GetBlockLocationsResult ret; final INodeFile inodeFile = INodeFile.valueOf(dir.getINode(src), src); if (inodeFile.isFileStoredInDB()) { LOG.debug("SMALL_FILE The file is stored in the database. Returning Phantom Blocks"); ret = getPhantomBlockLocationsUpdateTimes(srcArg, src, needBlockToken); } else { ret = getBlockLocationsInt(srcArg, src, offset, length, needBlockToken); } if (checkSafeMode && isInSafeMode()) { for (LocatedBlock b : ret.blocks.getLocatedBlocks()) { if ((b.getLocations() == null) || (b.getLocations().length == 0)) { SafeModeException se = new SafeModeException( "Zero blocklocations for " + src, safeMode()); throw new RetriableException(se); } } <START> } <END> inodeFile.logProvenanceEvent(FileProvenanceEntry.Operation.getBlockLocations()); return ret; }</code><technical_language>Do support this for now? operation is run a READ lock work</technical_language>

Target:
private GetBlockLocationsResult getBlockLocationsInt(final String srcArg, final String src, final long offset, final long length, final boolean needBlockToken, final boolean checkSafeMode) throws IOException { if (offset < 0) { throw new HadoopIllegalArgumentException( "Negative offset is not supported. File: " + src); } if (length < 0) { throw new HadoopIllegalArgumentException( "Negative length is not supported. File: " + src); } GetBlockLocationsResult ret; final INodeFile inodeFile = INodeFile.valueOf(dir.getINode(src), src); if (inodeFile.isFileStoredInDB()) { LOG.debug("SMALL_FILE The file is stored in the database. Returning Phantom Blocks"); ret = getPhantomBlockLocationsUpdateTimes(srcArg, src, needBlockToken); } else { ret = getBlockLocationsInt(srcArg, src, offset, length, needBlockToken); } if (checkSafeMode && isInSafeMode()) { for (LocatedBlock b : ret.blocks.getLocatedBlocks()) { if ((b.getLocations() == null) || (b.getLocations().length == 0)) { SafeModeException se = new SafeModeException( "Zero blocklocations for " + src, safeMode()); throw new RetriableException(se); } } } inodeFile.logProvenanceEvent(getNamenodeId(), FileProvenanceEntry.Operation.getBlockLocations()); return ret; }
Source:
<code>public GraphicCanvas(Composite parent) { super(parent); m_objects = new ArrayList<IGraphicObject>(); Listener mouseListener = new Listener() { public void handleEvent(Event event) { switch (event.type) { case SWT.MouseEnter: case SWT.MouseMove: <START> IGraphicObject obj = getGraphicObject(event.x, event.y); <END> String tooltip = obj.getTooltip(); setToolTipText(tooltip); break; } } }; addListener(SWT.MouseMove, mouseListener); addListener(SWT.MouseEnter, mouseListener); }</code><technical_language>protect obj null</technical_language>

Target:
public GraphicCanvas(Composite parent) { super(parent); m_objects = new ArrayList<IGraphicObject>(); Listener mouseListener = new Listener() { public void handleEvent(Event event) { switch (event.type) { case SWT.MouseEnter: case SWT.MouseMove: IGraphicObject obj = getGraphicObject(event.x, event.y); String tooltip = obj.getTooltip(event.x, event.y); setToolTipText(tooltip); break; } } }; addListener(SWT.MouseMove, mouseListener); addListener(SWT.MouseEnter, mouseListener); }
Source:
<code>public LdapUserData getUserByAid(String aid, LDAPConnection conn) { <START> String filter = ldapAttributeMapper.getFindUserByAidFilter(aid.replaceAll("@OX.AC.UK", "")); <END> LdapUserData mappedEntry = null; try { mappedEntry = (LdapUserData) searchDirectoryForSingleEntry(filter, conn, null, null, null); } catch (LDAPException e) { M_log.error("Failed to find user for AID: " + aid, e); } return mappedEntry; }</code><technical_language>Robert mentioned in shibboleth domain is lowercase be@ox.ac.uk. replaceAll() takes a regular expressions escaped</technical_language>

Target:
public LdapUserData getUserByAid(String aid, LDAPConnection conn) { String filter = ldapAttributeMapper.getFindUserByAidFilter(aid.replace("@ox.ac.uk", "")); LdapUserData mappedEntry = null; try { mappedEntry = (LdapUserData) searchDirectoryForSingleEntry(filter, conn, null, null, null); } catch (LDAPException e) { M_log.error("Failed to find user for AID: " + aid, e); } return mappedEntry; }
Source:
<code>public void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); <START> assertEquals("[Test] \nExpecting:\n <[\"Yoda\", \"Luke\"]>\nto not start with:\n <[\"Han\", \"Leia\"]>\n", <END> message); }</code><technical_language>assertThat instead of assertEquals :)</technical_language>

Target:
public void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); assertThat(message).isEqualTo("[Test] \nExpecting:\n <[\"Yoda\", \"Luke\"]>\nto not start with:\n " + "<[\"Han\", \"Leia\"]>\n"); }
Source:
<code>private boolean valueEquals(SAMBinaryTagAndValue that) { if (this.value == null) { return that.value == null; } else if (that.value == null) { return false; } else if (this.value instanceof byte[]) { return that.value instanceof byte[] ? Arrays.equals((byte[])this.value, (byte[])that.value) : false; } else if (this.value instanceof short[]) { return that.value instanceof short[] ? Arrays.equals((short[])this.value, (short[])that.value) : false; } else if (this.value instanceof int[]) { return that.value instanceof int[] ? Arrays.equals((int[])this.value, (int[])that.value) : false; } else if (this.value instanceof float[]) { return that.value instanceof float[] ? Arrays.equals((float[])this.value, (float[])that.value) : false; } else { <START> return this.value.equals(that.value); <END> } }</code><technical_language>include a note explaining double, char, long included</technical_language>

Target:
private boolean valueEquals(SAMBinaryTagAndValue that) { if (this.value instanceof byte[]) { return that.value instanceof byte[] ? Arrays.equals((byte[])this.value, (byte[])that.value) : false; } else if (this.value instanceof short[]) { return that.value instanceof short[] ? Arrays.equals((short[])this.value, (short[])that.value) : false; } else if (this.value instanceof int[]) { return that.value instanceof int[] ? Arrays.equals((int[])this.value, (int[])that.value) : false; } else if (this.value instanceof float[]) { return that.value instanceof float[] ? Arrays.equals((float[])this.value, (float[])that.value) : false; } else { return this.value.equals(that.value); } }
Source:
<code>private void validateIdentifier(final Contentlet contentlet) { if (UtilMethods.isSet(contentlet.getIdentifier())) { boolean isIdentifier = false; try { <START> isIdentifier = APILocator.getIdentifierAPI().isIdentifier(contentlet.getIdentifier()); <END> } catch (DotDataException e) { isIdentifier = false; } if (!isIdentifier) { throw new DoesNotExistException("The identifier: " + contentlet.getIdentifier() + " does not exists"); } } }</code><technical_language>Is performance care here? If shortyapi. this lookup caches result. Usage shortyAPI.getShorty(contentlet.getIdentifier()).isPreset() && shortyAPI.getShorty(contentlet.getIdentifier()).get().shortType==ShortType.Identifier)</technical_language>

Target:
private void validateIdentifier(final Contentlet contentlet) { if (UtilMethods.isSet(contentlet.getIdentifier())) { final Optional<ShortyId> shortyId = APILocator.getShortyAPI().getShorty(contentlet.getIdentifier()); final boolean isIdentifier = shortyId.isPresent() && shortyId.get().subType== ShortType.IDENTIFIER; if (!isIdentifier) { throw new DoesNotExistException("The identifier: " + contentlet.getIdentifier() + " does not exists"); } } }
Source:
<code>public void zoom(boolean zoomIn) { Point cursorDisplayLocation = getDisplay().getCursorLocation(); Point cursorControlLocation = toControl(cursorDisplayLocation); Point cursorScaleLocation = fTimeGraphScale.toControl(cursorDisplayLocation); <START> if (!getBounds().contains(cursorControlLocation) && !fTimeGraphScale.getBounds().contains(cursorScaleLocation)) { <END> return; } int nameSpace = fTimeProvider.getNameSpace(); int timeSpace = fTimeProvider.getTimeSpace(); int xPos = Math.max(nameSpace, Math.min(nameSpace + timeSpace, cursorControlLocation.x)); long time0 = fTimeProvider.getTime0(); long time1 = fTimeProvider.getTime1(); long interval = time1 - time0; if (interval == 0) { interval = 1; } long newInterval; if (zoomIn) { newInterval = Math.max(Math.round(interval * ZOOM_IN_FACTOR), fTimeProvider.getMinTimeInterval()); } else { newInterval = (long) Math.ceil(interval * ZOOM_OUT_FACTOR); } long center = time0 + Math.round(((double) (xPos - nameSpace) / timeSpace * interval)); long newTime0 = center - Math.round((double) newInterval * (center - time0) / interval); newTime0 = Math.max(fTimeProvider.getMinTime(), Math.min(newTime0, fTimeProvider.getMaxTime() - newInterval)); long newTime1 = newTime0 + newInterval; fTimeProvider.setStartFinishTimeNotify(newTime0, newTime1); }</code><technical_language>This work for scale bounds in coordinates of scale's parent, location is in coordinates of scale (and scale's bounds start 0 in parent's coordinates). This error caused zoom work mouse is horizontal scroll bar. If coordinates fixed, horizontal bar is out of bounds of time graph control needs checked separately</technical_language>

Target:
public void zoom(boolean zoomIn) { Point cursorDisplayLocation = getDisplay().getCursorLocation(); Point cursorControlLocation = getParent().toControl(cursorDisplayLocation); Rectangle controlBounds = getBounds(); if (!controlBounds.contains(cursorControlLocation.x, controlBounds.y)) { return; } int nameSpace = fTimeProvider.getNameSpace(); int timeSpace = fTimeProvider.getTimeSpace(); int xPos = Math.max(nameSpace, Math.min(nameSpace + timeSpace, cursorControlLocation.x)); long time0 = fTimeProvider.getTime0(); long time1 = fTimeProvider.getTime1(); long interval = time1 - time0; if (interval == 0) { interval = 1; } long newInterval; if (zoomIn) { newInterval = Math.max(Math.round(interval * ZOOM_IN_FACTOR), fTimeProvider.getMinTimeInterval()); } else { newInterval = (long) Math.ceil(interval * ZOOM_OUT_FACTOR); } long center = time0 + Math.round(((double) (xPos - nameSpace) / timeSpace * interval)); long newTime0 = center - Math.round((double) newInterval * (center - time0) / interval); newTime0 = Math.max(fTimeProvider.getMinTime(), Math.min(newTime0, fTimeProvider.getMaxTime() - newInterval)); long newTime1 = newTime0 + newInterval; fTimeProvider.setStartFinishTimeNotify(newTime0, newTime1); }
Source:
<code>public CustomThreadListAdapter(HomeActivity activity, String label, ListView listView, List<MailThread> mails) { super(); this.label = label; this.activity = activity; this.listView = listView; this.threads = new ArrayList<>(); <START> this.threads_in_DB = new ArrayList<>(); <END> this.threads_not_in_DB = new ArrayList<>(); threads_in_DB = mails; refreshThreads(); }</code><technical_language>need this anymore ? instance after</technical_language>

Target:
public CustomThreadListAdapter(HomeActivity activity, String label, ListView listView, List<MailThread> mails) { super(); this.label = label; this.activity = activity; this.listView = listView; this.threads = new ArrayList<>(); this.threads_not_in_DB = new ArrayList<>(); this.threads_in_DB = mails; refreshThreads(); }
Source:
<code>private void createColumns(final Composite parent, final TableViewer viewer) { String[] titles = { "Function", "New Overhead (%)", "Old Overhead (%)", "Result", "Event", "" }; int[] bounds = { 100, 133, 135, 100, 100, 1 }; final PerfDiffTableSorter tableSorter = new PerfDiffTableSorter(); final Table table = tableviewer.getTable(); for (int i = 0; i < titles.length; i++) { <START> final int index = i; <END> createTableViewerColumn(titles[i], bounds[i], index, tableSorter, table); } tableviewer.setLabelProvider(new PerfDiffLabelProvider()); tableviewer.setSorter(tableSorter); }</code><technical_language>point of saving i index ? pass createTableViewerColumn directly</technical_language>

Target:
private void createColumns(final Composite parent, final TableViewer viewer) { final PerfDiffTableSorter tableSorter = new PerfDiffTableSorter(); final Table table = tableviewer.getTable(); for (int i = 0; i < COL_TITLES.length; i++) { createTableViewerColumn(COL_TITLES[i], COL_BOUNDS[i], i, tableSorter, table); } tableviewer.setLabelProvider(new PerfDiffLabelProvider()); tableviewer.setSorter(tableSorter); }
Source:
<code>public void shouldSolveProblem() throws Exception { Problem problem = new Problem(); problem.setId(5); problem.setMessage("Fix it!"); Solution solution = new Solution(); solution.setId(7); solution.setMessage("Fixed"); workflowService.setProblem(problem); workflowService.setSolution(solution); Task currentTask = taskService.getById(7); workflowService.reportProblem(currentTask); currentTask = taskService.getById(5); workflowService.solveProblem(currentTask); Task correctionTask = taskService.getById(7); Process process = currentTask.getProcess(); for (Task task : process.getTasks()) { if (currentTask.getOrdering() < task.getOrdering() && task.getOrdering() < correctionTask.getOrdering()) { <START> System.out.println(task.getTitle() + " " + task.getProcessingStatusAsString()); <END> assertEquals("Solve of problem was incorrect - tasks between were not set up to done!", TaskStatus.DONE, task.getProcessingStatusEnum()); } } assertEquals("Solve of problem was incorrect - tasks from which correction was send was not set up to open!", TaskStatus.OPEN, correctionTask.getProcessingStatusEnum()); MockDatabase.cleanDatabase(); MockDatabase.insertProcessesForWorkflowFull(); }</code><technical_language>I think, this line is needed or</technical_language>

Target:
public void shouldSolveProblem() throws Exception { Problem problem = new Problem(); problem.setId(5); problem.setMessage("Fix it!"); Solution solution = new Solution(); solution.setId(7); solution.setMessage("Fixed"); workflowService.setProblem(problem); workflowService.setSolution(solution); Task currentTask = taskService.getById(7); workflowService.reportProblem(currentTask); currentTask = taskService.getById(5); workflowService.solveProblem(currentTask); Task correctionTask = taskService.getById(7); Process process = currentTask.getProcess(); for (Task task : process.getTasks()) { if (currentTask.getOrdering() < task.getOrdering() && task.getOrdering() < correctionTask.getOrdering()) { assertEquals("Solve of problem was incorrect - tasks between were not set up to done!", TaskStatus.DONE, task.getProcessingStatusEnum()); } } assertEquals("Solve of problem was incorrect - tasks from which correction was send was not set up to open!", TaskStatus.OPEN, correctionTask.getProcessingStatusEnum()); MockDatabase.cleanDatabase(); MockDatabase.insertProcessesForWorkflowFull(); }
Source:
<code>public boolean doubleClick(final String place) { boolean result = false; try { WebElement element = getElementToClick(place); result = doubleClickElement(element); <START> } catch (WebDriverException e) { <END> String msg = e.getMessage(); if (msg == null || !msg.contains("Other element would receive the double click")) { throw e; } } return result; }</code><technical_language>I this catch block removed. standard WaitUntil handling sufficient I believe</technical_language>

Target:
public boolean doubleClick(final String place) { WebElement element = getElementToClick(place); boolean result = false; if (element != null) { scrollIfNotOnScreen(element); if (isInteractable(element)) { WebDriver driver = getSeleniumHelper().driver(); Actions action = new Actions(driver); action.doubleClick(element).perform(); result = true; } } return result; }
Source:
<code>private static String doReplace(JsonObject object, String input) { String result = input; <START> for (Entry<String, JsonElement> key : object.entrySet()) { <END> JsonElement jsonElement = object.get(key.getKey()); if (jsonElement.isJsonPrimitive()) { String search = "${" + key + "}"; String replace = jsonElement.getAsString(); int index = result.indexOf(search); while (index > -1) { result = result.substring(0, index) + replace + result.substring(index + search.length()); index = result.indexOf(search); } } } return result; }</code><technical_language>call "entry"</technical_language>

Target:
private static String doReplace(JsonObject object, String input) { String result = input; for (Entry<String, JsonElement> entry : object.entrySet()) { String key = entry.getKey(); JsonElement jsonElement = object.get(key); if (jsonElement.isJsonPrimitive()) { String search = "${" + key + "}"; String replace = jsonElement.getAsString(); int index = result.indexOf(search); while (index > -1) { result = result.substring(0, index) + replace + result.substring(index + search.length()); index = result.indexOf(search); } } } return result; }
Source:
<code>public void setupManager( String startPoint, String inputFile, String protocol, String host, int port, String extention, int ThreadNumber, boolean doDirs, boolean doFiles, boolean recursive, boolean blankExt, Vector extToUse) { totalDone = 0; this.startPoint = startPoint; this.inputFile = inputFile; this.firstPartOfURL = protocol + "://" + host + ":" + port; this.extention = extention; this.protocol = protocol; this.host = host; this.port = port; workerCount = ThreadNumber; this.doFiles = doFiles; this.doDirs = doDirs; this.recursive = recursive; this.blankExt = blankExt; this.extToUse = extToUse; URL url; try { url = new URL(firstPartOfURL + startPoint); } catch (MalformedURLException ex) { <START> LOG.error(ex); <END> } LOG.info("Starting dir/file list based brute forcing"); setpUpHttpClient(); createTheThreads(); workGen = new WorkerGenerator(this); }</code><technical_language>consistent throughout, ex: ("Bad URL", ex) ("Malformed URL", ex)</technical_language>

Target:
public void setupManager( String startPoint, String inputFile, String protocol, String host, int port, String extention, int ThreadNumber, boolean doDirs, boolean doFiles, boolean recursive, boolean blankExt, Vector extToUse) { totalDone = 0; this.startPoint = startPoint; this.inputFile = inputFile; this.firstPartOfURL = protocol + "://" + host + ":" + port; this.extention = extention; this.protocol = protocol; this.host = host; this.port = port; workerCount = ThreadNumber; this.doFiles = doFiles; this.doDirs = doDirs; this.recursive = recursive; this.blankExt = blankExt; this.extToUse = extToUse; URL url; try { url = new URL(firstPartOfURL + startPoint); } catch (MalformedURLException ex) { LOG.error("Bad URL", ex); } LOG.info("Starting dir/file list based brute forcing"); setpUpHttpClient(); createTheThreads(); workGen = new WorkerGenerator(this); }
Source:
<code><START> public void clearAnnotation(String operationId) { <END> processEngine.getHistoryService() .clearAnnotationForOperationLogById(operationId); }</code><technical_language>return a Response object noContent instead of void, able change return stay backwards-compatible</technical_language>

Target:
public Response clearAnnotation(String operationId) { processEngine.getHistoryService() .clearAnnotationForOperationLogById(operationId); return Response.noContent().build(); }
Source:
<code>private void setDefaultMessageListener() { setMessageListener(new ISwrveMessageListener() { public void onMessage(final SwrveMessage message) { if (SwrveBase.this.context != null) { final Context ctx = SwrveBase.this.context.get(); if (ctx == null) { SwrveLogger.e(LOG_TAG, "Can't display a in-app message without a context"); return; } Intent intent = new Intent(ctx, SwrveInAppMessageActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra("inAppMessage", message); intent.putExtra("hideToolbar", config.isHideToolbar()); intent.putExtra("minSampleSize", config.getMinSampleSize()); <START> intent.putExtra("defaultBackgroundColor", config.getDefaultBackgroundColor()); <END> Handler iamHandler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { try { Bundle bundle = msg.peekData(); String eventType = bundle.getString("eventType"); processIAMMessage(message, eventType, bundle); } catch(Exception exp) { SwrveLogger.e(LOG_TAG, "Swrve IAM event from Activity error", exp); } return true; } }); intent.putExtra("messenger", new Messenger(iamHandler)); ctx.startActivity(intent); } } }); }</code><technical_language>constants for values: inAppMessage, hideToolbar, minSampleSize, defaultBackgroundColor</technical_language>

Target:
private void setDefaultMessageListener() { setMessageListener(new ISwrveMessageListener() { public void onMessage(final SwrveMessage message) { if (SwrveBase.this.context != null) { final Context ctx = SwrveBase.this.context.get(); if (ctx == null) { SwrveLogger.e(LOG_TAG, "Can't display a in-app message without a context"); return; } Intent intent = new Intent(ctx, SwrveInAppMessageActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra(SwrveInAppMessageActivity.MESSAGE_ID_KEY, message.getId()); ctx.startActivity(intent); } } }); }
Source:
<code>public Response update(@PathParam("id") long id, User entity) throws SQLException { User old = Context.getPermissionsManager().getUser(entity.getId()); if (old.getExpirationTime() == null && entity.getExpirationTime() != null || old.getExpirationTime() != null && !old.getExpirationTime().equals(entity.getExpirationTime()) || old.getAdmin() != entity.getAdmin() || old.getReadonly() != entity.getReadonly() || old.getDisabled() != entity.getDisabled() || old.getDeviceLimit() != entity.getDeviceLimit() <START> || !old.getToken().equals(entity.getToken())) { <END> Context.getPermissionsManager().checkAdmin(getUserId()); } else { Context.getPermissionsManager().checkUser(getUserId(), entity.getId()); } Context.getPermissionsManager().updateUser(entity); if (Context.getNotificationManager() != null) { Context.getNotificationManager().refresh(); } return Response.ok(entity).build(); }</code><technical_language>if null? Is possible</technical_language>

Target:
public Response update(@PathParam("id") long id, User entity) throws SQLException { User old = Context.getPermissionsManager().getUser(entity.getId()); if (old.getExpirationTime() == null && entity.getExpirationTime() != null || old.getExpirationTime() != null && !old.getExpirationTime().equals(entity.getExpirationTime()) || old.getAdmin() != entity.getAdmin() || old.getReadonly() != entity.getReadonly() || old.getDisabled() != entity.getDisabled() || old.getDeviceLimit() != entity.getDeviceLimit() || old.getToken() == null && entity.getToken() != null || old.getToken() != null && !old.getToken().equals(entity.getToken())) { Context.getPermissionsManager().checkAdmin(getUserId()); } else { Context.getPermissionsManager().checkUser(getUserId(), entity.getId()); } Context.getPermissionsManager().updateUser(entity); if (Context.getNotificationManager() != null) { Context.getNotificationManager().refresh(); } return Response.ok(entity).build(); }
Source:
<code>public Iterable<Map<String, String>> list() { return Iterables.transform(store.entries(), new Function<Map.Entry<Integer, Location>, Map<String, String>>() { @Override public Map<String, String> apply(Map.Entry<Integer, Location> entry) { <START> return asMap(entry.getKey(), entry.getValue()); <END> } }); }</code><technical_language>I agree this. Map returned a list() method is amusing, in a REST world sense. observation is Location id field, a name field (note inconsistency enitty.getDisplayName). for location pattern entity, integer keys? I strong feelings here</technical_language>

Target:
public Iterable<LocationSummary> list() { return Iterables.transform(store.entries(), new Function<Map.Entry<Integer, Location>, LocationSummary>() { @Override public LocationSummary apply(Map.Entry<Integer, Location> entry) { return new LocationSummary(entry.getKey().toString(), entry.getValue()); } }); }
Source:
<code>public List<Sample> getLast24hours( @Scope({OAuthScope.SENSORS_BASIC}) final AccessToken accessToken, @PathParam("sensor") String sensor, @QueryParam("from_utc") Long queryEndTimestampUTC) { <START> final int slotDurationInMinutes = 1; <END> final long queryStartTimeUTC = new DateTime(queryEndTimestampUTC, DateTimeZone.UTC).minusHours(24).getMillis(); final Optional<Long> deviceId = deviceDAO.getMostRecentSenseByAccountId(accessToken.accountId); if(!deviceId.isPresent()) { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).build()); } return deviceDataDAO.generateTimeSeriesByUTCTime(queryStartTimeUTC, queryEndTimestampUTC, accessToken.accountId, deviceId.get(), slotDurationInMinutes, sensor, missingDataDefaultValue(accessToken.accountId)); }</code><technical_language>is this changed</technical_language>

Target:
public List<Sample> getLast24hours( @Scope({OAuthScope.SENSORS_BASIC}) final AccessToken accessToken, @PathParam("sensor") String sensor, @QueryParam("from_utc") Long queryEndTimestampUTC) { validateQueryRange(queryEndTimestampUTC, DateTime.now(), accessToken.accountId, allowedRangeInSeconds); final int slotDurationInMinutes = 5; final long queryStartTimeUTC = new DateTime(queryEndTimestampUTC, DateTimeZone.UTC).minusHours(24).getMillis(); final Optional<Long> deviceId = deviceDAO.getMostRecentSenseByAccountId(accessToken.accountId); if(!deviceId.isPresent()) { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).build()); } return deviceDataDAO.generateTimeSeriesByUTCTime(queryStartTimeUTC, queryEndTimestampUTC, accessToken.accountId, deviceId.get(), slotDurationInMinutes, sensor, missingDataDefaultValue(accessToken.accountId)); }
Source:
<code>public void close() throws IOException { if (out != null) { try { finish(); } finally { try { def.end(); } catch (Exception e) { } <START> try { out.close(); } catch (Exception e) { } <END> out = null; } } }</code><technical_language>closeQuietly called</technical_language>

Target:
public void close() throws IOException { if (out != null) { try { finish(); } finally { try { def.end(); } catch (Exception ignored) { } IoUtils.closeQuietly(out); out = null; } } }
Source:
<code>public void testImportViaFileManager() throws Exception { File archive = getArchiveFile("test-data/testCSVArchive.zip"); FileManager fm = Framework.getService(FileManager.class); Blob blob = Blobs.createBlob(archive); FileImporterContext context = FileImporterContext.builder(coreSession, blob, workspace1.getPathAsString()) .overwrite(true) .build(); fm.createOrUpdateDocument(context); DocumentModelList children = coreSession.getChildren(workspace1.getRef()); <START> assertSame(2, children.size()); <END> DocumentModel MyFile = coreSession.getChild(workspace1.getRef(), "MyFile"); DocumentModel MyNote = coreSession.getChild(workspace1.getRef(), "MyNote"); assertEquals("My File", MyFile.getTitle()); assertEquals("My Note", MyNote.getTitle()); assertEquals("MyFile", MyFile.getName()); assertEquals("MyNote", MyNote.getName()); assertEquals("this is text", MyNote.getProperty("note", "note")); assertNotNull(MyFile.getProperty("file", "content")); }</code><technical_language>shoud assertEquals this. assertSame is check reference equality. arguments boxed a reason</technical_language>

Target:
public void testImportViaFileManager() throws Exception { File archive = getArchiveFile("test-data/completeZipTestArchive.zip"); FileManager fm = Framework.getService(FileManager.class); Blob blob = Blobs.createBlob(archive); FileImporterContext context = FileImporterContext.builder(coreSession, blob, workspace1.getPathAsString()) .overwrite(true) .build(); fm.createOrUpdateDocument(context); DocumentModelList children = coreSession.getChildren(workspace1.getRef()); assertEquals(2, children.size()); DocumentModel MyFile = coreSession.getChild(workspace1.getRef(), "My File"); DocumentModel MyNote = coreSession.getChild(workspace1.getRef(), "MyNote"); assertEquals("My File", MyFile.getTitle()); assertEquals("My Note", MyNote.getTitle()); assertEquals("My File", MyFile.getName()); assertEquals("MyNote", MyNote.getName()); assertEquals("this is text", MyNote.getPropertyValue("note:note")); assertNotNull(MyFile.getPropertyValue("file:content")); List<String> contributors = Arrays.asList((String[]) MyFile.getPropertyValue("dc:contributors")); assertEquals(4, contributors.size()); assertEquals("project", MyFile.getCurrentLifeCycleState()); assertEquals("approved", MyNote.getCurrentLifeCycleState()); List<HashMap> tags = (List<HashMap>) MyFile.getPropertyValue("nxtag:tags"); assertEquals(1, tags.size()); assertEquals("mynewtag", tags.get(0).get("label")); assertEquals(2, ((List<String>) MyNote.getPropertyValue("nxtag:tags")).size()); }
Source:
<code>public boolean isPutIntoOven() throws OvenException, BurntException { try { long begin = System.currentTimeMillis(); final URL url = new URL("<LINK_0>"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.addRequestProperty("User-Agent", "Potato/1.7.5"); connection.connect(); int inOven = connection.getResponseCode(); long bakeTime = (System.currentTimeMillis() - begin); <START> if (bakeTime > 1000) throw new BurntException(bakeTime); <END> return inOven == 200; } catch (IOException ex) { throw new OvenException(ex); } }</code><technical_language>this time changed? This do horseradish</technical_language>

Target:
public boolean isPutIntoOven() throws OvenException, BurntException { try { long begin = System.currentTimeMillis(); final URL url = new URL("<LINK_0>"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.addRequestProperty("User-Agent", "Potato/1.7.5"); connection.connect(); int inOven = connection.getResponseCode(); long bakeTime = (System.currentTimeMillis() - begin); if (bakeTime > 1100) throw new BurntException(bakeTime); return inOven == 200; } catch (IOException ex) { throw new OvenException(ex); } }