auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void validate(Object object, Errors errors) { if(object == null){ throw new IllegalArgumentException("The object parameter should not be null"); } if(!(object instanceof Condition)){ throw new IllegalArgumentException("The object parameter should be of type " + Condition.class); } Condition condition = (Condition) object; if(condition.getCondition() == null){ throw new APIException("The condition parameter is required"); } if(condition.getClinicalStatus() == null){ throw new APIException("The clinical status is required"); } }

Target:
public void validate(Object object, Errors errors) { if(object == null){ throw new IllegalArgumentException("The object parameter should not be null"); } if(!(object instanceof Condition)){ throw new IllegalArgumentException("The object parameter should be of type " + Condition.class); } Condition condition = (Condition) object; if(condition.getCondition() == null){ errors.rejectValue("condition", "Condition.conditionShouldNotBeNull", "The condition is required"); } if(condition.getClinicalStatus() == null){ errors.rejectValue("clinicalStatus", "Condition.clinicalStatusShouldNotBeNull", "The clinical status is required"); } }
Source:
private void dropStrict() throws IOException { if ( index != null ) { index.close(); index = null; } fileSystem.deleteFile( storeFile ); }

Target:
private void dropStrict() throws IOException { if ( index != null ) { index.close(); index = null; } fileSystem.deleteFileOrThrow( storeFile ); }
Source:
public String toString() { return "[" + a.toString() + ", " + b.toString() + "]"; }

Target:
public String toString() { return "[" + a + ", " + b + "]"; }
Source:
private void skip(long timestamp) { try { long offset = frameSize * (timestamp / period / 1000000L); byte[] skip = new byte[(int) offset]; int bytesRead = 0; buff.position(0); buff.limit(skip.length); while (bytesRead < skip.length && buff.remaining() > 0) { int len = rbChannel.read(buff.get(skip)); if (len == -1) return; totalRead += len; bytesRead += len; } } catch (IOException e) { logger.error(e); } }

Target:
private void skip(long timestamp) { try { long offset = frameSize * (timestamp / period / 1000000L); byte[] skip = new byte[(int) offset]; int buffSize = header.length + skip.length; if (buff.capacity()< skip.length){ ByteBuffer newBuff = ByteBuffer.allocate(buffSize); newBuff.put((ByteBuffer) buff.flip()); buff = newBuff; } buff.position(header.length); int bytesRead = rbChannel.read(buff); while (bytesRead < skip.length && buff.remaining() > 0) { int len = rbChannel.read(ByteBuffer.wrap(skip, bytesRead , skip.length - bytesRead)); if (len == -1) { return; } totalRead += len; bytesRead += len; } } catch (IOException e) { logger.error(e); } }
Source:
public static Cipher getInstance( Properties props, CipherTransformation transformation) throws IOException { try { List<Class<? extends Cipher>> klasses = getCipherClasses(props); Cipher cipher = null; if (klasses != null) { for (Class<? extends Cipher> klass : klasses) { try { cipher = ReflectionUtils.newInstance(klass, props, transformation); if(cipher != null) { LOG.debug("Using cipher for transformation {}.", klass.getName(), transformation.getName()); break; } } catch (Exception e) { LOG.debug("Cipher is not available or transformation is not supported.", klass.getName(), transformation.getName()); } } } return (cipher == null) ? new JceCipher(props, transformation) : cipher; } catch (GeneralSecurityException e) { throw new IOException(e); } }

Target:
public static Cipher getInstance( Properties props, CipherTransformation transformation) throws IOException { try { List<Class<? extends Cipher>> klasses = getCipherClasses(props); Cipher cipher = null; if (klasses != null) { for (Class<? extends Cipher> klass : klasses) { try { cipher = ReflectionUtils.newInstance(klass, props, transformation); if(cipher != null) { LOG.debug("Using cipher for transformation {}.", klass.getName(), transformation.getName()); break; } } catch (Exception e) { LOG.error("Cipher is not available or transformation is not supported.", klass.getName(), transformation.getName()); } } } return (cipher == null) ? new JceCipher(props, transformation) : cipher; } catch (GeneralSecurityException e) { throw new IOException(e); } }
Source:
public static boolean validQuestionGroups(final Survey survey){ return survey.getQuestionGroupMap().values().stream().filter(i -> i.getRepeatable().booleanValue()).collect(Collectors.toList()).size() == 0; }

Target:
public static boolean validQuestionGroups(final Survey survey) { return survey.getQuestionGroupMap().values().stream().filter(i -> i.getRepeatable()).collect(Collectors.toList()).size() == 0; }
Source:
public void createPOM(File pomLocation) throws Exception { ProjectDataModel modelkushan = getModel(); log.info("ProjectDataModel sucssefully created"); MavenInfo mavenInfo = modelkushan.getMavenInfo(); log.info("MavenInfo sucssefully created"); String customGroupId = preferencesService.getString("org.wso2.developerstudio.eclipse.platform.ui", GLOBAL_MAVEN_GROUP_ID, null, null); String customVersion = preferencesService.getString("org.wso2.developerstudio.eclipse.platform.ui", GLOBAL_MAVEN_VERSION, null, null); MavenProject mavenProject = MavenUtils.createMavenProject(customGroupId != null ? customGroupId : mavenInfo.getGroupId(), mavenInfo.getArtifactId(), customVersion != null ? customVersion : mavenInfo.getVersion(), mavenInfo.getPackageName()); Parent parentProject = getModel().getMavenInfo().getParentProject(); log.info("parent project creartion sucsseful"); if (parentProject != null) { log.info("if parent null"); mavenProject.getModel().setParent(parentProject); log.info("get model and set parent"); } String disableWSO2Repo = preferencesService.getString("org.wso2.developerstudio.eclipse.platform.ui", DISABLE_WSO2_REPOSITORY, null, null); if (disableWSO2Repo == null) { log.info("if disable reapo"); MavenUtils.updateMavenRepo(mavenProject); log.info("update reapo"); } Repository globalRepositoryFromPreference = getGlobalRepositoryFromPreference(); log.info("global repo"); if (globalRepositoryFromPreference != null) { log.info("if global repo null"); mavenProject.getModel().addRepository(globalRepositoryFromPreference); log.info("add repo"); mavenProject.getModel().addPluginRepository(globalRepositoryFromPreference); log.info("add plugin repo"); } log.info("saving pro"); MavenUtils.saveMavenProject(mavenProject, pomLocation); log.info("save sucsessful"); }

Target:
public void createPOM(File pomLocation) throws Exception { MavenInfo mavenInfo = getModel().getMavenInfo(); String customGroupId = preferencesService.getString("org.wso2.developerstudio.eclipse.platform.ui", GLOBAL_MAVEN_GROUP_ID, null, null); String customVersion = preferencesService.getString("org.wso2.developerstudio.eclipse.platform.ui", GLOBAL_MAVEN_VERSION, null, null); MavenProject mavenProject = MavenUtils.createMavenProject(customGroupId != null ? customGroupId : mavenInfo.getGroupId(), mavenInfo.getArtifactId(), customVersion != null ? customVersion : mavenInfo.getVersion(), mavenInfo.getPackageName()); Parent parentProject = getModel().getMavenInfo().getParentProject(); if (parentProject != null) { mavenProject.getModel().setParent(parentProject); } String disableWSO2Repo = preferencesService.getString("org.wso2.developerstudio.eclipse.platform.ui", DISABLE_WSO2_REPOSITORY, null, null); if (disableWSO2Repo == null) { MavenUtils.updateMavenRepo(mavenProject); } Repository globalRepositoryFromPreference = getGlobalRepositoryFromPreference(); if (globalRepositoryFromPreference != null) { mavenProject.getModel().addRepository(globalRepositoryFromPreference); mavenProject.getModel().addPluginRepository(globalRepositoryFromPreference); } MavenUtils.saveMavenProject(mavenProject, pomLocation); }
Source:
public void execute() throws Exception { VirtualFile root = VFS.getChild(this.env.getJbossHome()); List<VirtualFile> matches = root.getChildrenRecursively(Filters.and(this.filter, this.blacklistFilter)); if(sorter != null){ Collections.sort(matches, sorter); } Limiter limiter = new Limiter(limit); Iterator<VirtualFile> iter = matches.iterator(); while(iter.hasNext() && !limiter.isDone()) { VirtualFile f = iter.next(); try (InputStream stream = limiter.limit(f)) { InputStream modifiedStream = stream; for (Sanitizer sanitizer : this.sanitizers) { if (sanitizer.accepts(f)) { modifiedStream = sanitizer.sanitize(stream); } } this.env.getZip().add(f, modifiedStream); } } }

Target:
public void execute() throws Exception { VirtualFile root = VFS.getChild(this.env.getJbossHome()); List<VirtualFile> matches = root.getChildrenRecursively(Filters.and(this.filter, this.blacklistFilter)); if(sorter != null){ Collections.sort(matches, sorter); } Limiter limiter = new Limiter(limit); Iterator<VirtualFile> iter = matches.iterator(); while(iter.hasNext() && !limiter.isDone()) { VirtualFile f = iter.next(); try (InputStream stream = limiter.limit(f)) { InputStream modifiedStream = stream; for (Sanitizer sanitizer : this.sanitizers) { if (sanitizer.accepts(f)) { modifiedStream = sanitizer.sanitize(modifiedStream); } } this.env.getZip().add(f, modifiedStream); } } }
Source:
public Result upload(Long folderId) { MultipartFormData body = request().body().asMultipartFormData(); Http.MultipartFormData.FilePart upload = body.getFile("file"); Folder folder = folderManager.findById(folderId); if (!Secured.viewFolder(folder)) { return forbidden("Dazu hast du keine Berechtigung"); } if (upload != null) { if (mediaManager.byteAsMB(upload.getFile().length()) > MAX_FILESIZE) { return status(REQUEST_ENTITY_TOO_LARGE, "Es sind maximal "+ MAX_FILESIZE + " MByte pro Datei möglich."); } if (mediaManager.existsInFolder(upload.getFilename(), folder)) { return status(CONFLICT, "Eine Datei mit diesem Namen existiert bereits."); } Media med = new Media(); med.title = upload.getFilename(); med.mimetype = upload.getContentType(); med.fileName = upload.getFilename(); med.file = upload.getFile(); med.owner = Component.currentAccount(); med.folder = folder; med.temporarySender = Component.currentAccount(); try { mediaManager.create(med); NotificationService.getInstance().createNotification(med, Media.MEDIA_NEW_MEDIA); } catch (Exception e) { return internalServerError("Während des Uploads ist etwas schiefgegangen!"); } Folder rootFolder = FolderManager.findRoot(folder); List<Media> mediaSet = folder.files; List<Folder> folderList = folder.folders; return created(list.render(mediaSet, folderList, rootFolder.id)); } else { return internalServerError("Es konnte keine Datei gefunden werden!"); } }

Target:
public Result upload(Long folderId) { MultipartFormData body = request().body().asMultipartFormData(); Http.MultipartFormData.FilePart upload = body.getFile("file"); Folder folder = folderManager.findById(folderId); if (!Secured.viewFolder(folder)) { return forbidden("Dazu hast du keine Berechtigung"); } if (upload != null) { if (mediaManager.byteAsMB(upload.getFile().length()) > MAX_FILESIZE) { return status(REQUEST_ENTITY_TOO_LARGE, "Es sind maximal "+ MAX_FILESIZE + " MByte pro Datei möglich."); } if (mediaManager.existsInFolder(upload.getFilename(), folder)) { return status(CONFLICT, "Eine Datei mit diesem Namen existiert bereits."); } Media med = new Media(); med.title = upload.getFilename(); med.mimetype = upload.getContentType(); med.fileName = upload.getFilename(); med.file = upload.getFile(); med.owner = Component.currentAccount(); med.folder = folder; med.temporarySender = Component.currentAccount(); try { mediaManager.create(med); NotificationService.getInstance().createNotification(med, Media.MEDIA_NEW_MEDIA); } catch (Exception e) { return internalServerError("Während des Uploads ist etwas schiefgegangen!"); } return created("/media/" + med.id); } else { return internalServerError("Es konnte keine Datei gefunden werden!"); } }
Source:
private int sendMergingUpdateBatch(String entityPrefix, String statementPrefix, Set<String> entityIds, List<Statement> insertStatements, Set<String> valueSet, Set<String> refSet, boolean verifyResult ) { log.debug("Processing IDs and statements", entityIds.size(), insertStatements.size()); long start = System.currentTimeMillis(); Integer modified = rdfClient.mergingUpdate( entityPrefix, statementPrefix, insertStatements, valueSet, refSet); log.debug("Update query took millis and modified statements", System.currentTimeMillis() - start, modified); if (verifyResult) { try { verifyStatements(entityIds, insertStatements); } catch (QueryEvaluationException e) { throw new FatalException("Can't load verify results: " + e, e); } } return modified; }

Target:
private int sendMergingUpdateBatch(String entityPrefix, String statementPrefix, Set<String> entityIds, List<Statement> insertStatements, Set<String> valueSet, Set<String> refSet, boolean verifyResult ) { log.debug("Processing IDs and statements", entityIds.size(), insertStatements.size()); long start = System.currentTimeMillis(); Integer modified = rdfClient.mergingUpdate( entityPrefix, statementPrefix, insertStatements, valueSet, refSet); log.debug("Update query took millis and modified statements", System.currentTimeMillis() - start, modified); if (verifyResult) { try { verifyStatements(entityIds, insertStatements); } catch (QueryEvaluationException e) { throw new FatalException("Can't verify update results: " + e, e); } } return modified; }
Source:
void convertToType() { XWikiContext context = mock(XWikiContext.class); when(this.xcontextProvider.get()).thenReturn(context); when(context.getWikiReference()).thenReturn(new WikiReference("s1")); this.converter.convertToType(mock(Type.class), "XWiki.U1"); verify(this.userReferenceResolver).resolve("XWiki.U1", new WikiReference("s1")); }

Target:
void convertToType() { UserReference userReference = () -> false; when(this.userReferenceResolver.resolve("XWiki.U1")).thenReturn(userReference); UserReference actual = this.converter.convertToType(mock(Type.class), "XWiki.U1"); assertEquals(userReference, actual); }
Source:
private static Map<String, Set<Method>> extractMethods(Class<?> childClass, Class<?> clazz, Map<String, Set<Method>> collected) { Map<String, Set<Method>> methods = Maps.newHashMap(); Method[] declaredMethods = clazz.getDeclaredMethods(); Package childPackage = childClass.getPackage(); Package classPackage = clazz.getPackage(); boolean isSamePackage = false; if ((null == childPackage) && (null == classPackage)) { isSamePackage = true; } if ((null != childPackage) && (null != classPackage)) { isSamePackage = childPackage.getName().equals(classPackage.getName()); } for (final Method method : declaredMethods) { int methodModifiers = method.getModifiers(); if ((Modifier.isPublic(methodModifiers) || Modifier.isProtected(methodModifiers)) || (isSamePackage && !Modifier.isPrivate(methodModifiers))) { if (!isOverridden(method, collected) && !Modifier.isAbstract(methodModifiers)) { if (methods.containsKey(method.getName())) { methods.get(method.getName()).add(method); continue; } methods.put(method.getName(), new HashSet<Method>() {{add(method);}}); } } } return methods; }

Target:
private static Map<String, Set<Method>> extractMethods(Class<?> childClass, Class<?> clazz, Map<String, Set<Method>> collected) { Map<String, Set<Method>> methods = Maps.newHashMap(); Method[] declaredMethods = clazz.getDeclaredMethods(); Package childPackage = childClass.getPackage(); Package classPackage = clazz.getPackage(); boolean isSamePackage = false; if ((null == childPackage) && (null == classPackage)) { isSamePackage = true; } if ((null != childPackage) && (null != classPackage)) { isSamePackage = childPackage.getName().equals(classPackage.getName()); } for (final Method method : declaredMethods) { int methodModifiers = method.getModifiers(); if ((Modifier.isPublic(methodModifiers) || Modifier.isProtected(methodModifiers)) || (isSamePackage && !Modifier.isPrivate(methodModifiers))) { if (!isOverridden(method, collected) && !Modifier.isAbstract(methodModifiers)) { Set<Method> eligibleMethods = methods.get(method.getName()); if (eligibleMethods == null) { eligibleMethods = Sets.newHashSet(); methods.put(method.getName(), eligibleMethods); } eligibleMethods.add(method); } } } return methods; }
Source:
Predicate createPredicateNumeric(String theResourceName, String theParamName, From<?, ? extends BaseResourceIndexedSearchParam> theFrom, CriteriaBuilder builder, IQueryParameterType theParam, ParamPrefixEnum thePrefix, BigDecimal theValue, final Expression<BigDecimal> thePath, String invalidMessageName) { Predicate num; switch (thePrefix) { case GREATERTHAN: num = builder.gt(thePath, theValue); break; case GREATERTHAN_OR_EQUALS: num = builder.ge(thePath, theValue); break; case LESSTHAN: num = builder.lt(thePath, theValue); break; case LESSTHAN_OR_EQUALS: num = builder.le(thePath, theValue); break; case EQUAL: num = builder.equal(thePath, theValue); break; case NOT_EQUAL: num = builder.notEqual(thePath, theValue); break; case APPROXIMATE: BigDecimal mul = FuzzCalculator.calculateFuzzAmount(thePrefix, theValue); BigDecimal low = theValue.subtract(mul, MathContext.DECIMAL64); BigDecimal high = theValue.add(mul, MathContext.DECIMAL64); Predicate lowPred; Predicate highPred; lowPred = builder.ge(thePath.as(BigDecimal.class), low); highPred = builder.le(thePath.as(BigDecimal.class), high); num = builder.and(lowPred, highPred); ourLog.trace("Searching for <= val <= {}", low, high); break; case ENDS_BEFORE: case STARTS_AFTER: default: String msg = myContext.getLocalizer().getMessage(SearchBuilder.class, invalidMessageName, thePrefix.getValue(), theParam.getValueAsQueryToken(myContext)); throw new InvalidRequestException(msg); } if (theParamName == null) { return num; } return combineParamIndexPredicateWithParamNamePredicate(theResourceName, theParamName, theFrom, num); }

Target:
Predicate createPredicateNumeric(String theResourceName, String theParamName, From<?, ? extends BaseResourceIndexedSearchParam> theFrom, CriteriaBuilder builder, IQueryParameterType theParam, ParamPrefixEnum thePrefix, BigDecimal theValue, final Expression<BigDecimal> thePath, String invalidMessageName) { Predicate num; switch (thePrefix) { case GREATERTHAN: num = builder.gt(thePath, theValue); break; case GREATERTHAN_OR_EQUALS: num = builder.ge(thePath, theValue); break; case LESSTHAN: num = builder.lt(thePath, theValue); break; case LESSTHAN_OR_EQUALS: num = builder.le(thePath, theValue); break; case EQUAL: num = builder.equal(thePath, theValue); break; case NOT_EQUAL: num = builder.notEqual(thePath, theValue); break; case APPROXIMATE: BigDecimal mul = SearchFuzzUtil.calculateFuzzAmount(thePrefix, theValue); BigDecimal low = theValue.subtract(mul, MathContext.DECIMAL64); BigDecimal high = theValue.add(mul, MathContext.DECIMAL64); Predicate lowPred; Predicate highPred; lowPred = builder.ge(thePath.as(BigDecimal.class), low); highPred = builder.le(thePath.as(BigDecimal.class), high); num = builder.and(lowPred, highPred); ourLog.trace("Searching for <= val <= {}", low, high); break; case ENDS_BEFORE: case STARTS_AFTER: default: String msg = myContext.getLocalizer().getMessage(SearchBuilder.class, invalidMessageName, thePrefix.getValue(), theParam.getValueAsQueryToken(myContext)); throw new InvalidRequestException(msg); } if (theParamName == null) { return num; } return combineParamIndexPredicateWithParamNamePredicate(theResourceName, theParamName, theFrom, num); }
Source:
public boolean hasDlmsMessageListener() { return this.dlmsMessageListener != null; }

Target:
public boolean hasDlmsMessageListener() { return DO_NOTHING_LISTENER != this.dlmsMessageListener; }
Source:
private Menu getNatTableMenu() { Event event = createMouseEvent(x, y, 3, SWT.NONE, 1); MouseEvent mouseevent = new MouseEvent(event); IMouseAction action = ((NatTable)control).getUiBindingRegistry().getMouseDownAction(mouseevent); if (action instanceof PopupMenuAction) { PopupMenuAction popupMenuAction = (PopupMenuAction) action; Field privateMenu = null; try { privateMenu = PopupMenuAction.class.getDeclaredField("menu"); } catch (NoSuchFieldException | SecurityException e) { return null; } privateMenu.setAccessible(true); try { return (Menu) privateMenu.get(popupMenuAction); } catch (IllegalArgumentException | IllegalAccessException e) { return null; } } return null; }

Target:
private Menu getNatTableMenu() { Event event = createMouseEvent(x, y, 3, SWT.NONE, 1); MouseEvent mouseevent = new MouseEvent(event); IMouseAction action = ((NatTable)control).getUiBindingRegistry().getMouseDownAction(mouseevent); if (action instanceof PopupMenuAction) { PopupMenuAction popupMenuAction = (PopupMenuAction) action; Field privateMenu = null; try { privateMenu = PopupMenuAction.class.getDeclaredField("menu"); } catch (NoSuchFieldException e) { return null; } catch (SecurityException e) { return null; } privateMenu.setAccessible(true); try { return (Menu) privateMenu.get(popupMenuAction); } catch (IllegalArgumentException e) { return null; } catch (IllegalAccessException e) { return null; } } return null; }
Source:
private String getStorageDomainNameById(String storageDomainId) { for (StorageDomain storageDomainItem : storageDomainDao.getAll()) { if (storageDomainItem != null && storageDomainItem.getStorageStaticData() != null) { if (storageDomainItem.getStorageStaticData().getStorage().equals(storageDomainId)) { return storageDomainItem.getStorageStaticData().getName(); } } } return ""; }

Target:
private String getStorageDomainNameById(String storageDomainId) { if ( storageDomainId == null || storageDomainId.equals("")) return ""; for (StorageDomain storageDomainItem : storageDomainDao.getAll()) { if (storageDomainItem != null && storageDomainItem.getStorageStaticData() != null) { if (storageDomainItem.getStorageStaticData().getStorage().equals(storageDomainId)) { return storageDomainItem.getStorageStaticData().getName(); } } } return ""; }
Source:
protected Set<String> executeQueryTree(QueryNode node, SQLDatabase db) { if (node instanceof AndQueryNode) { Set<String> accumulator = null; AndQueryNode andNode = (AndQueryNode) node; for (QueryNode qNode: andNode.children) { Set<String> childIds = executeQueryTree(qNode, db); if (accumulator == null) { accumulator = new HashSet<String>(childIds); } else { if (childIds != null) { accumulator = Sets.intersection(accumulator, childIds); } } } return accumulator; } if (node instanceof OrQueryNode) { Set<String> accumulator = null; OrQueryNode orNode = (OrQueryNode) node; for (QueryNode qNode: orNode.children) { Set<String> childIds = executeQueryTree(qNode, db); if (accumulator == null) { accumulator = new HashSet<String>(childIds); } else { if (childIds != null) { accumulator = Sets.union(accumulator, childIds); } } } return accumulator; } else if (node instanceof SqlQueryNode) { SqlQueryNode sqlNode = (SqlQueryNode) node; SqlParts sqlParts = sqlNode.sql; List<String> docIds = new ArrayList<String>(); Cursor cursor = null; try { cursor = db.rawQuery(sqlParts.sqlWithPlaceHolders, sqlParts.placeHolderValues); while (cursor.moveToNext()) { String docId = cursor.getString(0); docIds.add(docId); } } catch (SQLException e) { logger.log(Level.SEVERE, "Failed to get a list of doc ids.", e); } finally { DatabaseUtils.closeCursorQuietly(cursor); } return new HashSet<String>(docIds); } else { return null; } }

Target:
protected Set<String> executeQueryTree(QueryNode node, SQLDatabase db) { if (node instanceof AndQueryNode) { Set<String> accumulator = null; AndQueryNode andNode = (AndQueryNode) node; for (QueryNode qNode: andNode.children) { Set<String> childIds = executeQueryTree(qNode, db); if (childIds == null) { continue; } if (accumulator == null) { accumulator = new HashSet<String>(childIds); } else { if (childIds != null) { accumulator = Sets.intersection(accumulator, childIds); } } } return accumulator; } if (node instanceof OrQueryNode) { Set<String> accumulator = null; OrQueryNode orNode = (OrQueryNode) node; for (QueryNode qNode: orNode.children) { Set<String> childIds = executeQueryTree(qNode, db); if (childIds == null) { continue; } if (accumulator == null) { accumulator = new HashSet<String>(childIds); } else { if (childIds != null) { accumulator = Sets.union(accumulator, childIds); } } } return accumulator; } else if (node instanceof SqlQueryNode) { SqlQueryNode sqlNode = (SqlQueryNode) node; SqlParts sqlParts = sqlNode.sql; List<String> docIds = new ArrayList<String>(); Cursor cursor = null; try { cursor = db.rawQuery(sqlParts.sqlWithPlaceHolders, sqlParts.placeHolderValues); while (cursor.moveToNext()) { String docId = cursor.getString(0); docIds.add(docId); } } catch (SQLException e) { logger.log(Level.SEVERE, "Failed to get a list of doc ids.", e); } finally { DatabaseUtils.closeCursorQuietly(cursor); } return new HashSet<String>(docIds); } else { return null; } }
Source:
private boolean eventExists(String eventName) { for (AuditLogType alt : AuditLogType.values()) { if (alt.name().equals(eventName)) { return true; } } return false; }

Target:
private boolean eventExists(String eventName) { boolean exists = false; try { AuditLogType.valueOf(eventName); exists = true; } catch (Exception ex) { } return exists; }
Source:
private String getExpectedInstructorString(InstructorAttributes[] instructors) { StringJoiner expected = new StringJoiner("\n"); for (InstructorAttributes instructor : instructors) { expected.add(instructor.getRole() + ": " + instructor.getName() + " (" + instructor.getEmail() + ")"); } return expected.toString(); }

Target:
private String getExpectedInstructorString(InstructorAttributes[] instructors) { StringJoiner expected = new StringJoiner(System.lineSeparator()); for (InstructorAttributes instructor : instructors) { expected.add(instructor.getRole() + ": " + instructor.getName() + " (" + instructor.getEmail() + ")"); } return expected.toString(); }
Source:
public SignatureWidget( final PopupResources popupResources, @Assisted final OrionEditorWidget textEditor, @Assisted final OrionKeyModeOverlay assistMode) { this.popupResources = popupResources; this.textEditor = textEditor; this.assistMode = assistMode; popupElement = Elements.createDivElement(popupResources.popupStyle().popup()); Element headerElement = Elements.createDivElement(popupResources.popupStyle().header()); headerElement.setInnerText("Signatures:"); popupElement.appendChild(headerElement); popupBodyElement = Elements.createDivElement(popupResources.popupStyle().body()); popupBodyElement.setClassName("signaturesContent"); popupElement.appendChild(popupBodyElement); listElement = Elements.createUListElement(); popupBodyElement.appendChild(listElement); docPopup = new FlowPanel(); docPopup.setStyleName(popupResources.popupStyle().popup()); docPopup.setSize("370px", "180px"); popupListener = evt -> { if (!(evt instanceof MouseEvent)) { return; } final MouseEvent mouseEvent = (MouseEvent) evt; final EventTarget target = mouseEvent.getTarget(); if (target instanceof Element) { final Element elementTarget = (Element) target; if (docPopup.isVisible() && (elementTarget.equals(docPopup.getElement()) || elementTarget.getParentElement().equals(docPopup.getElement()))) { return; } if (!SignatureWidget.this.popupElement.contains(elementTarget)) { hide(); evt.preventDefault(); } } }; }

Target:
public SignatureWidget( final PopupResources popupResources, @Assisted final OrionEditorWidget textEditor, @Assisted final OrionKeyModeOverlay assistMode) { this.popupResources = popupResources; this.textEditor = textEditor; this.assistMode = assistMode; popupElement = Elements.createDivElement(popupResources.popupStyle().popup()); Element headerElement = Elements.createDivElement(popupResources.popupStyle().header()); headerElement.setInnerText("Signatures:"); popupElement.appendChild(headerElement); popupBodyElement = Elements.createDivElement(popupResources.popupStyle().body()); popupBodyElement.setId(SIGNATURES_CONTENT_ID); popupElement.appendChild(popupBodyElement); listElement = Elements.createUListElement(); popupBodyElement.appendChild(listElement); docPopup = new FlowPanel(); docPopup.setStyleName(popupResources.popupStyle().popup()); docPopup.setSize("370px", "180px"); popupListener = evt -> { if (!(evt instanceof MouseEvent)) { return; } final MouseEvent mouseEvent = (MouseEvent) evt; final EventTarget target = mouseEvent.getTarget(); if (target instanceof Element) { final Element elementTarget = (Element) target; if (docPopup.isVisible() && (elementTarget.equals(docPopup.getElement()) || elementTarget.getParentElement().equals(docPopup.getElement()))) { return; } if (!SignatureWidget.this.popupElement.contains(elementTarget)) { hide(); evt.preventDefault(); } } }; }
Source:
public void run() { doIt(); logger.trace("Task #" + this.taskID + " is rescheduling a new task now..."); this.executor.execute(new ReSchedulingTask(this.executor)); logger.trace("... task #" + this.taskID + " has completed recheduling a new task."); }

Target:
public void run() { doIt(); logger.trace("Task #" + this.taskID + " is rescheduling a new task now..."); if (tasksCounter <= MAX_TASKS) { this.executor.execute(new ReSchedulingTask(this.executor)); } logger.trace("... task #" + this.taskID + " has completed rescheduling a new task."); }
Source:
public int getSizeInventory() { if (cached == null) { initCache(); } if(cached.size() == 0) return 1; return cached.size(); }

Target:
public int getSizeInventory() { if (cached == null) { initCache(); } if(cached.size() == 0) { return 1; } return cached.size(); }
Source:
private static StructuredProperty buildContextualisedTitle(String softwareTitle, String repositoryName, String publicationTitle) { return buildTitle( MessageFormat.format(SOFTWARE_TITLE_ALTERNATIVE_TEMPLATE, new Object[] { softwareTitle, repositoryName, publicationTitle }), InfoSpaceConstants.SEMANTIC_CLASS_ALTERNATIVE_TITLE); }

Target:
private static StructuredProperty buildContextualisedTitle(String softwareTitle, String repositoryName, String publicationTitle) { return buildTitle(MessageFormat.format(SOFTWARE_TITLE_ALTERNATIVE_TEMPLATE, softwareTitle, repositoryName, publicationTitle), InfoSpaceConstants.SEMANTIC_CLASS_ALTERNATIVE_TITLE); }
Source:
public static <V> ExecutorCompletionService<V> createCompletionService() { ExecutorCompletionService<V> ecs = new ExecutorCompletionService<V>(es); return ecs; }

Target:
public static <V> ExecutorCompletionService<V> createCompletionService() { return new ExecutorCompletionService<V>(es); }
Source:
private void addIngestionEventForContainer(ContentContainerObject obj, Resource parentResc) throws IOException { NodeIterator childIt = getChildIterator(parentResc); int numChildren = 0; PID childPid = null; while (childIt.hasNext()) { Resource resc = (Resource) childIt.next(); if (numChildren < 1) { childPid = PIDs.get(resc.getURI()); } numChildren++; } if (numChildren > 0) { PremisLogger premisLogger = getPremisLogger(obj.getPid()); PremisEventBuilder builder = premisLogger.buildEvent(Premis.Ingestion); if (numChildren == 1 && childPid != null) { builder.addEventDetail("added child object {0} to this container", childPid.toString()).write(); } else { builder.addEventDetail("added {0} child objects to this container", numChildren).write(); } } }

Target:
private void addIngestionEventForContainer(ContentContainerObject obj, Resource parentResc) throws IOException { NodeIterator childIt = getChildIterator(parentResc); int numChildren = 0; PID childPid = null; while (childIt.hasNext()) { Resource resc = (Resource) childIt.next(); if (numChildren < 1) { childPid = PIDs.get(resc.getURI()); } numChildren++; } if (numChildren > 0) { PremisLogger premisLogger = getPremisLogger(obj.getPid()); PremisEventBuilder builder = premisLogger.buildEvent(Premis.Ingestion); if (numChildren == 1 && childPid != null) { builder.addEventDetail("added child object {0} to this container", childPid.toString()); } else { builder.addEventDetail("added {0} child objects to this container", numChildren); } builder.addSoftwareAgent(SoftwareAgent.depositService.getFullname()) .addAuthorizingAgent(DepositField.depositorName.name()) .write(); } }
Source:
public void testFindByStudyId() { List<String> studyIds = new ArrayList<>(); studyIds.add("secondStudyId"); Pageable pageable = new PageRequest(0, 1); List<VariantSourceEntity> variantSourceEntityList = repository.findByStudyIdIn(studyIds, pageable); assertEquals(1, variantSourceEntityList.size()); pageable = new PageRequest(0, 2); variantSourceEntityList = repository.findByStudyIdIn(studyIds, pageable); assertEquals(2, variantSourceEntityList.size()); studyIds.add("firstStudyId"); pageable = new PageRequest(1, 2); variantSourceEntityList = repository.findByStudyIdIn(studyIds, pageable); assertEquals(1, variantSourceEntityList.size()); pageable = new PageRequest(2, 2); variantSourceEntityList = repository.findByStudyIdIn(studyIds, pageable); assertEquals(0, variantSourceEntityList.size()); }

Target:
public void testFindByStudyId() { List<String> studyIds = new ArrayList<>(); studyIds.add(SECOND_STUDY_ID); Pageable pageable = new PageRequest(0, 1); List<VariantSourceEntity> variantSourceEntityList = repository.findByStudyIdIn(studyIds, pageable); assertEquals(1, variantSourceEntityList.size()); pageable = new PageRequest(0, 2); variantSourceEntityList = repository.findByStudyIdIn(studyIds, pageable); assertEquals(2, variantSourceEntityList.size()); studyIds.add(FIRST_STUDY_ID); pageable = new PageRequest(1, 2); variantSourceEntityList = repository.findByStudyIdIn(studyIds, pageable); assertEquals(1, variantSourceEntityList.size()); pageable = new PageRequest(2, 2); variantSourceEntityList = repository.findByStudyIdIn(studyIds, pageable); assertEquals(0, variantSourceEntityList.size()); }
Source:
protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, true); Button button = createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); button.setEnabled(false); }

Target:
protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); Button button = createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, false); button.setEnabled(false); }
Source:
private static boolean checkEqual(String cond1, String cond2) { RexNode rexNode1 = toRex(cond1); RexNode rexNode2 = toRex(cond2); Context z3Context = new Context(); List<SymbolicColumn> inputSymbolicColumns = new ArrayList<>(); for (int i = 0; i < 8; i++) { RelDataType intType = typeFactory.createJavaType(int.class); SymbolicColumn inputColumn = SymbolicColumn.mkNewSymbolicColumn(z3Context, intType); inputSymbolicColumns.add(inputColumn); } List<BoolExpr> env = new ArrayList<>(); SymbolicColumn symbolicCond1 = RexToSymbolicColumn.rexToColumn(rexNode1, inputSymbolicColumns, z3Context, env); SymbolicColumn symbolicCond2 = RexToSymbolicColumn.rexToColumn(rexNode2, inputSymbolicColumns, z3Context, env); return SymbolicColumn.checkCondEq(symbolicCond1, symbolicCond2, env, z3Context); }

Target:
private boolean checkEqual(String cond1, String cond2) { RexNode rexNode1 = toRex(cond1); RexNode rexNode2 = toRex(cond2); return RexVerifier.logicallyEquivalent(rexNode1, rexNode2); }
Source:
protected Permit addParents(Permit permit) { if (permit == null) { System.out.println("permit is null"); } if (parent == null) { System.out.println("parent is null"); } return parent.addParents(permit); }

Target:
protected Permit addParents(Permit permit) { return parent.addParents(permit); }
Source:
private static long getMillis(Config cfg, String name, String key, long defaultValue) { String valStr = cfg.getString(CONFIG_KEY_REMOTE, name, key); if (valStr == null) { return defaultValue; } valStr = valStr.trim(); if (valStr.isEmpty()) { return defaultValue; } Matcher m = matcher("^([1-9][0-9]*(?:\\.[0-9]*)?)\\s*(.*)$", valStr); if (!m.matches()) { return defaultValue; } String digits = m.group(1); String unitName = m.group(2).trim(); TimeUnit unit = UnitMap.UNITS.get(unitName); if (unit == null) { return defaultValue; } try { if (digits.indexOf('.') == -1) { return unit.toMillis(Long.parseLong(digits)); } double val = Double.parseDouble(digits); return (long) (val * unit.toMillis(1)); } catch (NumberFormatException nfe) { return defaultValue; } }

Target:
private static long getMillis(Config cfg, String name, String key, long defaultValue) { String valStr = cfg.getString(CONFIG_KEY_REMOTE, name, key); if (valStr == null) { return defaultValue; } valStr = valStr.trim(); if (valStr.isEmpty()) { return defaultValue; } Matcher m = UnitMap.PATTERN.matcher(valStr); if (!m.matches()) { return defaultValue; } String digits = m.group(1); String unitName = m.group(2).trim(); TimeUnit unit = UnitMap.UNITS.get(unitName); if (unit == null) { return defaultValue; } try { if (digits.indexOf('.') == -1) { return unit.toMillis(Long.parseLong(digits)); } double val = Double.parseDouble(digits); return (long) (val * unit.toMillis(1)); } catch (NumberFormatException nfe) { return defaultValue; } }
Source:
public void test_when_contentInodeIsNotNull_and_throwDotSecurityException() throws DotSecurityException, DotDataException { final HttpServletRequest request = mock(HttpServletRequest.class); final WebResource webResource = mock(WebResource.class); final LanguageAPI languageAPI = mock(LanguageAPI.class); final InitDataObject initDataObject = mock(InitDataObject.class); final User user = new User(); final DotSecurityException exception = mock(DotSecurityException.class); when(initDataObject.getUser()).thenReturn(user); when(webResource.init(null, true, request, true, null)).thenReturn(initDataObject); when(languageAPI.getAvailableContentLanguages("2", user)).thenThrow(exception); final LanguagesResource languagesResource = new LanguagesResource(languageAPI, webResource); try { languagesResource.list(request, "2"); assertTrue(false); } catch(DotSecurityException e) { assertTrue(true); } }

Target:
public void test_when_contentInodeIsNotNull_and_throwDotSecurityException() throws DotSecurityException, DotDataException { final HttpServletRequest request = mock(HttpServletRequest.class); final WebResource webResource = mock(WebResource.class); final LanguageAPI languageAPI = mock(LanguageAPI.class); final InitDataObject initDataObject = mock(InitDataObject.class); final User user = new User(); final DotSecurityException exception = mock(DotSecurityException.class); when(initDataObject.getUser()).thenReturn(user); when(webResource.init(null, true, request, true, null)).thenReturn(initDataObject); when(languageAPI.getAvailableContentLanguages("2", user)).thenThrow(exception); final LanguagesResource languagesResource = new LanguagesResource(languageAPI, webResource); languagesResource.list(request, "2"); }
Source:
private Future<PathsPromoteResult> submitRollbackPathsPromote( PathsPromoteResult result ) throws IndyWorkflowException { return detectOverload( () -> asyncPromotionService.submit( () -> { if ( result.getCompletedPaths().isEmpty() ) { return result; } PathsPromoteRequest request = result.getRequest(); PathsPromoteRequest newRequest = new PathsPromoteRequest( request.getTarget(), request.getSource(), result.getCompletedPaths() ); newRequest.setPurgeSource( true ); PathsPromoteResult ret; try { ret = doPathsPromotion( newRequest, true, null ); } catch ( Exception ex ) { String msg = "Rollback path promotion failed. Target: " + request.getTarget() + ", Source: " + request.getSource() + ", Reason: " + getStackTrace( ex ); logger.warn( msg ); ret = new PathsPromoteResult( request, msg ); } if ( ret.succeeded() ) { result.setPendingPaths( result.getCompletedPaths() ); result.setCompletedPaths( null ); } else { result.setError( ret.getError() ); } result.withPromotionId( result.getPromotionId() ); if ( result.getRequest().getCallback() != null ) { return callbackHelper.callback( result.getRequest().getCallback(), result ); } return result; } ) ); }

Target:
private Future<PathsPromoteResult> submitRollbackPathsPromote( PathsPromoteResult result ) throws IndyWorkflowException { return detectOverload( () -> asyncPromotionService.submit( () -> { if ( result.getCompletedPaths().isEmpty() ) { return result; } PathsPromoteRequest request = result.getRequest(); PathsPromoteRequest newRequest = new PathsPromoteRequest( request.getTarget(), request.getSource(), result.getCompletedPaths() ); newRequest.setPurgeSource( true ); newRequest.setFailWhenExists( false ); PathsPromoteResult ret; try { ret = doPathsPromotion( newRequest, true, null ); } catch ( Exception ex ) { String msg = "Rollback path promotion failed. Target: " + request.getTarget() + ", Source: " + request.getSource() + ", Reason: " + getStackTrace( ex ); logger.warn( msg ); ret = new PathsPromoteResult( request, msg ); } if ( ret.succeeded() ) { result.setPendingPaths( result.getCompletedPaths() ); result.setCompletedPaths( null ); } else { result.setError( ret.getError() ); } if ( result.getRequest().getCallback() != null ) { return callbackHelper.callback( result.getRequest().getCallback(), result ); } return result; } ) ); }
Source:
public IncomingTextMessage(SmsMessage message, int subscriptionId) { this.message = message.getDisplayMessageBody(); this.sender = message.getDisplayOriginatingAddress(); this.senderDeviceId = 1; this.protocol = message.getProtocolIdentifier(); this.serviceCenterAddress = message.getServiceCenterAddress(); this.replyPathPresent = message.isReplyPathPresent(); this.pseudoSubject = message.getPseudoSubject(); this.sentTimestampMillis = message.getTimestampMillis(); this.subscriptionId = subscriptionId; this.groupId = null; this.push = false; this.receivedWhenLocked = false; }

Target:
public IncomingTextMessage(SmsMessage message, int subscriptionId) { this(message, subscriptionId, false); }
Source:
public Option<BoundaryCheck> checkBoundaries(final Coordinates coords, final ObsContext ctx) { return ctx.getBaseCoordinates().map(baseCoordinates -> { final Angle positionAngle = ctx.getPositionAngleJava(); final Set<Offset> sciencePositions = ctx.getSciencePositions(); return getCorrectedPatrolField(ctx).map(pf -> { final BoundaryPosition bp = pf.checkBoundaries(coords, baseCoordinates, positionAngle, sciencePositions); if ((bp != BoundaryPosition.inside) && (bp != BoundaryPosition.innerBoundary)) { return BoundaryCheck.nearBoundary; } final double minLimit = getVignettingClearance(ctx).toArcsecs().getMagnitude(); final Ellipse2D e = new Ellipse2D.Double(-minLimit, -minLimit, minLimit * 2.0, minLimit * 2.0); final PatrolField p = getCorrectedPatrolField(new PatrolField(e, e, e), ctx); if (p.anyInside(coords, baseCoordinates, positionAngle, sciencePositions)) { return BoundaryCheck.vignetting; } return BoundaryCheck.inRange; }).getOrElse(BoundaryCheck.outOfRange); }); }

Target:
public Option<PwfsProbeRangeArea> checkBoundaries(final Coordinates coords, final ObsContext ctx) { return ctx.getBaseCoordinates().map(baseCoordinates -> { final Angle positionAngle = ctx.getPositionAngleJava(); final Set<Offset> sciencePositions = ctx.getSciencePositions(); return getCorrectedPatrolField(ctx).map(pf -> { final BoundaryPosition bp = pf.checkBoundaries(coords, baseCoordinates, positionAngle, sciencePositions); final PwfsProbeRangeArea result; switch (bp) { case inside: result = PwfsProbeRangeArea.inRange; break; case innerBoundary: final double minLimit = getVignettingClearance(ctx).toArcsecs().getMagnitude(); final Ellipse2D e = new Ellipse2D.Double(-minLimit, -minLimit, minLimit * 2.0, minLimit * 2.0); final PatrolField p = getCorrectedPatrolField(new PatrolField(e, e, e), ctx); if (p.anyInside(coords, baseCoordinates, positionAngle, sciencePositions)) { result = PwfsProbeRangeArea.vignetting; } else { result = PwfsProbeRangeArea.inRange; } break; default: result = PwfsProbeRangeArea.outOfRange; break; } return result; }).getOrElse(PwfsProbeRangeArea.outOfRange); }); }
Source:
public Optional<String> findPid() throws IOException { try { return ProcessHandle.allProcesses() .filter(ph -> commandPattern.matcher(ph.info().commandLine().orElse("")).matches()) .map(ProcessHandle::pid) .map(String::valueOf) .findFirst(); } catch (UnsupportedOperationException e) { throw new IOException("Your system doesn't support looking up of process", e); } }

Target:
public Optional<Long> findPid() throws IOException { try { return ProcessHandle.allProcesses() .filter(ph -> processPattern.matcher(ph.info().commandLine().orElse("")).matches()) .map(ProcessHandle::pid) .findFirst(); } catch (UnsupportedOperationException e) { throw new IOException("Your system doesn't support looking up of process", e); } }
Source:
private boolean filter(int i, int j, boolean hori) throws ContradictionException { boolean hasFiltered = false; int offSet = hori ? 0 : n; int s_i = vars[i + offSet].getUB(); int e_i = vars[i + offSet].getLB() + vars[i + 2 * n + offSet].getLB(); int s_j = vars[j + offSet].getUB(); int e_j = vars[j + offSet].getLB() + vars[j + 2 * n + offSet].getLB(); if (s_i < e_i || s_j < e_j) { if (e_j > s_i) { if(vars[j + offSet].updateLowerBound(e_i, this)) { if(!pruneList.contains(j)) { pruneList.add(j); } hasFiltered = true; } if(vars[i + offSet].updateUpperBound(s_j - vars[i + 2 * n + offSet].getLB(), this) || vars[i + offSet + 2 * n].updateUpperBound(s_j - vars[i + offSet].getLB(), this)) { if(!pruneList.contains(i)) { pruneList.add(i); } hasFiltered = true; } } if (s_j < e_i) { if(vars[i + offSet].updateLowerBound(e_j, this)) { if(!pruneList.contains(i)) { pruneList.add(i); } hasFiltered = true; } if(vars[j + offSet].updateUpperBound(s_i - vars[j + 2 * n + offSet].getLB(), this) || vars[j + offSet + 2 * n].updateUpperBound(s_i - vars[j + offSet].getLB(), this)) { if(!pruneList.contains(j)) { pruneList.add(j); } hasFiltered = true; } } } return hasFiltered; }

Target:
private boolean filter(int i, int j, boolean hori) throws ContradictionException { boolean hasFiltered = false; int offSet = hori ? 0 : n; int s_i = vars[i + offSet].getUB(); int e_i = vars[i + offSet].getLB() + vars[i + 2 * n + offSet].getLB(); int s_j = vars[j + offSet].getUB(); int e_j = vars[j + offSet].getLB() + vars[j + 2 * n + offSet].getLB(); if (s_i < e_i || s_j < e_j) { if (e_j > s_i) { if(vars[j + offSet].updateLowerBound(e_i, this)) { if(!pruneList.contains(j)) { pruneList.add(j); } hasFiltered = true; } boolean filtPrun1 = vars[i + offSet].updateUpperBound(s_j - vars[i + 2 * n + offSet].getLB(), this); boolean filtPrun2 = vars[i + offSet + 2 * n].updateUpperBound(s_j - vars[i + offSet].getLB(), this); if(filtPrun1 || filtPrun2) { if(!pruneList.contains(i)) { pruneList.add(i); } hasFiltered = true; } } if (s_j < e_i) { if(vars[i + offSet].updateLowerBound(e_j, this)) { if(!pruneList.contains(i)) { pruneList.add(i); } hasFiltered = true; } boolean filtPrun1 = vars[j + offSet].updateUpperBound(s_i - vars[j + 2 * n + offSet].getLB(), this); boolean filtPrun2 = vars[j + offSet + 2 * n].updateUpperBound(s_i - vars[j + offSet].getLB(), this); if(filtPrun1 || filtPrun2) { if(!pruneList.contains(j)) { pruneList.add(j); } hasFiltered = true; } } } return hasFiltered; }
Source:
public VCFSampleHeaderLine(String line, VCFHeaderVersion version) { super(VCFConstants.SAMPLE_HEADER_KEY, new VCF4Parser().parseLine(line, null)); }

Target:
public VCFSampleHeaderLine(String line, VCFHeaderVersion version) { super(VCFConstants.SAMPLE_HEADER_KEY, VCFHeaderLineTranslator.parseLine(version, line, null)); }