auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Fragment getItem(int pos) { CourseComponent unit = getUnit(pos); CourseUnitFragment unitFragment; if (unit instanceof VideoBlockModel && ((VideoBlockModel) unit).getData().encodedVideos.getPreferredVideoInfo() != null) { unitFragment = CourseUnitVideoFragment.newInstance((VideoBlockModel) unit); } else if (unit instanceof VideoBlockModel && ((VideoBlockModel) unit).getData().encodedVideos.getYoutubeVideoInfo() != null) { unitFragment = CourseUnitOnlyOnYoutubeFragment.newInstance(unit); } else if (unit.getType() == BlockType.DISCUSSION) { unitFragment = CourseUnitDiscussionFragment.newInstance(unit, courseData); } else if (!unit.isMultiDevice()) { unitFragment = CourseUnitMobileNotSupportedFragment.newInstance(unit); } else if (unit.getType() != BlockType.VIDEO && unit.getType() != BlockType.HTML && unit.getType() != BlockType.OTHERS && unit.getType() != BlockType.PROBLEM) { unitFragment = CourseUnitEmptyFragment.newInstance(unit); } else if (unit instanceof HtmlBlockModel) { unitFragment = CourseUnitWebViewFragment.newInstance((HtmlBlockModel) unit); } else { unitFragment = CourseUnitMobileNotSupportedFragment.newInstance(unit); } unitFragment.setHasComponentCallback(callback); return unitFragment; }

Target:
public Fragment getItem(int pos) { CourseComponent unit = getUnit(pos); CourseUnitFragment unitFragment; if (unit instanceof VideoBlockModel && ((VideoBlockModel) unit).getData().encodedVideos.getPreferredVideoInfo() != null) { unitFragment = CourseUnitVideoFragment.newInstance((VideoBlockModel) unit); } else if (unit instanceof VideoBlockModel && ((VideoBlockModel) unit).getData().encodedVideos.getYoutubeVideoInfo() != null) { unitFragment = CourseUnitOnlyOnYoutubeFragment.newInstance(unit); } else if (unit instanceof DiscussionBlockModel) { unitFragment = CourseUnitDiscussionFragment.newInstance(unit, courseData); } else if (!unit.isMultiDevice()) { unitFragment = CourseUnitMobileNotSupportedFragment.newInstance(unit); } else if (unit.getType() != BlockType.VIDEO && unit.getType() != BlockType.HTML && unit.getType() != BlockType.OTHERS && unit.getType() != BlockType.DISCUSSION && unit.getType() != BlockType.PROBLEM) { unitFragment = CourseUnitEmptyFragment.newInstance(unit); } else if (unit instanceof HtmlBlockModel) { unitFragment = CourseUnitWebViewFragment.newInstance((HtmlBlockModel) unit); } else { unitFragment = CourseUnitMobileNotSupportedFragment.newInstance(unit); } unitFragment.setHasComponentCallback(callback); return unitFragment; }
Source:
public int compareTo(final Type type) { if (type instanceof ConstT) { if (this.constructor.compareTo(((ConstT) type).constructor) == 0) { if (this.args.length == ((ConstT) type).args.length) { for (int i = 0; i < this.args.length; i++) { if (this.args[i].compareTo(((ConstT) type).args[i]) != 0) { return -1; } } return 0; } else { return -1; } } else { return this.constructor.compareTo(((ConstT) type).constructor); } } else { return -1; } }

Target:
public int compareTo(final Type type) { if (type == null) { throw new NullPointerException(); } else if (type instanceof ConstT) { final ConstT cType = (ConstT) type; if (this.constructor.equals(cType.constructor)) { if (this.args.length == cType.args.length) { for (int i = 0; i < this.args.length; i++) { if (this.args[i].compareTo(cType.args[i]) != 0) { return -1; } } return 0; } else { return -1; } } else { return this.constructor.compareTo(cType.constructor); } } else { return -1; } }
Source:
public String getCapabilities() { return capabilities; }

Target:
public String getCapabilities() { return StringUtils.notNullStr(capabilities); }
Source:
public void isAccountNull(){ ValidationResult validationResult = concurAccountValidationService.checkAccount(ConcurAccountValidationTestConstants.VALID_CHART, null); assertEquals("Validation was expected to fail but returned true", false, validationResult.isValid()); assertEquals( "Error message was expected for null account number", ConcurConstants.AccountingStringValidationErrorMessages.ERROR_ACCT_DOES_NOT_EXIST + KFSConstants.NEWLINE, validationResult.getErrorMessagesAsOneFormattedString()); }

Target:
public void isAccountNull(){ ValidationResult validationResult = concurAccountValidationService.checkAccount(ConcurAccountValidationTestConstants.VALID_CHART, null); Assert.assertFalse("Validation was expected to fail but returned true", validationResult.isValid()); Assert.assertEquals( "Error message was expected for null account number", MessageFormat.format(concurAccountValidationService.getConfigurationService().getPropertyValueAsString(KFSKeyConstants.ERROR_EXISTENCE), ConcurConstants.AccountingStringFieldNames.ACCOUNT_NUMBER) + KFSConstants.NEWLINE, validationResult.getErrorMessagesAsOneFormattedString()); }
Source:
public static void assertPlan(Session session, Metadata metadata, StatsProvider statsProvider, Plan actual, Lookup lookup, PlanMatchPattern pattern) { CostProvider costProvider = node -> UNKNOWN_COST; MatchResult matches = actual.getRoot().accept(new PlanMatchingVisitor(session, metadata, statsProvider, lookup), pattern); if (!matches.isMatch()) { String formattedPlan = textLogicalPlan(actual.getRoot(), actual.getTypes(), metadata.getFunctionRegistry(), actual.getStatsAndCosts(), session, 0); PlanNode resolvedPlan = resolveGroupReferences(actual.getRoot(), lookup); String resolvedFormattedPlan = textLogicalPlan(resolvedPlan, actual.getTypes(), metadata.getFunctionRegistry(), actual.getStatsAndCosts(), session, 0); throw new AssertionError(format( "Plan does not match, expected [\n\n%s\n] but found [\n\n%s\n] which resolves to [\n\n%s\n]", pattern, formattedPlan, resolvedFormattedPlan)); } }

Target:
public static void assertPlan(Session session, Metadata metadata, StatsProvider statsProvider, Plan actual, Lookup lookup, PlanMatchPattern pattern) { MatchResult matches = actual.getRoot().accept(new PlanMatchingVisitor(session, metadata, statsProvider, lookup), pattern); if (!matches.isMatch()) { String formattedPlan = textLogicalPlan(actual.getRoot(), actual.getTypes(), metadata.getFunctionRegistry(), StatsAndCosts.empty(), session, 0); PlanNode resolvedPlan = resolveGroupReferences(actual.getRoot(), lookup); String resolvedFormattedPlan = textLogicalPlan(resolvedPlan, actual.getTypes(), metadata.getFunctionRegistry(), StatsAndCosts.empty(), session, 0); throw new AssertionError(format( "Plan does not match, expected [\n\n%s\n] but found [\n\n%s\n] which resolves to [\n\n%s\n]", pattern, formattedPlan, resolvedFormattedPlan)); } }
Source:
private static Optional<ConditionAnalysis> analyzeCondition(final RexNode condition, final RelDataType leftRowType) { final List<RexNode> subConditions = decomposeAnd(condition); final List<Pair<RexNode, RexInputRef>> equalitySubConditions = new ArrayList<>(); final List<RexLiteral> literalSubConditions = new ArrayList<>(); final int numLeftFields = leftRowType.getFieldCount(); for (RexNode subCondition : subConditions) { if (RexUtil.isLiteral(subCondition, true)) { if (subCondition instanceof RexCall) { RexCall call = (RexCall) subCondition; literalSubConditions.add((RexLiteral) call.operands.get(0)); } else { literalSubConditions.add((RexLiteral) subCondition); } continue; } if (!subCondition.isA(SqlKind.EQUALS)) { return Optional.empty(); } final List<RexNode> operands = ((RexCall) subCondition).getOperands(); Preconditions.checkState(operands.size() == 2, "Expected 2 operands, got[%,d]", operands.size()); if (isLeftExpression(operands.get(0), numLeftFields) && isRightInputRef(operands.get(1), numLeftFields)) { equalitySubConditions.add(Pair.of(operands.get(0), (RexInputRef) operands.get(1))); } else if (isRightInputRef(operands.get(0), numLeftFields) && isLeftExpression(operands.get(1), numLeftFields)) { equalitySubConditions.add(Pair.of(operands.get(1), (RexInputRef) operands.get(0))); } else { return Optional.empty(); } } return Optional.of(new ConditionAnalysis(numLeftFields, equalitySubConditions, literalSubConditions)); }

Target:
private static Optional<ConditionAnalysis> analyzeCondition(final RexNode condition, final RelDataType leftRowType) { final List<RexNode> subConditions = decomposeAnd(condition); final List<Pair<RexNode, RexInputRef>> equalitySubConditions = new ArrayList<>(); final List<RexLiteral> literalSubConditions = new ArrayList<>(); final int numLeftFields = leftRowType.getFieldCount(); for (RexNode subCondition : subConditions) { if (RexUtil.isLiteral(subCondition, true)) { if (subCondition.isA(SqlKind.CAST)) { RexCall call = (RexCall) subCondition; if (call.getType().getSqlTypeName().equals(call.getOperands().get(0).getType().getSqlTypeName())) { literalSubConditions.add((RexLiteral) call.getOperands().get(0)); } else { return Optional.empty(); } } else { literalSubConditions.add((RexLiteral) subCondition); } continue; } if (!subCondition.isA(SqlKind.EQUALS)) { return Optional.empty(); } final List<RexNode> operands = ((RexCall) subCondition).getOperands(); Preconditions.checkState(operands.size() == 2, "Expected 2 operands, got[%,d]", operands.size()); if (isLeftExpression(operands.get(0), numLeftFields) && isRightInputRef(operands.get(1), numLeftFields)) { equalitySubConditions.add(Pair.of(operands.get(0), (RexInputRef) operands.get(1))); } else if (isRightInputRef(operands.get(0), numLeftFields) && isLeftExpression(operands.get(1), numLeftFields)) { equalitySubConditions.add(Pair.of(operands.get(1), (RexInputRef) operands.get(0))); } else { return Optional.empty(); } } return Optional.of(new ConditionAnalysis(numLeftFields, equalitySubConditions, literalSubConditions)); }
Source:
public boolean isInteresting(String project, String branch, String topic, List<String> files) { if (compareType.matches(pattern, project)) { for (Branch b : branches) { boolean foundInterestingForbidden = false; boolean foundInterestingTopicOrFile = false; if (b.isInteresting(branch)) { if (forbiddenFilePaths != null) { Iterator<String> i = files.iterator(); while (i.hasNext()) { String file = i.next(); for (FilePath ffp : forbiddenFilePaths) { if (ffp.isInteresting(file)) { if (!disableStrictForbiddenFileVerification) { return false; } else { i.remove(); break; } } } } } return isInterestingTopic(topic) && !files.isEmpty() && isInterestingFile(files); } } } return false; }

Target:
public boolean isInteresting(String project, String branch, String topic, List<String> files) { if (compareType.matches(pattern, project)) { for (Branch b : branches) { boolean foundInterestingForbidden = false; if (b.isInteresting(branch)) { if (forbiddenFilePaths != null) { Iterator<String> i = files.iterator(); while (i.hasNext()) { String file = i.next(); for (FilePath ffp : forbiddenFilePaths) { if (ffp.isInteresting(file)) { if (!disableStrictForbiddenFileVerification) { return false; } else { foundInterestingForbidden = true; i.remove(); break; } } } } } if (foundInterestingForbidden && files.isEmpty()) { return false; } return isInterestingTopic(topic) && isInterestingFile(files); } } } return false; }
Source:
public List<WorkspaceImpl> getWorkspaces(String user) throws ServerException { requireNonNull(user, "Required non-null workspace namespace"); final List<WorkspaceImpl> workspaces = workspaceDao.getWorkspaces(user); workspaces.forEach(this::normalizeState); return workspaces; }

Target:
public List<WorkspaceImpl> getWorkspaces(String user) throws ServerException { requireNonNull(user, "Required non-null user id"); final List<WorkspaceImpl> workspaces = workspaceDao.getWorkspaces(user); workspaces.forEach(this::normalizeState); return workspaces; }
Source:
public void testHeartbeatUnknownMemberResponseDuringRebalancing() throws InterruptedException { setupCoordinator(); mockClient.prepareResponse(groupCoordinatorResponse(node, Errors.NONE)); final int generation = 1; mockClient.prepareResponse(joinGroupFollowerResponse(generation, memberId, JoinGroupRequest.UNKNOWN_MEMBER_ID, Errors.NONE)); mockClient.prepareResponse(syncGroupResponse(Errors.NONE)); coordinator.ensureActiveGroup(); final AbstractCoordinator.Generation currGen = coordinator.generation(); mockTime.sleep(HEARTBEAT_INTERVAL_MS); long startMs = System.currentTimeMillis(); while (System.currentTimeMillis() - startMs < 1000 && !coordinator.heartbeat().hasInflight()) { Thread.sleep(10); } assertTrue(coordinator.heartbeat().hasInflight()); mockClient.respond(heartbeatResponse(Errors.UNKNOWN_MEMBER_ID)); coordinator.requestRejoin(); startMs = System.currentTimeMillis(); while (System.currentTimeMillis() - startMs < 1000 && coordinator.heartbeat().hasInflight()) { Thread.sleep(10); coordinator.ensureActiveGroup(new MockTime(1L).timer(100L)); } assertFalse(coordinator.heartbeat().hasInflight()); assertEquals(AbstractCoordinator.Generation.NO_GENERATION, coordinator.generation()); mockClient.respond(joinGroupFollowerResponse(generation, memberId, JoinGroupRequest.UNKNOWN_MEMBER_ID, Errors.NONE)); mockClient.prepareResponse(syncGroupResponse(Errors.NONE)); coordinator.ensureActiveGroup(); assertEquals(currGen, coordinator.generation()); }

Target:
public void testHeartbeatUnknownMemberResponseDuringRebalancing() throws InterruptedException { setupCoordinator(); mockClient.prepareResponse(groupCoordinatorResponse(node, Errors.NONE)); final int generation = 1; mockClient.prepareResponse(joinGroupFollowerResponse(generation, memberId, JoinGroupRequest.UNKNOWN_MEMBER_ID, Errors.NONE)); mockClient.prepareResponse(syncGroupResponse(Errors.NONE)); coordinator.ensureActiveGroup(); final AbstractCoordinator.Generation currGen = coordinator.generation(); mockTime.sleep(HEARTBEAT_INTERVAL_MS); TestUtils.waitForCondition(() -> coordinator.heartbeat().hasInflight(), 2000, "The heartbeat request was not sent in time after 2000ms elapsed"); assertTrue(coordinator.heartbeat().hasInflight()); mockClient.respond(heartbeatResponse(Errors.UNKNOWN_MEMBER_ID)); coordinator.requestRejoin(); TestUtils.waitForCondition(() -> { coordinator.ensureActiveGroup(new MockTime(1L).timer(100L)); return !coordinator.heartbeat().hasInflight(); }, 2000, "The heartbeat response was not been received in time after 2000ms elapsed"); assertFalse(coordinator.heartbeat().hasInflight()); assertEquals(AbstractCoordinator.Generation.NO_GENERATION, coordinator.generation()); mockClient.respond(joinGroupFollowerResponse(generation, memberId, JoinGroupRequest.UNKNOWN_MEMBER_ID, Errors.NONE)); mockClient.prepareResponse(syncGroupResponse(Errors.NONE)); coordinator.ensureActiveGroup(); assertEquals(currGen, coordinator.generation()); }
Source:
public boolean isToBeProcessed(CtLiteral candidate) { CtMethod parent = candidate.getParent(CtMethod.class); if (parent == null) { return false; } if (candidate.getValue() instanceof Boolean) { return false; } else if (candidate.getValue() instanceof Number) { if (candidate.getValue().equals(1) || candidate.getValue().equals(0) || candidate.getValue().equals(-1)) { return false; } } if (candidate.getParent(CtLocalVariable.class) != null) { return false; } if (candidate.getParent(CtAssignment.class) != null) { return false; } if (candidate.getParent(CtField.class) != null) { return false; } if (candidate.getParent(CtThrow.class) != null) { return false; } Object value = candidate.getValue(); if (value == null) { return false; } return Long.class.isAssignableFrom(value.getClass()) || Integer.class.isAssignableFrom(value.getClass()); }

Target:
public boolean isToBeProcessed(CtLiteral candidate) { if (candidate.getValue() instanceof Boolean) { return false; } Object value = candidate.getValue(); if (value == null) { return false; } return Long.class.isAssignableFrom(value.getClass()) || Integer.class.isAssignableFrom(value.getClass()); }
Source:
public Permission atLevels(Scope... levels) { Collection<Scope> l = asList(levels); if (operations.contains(IMPORT) && l.size() != 1) { throw new IllegalArgumentException(IMPORT + " operation is only compatible with one of " + Arrays.toString(Scope.values())); } return new Permission(clusterStates, operations, l); }

Target:
public Permission atLevels(Scope... levels) { Collection<Scope> levelList = asList(levels); if (operations.contains(IMPORT) && levelList.size() != 1) { throw new IllegalArgumentException(IMPORT + " operation is only compatible with one of " + Arrays.toString(Scope.values())); } return new Permission(clusterStates, operations, levelList); }
Source:
private void init(Context context, @Nullable AttributeSet attrs) { if (isInEditMode()) { return; } Preconditions.checkNotNull( sDraweeControllerBuilderSupplier, "SimpleDraweeView was not initialized!"); mSimpleDraweeControllerBuilder = sDraweeControllerBuilderSupplier.get(); if (attrs != null) { TypedArray gdhAttrs = context.obtainStyledAttributes( attrs, R.styleable.SimpleDraweeView); try { final int indexCount = gdhAttrs.getIndexCount(); for (int i = 0; i < indexCount; i++) { final int attr = gdhAttrs.getIndex(i); if (attr == R.styleable.SimpleDraweeView_imageUri) { setImageURI(Uri.parse(gdhAttrs.getString(R.styleable.SimpleDraweeView_imageUri)),null); } } } finally { gdhAttrs.recycle(); } } }

Target:
private void init(Context context, @Nullable AttributeSet attrs) { if (isInEditMode()) { return; } Preconditions.checkNotNull( sDraweeControllerBuilderSupplier, "SimpleDraweeView was not initialized!"); mSimpleDraweeControllerBuilder = sDraweeControllerBuilderSupplier.get(); if (attrs != null) { TypedArray gdhAttrs = context.obtainStyledAttributes( attrs, R.styleable.SimpleDraweeView); try { if(gdhAttrs.hasValue(R.styleable.SimpleDraweeView_actualImageUri)) { setImageURI(Uri.parse(gdhAttrs.getString(R.styleable.SimpleDraweeView_actualImageUri)), null); } } finally { gdhAttrs.recycle(); } } }
Source:
private void testGlusterNetworkInUseAndUnset(boolean glusterNetworkBefore, boolean glusterNetworkAfter, boolean glusterService, boolean hasBricks, Matcher<ValidationResult> expectedResult) { when(oldNetworkCluster.isGluster()).thenReturn(glusterNetworkBefore); when(networkCluster.isGluster()).thenReturn(glusterNetworkAfter); when(cluster.supportsGlusterService()).thenReturn(glusterService); doReturn(brickDao).when(validator).getGlusterBrickDao(); ArrayList<GlusterBrickEntity> list = new ArrayList<>(); if (hasBricks) { list.add(Mockito.mock(GlusterBrickEntity.class)); } when(brickDao.getAllByClusterAndNetworkId(any(Guid.class), any(Guid.class))).thenReturn(list); assertThat(validator.glusterNetworkInUseAndUnset(cluster), expectedResult); }

Target:
private void testGlusterNetworkInUseAndUnset(boolean glusterNetworkBefore, boolean glusterNetworkAfter, boolean glusterService, boolean hasBricks, Matcher<ValidationResult> expectedResult) { when(oldNetworkCluster.isGluster()).thenReturn(glusterNetworkBefore); when(networkCluster.isGluster()).thenReturn(glusterNetworkAfter); when(cluster.supportsGlusterService()).thenReturn(glusterService); doReturn(brickDao).when(validator).getGlusterBrickDao(); ArrayList<GlusterBrickEntity> list = new ArrayList<>(); if (hasBricks) { list.add(mock(GlusterBrickEntity.class)); } when(brickDao.getAllByClusterAndNetworkId(any(Guid.class), any(Guid.class))).thenReturn(list); assertThat(validator.glusterNetworkInUseAndUnset(cluster), expectedResult); }
Source:
private void downloadSourceFiles(Path lib_root) throws IOException { Files.createDirectories(lib_root); Path handle_dir = lib_root.resolve("AbstractHandle"); Files.createDirectories(handle_dir); String handle_repo_prefix = "<LINK_1>"; String handle_impl_files = {"__init__.py", "AbstractHandleImpl.py", "AbstractHandleServer.py", "authclient.py", "baseclient.py"}; for (String file_name : handle_impl_files) { FileUtils.copyURLToFile(new URL(handle_repo_prefix + file_name), handle_dir.resolve(file_name).toFile()); } Path handle_utils_dir = handle_dir.resolve("Utils"); Files.createDirectories(handle_utils_dir); String handle_util_files = {"__init__.py", "Handler.py", "MongoUtil.py", "ShockUtil.py", "TokenCache.py"}; for (String file_name : handle_util_files) { FileUtils.copyURLToFile(new URL(handle_repo_prefix + "Utils/" + file_name), handle_utils_dir.resolve(file_name).toFile()); } Path biokbase_dir = lib_root.resolve("biokbase"); Files.createDirectories(biokbase_dir); String biokbase_repo_prefix = "<LINK_0>"; String biokbase_files = {"log.py"}; for (String file_name : biokbase_files) { FileUtils.copyURLToFile(new URL(biokbase_repo_prefix + file_name), biokbase_dir.resolve(file_name).toFile()); } Path log_file = null; Stream <String> lines = null; List <String> replaced = null; log_file = handle_dir.resolve("AbstractHandleServer.py"); lines = Files.lines(log_file); replaced = lines.map(line -> line.replaceAll("loads\\(request_body\\)", "loads(request_body.decode('utf-8'))")).collect(Collectors.toList()); Files.write(log_file, replaced); lines.close(); }

Target:
private void downloadSourceFiles(Path lib_root) throws IOException { Files.createDirectories(lib_root); Path handle_dir = lib_root.resolve("AbstractHandle"); Files.createDirectories(handle_dir); String handle_repo_prefix = "<LINK_1>"; String handle_impl_files = {"__init__.py", "AbstractHandleImpl.py", "AbstractHandleServer.py", "authclient.py", "baseclient.py"}; for (String file_name : handle_impl_files) { FileUtils.copyURLToFile(new URL(handle_repo_prefix + file_name), handle_dir.resolve(file_name).toFile()); } Path handle_utils_dir = handle_dir.resolve("Utils"); Files.createDirectories(handle_utils_dir); String handle_util_files = {"__init__.py", "Handler.py", "MongoUtil.py", "ShockUtil.py", "TokenCache.py"}; for (String file_name : handle_util_files) { FileUtils.copyURLToFile(new URL(handle_repo_prefix + "Utils/" + file_name), handle_utils_dir.resolve(file_name).toFile()); } Path biokbase_dir = lib_root.resolve("biokbase"); Files.createDirectories(biokbase_dir); String biokbase_repo_prefix = "<LINK_0>"; String biokbase_files = {"log.py"}; for (String file_name : biokbase_files) { FileUtils.copyURLToFile(new URL(biokbase_repo_prefix + file_name), biokbase_dir.resolve(file_name).toFile()); } }
Source:
public void notifySuperUsers(String messageCode, Exception cause, Object... messageArguments) { String message = Context.getMessageSourceService().getMessage(messageCode, messageArguments, Context.getLocale()); if (cause != null) { StringBuilder stackTrace = new StringBuilder(); for (StackTraceElement traceElement : cause.getStackTrace()) { stackTrace.append(traceElement); stackTrace.append("\n"); if (stackTrace.length() >= Alert.TEXT_MAX_LENGTH) { break; } } message = message + ":" + stackTrace; message = message.substring(0, Math.min(message.length(), Alert.TEXT_MAX_LENGTH)); } Alert alert = new Alert(message, Context.getUserService().getUsersByRole(new Role(RoleConstants.SUPERUSER))); alert.setSatisfiedByAny(true); if (alert.getCreator() == null) { alert.setCreator(new User(1)); } Context.getAlertService().saveAlert(alert); }

Target:
public void notifySuperUsers(String messageCode, Exception cause, Object... messageArguments) { String message = Context.getMessageSourceService().getMessage(messageCode, messageArguments, Context.getLocale()); if (cause != null) { StringBuilder stackTrace = new StringBuilder(); for (StackTraceElement traceElement : cause.getStackTrace()) { stackTrace.append(traceElement); stackTrace.append("\n"); if (stackTrace.length() >= Alert.TEXT_MAX_LENGTH) { break; } } message = message + ":" + stackTrace; message = message.substring(0, Math.min(message.length(), Alert.TEXT_MAX_LENGTH)); } Alert alert = new Alert(message, Context.getUserService().getUsersByRole(new Role(RoleConstants.SUPERUSER))); alert.setSatisfiedByAny(true); if (alert.getCreator() == null) { User daemonUser = Context.getUserService().getUserByUuid(Daemon.getDaemonUserUuid()); alert.setCreator(daemonUser); } Context.getAlertService().saveAlert(alert); }
Source:
private void validateByType(ModuleOption option, String value) { if (value == null || option == null || option.getType() == null) { return; } try { if (int.class.isAssignableFrom(option.getType()) || Integer.class.isAssignableFrom(option.getType())) { Integer.parseInt(value); } else if (boolean.class.isAssignableFrom(option.getType()) || Boolean.class.isAssignableFrom(option.getType())) { Boolean.parseBoolean(value); } else if (float.class.isAssignableFrom(option.getType()) || Float.class.isAssignableFrom(option.getType())) { Float.parseFloat(value); } else if (double.class.isAssignableFrom(option.getType()) || Double.class.isAssignableFrom(option.getType())) { Double.parseDouble(value); } else if (short.class.isAssignableFrom(option.getType()) || Short.class.isAssignableFrom(option.getType())) { Short.parseShort(value); } } catch (Exception e) { throw new RuntimeException(String.format( "The value '%s' is the wrong type for option '%s'. The required type is %s.", value, option.getName(), option.getType().getSimpleName())); } }

Target:
private void validateByType(ModuleOption option, String value) { if (value == null || option.getType() == null) { return; } if (boolean.class.isAssignableFrom(option.getType()) || Boolean.class.isAssignableFrom(option.getType())) { if (!(value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false") || value.equals("1") || value.equals("0"))) { throw new RuntimeException(String.format( "The value '%s' is the wrong type for option '%s'. The required type is %s.", value, option.getName(), option.getType().getSimpleName())); } } else { try { if (int.class.isAssignableFrom(option.getType()) || Integer.class.isAssignableFrom(option.getType())) { Integer.parseInt(value); } else if (float.class.isAssignableFrom(option.getType()) || Float.class.isAssignableFrom(option.getType())) { Float.parseFloat(value); } else if (double.class.isAssignableFrom(option.getType()) || Double.class.isAssignableFrom(option.getType())) { Double.parseDouble(value); } else if (short.class.isAssignableFrom(option.getType()) || Short.class.isAssignableFrom(option.getType())) { Short.parseShort(value); } } catch (NumberFormatException e) { throw new RuntimeException(String.format( "The value '%s' is the wrong type for option '%s'. The required type is %s.", value, option.getName(), option.getType().getSimpleName())); } } }
Source:
public OrcOutputBuffer(CompressionKind compression, int maxBufferSize) { requireNonNull(compression, "compression is null"); checkArgument(maxBufferSize > 0, "maximum buffer size should be greater than 0"); this.maxBufferSize = maxBufferSize; this.buffer = new byte[INITIAL_BUFFER_SIZE]; this.slice = wrappedBuffer(buffer); compressedOutputStream = new ChunkedSliceOutput(MINIMUM_OUTPUT_BUFFER_CHUNK_SIZE, MAXIMUM_OUTPUT_BUFFER_CHUNK_SIZE); this.compressionBuffer = new byte[0]; if (compression == CompressionKind.NONE) { this.compressor = null; } else if (compression == CompressionKind.SNAPPY) { this.compressor = new SnappyCompressor(); } else if (compression == CompressionKind.ZLIB) { this.compressor = new DeflateCompressor(); } else if (compression == CompressionKind.LZ4) { this.compressor = new Lz4Compressor(); } else { throw new IllegalArgumentException("Unsupported compression " + compression); } }

Target:
public OrcOutputBuffer(CompressionKind compression, int maxBufferSize) { requireNonNull(compression, "compression is null"); checkArgument(maxBufferSize > 0, "maximum buffer size should be greater than 0"); this.maxBufferSize = maxBufferSize; this.buffer = new byte[INITIAL_BUFFER_SIZE]; this.slice = wrappedBuffer(buffer); compressedOutputStream = new ChunkedSliceOutput(MINIMUM_OUTPUT_BUFFER_CHUNK_SIZE, MAXIMUM_OUTPUT_BUFFER_CHUNK_SIZE); if (compression == CompressionKind.NONE) { this.compressor = null; } else if (compression == CompressionKind.SNAPPY) { this.compressor = new SnappyCompressor(); } else if (compression == CompressionKind.ZLIB) { this.compressor = new DeflateCompressor(); } else if (compression == CompressionKind.LZ4) { this.compressor = new Lz4Compressor(); } else { throw new IllegalArgumentException("Unsupported compression " + compression); } }
Source:
public void testTupleSaving() throws Exception { String script = "REGISTER "+ Provisioner.ESHADOOP_TESTING_JAR + ";" + "answers = LOAD 'src/itest/resources/tuple.txt' using PigStorage(',') as (id:int, parentId:int, score:int);" + "grouped = GROUP answers by id;" + "ILLUSTRATE grouped;" + "STORE grouped into '"+resource("pig-test-tuple-structure", "data")+"' using org.elasticsearch.hadoop.pig.EsStorage('es.mapping.pig.tuple.use.field.names = true');"; pig.executeScript(script); String string = RestUtils.get("pig-test-tuple-structure/_search"); assertThat(string, containsString("parentId")); }

Target:
public void testTupleSaving() throws Exception { String script = "REGISTER "+ Provisioner.ESHADOOP_TESTING_JAR + ";" + "answers = LOAD 'src/itest/resources/tuple.txt' using PigStorage(',') as (id:int, parentId:int, score:int);" + "grouped = GROUP answers by id;" + "ILLUSTRATE grouped;" + "STORE grouped into '"+resource("pig-test-tuple-structure", "data", VERSION)+"' using org.elasticsearch.hadoop.pig.EsStorage('es.mapping.pig.tuple.use.field.names = true');"; pig.executeScript(script); String string = RestUtils.get("pig-test-tuple-structure/_search"); assertThat(string, containsString("parentId")); }
Source:
public void emptyChangeSet_findAllAsync(){ Realm realm = looperThread.realm; populateData(realm, 10); final RealmResults<AllTypes> results = realm.where(AllTypes.class).findAllSortedAsync(AllTypes.FIELD_LONG); results.addChangeListener(new OrderedRealmCollectionChangeListener<RealmResults<AllTypes>>() { @Override public void onChange(RealmResults<AllTypes> collection, OrderedCollectionChangeSet changes) { assertSame(collection, results); assertEquals(9, collection.size()); assertNull(changes); looperThread.testComplete(); } }); final CountDownLatch bgDeletionLatch = new CountDownLatch(1); new Thread(new Runnable() { @Override public void run() { Realm realm = Realm.getInstance(looperThread.realmConfiguration) ; realm.beginTransaction(); realm.where(AllTypes.class).equalTo(AllTypes.FIELD_LONG, 0).findFirst().deleteFromRealm(); realm.commitTransaction(); realm.close(); bgDeletionLatch.countDown(); } }).start(); TestHelper.awaitOrFail(bgDeletionLatch); }

Target:
public void emptyChangeSet_findAllAsync(){ Realm realm = looperThread.realm; populateData(realm, 10); final RealmResults<AllTypes> results = realm.where(AllTypes.class).findAllSortedAsync(AllTypes.FIELD_LONG); results.addChangeListener(new OrderedRealmCollectionChangeListener<RealmResults<AllTypes>>() { @Override public void onChange(RealmResults<AllTypes> collection, OrderedCollectionChangeSet changeSet) { assertSame(collection, results); assertEquals(9, collection.size()); assertNull(changeSet); looperThread.testComplete(); } }); final CountDownLatch bgDeletionLatch = new CountDownLatch(1); new Thread(new Runnable() { @Override public void run() { Realm realm = Realm.getInstance(looperThread.realmConfiguration) ; realm.beginTransaction(); realm.where(AllTypes.class).equalTo(AllTypes.FIELD_LONG, 0).findFirst().deleteFromRealm(); realm.commitTransaction(); realm.close(); bgDeletionLatch.countDown(); } }).start(); TestHelper.awaitOrFail(bgDeletionLatch); }
Source:
public AllelicCountCollection(final File inputFile) { Utils.nonNull(inputFile); Utils.regularReadableUserFile(inputFile); try (final TableReader<AllelicCount> reader = TableUtils.reader(inputFile, (columns, formatExceptionFactory) -> { if (columns.containsAll(AllelicCountTableColumns.FULL_COLUMN_NAME_ARRAY)) { return AllelicCount.fullParser; } if (columns.containsAll(AllelicCountTableColumns.INTERMEDIATE_COLUMN_NAME_ARRAY)) { return AllelicCount.intermediateParser; } if (columns.containsAll(AllelicCountTableColumns.BASIC_COLUMN_NAME_ARRAY)) { return AllelicCount.basicParser; } throw formatExceptionFactory.apply("The AllelicCountCollection input file does not have the" + " mandatory colums. Required: " + StringUtils.join( AllelicCountTableColumns.BASIC_COLUMN_NAME_ARRAY, ", ")); })) { counts = reader.stream().collect(Collectors.toList()); } catch (final IOException | UncheckedIOException e) { throw new UserException.CouldNotReadInputFile(inputFile, e); } }

Target:
public AllelicCountCollection(final File inputFile) { Utils.nonNull(inputFile); Utils.regularReadableUserFile(inputFile); try (final AllelicCountReader reader = new AllelicCountReader(inputFile)) { counts = reader.stream().collect(Collectors.toList()); } catch (final IOException | UncheckedIOException e) { throw new UserException.CouldNotReadInputFile(inputFile, e); } }
Source:
public boolean onTouchEvent(MotionEvent ev) { return getAdapter() == null || super.onTouchEvent(ev); }

Target:
public boolean onTouchEvent(MotionEvent ev) { return mAdapter == null || super.onTouchEvent(ev); }
Source:
public static synchronized void initXmlParser() throws Exception { xmlParser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); attributeNames = ImmutableList.of("columns", "foreign-keys", "indexes", "primary-keys", "sequences", "tables", "unique-constraints", "views"); }

Target:
public static void initXmlParser() throws Exception { xmlParser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); attributeNames = ImmutableList.of("columns", "foreign-keys", "indexes", "primary-keys", "sequences", "tables", "unique-constraints", "views"); }
Source:
default CompletableFuture<Void> applyToAll(Consumer<Subject> action, Set<String> identifiers) { Preconditions.checkNotNull(action, "action"); Preconditions.checkNotNull(identifiers, "identifiers"); return CompletableFuture.runAsync(() -> { for (String id : identifiers) { try { Subject s = loadSubject(id).get(); action.accept(s); suggestUnload(s.getIdentifier()); } catch (Exception e) { e.printStackTrace(); } } }); }

Target:
default CompletableFuture<Void> applyToAll(Consumer<Subject> action, Set<String> identifiers) { Preconditions.checkNotNull(action, "action"); Preconditions.checkNotNull(identifiers, "identifiers"); return CompletableFuture.runAsync(() -> { for (String id : identifiers) { Subject subject = loadSubject(id).join(); action.accept(subject); suggestUnload(subject.getIdentifier()); } }); }
Source:
public byte[] rawValue(final V value) { try { return valueSerde.serializer().serialize(topic, value); } catch (final ClassCastException e) { final String valueClass; final Class<? extends Serializer> serializerClass; if (valueSerializer() instanceof ValueAndTimestampSerializer) { serializerClass = ((ValueAndTimestampSerializer) valueSerializer()).valueSerializer.getClass(); valueClass = value == null ? "unknown because value is null" : ((ValueAndTimestamp) value).value().getClass().getName(); } else { serializerClass = valueSerializer().getClass(); valueClass = value == null ? "unknown because value is null" : value.getClass().getName(); } throw new StreamsException( String.format("A serializer (value: %s) is not compatible to the actual value type " + "(value type: %s). Change the default Serdes in StreamConfig or " + "provide correct Serdes via method parameters.", serializerClass.getName(), valueClass), e); } }

Target:
public byte[] rawValue(final V value) { try { return valueSerde.serializer().serialize(topic, value); } catch (final ClassCastException e) { final String valueClass; final Class<? extends Serializer> serializerClass; if (valueSerializer() instanceof ValueAndTimestampSerializer) { serializerClass = ((ValueAndTimestampSerializer) valueSerializer()).valueSerializer.getClass(); valueClass = value == null ? "unknown because value is null" : ((ValueAndTimestamp) value).value().getClass().getName(); } else { serializerClass = valueSerializer().getClass(); valueClass = value == null ? "unknown because value is null" : value.getClass().getName(); } throw new StreamsException( String.format("A serializer (%s) is not compatible to the actual value type " + "(value type: %s). Change the default Serdes in StreamConfig or " + "provide correct Serdes via method parameters.", serializerClass.getName(), valueClass), e); } }
Source:
public String processElement(ParserContext handlerManager, Element element) throws ConfigurationException { String executeAfterId = element.getTextContent(); return executeAfterId; }

Target:
public String processElement(ParserContext handlerManager, Element element) throws ConfigurationException { String executeAfterId = element.getTextContent(); if(executeAfterId == null || executeAfterId.equals("")) { throw new WindupXMLRulesetParsingException("The '" + EXECUTE_AFTER_ELEMENT + "' must contain non-empty text value"); } return executeAfterId; }
Source:
public DataSection genesBody(Patient patient) throws Exception { String sectionName = "genes"; Set<String> present = this.enabledHeaderIdsBySection.get(sectionName); if (present == null || present.isEmpty()) { return null; } DataSection section = new DataSection(sectionName); int Y = 0; if (present.contains("candidate")) { PatientData<Map<String, String>> candidateGenes = patient.getData("genes"); if (candidateGenes != null && candidateGenes.isIndexed()) { for (Map<String, String> candidateGene : candidateGenes) { DataCell cell = new DataCell("candidate", 0, Y); section.addCell(cell); String geneName = candidateGene.get("gene"); cell = new DataCell(geneName, 1, Y); section.addCell(cell); if (present.contains("comments")) { String comment = candidateGene.get("comments"); cell = new DataCell(comment, 2, Y); section.addCell(cell); } Y++; } } } if (present.contains("rejected")) { PatientData<Map<String, String>> rejectedGenes = patient.getData("rejectedGenes"); if (rejectedGenes != null && rejectedGenes.isIndexed()) { for (Map<String, String> rejectedGene : rejectedGenes) { DataCell cell = new DataCell("Previously tested", 0, Y); section.addCell(cell); String geneName = rejectedGene.get("gene"); cell = new DataCell(geneName, 1, Y); section.addCell(cell); if (present.contains("rejected_comments")) { String comment = rejectedGene.get("comments"); cell = new DataCell(comment, 2, Y); section.addCell(cell); } Y++; } } } return section; }

Target:
public DataSection genesBody(Patient patient) throws Exception { String sectionName = "genes"; Set<String> present = this.enabledHeaderIdsBySection.get(sectionName); if (present == null || present.isEmpty()) { return null; } DataSection section = new DataSection(sectionName); int y = 0; if (present.contains("candidate")) { PatientData<Map<String, String>> candidateGenes = patient.getData("genes"); if (candidateGenes != null && candidateGenes.isIndexed()) { DataCell cell = new DataCell("Candidate", 0, y); section.addCell(cell); for (Map<String, String> candidateGene : candidateGenes) { String geneName = candidateGene.get("gene"); cell = new DataCell(geneName, 1, y); section.addCell(cell); if (present.contains("comments")) { String comment = candidateGene.get("comments"); cell = new DataCell(comment, 2, y); section.addCell(cell); } y++; } } } if (present.contains("rejected")) { PatientData<Map<String, String>> rejectedGenes = patient.getData("rejectedGenes"); if (rejectedGenes != null && rejectedGenes.isIndexed()) { DataCell cell = new DataCell("Previously tested", 0, y, StyleOption.YES_NO_SEPARATOR); section.addCell(cell); for (Map<String, String> rejectedGene : rejectedGenes) { String geneName = rejectedGene.get("gene"); cell = new DataCell(geneName, 1, y); section.addCell(cell); if (present.contains("rejected_comments")) { String comment = rejectedGene.get("comments"); cell = new DataCell(comment, 2, y); section.addCell(cell); } y++; } } } return section; }
Source:
private static int getFileLength(File file) throws IOException { int lines = 0; BufferedReader reader = Files.newBufferedReader(file.toPath(), UTF_8); while (reader.readLine() != null) { lines++; } reader.close(); return lines; }

Target:
private static int getFileLength(File file) throws IOException { int lines = 0; try (BufferedReader reader = Files.newBufferedReader(file.toPath(), UTF_8)) { while (reader.readLine() != null) { lines++; } } return lines; }
Source:
private File convertInputStreamToFile(InputStream inputStream, Long size) throws IOException { OutputStream out = null; try { File file = new File(fileNameOrId); out = new FileOutputStream(file); byte[] bytes = new byte[size.intValue()]; int read = 0; while ((read = inputStream.read(bytes)) != -1) { length += read; out.write(Base64.decodeBase64(bytes)); out.flush(); } inputStream.close(); out.close(); return file; } catch (IOException e) { throw e; } finally { inputStream.close(); if (out != null) { out.close(); } } }

Target:
private File convertInputStreamToFile(InputStream inputStream, Long size) throws IOException { OutputStream out = null; try { File file = new File(fileNameOrId); out = new FileOutputStream(file); int bufferSize = size.intValue() < 8192 ? size.intValue() : 8192; byte[] bytes = new byte[bufferSize]; int read = 0; while ((read = inputStream.read(bytes)) != -1) { length += read; out.write(Base64.decodeBase64(bytes)); out.flush(); } inputStream.close(); out.close(); return file; } catch (IOException e) { throw e; } finally { inputStream.close(); if (out != null) { out.close(); } } }
Source:
public void onCompleted() { if (done) { return; } List<GroupedUnicast<K, V>> list = new ArrayList<GroupedUnicast<K, V>>(groups.values()); groups.clear(); for (GroupedUnicast<K, V> e : list) { e.onComplete(); } done = true; GROUP_COUNT.decrementAndGet(this); drain(); }

Target:
public void onCompleted() { if (done) { return; } for (GroupedUnicast<K, V> e : groups.values()) { e.onComplete(); } groups.clear(); done = true; GROUP_COUNT.decrementAndGet(this); drain(); }
Source:
public List<DiskImage> asList() { return memoryDisk == null && metadataDisk == null ? List.of() : List.of(memoryDisk, metadataDisk); }

Target:
public List<DiskImage> asList() { if (diskList == null) { diskList = memoryDisk == null && metadataDisk == null ? List.of() : List.of(memoryDisk, metadataDisk); } return diskList; }
Source:
public static DatastreamPositionResponse merge(DatastreamPositionResponse first, DatastreamPositionResponse second) { DatastreamPositionResponse response = new DatastreamPositionResponse(); first.getDatastreams() .forEach((datastream, sources) -> sources.getPhysicalSources() .forEach((source, position) -> response.updatePosition(datastream, source, position))); second.getDatastreams() .forEach((datastream, sources) -> sources.getPhysicalSources() .forEach((source, position) -> response.updatePosition(datastream, source, position))); return response; }

Target:
public static DatastreamPositionResponse merge(DatastreamPositionResponse first, DatastreamPositionResponse second) { DatastreamPositionResponse result = new DatastreamPositionResponse(); first.getDatastreamToPhysicalSources().forEach((datastream, sources) -> sources.getPhysicalSourceToPosition().forEach((source, position) -> result.update(datastream, source, position))); second.getDatastreamToPhysicalSources().forEach((datastream, sources) -> sources.getPhysicalSourceToPosition().forEach((source, position) -> result.update(datastream, source, position))); return result; }
Source:
public synchronized double getBPSAtoB() { if (DoubleMath.fuzzyEquals(getDuration(), 0, Double.MIN_VALUE)) { return 0; } return fNbBytesAtoB / getDuration(); }

Target:
public synchronized double getBPSAtoB() { if (DoubleMath.fuzzyEquals(getDuration(), 0, DELTA)) { return 0; } return fNbBytesAtoB / getDuration(); }
Source:
public void restart(String settingId, String noteId) { InterpreterSetting intpsetting = interpreterSettings.get(settingId); if (intpsetting != null && noteIdIsExist(noteId) && intpsetting.getOption().isProcess()) { intpsetting.closeAndRemoveInterpreterGroup(noteId); return; } restart(settingId); }

Target:
public void restart(String settingId, String noteId) { InterpreterSetting intpsetting = interpreterSettings.get(settingId); Preconditions.checkNotNull(intpsetting); if (noteIdIsExist(noteId) && intpsetting.getOption().isProcess()) { intpsetting.closeAndRemoveInterpreterGroup(noteId); return; } restart(settingId); }
Source:
public static Executor of(Executable executable) { Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) { return null; } for (Computer computer : jenkins.getComputers()) { for (Executor executor : computer.getExecutors()) { if (executor.getCurrentExecutable() == executable) { return executor; } } for (Executor executor : computer.getOneOffExecutors()) { if (executor.getCurrentExecutable() == executable) { return executor; } } } return null; }

Target:
public static @CheckForNull Executor of(Executable executable) { Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) { return null; } for (Computer computer : jenkins.getComputers()) { for (Executor executor : computer.getExecutors()) { if (executor.getCurrentExecutable() == executable) { return executor; } } for (Executor executor : computer.getOneOffExecutors()) { if (executor.getCurrentExecutable() == executable) { return executor; } } } return null; }
Source:
public void testString() { ToolTipString empty = ToolTipString.fromString(""); ToolTipString complicatedString = ToolTipString.fromString("¯\\_(ツ)_/¯"); assertNotNull(empty); assertNotNull(complicatedString); assertEquals("", empty.toString()); assertEquals("¯\\_(ツ)_/¯", complicatedString.toString()); assertEquals("", empty.toHtmlString()); assertEquals("&macr;\\_(ツ)_/&macr;", complicatedString.toHtmlString()); }

Target:
public void testString() { ToolTipString empty = ToolTipString.fromString(""); ToolTipString complicatedString = ToolTipString.fromString("¯\\_(ツ)_/¯"); assertEquals("", empty.toString()); assertEquals("¯\\_(ツ)_/¯", complicatedString.toString()); assertEquals("", empty.toHtmlString()); assertEquals("&macr;\\_(ツ)_/&macr;", complicatedString.toHtmlString()); }
Source:
private boolean kfsVendorMaintenanceDocumentValidatedForSave(MaintenanceDocument vendorMaintenceDoc, PaymentWorksNewVendorRequestsBatchReportData reportData, PaymentWorksVendor pmwVendor) { boolean documentValidated = false; try { vendorMaintenceDoc.validateBusinessRules(new SaveDocumentEvent(vendorMaintenceDoc)); LOG.info("kfsVendorMaintenanceDocumentValidatedForSave: vendorMaintenceDoc validate."); documentValidated = true; } catch (ValidationException ve) { List<String> validationErrors = getPaymentWorksBatchUtilityService().convertReportDataValidationErrors(GlobalVariables.getMessageMap().getErrorMessages()); captureKfsProcessingErrorsForVendor(pmwVendor, reportData, validationErrors); LOG.error("kfsVendorMaintenanceDocumentValidatedForSave: eDoc validation error(s): " + validationErrors.toString()); LOG.error("kfsVendorMaintenanceDocumentValidatedForSave: eDoc validation exception caught: " + ve.getMessage()); } finally { GlobalVariables.getMessageMap().clearErrorMessages(); } return documentValidated; }

Target:
private boolean kfsVendorMaintenanceDocumentValidatedForSave(MaintenanceDocument vendorMaintenceDoc, PaymentWorksNewVendorRequestsBatchReportData reportData, PaymentWorksVendor pmwVendor) { return kfsVendorMaintenanceDocumentValidatedForEvent(vendorMaintenceDoc, reportData, pmwVendor, new SaveDocumentEvent(vendorMaintenceDoc)); }
Source:
public JavaScriptHeaderItem setNonce(String nonce) { Args.notNull(nonce, "nonce"); this.nonce = nonce; return this; }

Target:
public JavaScriptHeaderItem setNonce(String nonce) { this.nonce = nonce; return this; }