auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean isGrantedForGroup(List<GroupAce> controlEntries, Authentication authentication, Permission permission, boolean isCheckAllowedGrant) { Object auth = authentication.getPrincipal(); if (auth instanceof JCUser) { List<Long> groupsIDs = ((JCUser) auth).getGroupsIDs(); for (GroupAce ace : controlEntries) { if (groupsIDs.contains(ace.getGroupId())){ if (isGrantedForGroup(ace, permission, isCheckAllowedGrant)) { return true; } } } } return false; }

Target:
private boolean isGrantedForGroup(List<GroupAce> controlEntries, Authentication authentication, Permission permission, boolean isCheckAllowedGrant) { Object auth = authentication.getPrincipal(); if (!(auth instanceof JCUser)) return false; List<Long> groupsIDs = ((JCUser) auth).getGroupsIDs(); for (GroupAce ace : controlEntries) { if (groupsIDs.contains(ace.getGroupId())) { if (isGrantedForGroup(ace, permission, isCheckAllowedGrant)) return true; } } return false; }
Source:
private static void setWorkspaceNameDefault() { IPath workspaceDir = Platform.getLocation(); if (workspaceDir == null) return; String workspaceName = workspaceDir.lastSegment(); if (workspaceName == null) return; IPreferenceStore preferences = IDEWorkbenchPlugin.getDefault().getPreferenceStore(); preferences.setDefault(IDEInternalPreferences.WORKSPACE_NAME, workspaceName); }

Target:
private static void setWorkspaceNameDefault() { IPreferenceStore preferences = IDEWorkbenchPlugin.getDefault().getPreferenceStore(); String workspaceNameDefault = preferences.getDefaultString(IDEInternalPreferences.WORKSPACE_NAME); if (workspaceNameDefault != null) return; IPath workspaceDir = Platform.getLocation(); if (workspaceDir == null) return; String workspaceName = workspaceDir.lastSegment(); if (workspaceName == null) return; preferences.setDefault(IDEInternalPreferences.WORKSPACE_NAME, workspaceName); }
Source:
public void in_stringNull() { populateNoPrimaryKeyNullTypesRows(); try { realm.where(NoPrimaryKeyNullTypes.class).in(NoPrimaryKeyNullTypes.FIELD_STRING_NULL, (String[]) null).findAll(); fail(); } catch (IllegalArgumentException ignored) { } try { realm.where(NoPrimaryKeyNullTypes.class).in(NoPrimaryKeyNullTypes.FIELD_STRING_NULL, new String[]{}).findAll(); fail(); } catch (IllegalArgumentException ignored) { } RealmResults<NoPrimaryKeyNullTypes> resultList = realm.where(NoPrimaryKeyNullTypes.class).in(NoPrimaryKeyNullTypes.FIELD_STRING_NULL, new String[]{"test data 14"}).findAll(); assertEquals(1, resultList.size()); resultList = realm.where(NoPrimaryKeyNullTypes.class).in(NoPrimaryKeyNullTypes.FIELD_STRING_NULL, new String[]{"test data 14", "test data 118", "test data 31", "test data 199"}).findAll(); assertEquals(4, resultList.size()); resultList = realm.where(NoPrimaryKeyNullTypes.class).in(NoPrimaryKeyNullTypes.FIELD_STRING_NULL, new String[]{"TEST data 14", "test data 118", "test data 31", "test DATA 199"}, Case.INSENSITIVE).findAll(); assertEquals(4, resultList.size()); resultList = realm.where(NoPrimaryKeyNullTypes.class).not().in(NoPrimaryKeyNullTypes.FIELD_STRING_NULL, new String[]{"TEST data 14", "test data 118", "test data 31", "test DATA 199"}, Case.INSENSITIVE).findAll(); assertEquals(196, resultList.size()); resultList = realm.where(NoPrimaryKeyNullTypes.class).not().in(NoPrimaryKeyNullTypes.FIELD_STRING_NULL, new String[]{"TEST data 14", "test data 118", "test data 31", "test DATA 199"}, Case.INSENSITIVE).findAll(); assertEquals(196, resultList.size()); resultList = realm.where(NoPrimaryKeyNullTypes.class).not().in(NoPrimaryKeyNullTypes.FIELD_STRING_NULL, new String[]{"TEST data 14", "test data 118", null, "test DATA 199"}, Case.INSENSITIVE).findAll(); assertEquals(130, resultList.size()); }

Target:
public void in_stringNull() { doTestForInString(NoPrimaryKeyNullTypes.FIELD_STRING_NULL); RealmResults<NoPrimaryKeyNullTypes> resultList = realm.where(NoPrimaryKeyNullTypes.class).not().in(NoPrimaryKeyNullTypes.FIELD_STRING_NULL, new String[]{"TEST data 14", "test data 118", null, "test DATA 199"}, Case.INSENSITIVE).findAll(); assertEquals(130, resultList.size()); }
Source:
public List<PatchLineComment> byChange(ReviewDb db, ChangeNotes notes) throws OrmException { if (!migration.readComments()) { return db.patchComments().byChange(notes.getChangeId()).toList(); } notes.load(); List<PatchLineComment> comments = Lists.newArrayList(); comments.addAll(notes.getBaseComments().values()); comments.addAll(notes.getPatchSetComments().values()); Set<String> refNames = getRefNamesAllUsers(RefNames.REFS_USER); for (String refName : refNames) { String suffix = Integer.toString(notes.getChangeId().get()); if (!refName.endsWith(suffix)) { continue; } String[] parts = refName.split(RefNames.DRAFTS); if (parts.length != 2) { continue; } Account.Id account = Account.Id.fromRefPart(parts[0]); comments.addAll(draftByChangeAuthor(db, notes, account)); } return comments; }

Target:
public List<PatchLineComment> byChange(ReviewDb db, ChangeNotes notes) throws OrmException { if (!migration.readComments()) { return db.patchComments().byChange(notes.getChangeId()).toList(); } notes.load(); List<PatchLineComment> comments = Lists.newArrayList(); comments.addAll(notes.getBaseComments().values()); comments.addAll(notes.getPatchSetComments().values()); Set<String> refNames = getRefNamesAllUsers(RefNames.REFS_USER); Iterable<String> filtered = Iterables.filter(refNames, new IsDraftRefForChange(notes.getChangeId())); for (String refName : filtered) { Account.Id account = Account.Id.fromRefPart(refName); comments.addAll(draftByChangeAuthor(db, notes, account)); } return comments; }
Source:
public void visit(NodeTraversal t, Node n, Node parent) { if (n.isName()) { switch (parent.getType()) { case Token.VAR: case Token.LET: case Token.CONST: case Token.FUNCTION: case Token.CLASS: case Token.PARAM_LIST: break; case Token.GETPROP: if (n == parent.getFirstChild()) { Scope scope = t.getScope(); Var var = scope.getVar(n.getString()); if (var == null) { t.report(n, UNDEFINED_EXTERN_VAR_ERROR, n.getString()); varsToDeclareInExterns.add(n.getString()); } } break; case Token.ASSIGN: if (n == parent.getLastChild() && parent.getFirstChild().isGetProp() && parent.getFirstChild().getLastChild().getString().equals(n.getString())) { break; } default: if (parent.getType() != Token.NAME || parent.getParent() == null || parent.getParent().getType() != Token.VAR) { t.report(n, NAME_REFERENCE_IN_EXTERNS_ERROR, n.getString()); } Scope scope = t.getScope(); Var var = scope.getVar(n.getString()); if (var == null) { varsToDeclareInExterns.add(n.getString()); } break; } } }

Target:
public void visit(NodeTraversal t, Node n, Node parent) { if (n.isName()) { switch (parent.getType()) { case Token.VAR: case Token.LET: case Token.CONST: case Token.FUNCTION: case Token.CLASS: case Token.PARAM_LIST: break; case Token.GETPROP: if (n == parent.getFirstChild()) { Scope scope = t.getScope(); Var var = scope.getVar(n.getString()); if (var == null) { t.report(n, UNDEFINED_EXTERN_VAR_ERROR, n.getString()); varsToDeclareInExterns.add(n.getString()); } } break; case Token.ASSIGN: if (n == parent.getLastChild() && parent.getFirstChild().isGetProp() && parent.getFirstChild().getLastChild().getString().equals(n.getString())) { break; } default: if (parent.getType() != Token.NAME || parent.getParent() == null || !NodeUtil.isNameDeclaration(parent.getParent())) { t.report(n, NAME_REFERENCE_IN_EXTERNS_ERROR, n.getString()); } Scope scope = t.getScope(); Var var = scope.getVar(n.getString()); if (var == null) { varsToDeclareInExterns.add(n.getString()); } break; } } }
Source:
public void setLabels() { turnLabel.setText(playerList.get(turnOrder.get(currentPlayer)).getName() + "'s Turn " + timeLeft); resourceLabel.setText(playerList.get(turnOrder.get(currentPlayer)).getName() + "'s Money: " + playerList.get(turnOrder.get(currentPlayer)).getMoney() + " F: " + playerList.get(turnOrder.get(currentPlayer)).stockOf(ResourceType.FOOD) + " E: " + playerList.get(turnOrder.get(currentPlayer)).stockOf(ResourceType.ENERGY) + " S: " + playerList.get(turnOrder.get(currentPlayer)).stockOf(ResourceType.SMITHORE) + " C: " + playerList.get(turnOrder.get(currentPlayer)).stockOf(ResourceType.CRYSTITE)); }

Target:
public void setLabels() { turnLabel.setText(playerList.get(turnOrder.get(currentPlayer)).getName() + "'s Turn " + timeLeft); String s = String.format("%1$s's Money: %2$s F: %3$s E: %4$s S: %5$s C: %6$s", playerList.get(turnOrder.get(currentPlayer)).getName(), playerList.get(turnOrder.get(currentPlayer)).getMoney(), playerList.get(turnOrder.get(currentPlayer)).stockOf(ResourceType.FOOD), playerList.get(turnOrder.get(currentPlayer)).stockOf(ResourceType.ENERGY), playerList.get(turnOrder.get(currentPlayer)).stockOf(ResourceType.SMITHORE), playerList.get(turnOrder.get(currentPlayer)).stockOf(ResourceType.CRYSTITE)); resourceLabel.setText(s); }
Source:
public boolean Validate() { boolean isNew = getModel().getIsNew(); int maxAllowedVms = getMaxVmsInPool(); int assignedVms = getModel().getAssignedVms().AsConvertible().Integer(); getModel().getNumOfDesktops().ValidateEntity( union(new IValidation[] { new NotEmptyValidation(), new LengthValidation(4), new IntegerValidation(isNew ? 1 : 0, isNew ? maxAllowedVms : maxAllowedVms - assignedVms) }, getNumOfDesktopsSpecificValidations() ) ); getModel().getPrestartedVms().ValidateEntity( new IValidation[] { new NotEmptyValidation(), new IntegerValidation(0, assignedVms) }); if (getModel().getName().getIsValid()) { getModel().getName().ValidateEntity(getPoolNameSpecificValidations()); } getModel().setIsGeneralTabValid(getModel().getIsGeneralTabValid() && getModel().getName().getIsValid() && getModel().getNumOfDesktops().getIsValid() && getModel().getPrestartedVms().getIsValid()); getModel().setIsPoolTabValid(true); return super.Validate() && getModel().getName().getIsValid() && getModel().getNumOfDesktops().getIsValid() && getModel().getPrestartedVms().getIsValid(); }

Target:
public boolean Validate() { boolean isNew = getModel().getIsNew(); int maxAllowedVms = getMaxVmsInPool(); int assignedVms = getModel().getAssignedVms().AsConvertible().Integer(); getModel().getNumOfDesktops().ValidateEntity( new IValidation[] { new NotEmptyValidation(), new LengthValidation(4), new IntegerValidation(isNew ? 1 : 0, isNew ? maxAllowedVms : maxAllowedVms - assignedVms) }); getModel().getPrestartedVms().ValidateEntity( new IValidation[] { new NotEmptyValidation(), new IntegerValidation(0, assignedVms) }); getModel().setIsGeneralTabValid(getModel().getIsGeneralTabValid() && getModel().getName().getIsValid() && getModel().getNumOfDesktops().getIsValid() && getModel().getPrestartedVms().getIsValid()); getModel().setIsPoolTabValid(true); return super.Validate() && getModel().getName().getIsValid() && getModel().getNumOfDesktops().getIsValid() && getModel().getPrestartedVms().getIsValid(); }
Source:
protected Scope decorateScope(@Nullable TraceContext currentSpan, Scope scope) { int length = scopeDecorators.size(); if (length == 0) return scope; for (int i = 0; i < length; i++) { scope = scopeDecorators.get(i).decorateScope(currentSpan, scope); } return scope; }

Target:
protected Scope decorateScope(@Nullable TraceContext currentSpan, Scope scope) { int length = scopeDecorators.size(); for (int i = 0; i < length; i++) { scope = scopeDecorators.get(i).decorateScope(currentSpan, scope); } return scope; }
Source:
private String[] getHeaders() { String[] toReturn = { "Test Case", "Dry Run Results:Test Points", "Dry Run Results:Total Fails", "DemoResults:Total Test Points", "Demo: Code Problems", "Script Problems", "Requirements", "Under Investigation", "Other", "Total Fails", "Verification of RPCR", "Commnets"}; return toReturn; }

Target:
private static String[] getHeaders() { String[] toReturn = { "Test Case", "Dry Run Results:Test Points", "Dry Run Results:Total Fails", "DemoResults:Total Test Points", "Demo: Code Problems", "Script Problems", "Requirements", "Under Investigation", "Other", "Total Fails", "Verification of RPCR", "Commnets"}; return toReturn; }
Source:
public T next() { if (closed) { return null; } T res = buffer.next(); if (res != null) { return res; } else if (jobTerminated) { return null; } while (true) { if (isJobTerminated()) { jobTerminated = true; Tuple2<Long, CollectCoordinationResponse> accResults = getAccumulatorResults(); if (accResults != null) { buffer.dealWithResponse(accResults.f1, accResults.f0); } buffer.complete(); } else { CollectCoordinationResponse<T> response; try { response = sendRequest(buffer.version, buffer.offset); } catch (Exception e) { LOG.warn("An exception occurs when fetching query results", e); sleepBeforeRetry(); continue; } buffer.dealWithResponse(response); } res = buffer.next(); if (res != null) { return res; } else if (jobTerminated) { return null; } else { sleepBeforeRetry(); } } }

Target:
public T next() throws IOException { if (closed) { return null; } boolean beforeFirstTry = true; do { T res = buffer.next(); if (res != null) { return res; } else if (jobTerminated) { return null; } else if (!beforeFirstTry) { sleepBeforeRetry(); } beforeFirstTry = false; if (isJobTerminated()) { jobTerminated = true; Tuple2<Long, CollectCoordinationResponse<T>> accResults = getAccumulatorResults(); buffer.dealWithResponse(accResults.f1, accResults.f0); buffer.complete(); } else { long requestOffset = buffer.offset; CollectCoordinationResponse<T> response; try { response = sendRequest(buffer.version, requestOffset); } catch (Exception e) { LOG.warn("An exception occurs when fetching query results", e); continue; } buffer.dealWithResponse(response, requestOffset); } } while (true); }
Source:
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof DiskUsage)) return false; DiskUsage diskUsage = (DiskUsage) o; if (!Objects.equals(tables, diskUsage.tables)) return false; return Objects.equals(usage, diskUsage.usage); }

Target:
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof DiskUsage)) return false; DiskUsage diskUsage = (DiskUsage) o; return Objects.equals(tables, diskUsage.tables) && Objects.equals(usage, diskUsage.usage); }
Source:
public double distance(OGCGeometry another) { if (another.geometryType() == OGCConcreteGeometryCollection.TYPE) { return another.distance(this); } com.esri.core.geometry.Geometry geom1 = getEsriGeometry(); com.esri.core.geometry.Geometry geom2 = another.getEsriGeometry(); return com.esri.core.geometry.GeometryEngine.distance(geom1, geom2, getEsriSpatialReference()); }

Target:
public double distance(OGCGeometry another) { if (this == another) { return isEmpty() ? Double.NaN : 0; } if (another.geometryType() == OGCConcreteGeometryCollection.TYPE) { return another.distance(this); } com.esri.core.geometry.Geometry geom1 = getEsriGeometry(); com.esri.core.geometry.Geometry geom2 = another.getEsriGeometry(); return com.esri.core.geometry.GeometryEngine.distance(geom1, geom2, getEsriSpatialReference()); }
Source:
public Response updateItem(@Context HttpServletRequest request, @PathParam("id") String id, String content) { Response response = null; String mergedId = null; try (ItemManager itemManager = new ItemManager()) { Item dbItem = itemManager.load(id); Item updatedItem = Item.fromJSON(content); String trackId = null; if(dbItem != null && !updatedItem.isActiveStorm() && dbItem.isActiveStorm()) { Item trackItem = StormUtil.findTrackChildItem(updatedItem); if(trackItem != null) { trackId = trackItem.getId(); updatedItem.getChildren().remove( updatedItem.getChildren().indexOf(trackItem) ); } } Item mergedItem = Item.copyValues(updatedItem, dbItem); if (dbItem == null) { mergedId = itemManager.persist(mergedItem); } else { mergedId = itemManager.merge(mergedItem); } if (trackId != null && mergedId != null) { itemManager.delete(trackId, true); } } if (null != mergedId) { response = Response.ok().build(); } else { throw new BadRequestException(); } try (StatusManager statusMan = new StatusManager(); ThumbnailManager thumbMan = new ThumbnailManager()) { Status status = new Status(); status.setStatusName(Status.StatusName.ITEM_UPDATE); statusMan.save(status); thumbMan.updateDirtyBits(id); } return response; }

Target:
public Response updateItem(@Context HttpServletRequest request, @PathParam("id") String id, String content) { Response response = null; String mergedId = null; try (ItemManager itemManager = new ItemManager()) { Item dbItem = itemManager.load(id); Item updatedItem = Item.fromJSON(content); String trackId = null; if(dbItem != null && !updatedItem.isActiveStorm() && dbItem.isActiveStorm()) { Item trackItem = StormUtil.findTrackChildItem(updatedItem); if(trackItem != null) { trackId = trackItem.getId(); updatedItem.getChildren().remove( updatedItem.getChildren().indexOf(trackItem) ); } } Item mergedItem = Item.copyValues(updatedItem, dbItem); if (dbItem == null) { mergedId = itemManager.persist(mergedItem); } else { mergedId = itemManager.merge(mergedItem); } if (null != mergedId) { response = Response.ok().build(); } else { throw new BadRequestException(); } if (trackId != null) { itemManager.delete(trackId, true); } } try (StatusManager statusMan = new StatusManager(); ThumbnailManager thumbMan = new ThumbnailManager()) { Status status = new Status(); status.setStatusName(Status.StatusName.ITEM_UPDATE); statusMan.save(status); thumbMan.updateDirtyBits(id); } return response; }
Source:
private Class<?> getFirstInterfaceOrDefined(Object bean, Class defInterface) { Class<?>[] interfaces = bean.getClass().getInterfaces(); for (Class<?> clazz : interfaces) { if (defInterface == null) { return clazz; } else { if (clazz.equals(defInterface)) { return clazz; } } } throw new IllegalStateException(bean.getClass().getCanonicalName() + " not implement interface " + defInterface .getCanonicalName()); }

Target:
private Class<?> getFirstInterfaceOrDefined(Object bean, Class defInterface) { Class<?>[] interfaces = bean.getClass().getInterfaces(); for (Class<?> clazz : interfaces) { if (defInterface == null) { return clazz; } else { if (clazz.equals(defInterface)) { return clazz; } } } throw new PublishException( bean.getClass().getCanonicalName() + " does not implement interface " + defInterface.getCanonicalName()); }
Source:
protected ActionResult execute() throws EntityDoesNotExistException { courseId = getRequestParamValue(Const.ParamsNames.COURSE_ID); feedbackSessionName = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME); Assumption.assertPostParamNotNull(Const.ParamsNames.COURSE_ID, courseId); Assumption.assertPostParamNotNull(Const.ParamsNames.FEEDBACK_SESSION_NAME, feedbackSessionName); String regKey = getRequestParamValue(Const.ParamsNames.REGKEY); String email = getRequestParamValue(Const.ParamsNames.STUDENT_EMAIL); if (!isSpecificUserJoinedCourse()) { return createPleaseJoinCourseResponse(courseId); } FeedbackSessionAttributes feedbackSession = logic.getFeedbackSession(feedbackSessionName, courseId); if (feedbackSession == null) { statusToUser.add(new StatusMessage("The feedback session has been deleted and is no longer accessible.", StatusMessageColor.WARNING)); return createSpecificRedirectResult(); } verifyAccesibleForSpecificUser(feedbackSession); String userEmailForCourse = getUserEmailForCourse(); data = new FeedbackSubmissionEditPageData(account, student); setDataBundle(userEmailForCourse); data.setSessionOpenForSubmission(isSessionOpenForSpecificUser(data.bundle.feedbackSession)); setStatusToAdmin(); if (!data.isSessionOpenForSubmission()) { statusToUser.add(new StatusMessage(Const.StatusMessages.FEEDBACK_SUBMISSIONS_NOT_OPEN, StatusMessageColor.WARNING)); } data.init(regKey, email, courseId); return createSpecificShowPageResult(); }

Target:
protected ActionResult execute() throws EntityDoesNotExistException { courseId = getRequestParamValue(Const.ParamsNames.COURSE_ID); feedbackSessionName = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME); Assumption.assertPostParamNotNull(Const.ParamsNames.COURSE_ID, courseId); Assumption.assertPostParamNotNull(Const.ParamsNames.FEEDBACK_SESSION_NAME, feedbackSessionName); String regKey = getRequestParamValue(Const.ParamsNames.REGKEY); String email = getRequestParamValue(Const.ParamsNames.STUDENT_EMAIL); if (!isSpecificUserJoinedCourse()) { return createPleaseJoinCourseResponse(courseId); } FeedbackSessionAttributes feedbackSession = logic.getFeedbackSession(feedbackSessionName, courseId); if (feedbackSession == null) { statusToUser.add(new StatusMessage("The feedback session has been deleted and is no longer accessible.", StatusMessageColor.WARNING)); return createSpecificRedirectResult(); } verifyAccesibleForSpecificUser(feedbackSession); String userEmailForCourse = getUserEmailForCourse(); data = new FeedbackSubmissionEditPageData(account, student); data.bundle = getDataBundle(userEmailForCourse); data.setSessionOpenForSubmission(isSessionOpenForSpecificUser(data.bundle.feedbackSession)); setStatusToAdmin(); if (!data.isSessionOpenForSubmission()) { statusToUser.add(new StatusMessage(Const.StatusMessages.FEEDBACK_SUBMISSIONS_NOT_OPEN, StatusMessageColor.WARNING)); } data.init(regKey, email, courseId); return createSpecificShowPageResult(); }
Source:
private static int findNextSibling(DetailAST ast, int tokenType) { int token = -1; DetailAST node = ast.getNextSibling(); while (node != null) { if (node.getType() == tokenType) { token = node.getType(); break; } node = node.getNextSibling(); } return token; }

Target:
private static DetailAST findNextSibling(DetailAST ast, int tokenType) { DetailAST token = null; DetailAST node = ast.getNextSibling(); while (node != null) { if (node.getType() == tokenType) { token = node; break; } node = node.getNextSibling(); } return token; }
Source:
public abstract ExecutionResult execute(int selectedConfigurationId, @NotNull String cloudProjectId, @NotNull AndroidRunningState runningState, @NotNull Executor executor) throws ExecutionException; public boolean isCloudTestingOptionEnabled(Project project) { GoogleCloudTestingConfigurable.GoogleCloudTestingState googleCloudTestingState = GoogleCloudTestingSettings.getInstance(project).getState(); return googleCloudTestingState != null && googleCloudTestingState.enableCloudTesting; }

Target:
public abstract ExecutionResult execute(int selectedConfigurationId, @NotNull String cloudProjectId, @NotNull AndroidRunningState runningState, @NotNull Executor executor) throws ExecutionException; public static boolean isEnabled() { CloudTestingConfigurable.cloudTestingState cloudTestingState = CloudTestingSettings.getInstance().getState(); return cloudTestingState != null && cloudTestingState.enableCloudTesting; }
Source:
protected static void init(PerunSession sess) throws InternalErrorException { log.trace("Initializing AuthzResolver for [{}]", sess.getPerunPrincipal()); refreshAuthz(sess); log.debug("AuthzResolver: Complete PerunPrincipal: {}", sess.getPerunPrincipal()); }

Target:
protected static void init(PerunSession sess) throws InternalErrorException { log.trace("Initializing AuthzResolver for [{}]", sess.getPerunPrincipal()); refreshAuthz(sess); log.trace("AuthzResolver: Complete PerunPrincipal: {}", sess.getPerunPrincipal()); }
Source:
public void record(String hostname, int statusCode) { hostMetrics.getUnchecked(hostname).record(statusCode); }

Target:
public void record(String hostname, int statusCode) { try { hostMetrics.getUnchecked(hostname).record(statusCode); } catch (Exception e) { log.warn("Unable to record metrics for host", UnsafeArg.of("hostname", hostname)); } }
Source:
public static void withinTransaction(EntityManager em, Runnable codeblock) { EntityTransaction transaction = em.getTransaction(); transaction.begin(); try { codeblock.run(); transaction.commit(); } catch (Throwable t) { if ( transaction.isActive() ) { transaction.rollback(); } throw t; } }

Target:
public static void withinTransaction(EntityManager em, Runnable codeblock) { EntityTransaction transaction = em.getTransaction(); transaction.begin(); try { codeblock.run(); transaction.commit(); } catch (Throwable mainError) { try { if ( transaction.isActive() ) { transaction.rollback(); } } catch (Throwable errorOnRollBack) { mainError.addSuppressed( errorOnRollBack ); } throw mainError; } }
Source:
public long transferTo(long position, long count, WritableByteChannel target) throws IOException { long bytesRead = 0; try { ensureProperFile(false, position); bytesRead = sageFileChannel.transferTo(position - fileOffsets[currFileIndex], count, target); if (bytesRead < count) { ensureProperFile(false, position); bytesRead += sageFileChannel.transferTo(position + bytesRead - fileOffsets[currFileIndex], count - bytesRead, target); } } finally { ensureProperFile(false); } return bytesRead; }

Target:
public long transferTo(long position, long count, WritableByteChannel target) throws IOException { long remaining = size() - position; if (remaining < count) count = remaining; long bytesRead = 0; try { while (bytesRead < count) { ensureProperFile(false, position); bytesRead += sageFileChannel.transferTo(position + bytesRead - fileOffsets[currFileIndex], count - bytesRead, target); } } finally { ensureProperFile(false); } return bytesRead; }
Source:
public void init(Properties props, String topicName) { super.init(props, topicName); try { SchemaRegistry<Schema> registry = (SchemaRegistry<Schema>) Class.forName( props.getProperty(KafkaAvroMessageEncoder.KAFKA_MESSAGE_CODER_SCHEMA_REGISTRY_CLASS)).newInstance(); registry.init(props); this.registry = new CachedSchemaRegistry<Schema>(registry); this.latestSchema = registry.getLatestSchemaByTopic(topicName).getSchema(); timestampField = props.getProperty(JsonStringMessageDecoder.CAMUS_MESSAGE_TIMESTAMP_FIELD); timestampFormat = props.getProperty(JsonStringMessageDecoder.CAMUS_MESSAGE_TIMESTAMP_FORMAT, JsonStringMessageDecoder.CAMUS_MESSAGE_TIMESTAMP_FORMAT); } catch (Exception e) { throw new MessageDecoderException(e); } decoderFactory = DecoderFactory.get(); }

Target:
public void init(Properties props, String topicName) { super.init(props, topicName); try { SchemaRegistry<Schema> registry = (SchemaRegistry<Schema>) Class.forName( props.getProperty(KafkaAvroMessageEncoder.KAFKA_MESSAGE_CODER_SCHEMA_REGISTRY_CLASS)).newInstance(); registry.init(props); this.registry = new CachedSchemaRegistry<Schema>(registry); this.latestSchema = registry.getLatestSchemaByTopic(topicName).getSchema(); timestampField = props.getProperty(CAMUS_MESSAGE_TIMESTAMP_FIELD, DEFAULT_TIMESTAMP_FIELD); timestampFormat = props.getProperty(CAMUS_MESSAGE_TIMESTAMP_FORMAT, UNIX_MILLISECONDS); } catch (Exception e) { throw new MessageDecoderException(e); } decoderFactory = DecoderFactory.get(); }
Source:
public void askAKafkaConsumerWithoutServerUpTest(){ SnapshotOnDemandUtils snapshotOnDemandUtils = new SnapshotOnDemandUtilsImpl(); EnvConfig config = EnvConfig.getDefaultEnvConfig(); config.local(false); config.underTest(false); KafkaConsumer consumer = snapshotOnDemandUtils.getConfiguredSnapshotConsumer(config); assertNull(consumer); }

Target:
public void askAKafkaConsumerWithoutServerUpTest(){ KafkaConsumer consumer = snapshotOnDemandUtils.getConfiguredSnapshotConsumer(config); assertNull(consumer); }
Source:
public void searchRoles(@NonNull final JSONObject filters, final KuzzleOptions options, @NonNull final KuzzleResponseListener<KuzzleSecurityDocumentList> listener) throws JSONException { if (filters == null) { throw new IllegalArgumentException("KuzzleSecurity.searchRoles: filters cannot be null"); } if (listener == null) { throw new IllegalArgumentException("KuzzleSecurity.searchRoles: a callback listener is required"); } JSONObject data = new JSONObject().put("body", filters); this.kuzzle.query(buildQueryArgs("searchRoles"), data, options, new OnQueryDoneListener() { @Override public void onSuccess(JSONObject response) { try { JSONObject result = response.getJSONObject("result"); JSONArray documents = result.getJSONArray("hits"); int documentsLength = documents.length(); LinkedList<AbstractKuzzleSecurityDocument> roles = new LinkedList<>(); for (int i = 0; i < documentsLength; i++) { JSONObject document = documents.getJSONObject(i); roles.add(new KuzzleRole(KuzzleSecurity.this.kuzzle, document.getString("_id"), document.getJSONObject("_source"))); } listener.onSuccess(new KuzzleSecurityDocumentList(roles, result.getLong("total"))); } catch (JSONException e) { throw new RuntimeException(e); } } @Override public void onError(JSONObject error) { listener.onError(error); } }); }

Target:
public void searchRoles(@NonNull final JSONObject filters, final KuzzleOptions options, @NonNull final KuzzleResponseListener<KuzzleSecurityDocumentList> listener) throws JSONException { if (filters == null) { throw new IllegalArgumentException("KuzzleSecurity.searchRoles: filters cannot be null"); } if (listener == null) { throw new IllegalArgumentException("KuzzleSecurity.searchRoles: a callback listener is required"); } JSONObject data = new JSONObject().put("body", filters); this.kuzzle.query(buildQueryArgs("searchRoles"), data, options, new OnQueryDoneListener() { @Override public void onSuccess(JSONObject response) { try { JSONObject result = response.getJSONObject("result"); JSONArray documents = result.getJSONArray("hits"); int documentsLength = documents.length(); ArrayList<AbstractKuzzleSecurityDocument> roles = new ArrayList<>(); for (int i = 0; i < documentsLength; i++) { JSONObject document = documents.getJSONObject(i); roles.add(new KuzzleRole(KuzzleSecurity.this.kuzzle, document.getString("_id"), document.getJSONObject("_source"))); } listener.onSuccess(new KuzzleSecurityDocumentList(roles, result.getLong("total"))); } catch (JSONException e) { throw new RuntimeException(e); } } @Override public void onError(JSONObject error) { listener.onError(error); } }); }
Source:
private void bindParameterValues( long lo, long msgLimit, short parameterValueCount, @Transient ObjList<BindVariableSetter> bindVariableSetters ) throws BadProtocolException, SqlException { boolean inferTypes = parameterValueCount != bindVariableService.getIndexedVariableCount(); boolean allTextFormat = parameterFormats.size() == 0 || (parameterFormats.size() == 1 && parameterFormats.get(0) == 0); boolean allBinaryFormat = parameterFormats.size() == 1 && parameterFormats.get(0) == 1; for (int j = 0; j < parameterValueCount; j++) { if (lo + Integer.BYTES > msgLimit) { LOG.error().$("could not read parameter value length [index=").$(j).$(']').$(); throw BadProtocolException.INSTANCE; } int valueLen = getInt(lo); lo += Integer.BYTES; if (valueLen == -1) { continue; } if (lo + valueLen > msgLimit) { LOG.error() .$("value length is outside of buffer [parameterIndex=").$(j) .$(", valueLen=").$(valueLen) .$(", messageRemaining=").$(msgLimit - lo) .$(']').$(); throw BadProtocolException.INSTANCE; } ensureData(lo, valueLen, msgLimit, j); if (inferTypes) { int pgType = inferParameterType(lo, valueLen); setupBindVariable(bindVariableSetters, j, pgType); } if (allTextFormat || (!allBinaryFormat) && parameterFormats.get(j) == 0) { bindVariableSetters.setQuick(j * 2, bindVariableSetters.getQuick(j * 2 + 1)); } bindVariableSetters.getQuick(j * 2).set(j, lo, valueLen); lo += valueLen; } }

Target:
private void bindParameterValues( long lo, long msgLimit, short parameterValueCount, @Transient ObjList<BindVariableSetter> bindVariableSetters ) throws BadProtocolException, SqlException { boolean inferTypes = parameterValueCount != bindVariableService.getIndexedVariableCount(); boolean allTextFormat = parameterFormats.size() == 0 || (parameterFormats.size() == 1 && parameterFormats.get(0) == 0); boolean allBinaryFormat = parameterFormats.size() == 1 && parameterFormats.get(0) == 1; for (int j = 0; j < parameterValueCount; j++) { if (lo + Integer.BYTES > msgLimit) { LOG.error().$("could not read parameter value length [index=").$(j).$(']').$(); throw BadProtocolException.INSTANCE; } int valueLen = getInt(lo); lo += Integer.BYTES; if (valueLen == -1) { continue; } if (lo + valueLen > msgLimit) { LOG.error() .$("value length is outside of buffer [parameterIndex=").$(j) .$(", valueLen=").$(valueLen) .$(", messageRemaining=").$(msgLimit - lo) .$(']').$(); throw BadProtocolException.INSTANCE; } ensureData(lo, valueLen, msgLimit, j); if (inferTypes) { int pgType = inferParameterType(lo, valueLen); if (pgType == -1) { LOG.error().$("invalid parameter type for parameter #[").$(j).$(']').$(); throw BadProtocolException.INSTANCE; } setupBindVariable(bindVariableSetters, j, pgType); } if (allTextFormat || (!allBinaryFormat) && parameterFormats.get(j) == 0) { bindVariableSetters.setQuick(j * 2, bindVariableSetters.getQuick(j * 2 + 1)); } bindVariableSetters.getQuick(j * 2).set(j, lo, valueLen); lo += valueLen; } }
Source:
public List<ServiceTaskSummary> getServiceTasks() { return repoService.getServices().stream() .map(repoData -> new ServiceTaskSummary(repoData.getId(), "fa fa-cogs", repoData.getName(), repoData.getDescription(), repoData.getActiontitle(), repoData.isEnabled(), repoData.getInstalledOn())) .collect(Collectors.toList()); }

Target:
public List<ServiceTaskSummary> getServiceTasks() { return repoService.getServices().stream() .map(repoData -> new ServiceTaskSummary(repoData.getId(), "fa fa-cogs", repoData.getName(), repoData.getDescription(), repoData.getActiontitle(), repoData.isEnabled(), repoData.getInstalledOn())) .sorted((service, service2) -> service.getName().compareTo(service2.getName())) .collect(Collectors.toList()); }
Source:
public V apply(EntryView.ReadWriteEntryView<K, V> entry) { try { V merged = value; if (entry.find().isPresent()) { V t = entry.get(); if (remappingFunction instanceof BiFunctionMapper) { BiFunctionMapper mapper = (BiFunctionMapper) this.remappingFunction; Object toStorage = mapper.getValueDataConversion().toStorage(t); merged = remappingFunction.apply((V) toStorage, value); } else { merged = remappingFunction.apply(t, value); } } if (merged == null) { entry.set(merged); } else { if (remappingFunction instanceof BiFunctionMapper) { BiFunctionMapper mapper = (BiFunctionMapper) this.remappingFunction; Object fromStorage = mapper.getValueDataConversion().fromStorage(merged); entry.set((V) fromStorage, metadata); } else { entry.set(merged, metadata); } } return merged; } catch (Exception ex) { throw new UserRaisedFunctionalException(ex); } }

Target:
public V apply(EntryView.ReadWriteEntryView<K, V> entry) { try { V merged = value; if (entry.find().isPresent()) { V t = entry.get(); if (remappingFunction instanceof BiFunctionMapper) { BiFunctionMapper mapper = (BiFunctionMapper) this.remappingFunction; Object toStorage = mapper.getValueDataConversion().toStorage(t); merged = remappingFunction.apply((V) toStorage, value); } else { merged = remappingFunction.apply(t, value); } } if (merged == null) { entry.set(merged); } else if (remappingFunction instanceof BiFunctionMapper) { BiFunctionMapper mapper = (BiFunctionMapper) this.remappingFunction; Object fromStorage = mapper.getValueDataConversion().fromStorage(merged); entry.set((V) fromStorage, metadata); } else { entry.set(merged, metadata); } return merged; } catch (Exception ex) { throw new UserRaisedFunctionalException(ex); } }
Source:
private void validateTimeRange() { Long currentTime = EnvironmentEdgeManager.currentTimeMillis(); if (startTime != null && (startTime.compareTo(currentTime) > 0 || (endTime != null && startTime.compareTo(endTime) >= 0))) { throw new RuntimeException(INVALID_TIME_RANGE_EXCEPTION_MESSAGE); } }

Target:
private void validateTimeRange() { Long currentTime = EnvironmentEdgeManager.currentTimeMillis(); Long st = (startTime == null) ? 0 : startTime; Long et = (endTime == null) ? currentTime : endTime; if (st.compareTo(currentTime) > 0 || et.compareTo(currentTime) > 0 || st.compareTo(et) >= 0) { throw new RuntimeException(INVALID_TIME_RANGE_EXCEPTION_MESSAGE); } }
Source:
public Object execute(final ExecutionEvent event) throws ExecutionException { final INattableModelManager manager = getCurrentNattableModelManager(); final ExportAsTableConfigurationWizard wizard = new ExportAsTableConfigurationWizard(); IStructuredSelection selection = new StructuredSelection(manager.getTable()); wizard.init(null, selection); WizardDialog dialog = new WizardDialog(Display.getDefault().getActiveShell(), wizard); dialog.open(); return null; }

Target:
public Object execute(final ExecutionEvent event) throws ExecutionException { final INattableModelManager manager = getCurrentNattableModelManager(); final Table table = manager.getTable(); if (table != null) { final ExportAsTableConfigurationWizard wizard = new ExportAsTableConfigurationWizard(); IStructuredSelection selection = new StructuredSelection(table); wizard.init(null, selection); WizardDialog dialog = new WizardDialog(Display.getDefault().getActiveShell(), wizard); dialog.open(); } return null; }
Source:
private void initWaypoints() { SwingWorker<List<Waypoint>, Waypoint> worker = new SwingWorker<List<Waypoint>, Waypoint>() { @Override protected List<Waypoint> doInBackground() throws Exception { Case currentCase = Case.getCurrentCaseThrows(); return MapWaypoint.getWaypoints(currentCase.getSleuthkitCase()); } @Override protected void done() { if (isDone() && !isCancelled()) { try { List<Waypoint> waypoints = get(); if (waypoints == null || waypoints.isEmpty()) { return; } for (Waypoint point : waypoints) { mapPanel.addWaypoint(point); } mapPanel.setCenterLocation(waypoints.get(0)); } catch (ExecutionException ex) { logger.log(Level.WARNING, "An exception occured while initalizing waypoints for geolocation window.", ex); MessageNotifyUtil.Message.error(Bundle.GLTopComponent_initilzation_error()); } catch (InterruptedException ex) { logger.log(Level.WARNING, "The initilization thread for geolocation window was interrupted.", ex); } } } }; worker.execute(); }

Target:
private void initWaypoints() { SwingWorker<List<Waypoint>, Waypoint> worker = new SwingWorker<List<Waypoint>, Waypoint>() { @Override protected List<Waypoint> doInBackground() throws Exception { Case currentCase = Case.getCurrentCaseThrows(); return MapWaypoint.getWaypoints(currentCase.getSleuthkitCase()); } @Override protected void done() { if (isDone() && !isCancelled()) { try { List<Waypoint> waypoints = get(); if (waypoints == null || waypoints.isEmpty()) { return; } for (Waypoint point : waypoints) { mapPanel.addWaypoint(point); } mapPanel.setCenterLocation(waypoints.get(0)); } catch (ExecutionException ex) { logger.log(Level.WARNING, "An exception occured while initializing waypoints for geolocation window.", ex); MessageNotifyUtil.Message.error(Bundle.GLTopComponent_initilzation_error()); } catch (InterruptedException ex) { logger.log(Level.WARNING, "The initializing thread for geolocation window was interrupted.", ex); } } } }; worker.execute(); }
Source:
private void appendUserData(Account user) { sb.append(user.getFullName()).append(" <").append(user.getPreferredEmail()) .append(">"); }

Target:
private void appendUserData(Account user) { if (user.getFullName() != null && ! user.getFullName().isEmpty()) { sb.append(user.getFullName()); } if (user.getPreferredEmail() != null && ! user.getPreferredEmail().isEmpty()) { if (sb.length() > 0) { sb.append(" "); } sb.append(user.getPreferredEmail()); } if (sb.length() == 0) { sb.append("Anonymout Coward #").append(user.getId()); } }
Source:
private boolean isValidNpmUser(NpmUser npmUser) { return npmUser != null && npmUser.getName() != null && npmUser.getPassword() != null && npmUser.getDate() != null && npmUser.getRoles() != null && npmUser.getType() != null && npmUser.getId() != null; }

Target:
private boolean isValidNpmUser(NpmUser npmUser) { return npmUser != null && npmUser.getName() != null && npmUser.getPassword() != null; }
Source:
public void afterPropertiesSet() throws Exception { Assert.isTrue(!(jsrDecider == null), "A decider implementation is required"); Assert.notNull(name, "A name is required for a decision state"); }

Target:
public void afterPropertiesSet() throws Exception { Assert.isTrue(jsrDecider != null, "A decider implementation is required"); Assert.notNull(name, "A name is required for a decision state"); }
Source:
public void downloadAsyncLanguagesFromServer() throws Exception { Log.i(TAG, "Starting to download Languages From Server"); AsyncExecutor asyncExecutor = new AsyncExecutor(); CredentialsReader credentialsReader = CredentialsReader.getInstance(); IConnectivityManager connectivity = NetworkManagerFactory.getConnectivityManager( PreferencesState.getInstance().getContext()); ISettingsRepository settingsRepository = new SettingsDataSource( PreferencesState.getInstance().getContext()); DownloadLanguageTranslationUseCase downloader = new DownloadLanguageTranslationUseCase(credentialsReader, connectivity, settingsRepository); downloader.downloadAsync(asyncExecutor); }

Target:
public void downloadAsyncLanguagesFromServer() throws Exception { Log.i(TAG, "Starting to download Languages From Server"); AsyncExecutor asyncExecutor = new AsyncExecutor(); CredentialsReader credentialsReader = CredentialsReader.getInstance(); IConnectivityManager connectivity = NetworkManagerFactory.getConnectivityManager( PreferencesState.getInstance().getContext()); DownloadLanguageTranslationUseCase downloader = new DownloadLanguageTranslationUseCase(credentialsReader, connectivity); downloader.downloadAsync(asyncExecutor); }
Source:
public boolean execute(final IDebugCommandRequest request) { final Optional<ICommandControlDMContext> context = getContext(request); if (!context.isPresent()) { request.done(); return false; } fExecutor.execute(new DsfRunnable() { @Override public void run() { final IGDBExtendedFunctions funcService = fTracker.getService(IGDBExtendedFunctions.class); if (funcService == null) { request.done(); } else { funcService.getVersion(context.get(), new DataRequestMonitor<String>(fExecutor, null) { @Override protected void handleCompleted() { String str; if (isSuccess()) { str = "======= GDB version: " + getData() + " ======="; } else { str = "Could not obtain GDB version. Error: " + getStatus(); } funcService.notify(context.get(), str, new RequestMonitor(fExecutor, null) { @Override protected void handleCompleted() { request.done(); } }); } }); } } }); return false; }

Target:
public boolean execute(final IDebugCommandRequest request) { final Optional<ICommandControlDMContext> context = getContext(request); if (!context.isPresent()) { request.done(); return false; } fExecutor.execute(new DsfRunnable() { @Override public void run() { final IGDBExtendedFunctions funcService = fTracker.getService(IGDBExtendedFunctions.class); if (funcService == null) { request.done(); } else { funcService.getVersion(context.get(), new DataRequestMonitor<String>(fExecutor, null) { @Override protected void handleCompleted() { String str; if (isSuccess()) { str = "======= GDB version: " + getData() + " ======="; } else { str = "Could not obtain GDB version. Error: " + getStatus(); } funcService.notify(context.get(), str, new RequestMonitor(fExecutor, null) { @Override protected void handleCompleted() { request.done(); } }); } }); } } }); return true; }
Source:
private boolean matchAllConfigs(String[] configs) { if (configs != null) { for (String config : configs) { switch (config) { case CONFIG_VOICE_CAPABLE: TelephonyManager telephonyManager = mContext.getSystemService( TelephonyManager.class); if (!telephonyManager.isVoiceCapable()) { return false; } break; case CONFIG_HAS_RECENTS: final Resources systemRes = mContext.getResources().getSystem(); final int id = systemRes.getIdentifier("config_hasRecents", "bool", "android"); if (id == Resources.ID_NULL || !systemRes.getBoolean(id)) { return false; } break; case CONFIG_HDMI_SOURCE: final String DEVICE_TYPE_HDMI_SOURCE = "4"; if (!getSystemProperty("ro.hdmi.device_type") .equals(DEVICE_TYPE_HDMI_SOURCE)) { return false; } break; default: break; } } } return true; }

Target:
private boolean matchAllConfigs(String[] configs) { if (configs != null) { for (String config : configs) { switch (config) { case CONFIG_VOICE_CAPABLE: TelephonyManager telephonyManager = mContext.getSystemService( TelephonyManager.class); if (!telephonyManager.isVoiceCapable()) { return false; } break; case CONFIG_HAS_RECENTS: final Resources systemRes = mContext.getResources().getSystem(); final int id = systemRes.getIdentifier("config_hasRecents", "bool", "android"); if (id == Resources.ID_NULL || !systemRes.getBoolean(id)) { return false; } break; case CONFIG_HDMI_SOURCE: final int DEVICE_TYPE_HDMI_SOURCE = 4; try { if (!getDeviceType().contains(DEVICE_TYPE_HDMI_SOURCE)) { return false; } } catch (Exception exception) { Log.e( LOG_TAG, "Exception while looking up HDMI device type.", exception); } break; default: break; } } } return true; }
Source:
private static void generateGetOutputChannelsMethod(ClassDefinition classDefinition, FieldDefinition probeOutputChannelsField) { MethodDefinition method = classDefinition.declareMethod( a(PUBLIC), "getOutputChannels", type(int[].class)); Variable thisVariable = method.getThis(); method.getBody() .append(thisVariable.getField(probeOutputChannelsField)) .ret(int[].class); }

Target:
private static void generateGetOutputChannelsMethod(ClassDefinition classDefinition, FieldDefinition probeOutputChannelsField) { MethodDefinition method = classDefinition.declareMethod( a(PUBLIC), "getOutputChannels", type(int[].class)); method.getBody() .append(method.getThis().getField(probeOutputChannelsField)) .ret(int[].class); }
Source:
public PiecewisePolynomialResult interpolate(double[] xValues, double[] yValues) { ArgumentChecker.notNull(xValues, "xValues"); ArgumentChecker.notNull(yValues, "yValues"); ArgumentChecker.isTrue(xValues.length == yValues.length, "xValues length = yValues length"); PiecewisePolynomialResult result; if (isClamped()) { double[][] xyValuesAll = getDataTotal(xValues, yValues); result = _baseMethod.interpolate(xyValuesAll[0], xyValuesAll[1]); } else { double[] xyValues = getProduct(xValues, yValues); result = _baseMethod.interpolate(xValues, xyValues); } int nIntervalsAll = result.getNumberOfIntervals(); double[] nodes = result.getKnots().getData(); if (Math.abs(xValues[xValues.length - 1] - nodes[nIntervalsAll]) < EPS) { double lastNodeX = nodes[nIntervalsAll]; double lastNodeY = FUNC.evaluate(result, lastNodeX).getEntry(0); double extraNode = 2.0 * nodes[nIntervalsAll] - nodes[nIntervalsAll - 2]; double extraDerivative = FUNC.differentiate(result, lastNodeX).getEntry(0); double[] newKnots = new double[nIntervalsAll + 2]; System.arraycopy(result.getKnots().getData(), 0, newKnots, 0, nIntervalsAll + 1); newKnots[nIntervalsAll + 1] = extraNode; double[][] newCoefMatrix = new double[nIntervalsAll + 1][]; for (int i = 0; i < nIntervalsAll; ++i) { newCoefMatrix[i] = Arrays.copyOf(result.getCoefMatrix().getRowVector(i).getData(), result.getOrder()); } newCoefMatrix[nIntervalsAll] = new double[result.getOrder()]; newCoefMatrix[nIntervalsAll][result.getOrder() - 1] = lastNodeY; newCoefMatrix[nIntervalsAll][result.getOrder() - 2] = extraDerivative; result = new PiecewisePolynomialResult(new DoubleMatrix1D(newKnots), new DoubleMatrix2D(newCoefMatrix), result.getOrder(), 1); } return result; }

Target:
public PiecewisePolynomialResult interpolate(double[] xValues, double[] yValues) { ArgumentChecker.notNull(xValues, "xValues"); ArgumentChecker.notNull(yValues, "yValues"); ArgumentChecker.isTrue(xValues.length == yValues.length, "xValues length = yValues length"); PiecewisePolynomialResult result; if (_isClamped) { double[][] xyValuesAll = getDataTotal(xValues, yValues); result = _baseMethod.interpolate(xyValuesAll[0], xyValuesAll[1]); } else { double[] xyValues = getProduct(xValues, yValues); result = _baseMethod.interpolate(xValues, xyValues); } return extrapolateByLinearFunction(result, xValues); }