auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public FEELFnResult<Boolean> invoke(@ParameterName( "number" ) BigDecimal number) { if ( number == null ) { return FEELFnResult.ofError( new InvalidParametersEvent( FEELEvent.Severity.ERROR, "number", "cannot be null" ) ); } if ( number.remainder( BigDecimal.ONE ).signum() != 0 ) { return FEELFnResult.ofError( new InvalidParametersEvent( FEELEvent.Severity.ERROR, "number", "cannot have non-zero fractional part" ) ); } return FEELFnResult.ofResult( BigInteger.ZERO.equals( number.toBigInteger().remainder(TWO) ) ); }

Target:
public FEELFnResult<Boolean> invoke(@ParameterName( "number" ) BigDecimal number) { if ( number == null ) { return FEELFnResult.ofError( new InvalidParametersEvent( FEELEvent.Severity.ERROR, "number", "cannot be null" ) ); } if ( number.remainder( BigDecimal.ONE ).signum() != 0 ) { return FEELFnResult.ofError( new InvalidParametersEvent( FEELEvent.Severity.ERROR, "number", "cannot have non-zero fractional part" ) ); } return FEELFnResult.ofResult( BigDecimal.ZERO.compareTo( number.remainder(TWO) ) == 0); }
Source:
public static org.ovirt.engine.api.model.VmPayload map(VmPayload entity, org.ovirt.engine.api.model.VmPayload template) { org.ovirt.engine.api.model.VmPayload model = template != null ? template : new org.ovirt.engine.api.model.VmPayload(); model.setType(entity.getType().getName()); VmPayloadFile file = new VmPayloadFile(); file.setName(entity.getFileName()); file.setContent(entity.getContent()); model.setFile(file); return model; }

Target:
public static org.ovirt.engine.api.model.VmPayload map(VmPayload entity, org.ovirt.engine.api.model.VmPayload template) { org.ovirt.engine.api.model.VmPayload model = template != null ? template : new org.ovirt.engine.api.model.VmPayload(); if (entity.getType() != null) { model.setType(entity.getType().getName()); } VmPayloadFile file = new VmPayloadFile(); file.setName(entity.getFileName()); file.setContent(entity.getContent()); model.setFile(file); return model; }
Source:
AbstractStreamingCommitterOperator<CommT, GlobalCommT> createStreamingCommitterOperator() { return new GlobalStreamingCommitterOperator<>( sink.createGlobalCommitter() .orElseThrow(() -> new IllegalArgumentException( "Could not create global committer from the sink")), sink.getGlobalCommittableSerializer() .orElseThrow(() -> new IllegalArgumentException( "Could not create global committable serializer from the sink"))); }

Target:
AbstractStreamingCommitterOperator<CommT, GlobalCommT> createStreamingCommitterOperator() { return new GlobalStreamingCommitterOperator<>( sink.createGlobalCommitter() .orElseThrow(() -> new IllegalStateException( "Could not create global committer from the sink")), sink.getGlobalCommittableSerializer() .orElseThrow(() -> new IllegalStateException( "Could not create global committable serializer from the sink"))); }
Source:
private void logCraftingJob( String type, Stopwatch timer ) { if( AELog.isCraftingLogEnabled() ) { final String itemToOutput = this.output.toString(); final long elapsedTime = timer.elapsed( TimeUnit.MILLISECONDS ); final String actionSource; if( this.actionSrc.player().isPresent() ) { final PlayerSource source = (PlayerSource) this.actionSrc; final EntityPlayer player = this.actionSrc.player().get(); actionSource = player.toString(); } else if( this.actionSrc.machine().isPresent() ) { final IActionHost machineSource = this.actionSrc.machine().get(); final IGridNode actionableNode = machineSource.getActionableNode(); final IGridHost machine = actionableNode.getMachine(); final DimensionalCoord location = actionableNode.getGridBlock().getLocation(); actionSource = String.format( LOG_MACHINE_SOURCE_DETAILS, machine, location ); } else { actionSource = "[unknown source]"; } AELog.crafting( LOG_CRAFTING_JOB, type, actionSource, itemToOutput, this.bytes, elapsedTime ); } }

Target:
private void logCraftingJob( String type, Stopwatch timer ) { if( AELog.isCraftingLogEnabled() ) { final String itemToOutput = this.output.toString(); final long elapsedTime = timer.elapsed( TimeUnit.MILLISECONDS ); final String actionSource; if( this.actionSrc.player().isPresent() ) { final EntityPlayer player = this.actionSrc.player().get(); actionSource = player.toString(); } else if( this.actionSrc.machine().isPresent() ) { final IActionHost machineSource = this.actionSrc.machine().get(); final IGridNode actionableNode = machineSource.getActionableNode(); final IGridHost machine = actionableNode.getMachine(); final DimensionalCoord location = actionableNode.getGridBlock().getLocation(); actionSource = String.format( LOG_MACHINE_SOURCE_DETAILS, machine, location ); } else { actionSource = "[unknown source]"; } AELog.crafting( LOG_CRAFTING_JOB, type, actionSource, itemToOutput, this.bytes, elapsedTime ); } }
Source:
CommitFileDiffViewer(final Composite parent) { super(new SashForm(parent, SWT.HORIZONTAL), SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | SWT.FULL_SELECTION); sash = (SashForm) getTable().getParent(); errorText = new TextViewer(sash, SWT.NONE); errorText.getTextWidget().setFont(UIUtils.getFont(UIPreferences.THEME_CommitMessageFont)); errorText.setDocument(new Document(UIText.CommitFileDiffViewer_SelectOneCommitMessage)); final Table rawTable = getTable(); rawTable.setHeaderVisible(true); rawTable.setLinesVisible(true); final TableLayout layout = new TableLayout(); rawTable.setLayout(layout); createColumns(rawTable, layout); setLabelProvider(new FileDiffLabelProvider()); setContentProvider(new FileDiffContentProvider()); addOpenListener(new IOpenListener() { public void open(final OpenEvent event) { final ISelection s = event.getSelection(); if (s.isEmpty() || !(s instanceof IStructuredSelection)) return; final IStructuredSelection iss = (IStructuredSelection) s; final FileDiff d = (FileDiff) iss.getFirstElement(); if (walker != null && d.getBlobs().length <= 2) if (compareMode) showTwoWayFileDiff(d); else openFileInEditor(d); } }); clipboard = new Clipboard(rawTable.getDisplay()); rawTable.addDisposeListener(new DisposeListener() { public void widgetDisposed(final DisposeEvent e) { clipboard.dispose(); } }); }

Target:
CommitFileDiffViewer(final Composite parent) { super(new Composite(parent, SWT.NONE), SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | SWT.FULL_SELECTION); final Table rawTable = getTable(); Composite main = rawTable.getParent(); stackLayout = new StackLayout(); main.setLayout(stackLayout); noInputText = new StyledText(main, SWT.NONE); noInputText.setFont(UIUtils .getFont(UIPreferences.THEME_CommitMessageFont)); noInputText.setText(UIText.CommitFileDiffViewer_SelectOneCommitMessage); rawTable.setHeaderVisible(true); rawTable.setLinesVisible(true); final TableLayout layout = new TableLayout(); rawTable.setLayout(layout); createColumns(rawTable, layout); setLabelProvider(new FileDiffLabelProvider()); setContentProvider(new FileDiffContentProvider()); addOpenListener(new IOpenListener() { public void open(final OpenEvent event) { final ISelection s = event.getSelection(); if (s.isEmpty() || !(s instanceof IStructuredSelection)) return; final IStructuredSelection iss = (IStructuredSelection) s; final FileDiff d = (FileDiff) iss.getFirstElement(); if (walker != null && d.getBlobs().length <= 2) if (compareMode) showTwoWayFileDiff(d); else openFileInEditor(d); } }); clipboard = new Clipboard(rawTable.getDisplay()); rawTable.addDisposeListener(new DisposeListener() { public void widgetDisposed(final DisposeEvent e) { clipboard.dispose(); } }); }
Source:
public static SSLContext createDefaultSSLContext(final InputStream keystoreInputStream, final String keystorePassword) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException, IOException { final KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(keystoreInputStream, keystorePassword != null ? keystorePassword.toCharArray() : null); return SSLContextUtil.createDefaultSSLContext(keyStore, keystorePassword != null ? keystorePassword.toCharArray() : null); }

Target:
public static SSLContext createDefaultSSLContext(final InputStream keystoreInputStream, final String keystorePassword) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException, IOException { final KeyStore keyStore = KeyStore.getInstance("PKCS12"); final char[] password = keystorePassword != null ? keystorePassword.toCharArray() : null; keyStore.load(keystoreInputStream, password); return createDefaultSSLContext(keyStore, keystorePassword != null ? keystorePassword.toCharArray() : null); }
Source:
public SwaggerParseResult readContents(String swaggerAsString, List<AuthorizationValue> auth, ParseOptions options) { SwaggerParseResult result = new SwaggerParseResult(); if(swaggerAsString != null && !"".equals(swaggerAsString.trim())) { try { JsonNode rootNode = mapDataToJsonNode(swaggerAsString); result = readWithInfo(rootNode); if (result.getOpenAPI() != null) { String version = result.getOpenAPI().getOpenapi(); if (version != null && version.startsWith("3.0")) { if (options != null) { if (auth == null) { auth = new ArrayList<>(); } OpenAPIResolver resolver = new OpenAPIResolver(result.getOpenAPI(), auth, null); if (options.isResolve() || options.isResolveFully()) { result.setOpenAPI(resolver.resolve()); } if (options.isResolveFully()) { new ResolverFully().resolveFully(result.getOpenAPI()); } } } } } catch (Exception e) { result.setMessages(Arrays.asList(e.getMessage())); } } else { result.setMessages(Arrays.asList("No swagger supplied")); } return result; }

Target:
public SwaggerParseResult readContents(String swaggerAsString, List<AuthorizationValue> auth, ParseOptions options) { SwaggerParseResult result = new SwaggerParseResult(); if(swaggerAsString != null && !"".equals(swaggerAsString.trim())) { ObjectMapper mapper = getRightMapper(swaggerAsString); if(auth == null) { auth = new ArrayList<>(); } if(options != null) { if (options.isResolve()) { try { OpenAPIDeserializer deserializer = new OpenAPIDeserializer(); JsonNode rootNode = mapper.readTree(swaggerAsString.getBytes()); result = deserializer.deserialize(rootNode); OpenAPIResolver resolver = new OpenAPIResolver(result.getOpenAPI(), auth, null); result.setOpenAPI(resolver.resolve()); } catch (Exception e) { result.setMessages(Arrays.asList(e.getMessage())); } }else{ try { JsonNode rootNode = mapper.readTree(swaggerAsString.getBytes()); result = new OpenAPIDeserializer().deserialize(rootNode); } catch (Exception e) { result.setMessages(Arrays.asList(e.getMessage())); } }if (options.isResolveFully()){ result.setOpenAPI(new OpenAPIResolver(result.getOpenAPI(), auth, null).resolve()); new ResolverFully().resolveFully(result.getOpenAPI()); } }else{ try { JsonNode rootNode = mapper.readTree(swaggerAsString.getBytes()); result = new OpenAPIDeserializer().deserialize(rootNode); } catch (Exception e) { result.setMessages(Arrays.asList(e.getMessage())); } } } else { result.setMessages(Arrays.asList("No swagger supplied")); } return result; }
Source:
public static HiveColumnStatistics merge(HiveColumnStatistics first, OptionalLong firstRowCount, HiveColumnStatistics second, OptionalLong secondRowCount) { return new HiveColumnStatistics( mergeIntegerStatistics(first.getIntegerStatistics(), second.getIntegerStatistics()), mergeDoubleStatistics(first.getDoubleStatistics(), second.getDoubleStatistics()), mergeDecimalStatistics(first.getDecimalStatistics(), second.getDecimalStatistics()), mergeDateStatistics(first.getDateStatistics(), second.getDateStatistics()), mergeBooleanStatistics(first.getBooleanStatistics(), second.getBooleanStatistics()), reduce(first.getMaxColumnLength(), second.getMaxColumnLength(), SELECT_MAX, true), mergeAverage(first.getAverageColumnLength(), firstRowCount, second.getAverageColumnLength(), secondRowCount), reduce(first.getNullsCount(), second.getNullsCount(), ADD, false), reduce(first.getDistinctValuesCount(), second.getDistinctValuesCount(), SELECT_MAX, false)); }

Target:
public static HiveColumnStatistics merge(HiveColumnStatistics first, OptionalLong firstRowCount, HiveColumnStatistics second, OptionalLong secondRowCount) { return new HiveColumnStatistics( mergeIntegerStatistics(first.getIntegerStatistics(), second.getIntegerStatistics()), mergeDoubleStatistics(first.getDoubleStatistics(), second.getDoubleStatistics()), mergeDecimalStatistics(first.getDecimalStatistics(), second.getDecimalStatistics()), mergeDateStatistics(first.getDateStatistics(), second.getDateStatistics()), mergeBooleanStatistics(first.getBooleanStatistics(), second.getBooleanStatistics()), reduce(first.getMaxColumnLength(), second.getMaxColumnLength(), MAX, true), mergeAverage(first.getAverageColumnLength(), firstRowCount, second.getAverageColumnLength(), secondRowCount), reduce(first.getNullsCount(), second.getNullsCount(), ADD, false), reduce(first.getDistinctValuesCount(), second.getDistinctValuesCount(), MAX, false)); }
Source:
public Crn getActingUserCrn() { try { return Crn.fromString(new String(Base64.getDecoder().decode(getActingUserAccessKey()))); } catch (Exception e) { if (Crn.isCrn(getActingUser().getCrn())) { return Crn.fromString(getActingUser().getCrn()); } if (!testParameter.get(CloudbreakTest.USER_CRN).isEmpty() || testParameter.get(CloudbreakTest.USER_CRN) != null) { return Crn.fromString(testParameter.get(CloudbreakTest.USER_CRN)); } LOGGER.error("Cannot find acting user: '{}' - Crn, because of: '{}'", getActingUserAccessKey(), e.getMessage(), e); throw new TestFailException(String.format("Cannot find acting user: '%s' - Crn, because of: '%s'", getActingUserAccessKey(), e.getMessage()), e); } }

Target:
public Crn getActingUserCrn() { return getMockUserCrn() .or(this::getRealUMSUserCrn) .or(this::getUserParameterCrn) .orElseThrow(() -> new TestFailException(String.format("Cannot find acting user: '%s' - Crn", getActingUserAccessKey()))); }
Source:
private InternalSchemaMetadata installNewVersionInMapOrDefault(int newVersion, ValueAndBound<InternalSchemaMetadata> valueAndBound) { if (!valueAndBound.value().isPresent()) { log.info("Attempting to install a new transactions schema version {}, but no past data was found," + " so we attempt to install default instead.", SafeArg.of("newVersion", newVersion)); return InternalSchemaMetadata.defaultValue(); } log.info("Attempting to install a new transactions schema version {}, on top of schema metadata" + " that is valid up till timestamp {}.", SafeArg.of("newVersion", newVersion), SafeArg.of("oldDataValidity", valueAndBound.bound())); InternalSchemaMetadata internalSchemaMetadata = valueAndBound.value().get(); return InternalSchemaMetadata.builder() .from(internalSchemaMetadata) .timestampToTransactionsTableSchemaVersion( installNewVersionInMap( internalSchemaMetadata.timestampToTransactionsTableSchemaVersion(), valueAndBound.bound() + 1, newVersion)) .build(); }

Target:
private InternalSchemaMetadata installNewVersionInMapOrDefault(int newVersion, ValueAndBound<InternalSchemaMetadata> valueAndBound) { if (!valueAndBound.value().isPresent()) { log.warn("Attempting to install a new transactions schema version {}, but no past data was found," + " so we attempt to install default instead. This should normally only happen once per" + " server, and only on or around first startup since upgrading to a version of AtlasDB" + " that is aware of the transactions table. If this message persists, please contact" + " support.", SafeArg.of("newVersion", newVersion)); return InternalSchemaMetadata.defaultValue(); } log.info("Attempting to install a new transactions schema version {}, on top of schema metadata" + " that is valid up till timestamp {}.", SafeArg.of("newVersion", newVersion), SafeArg.of("oldDataValidity", valueAndBound.bound())); InternalSchemaMetadata internalSchemaMetadata = valueAndBound.value().get(); return InternalSchemaMetadata.builder() .from(internalSchemaMetadata) .timestampToTransactionsTableSchemaVersion( installNewVersionInMap( internalSchemaMetadata.timestampToTransactionsTableSchemaVersion(), valueAndBound.bound() + 1, newVersion)) .build(); }
Source:
public StructuredRecord getCurrentValue(StructuredRecord.Builder recordBuilder) throws IOException, InterruptedException { AvroJob.setOutputKeySchema(job, new org.apache.avro.Schema.Parser().parse(schema.toString())); StructuredRecord ret = recordTransformer.transform(recordBuilder, delegate.getCurrentKey().datum(), schema, pathField); return ret; }

Target:
public StructuredRecord getCurrentValue(StructuredRecord.Builder recordBuilder) throws IOException, InterruptedException { return recordTransformer.transform(recordBuilder, delegate.getCurrentKey().datum(), schema, pathField); }
Source:
public String handleException(Exception e) throws IOException { LOGGER.error("Error while updating configs", e); return e.getMessage(); }

Target:
public String handleException(Exception e) { LOGGER.error("Error while updating configs", e); return e.getMessage(); }
Source:
public void testLocatedStatusNoDir() throws Throwable { describe("test the LocatedStatus call on a path which is not present"); getFileSystem().listLocatedStatus(path("missing")); }

Target:
public void testLocatedStatusNoDir() throws Throwable { describe("test the LocatedStatus call on a path which is not present"); intercept(FileNotFoundException.class, new LambdaTestUtils.VoidCallable() { @Override public void call() throws Exception { getFileSystem().listLocatedStatus(path("missing")); } }); }
Source:
public ScriptingJobs(ScriptingAdaptor adaptor, XenonEngine xenonEngine, SchedulerConnectionFactory connectionFactory) { this.adaptor = adaptor; this.xenonEngine = xenonEngine; this.adaptorName = adaptor.getName(); this.connectionFactory = connectionFactory; connections = Utils.emptyMap(1); }

Target:
public ScriptingJobs(ScriptingAdaptor adaptor, XenonEngine xenonEngine, SchedulerConnectionFactory connectionFactory) { this.adaptor = adaptor; this.xenonEngine = xenonEngine; this.adaptorName = adaptor.getName(); this.connectionFactory = connectionFactory; connections = new HashMap<>(); }
Source:
public void testNumberOfLocksAvailable() throws Exception { DummyTransactionManager tm = (DummyTransactionManager) TestingUtil.extractComponent(cache, TransactionManager.class); int initialAvailable = getAttrValue("NumberOfLocksAvailable"); tm.begin(); cache.put("key", "value"); tm.getTransaction().runPrepare(); assertAttributeValue("NumberOfLocksHeld", 1); assertAttributeValue("NumberOfLocksAvailable", initialAvailable - 1); try { tm.getTransaction().runCommit(true); fail("RollbackException expected!"); } catch (RollbackException e) { assertEquals(DummyTransaction.FORCE_ROLLBACK_MESSAGE, e.getLocalizedMessage()); } assertAttributeValue("NumberOfLocksAvailable", initialAvailable); assertAttributeValue("NumberOfLocksHeld", 0); }

Target:
public void testNumberOfLocksAvailable() throws Exception { DummyTransactionManager tm = (DummyTransactionManager) TestingUtil.extractComponent(cache, TransactionManager.class); int initialAvailable = getAttrValue("NumberOfLocksAvailable"); tm.begin(); cache.put("key", "value"); tm.getTransaction().runPrepare(); assertAttributeValue("NumberOfLocksHeld", 1); assertAttributeValue("NumberOfLocksAvailable", initialAvailable - 1); tm.getTransaction().runCommit(true); assertAttributeValue("NumberOfLocksAvailable", initialAvailable); assertAttributeValue("NumberOfLocksHeld", 0); }
Source:
public void addMassRepairOption(MassRepairOption mro) { if (mro.getType() == PartRepairType.UNKNOWN_LOCATION) { return; } int foundIdx = -1; for (int i = 0; i < massRepairOptions.size(); i++) { if (massRepairOptions.get(i).getType() == mro.getType()) { foundIdx = i; break; } } if (foundIdx == -1) { massRepairOptions.add(mro); } else { massRepairOptions.add(foundIdx, mro); massRepairOptions.remove(foundIdx + 1); } massRepairOptions.sort((mro1, mro2) -> (((Comparable<Integer>) mro1.getType().ordinal()).compareTo(mro2.getType().ordinal()))); }

Target:
public void addMassRepairOption(MassRepairOption mro) { if (mro.getType() == PartRepairType.UNKNOWN_LOCATION) { return; } getMassRepairOptions().removeIf(massRepairOption -> massRepairOption.getType() == mro.getType()); getMassRepairOptions().add(mro); }
Source:
private DirContext obtainContext() throws RealmUnavailableException { if (this.listenersPendingRegistration.size() == 0) { try { return dirContextSupplier.get(); } catch (NamingException e) { throw log.ldapRealmFailedToObtainContext(e); } } else { try { DirContext ctx = dirContextSupplier.get(); synchronized (this.listenersPendingRegistration) { for(Consumer<Principal> listener:this.listenersPendingRegistration){ innerIdentityChangeListener(ctx,listener); } this.listenersPendingRegistration.clear(); } return ctx; } catch (NamingException e) { throw log.ldapRealmFailedToObtainContext(e); } } }

Target:
private DirContext obtainContext() throws RealmUnavailableException { try { DirContext ctx = dirContextSupplier.get(); synchronized (this.listenersPendingRegistration) { final Iterator<Consumer<Principal>> it = this.listenersPendingRegistration.iterator(); while(it.hasNext()) { registerIdentityChangeListener(ctx, it.next()); it.remove(); } return ctx; } } catch (NamingException e) { throw log.ldapRealmFailedToObtainContext(e); } }
Source:
private TestResultRecord buildTestResultRecord(File file) { String[] parts = file.getName().split("_|\\."); Date date; try { date = dateFormat.parse(parts[0]); } catch (ParseException e) { throw new IllegalStateException("File format should have been verified", e); } TestResultRecord testResultRecord = new TestResultRecord( file, date, Integer.parseInt(parts[1]), Integer.parseInt(parts[2]), Integer.parseInt(parts[3]), Integer.parseInt(parts[4])); return testResultRecord; }

Target:
private TestResultRecord buildTestResultRecord(File file) { String[] parts = file.getName().split("_|\\."); Date date; try { date = dateFormat.parse(parts[0]); } catch (ParseException e) { throw new IllegalStateException(format("'%s' can not be parsed to a valid date", parts[0]), e); } return new TestResultRecord( file, date, Integer.parseInt(parts[1]), Integer.parseInt(parts[2]), Integer.parseInt(parts[3]), Integer.parseInt(parts[4])); }
Source:
public void waitCreateStackDialog() { WaitUtils.sleepQuietly(2); seleniumWebDriverHelper.waitVisibility(By.xpath(" seleniumWebDriverHelper.waitVisibility( By.xpath(" seleniumWebDriverHelper.waitVisibility(By.xpath(" }

Target:
public void waitCreateStackDialog() { WaitUtils.sleepQuietly(2); seleniumWebDriverHelper.waitVisibility(By.xpath(CREATE_STACK_DIALOG_FORM_XPATH)); seleniumWebDriverHelper.waitVisibility( By.xpath(" seleniumWebDriverHelper.waitVisibility(By.xpath(" }
Source:
protected void onDraw(Canvas canvas) { if (GRID_ENABLED) { DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics(); int screenWidth = metrics.widthPixels; int screenHeight = metrics.heightPixels; canvas.drawLine(2 * (screenWidth / 3), 0, 2 * (screenWidth / 3), screenHeight, paint); canvas.drawLine((screenWidth / 3), 0, (screenWidth / 3), screenHeight, paint); canvas.drawLine(0, 2 * (screenHeight / 3), screenWidth, 2 * (screenHeight / 3), paint); canvas.drawLine(0, (screenHeight / 3), screenWidth, (screenHeight / 3), paint); } }

Target:
protected void onDraw(Canvas canvas) { if (GRID_ENABLED) { int screenWidth = Utils.getScreenWidth(getContext()); int screenHeight = Utils.getScreenHeight(getContext()); canvas.drawLine(2 * (screenWidth / 3), 0, 2 * (screenWidth / 3), screenHeight, paint); canvas.drawLine((screenWidth / 3), 0, (screenWidth / 3), screenHeight, paint); canvas.drawLine(0, 2 * (screenHeight / 3), screenWidth, 2 * (screenHeight / 3), paint); canvas.drawLine(0, (screenHeight / 3), screenWidth, (screenHeight / 3), paint); } }
Source:
public void removeNotificationListener( ObjectName name, ObjectName listener, NotificationFilter filter, Object handback) { throw new UnsupportedOperationException("removeNotificationListener not supported for Jolokia"); }

Target:
public void removeNotificationListener( ObjectName name, ObjectName listener, NotificationFilter filter, Object handback) { throw new UnsupportedOperationException("removeNotificationListener not supported by Jolokia"); }
Source:
protected void onJoinPrepare(int generation, String memberId) { maybeAutoCommitOffsetsSync(time.timer(rebalanceConfig.rebalanceTimeoutMs)); final Set<TopicPartition> revokedPartitions; final AtomicReference<Exception> firstException = new AtomicReference<>(null); switch (protocol) { case EAGER: revokedPartitions = new HashSet<>(subscriptions.assignedPartitions()); firstException.compareAndSet(null, maybeInvokePartitionsRevoked(revokedPartitions)); subscriptions.assignFromSubscribed(Collections.emptySet()); break; case COOPERATIVE: Set<TopicPartition> ownedPartitions = new HashSet<>(subscriptions.assignedPartitions()); revokedPartitions = ownedPartitions.stream() .filter(tp -> !subscriptions.subscription().contains(tp.topic())) .collect(Collectors.toSet()); if (!revokedPartitions.isEmpty()) { firstException.compareAndSet(null, maybeInvokePartitionsRevoked(revokedPartitions)); ownedPartitions.removeAll(revokedPartitions); subscriptions.assignFromSubscribed(ownedPartitions); } break; } isLeader = false; subscriptions.resetGroupSubscription(); if (firstException.get() != null) { throw new KafkaException("User rebalance callback throws an error", firstException.get()); } }

Target:
protected void onJoinPrepare(int generation, String memberId) { log.debug("Executing onJoinPrepare with generation and memberId {}", generation, memberId); maybeAutoCommitOffsetsSync(time.timer(rebalanceConfig.rebalanceTimeoutMs)); Exception exception = null; final Set<TopicPartition> revokedPartitions; if (generation == Generation.NO_GENERATION.generationId && memberId.equals(Generation.NO_GENERATION.memberId)) { revokedPartitions = new HashSet<>(subscriptions.assignedPartitions()); if (!revokedPartitions.isEmpty()) { log.info("Giving away all assigned partitions as lost since generation has been reset," + "indicating that consumer is no longer part of the group"); exception = invokePartitionsLost(revokedPartitions); subscriptions.assignFromSubscribed(Collections.emptySet()); } } else { switch (protocol) { case EAGER: revokedPartitions = new HashSet<>(subscriptions.assignedPartitions()); exception = invokePartitionsRevoked(revokedPartitions); subscriptions.assignFromSubscribed(Collections.emptySet()); break; case COOPERATIVE: Set<TopicPartition> ownedPartitions = new HashSet<>(subscriptions.assignedPartitions()); revokedPartitions = ownedPartitions.stream() .filter(tp -> !subscriptions.subscription().contains(tp.topic())) .collect(Collectors.toSet()); if (!revokedPartitions.isEmpty()) { exception = invokePartitionsRevoked(revokedPartitions); ownedPartitions.removeAll(revokedPartitions); subscriptions.assignFromSubscribed(ownedPartitions); } break; } } isLeader = false; subscriptions.resetGroupSubscription(); if (exception != null) { throw new KafkaException("User rebalance callback throws an error", exception); } }
Source:
public SimpleObject getValue(PersonAttribute pa) { if (pa.getHydratedObject() == null) return null; SimpleObject simpleObject = new SimpleObject(); simpleObject.put("value", ConversionUtil.convertToRepresentation(pa.getHydratedObject(),Representation.REF)); return simpleObject; }

Target:
public Object getValue(PersonAttribute pa) { if (pa.getHydratedObject() == null) return null; SimpleObject simpleObject = new SimpleObject(); simpleObject.put("value", ConversionUtil.convertToRepresentation(pa.getHydratedObject(),Representation.REF)); return simpleObject; }
Source:
public boolean exists(Get get) throws IOException { try (Scope scope = TRACER.spanBuilder("BigtableTable.exists").startScopedSpan()) { LOG.trace("exists(Get)"); Result result = getResults(GetAdapter.setCheckExistenceOnly(get), "exists"); return result != null && !result.isEmpty(); } }

Target:
public boolean exists(Get get) throws IOException { try (Scope scope = TRACER.spanBuilder("BigtableTable.exists").startScopedSpan()) { LOG.trace("exists(Get)"); return !getResults(GetAdapter.setCheckExistenceOnly(get), "exists").isEmpty(); } }
Source:
public static LockStateYamlWriter create(File file) throws IOException { return new LockStateYamlWriter(new FileWriter(file, true)); }

Target:
public static LockStateYamlWriter create(File file) throws IOException { return new LockStateYamlWriter(new BufferedWriter(new FileWriter(file, true))); }
Source:
public <V> Injector<V> provides(final ServiceName... dependencies) { assertNotInstalled(); assertNotNull(dependencies); assertThreadSafety(); assertServiceNotConfigured(); for (ServiceName dependency : dependencies) { assertNotNull(dependency); assertNeitherRequiredNorProvided(dependency, false); } final WritableValueImpl retVal = new WritableValueImpl(); for (ServiceName dependency : dependencies) { addProvidesInternal(dependency, retVal); } return (Injector<V>)retVal; }

Target:
public <V> Consumer<V> provides(final ServiceName... dependencies) { assertNotInstalled(); assertNotNull(dependencies); assertThreadSafety(); assertServiceNotConfigured(); for (ServiceName dependency : dependencies) { assertNotNull(dependency); assertNotRequired(dependency, false); assertNotProvided(dependency, false); } final WritableValueImpl retVal = new WritableValueImpl(); for (ServiceName dependency : dependencies) { addProvidesInternal(dependency, retVal); } return (Consumer<V>)retVal; }
Source:
private long applyShadowStream(UUID streamId, long seqNum, long snapshot) { UUID shadowStreamId = uuidMap.get(streamId); StreamOptions options = StreamOptions.builder() .ignoreTrimmed(true) .cacheEntries(false) .build(); Stream shadowStream = (new OpaqueStream(rt, rt.getStreamsView().get(shadowStreamId, options))).streamUpTo(snapshot); Iterator<OpaqueEntry> iterator = shadowStream.iterator(); while (iterator.hasNext()) { OpaqueEntry opaqueEntry = iterator.next(); if (opaqueEntry.getVersion() > shadowStreamStartAddress) { processOpaqueEntry(opaqueEntry.getEntries().get(shadowStreamId), seqNum, streamId); seqNum = seqNum + 1; } } return seqNum; }

Target:
private long applyShadowStream(UUID streamId, long seqNum, long snapshot) { UUID shadowStreamId = uuidMap.get(streamId); StreamOptions options = StreamOptions.builder() .ignoreTrimmed(false) .cacheEntries(false) .build(); long currentMinShadowStreamTimestamp = logReplicationMetadataManager.getMinSnapshotSyncShadowStreamTs(); OpaqueStream shadowOpaqueStream = new OpaqueStream(rt, rt.getStreamsView().get(shadowStreamId, options)); shadowOpaqueStream.seek(currentMinShadowStreamTimestamp); Stream shadowStream = shadowOpaqueStream.streamUpTo(snapshot); Iterator<OpaqueEntry> iterator = shadowStream.iterator(); while (iterator.hasNext()) { OpaqueEntry opaqueEntry = iterator.next(); if (opaqueEntry.getVersion() >= shadowStreamStartAddress) { processOpaqueEntry(opaqueEntry.getEntries().get(shadowStreamId), seqNum, streamId); seqNum = seqNum + 1; } } return seqNum; }
Source:
private static boolean hasTaskCompleted(GlusterAsyncTask task) { if (JobExecutionStatus.ABORTED.equals(task.getStatus()) || JobExecutionStatus.FINISHED.equals(task.getStatus()) || JobExecutionStatus.FAILED.equals(task.getStatus())) { return true; } return false; }

Target:
private static boolean hasTaskCompleted(GlusterAsyncTask task) { if (JobExecutionStatus.ABORTED == task.getStatus() || JobExecutionStatus.FINISHED == task.getStatus() || JobExecutionStatus.FAILED == task.getStatus()) { return true; } return false; }
Source:
public void testFailure() throws Exception { doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) { invocation.getArgumentAt(1, ClientCall.Listener.class) .onClose(Status.DEADLINE_EXCEEDED, new Metadata()); return null; } }).when(mockRetryableRpc) .start(any(ReadRowsRequest.class), any(ClientCall.Listener.class), any(Metadata.class), any(ClientCall.class)); RetryingReadRowsOperation underTest = createOperation(CallOptions.DEFAULT, mockFlatRowObserver); try { underTest.getAsyncResult().get(100, TimeUnit.MILLISECONDS); } catch (ExecutionException e) { Assert.assertEquals(BigtableRetriesExhaustedException.class, e.getCause().getClass()); Assert.assertEquals(Status.DEADLINE_EXCEEDED.getCode(), Status.fromThrowable(e).getCode()); } Assert.assertEquals( ((ExponentialBackOff) underTest.getCurrentBackoff()).getMaxElapsedTimeMillis(), RETRY_OPTIONS.getMaxElapsedBackoffMillis(), 10); clock.assertTimeWithinExpectations( TimeUnit.MILLISECONDS.toNanos(RETRY_OPTIONS.getMaxElapsedBackoffMillis())); }

Target:
public void testFailure() throws Exception { doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) { invocation.getArgumentAt(1, ClientCall.Listener.class) .onClose(Status.DEADLINE_EXCEEDED, new Metadata()); return null; } }).when(mockRetryableRpc) .start(any(ReadRowsRequest.class), any(ClientCall.Listener.class), any(Metadata.class), any(ClientCall.class)); RetryingReadRowsOperation underTest = createOperation(CallOptions.DEFAULT, mockFlatRowObserver); try { underTest.getAsyncResult().get(100, TimeUnit.MILLISECONDS); } catch (ExecutionException e) { Assert.assertEquals(BigtableRetriesExhaustedException.class, e.getCause().getClass()); Assert.assertEquals(Status.DEADLINE_EXCEEDED.getCode(), Status.fromThrowable(e).getCode()); } int expectedMaxElapsedTimeMs = ((ExponentialBackOff) underTest.getCurrentBackoff()).getMaxElapsedTimeMillis(); int actualElapsedTimeMs = RETRY_OPTIONS.getMaxElapsedBackoffMillis(); Assert.assertEquals(expectedMaxElapsedTimeMs, actualElapsedTimeMs); clock.assertTimeWithinExpectations(TimeUnit.MILLISECONDS.toNanos(actualElapsedTimeMs)); }
Source:
public void parseArgs(ScriptEntry scriptEntry) throws InvalidArgumentsException { for (Argument arg : scriptEntry.getProcessedArgs()) { if (!scriptEntry.hasObject("targets") && arg.matchesArgumentList(MythicMobsMobTag.class)) { scriptEntry.addObject("targets", arg.asType(ListTag.class).filter(MythicMobsMobTag.class, scriptEntry)); } else if (!scriptEntry.hasObject("signal") && arg.matchesArgumentType(ElementTag.class)) { scriptEntry.addObject("signal", arg.asType(ElementTag.class)); } else if (!scriptEntry.hasObject("soruce") && arg.matchesPrefix("source") && arg.matchesArgumentType(EntityTag.class)) { scriptEntry.addObject("source", arg.asType(EntityTag.class)); } else { arg.reportUnhandled(); } } if (!scriptEntry.hasObject("targets")) { throw new InvalidArgumentsException("Must specify MythicMobs to send the signal to."); } if (!scriptEntry.hasObject("signal")) { throw new InvalidArgumentsException("Must specify a signal to send."); } }

Target:
public void parseArgs(ScriptEntry scriptEntry) throws InvalidArgumentsException { for (Argument arg : scriptEntry.getProcessedArgs()) { if (!scriptEntry.hasObject("targets") && arg.matchesArgumentList(MythicMobsMobTag.class)) { scriptEntry.addObject("targets", arg.asType(ListTag.class).filter(MythicMobsMobTag.class, scriptEntry)); } else if (!scriptEntry.hasObject("source") && arg.matchesPrefix("source") && arg.matchesArgumentType(EntityTag.class)) { scriptEntry.addObject("source", arg.asType(EntityTag.class)); } else if (!scriptEntry.hasObject("signal")) { scriptEntry.addObject("signal", arg.asType(ElementTag.class)); } else { arg.reportUnhandled(); } } if (!scriptEntry.hasObject("targets")) { throw new InvalidArgumentsException("Must specify MythicMobs to send the signal to."); } if (!scriptEntry.hasObject("signal")) { throw new InvalidArgumentsException("Must specify a signal to send."); } }
Source:
private <T> T applyOnDefaultChannel(Function<ClientChannel, T> function) { List<ClientChannelHolder> holders = channels; if (holders == null) throw new ClientException("Connections to nodes aren't initialized."); int size = holders.size(); int attemptsLimit = clientCfg.getRetryLimit() > 0 ? Math.min(clientCfg.getRetryLimit(), size) : size; return applyOnDefaultChannel(function, attemptsLimit).getKey(); }

Target:
private <T> T applyOnDefaultChannel(Function<ClientChannel, T> function) { return applyOnDefaultChannel(function, getRetryLimit(), DO_NOTHING); }
Source:
public void testToFromZNRecord() { RealtimeToOfflineSegmentsTaskMetadata metadata = new RealtimeToOfflineSegmentsTaskMetadata("testTable_REALTIME", 1000); ZNRecord znRecord = metadata.toZNRecord(); assertEquals(znRecord.getId(), "testTable_REALTIME"); assertEquals(znRecord.getSimpleField("watermarkMillis"), "1000"); RealtimeToOfflineSegmentsTaskMetadata realtimeToOfflineSegmentsTaskMetadata = RealtimeToOfflineSegmentsTaskMetadata.fromZNRecord(znRecord); assertEquals(realtimeToOfflineSegmentsTaskMetadata.getTableNameWithType(), "testTable_REALTIME"); assertEquals(realtimeToOfflineSegmentsTaskMetadata.getWatermarkMillis(), 1000); }

Target:
public void testToFromZNRecord() { RealtimeToOfflineSegmentsTaskMetadata metadata = new RealtimeToOfflineSegmentsTaskMetadata("testTable_REALTIME", 1000); ZNRecord znRecord = metadata.toZNRecord(); assertEquals(znRecord.getId(), "testTable_REALTIME"); assertEquals(znRecord.getSimpleField("watermarkMs"), "1000"); RealtimeToOfflineSegmentsTaskMetadata realtimeToOfflineSegmentsTaskMetadata = RealtimeToOfflineSegmentsTaskMetadata.fromZNRecord(znRecord); assertEquals(realtimeToOfflineSegmentsTaskMetadata.getTableNameWithType(), "testTable_REALTIME"); assertEquals(realtimeToOfflineSegmentsTaskMetadata.getWatermarkMs(), 1000); }
Source:
protected void handleClose() { if (foldLeftFn != null) { foldLeftFn.close(); } }

Target:
protected void handleClose() { if (foldLeftFn != null) { foldLeftFn.close(); } if (timeSeriesStore != null) { timeSeriesStore.close(); } }
Source:
public static FormValidation validateExecutable(String exe, FileValidator exeValidator) { if(!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) return ok(); exe = fixEmpty(exe); if(exe==null) return ok(); if(exe.indexOf(File.separatorChar)>=0) { File f = new File(exe); if(f.exists()) return exeValidator.validate(f); File fexe = new File(exe+".exe"); if(fexe.exists()) return exeValidator.validate(fexe); return error("There's no such file: "+exe); } String path = EnvVars.masterEnvVars.get("PATH"); String tokenizedPath; String delimiter = null; if(path!=null) { StringBuilder tokenizedPathBuilder = new StringBuilder(); for (String _dir : Util.tokenize(path.replace("\\", "\\\\"),File.pathSeparator)) { if (delimiter == null) { delimiter = ", "; } else { tokenizedPathBuilder.append(delimiter); } tokenizedPathBuilder.append(_dir.replace('\\', '/')); File dir = new File(_dir); File f = new File(dir,exe); if(f.exists()) return exeValidator.validate(f); File fexe = new File(dir,exe+".exe"); if(fexe.exists()) return exeValidator.validate(fexe); } tokenizedPath = tokenizedPathBuilder.toString(); tokenizedPath += "."; } else { tokenizedPath = "unavailable."; } return error("There's no such executable "+exe+" in PATH: "+tokenizedPath); }

Target:
public static FormValidation validateExecutable(String exe, FileValidator exeValidator) { if(!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) return ok(); exe = fixEmpty(exe); if(exe==null) return ok(); if(exe.indexOf(File.separatorChar)>=0) { File f = new File(exe); if(f.exists()) return exeValidator.validate(f); File fexe = new File(exe+".exe"); if(fexe.exists()) return exeValidator.validate(fexe); return error("There's no such file: "+exe); } String path = EnvVars.masterEnvVars.get("PATH"); String tokenizedPath; String delimiter = null; if(path!=null) { StringBuilder tokenizedPathBuilder = new StringBuilder(); for (String _dir : Util.tokenize(path.replace("\\", "\\\\"),File.pathSeparator)) { if (delimiter == null) { delimiter = ", "; } else { tokenizedPathBuilder.append(delimiter); } tokenizedPathBuilder.append(_dir.replace('\\', '/')); File dir = new File(_dir); File f = new File(dir,exe); if(f.exists()) return exeValidator.validate(f); File fexe = new File(dir,exe+".exe"); if(fexe.exists()) return exeValidator.validate(fexe); } tokenizedPathBuilder.append('.'); tokenizedPath = tokenizedPathBuilder.toString(); } else { tokenizedPath = "unavailable."; } return error("There's no such executable "+exe+" in PATH: "+tokenizedPath); }
Source:
private boolean isSensitiveSearchterm(String searchterm) { for (int i=0; i < logResultFilterPatterns.length; i++){ Matcher match = logResultFilterPatterns[i].matcher(searchterm); if (match.matches()) { return false; } } return true; }

Target:
private boolean isSensitiveSearchterm(String searchterm) { for (int i=0; i < logResultFilterPatterns.length; i++){ Matcher match = logResultFilterPatterns[i].matcher(searchterm); if (match.matches()) { return true; } } return false; }
Source:
protected void containerIsStarting(InspectContainerResponse containerInfo) { super.containerIsStarting(containerInfo); port = getMappedPort(KAFKA_PORT); final String zookeeperConnect; if (externalZookeeperConnect != null) { zookeeperConnect = externalZookeeperConnect; } else { zookeeperConnect = "localhost:" + ZOOKEEPER_PORT; ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(getContainerId()) .withCmd("sh", "-c", "" + "printf 'clientPort=" + ZOOKEEPER_PORT + "\ndataDir=/var/lib/zookeeper/data\ndataLogDir=/var/lib/zookeeper/log' > /zookeeper.properties\n" + "zookeeper-server-start /zookeeper.properties\n" ) .exec(); dockerClient.execStartCmd(execCreateCmdResponse.getId()).exec(new ExecStartResultCallback()).awaitStarted(10, TimeUnit.SECONDS); } String internalIp = containerInfo.getNetworkSettings().getIpAddress(); ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(getContainerId()) .withCmd("sh", "-c", "" + "export KAFKA_ZOOKEEPER_CONNECT=" + zookeeperConnect + "\n" + "export KAFKA_ADVERTISED_LISTENERS=" + getBootstrapServers() + "," + String.format("BROKER://%s:9092", internalIp) + "\n" + "/etc/confluent/docker/run" ) .exec(); dockerClient.execStartCmd(execCreateCmdResponse.getId()).exec(new ExecStartResultCallback()).awaitStarted(10, TimeUnit.SECONDS); }

Target:
protected void containerIsStarting(InspectContainerResponse containerInfo) { super.containerIsStarting(containerInfo); port = getMappedPort(KAFKA_PORT); final String zookeeperConnect; if (externalZookeeperConnect != null) { zookeeperConnect = externalZookeeperConnect; } else { zookeeperConnect = startZookeeper(); } String internalIp = containerInfo.getNetworkSettings().getIpAddress(); ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(getContainerId()) .withCmd("sh", "-c", "" + "export KAFKA_ZOOKEEPER_CONNECT=" + zookeeperConnect + "\n" + "export KAFKA_ADVERTISED_LISTENERS=" + getBootstrapServers() + "," + String.format("BROKER://%s:9092", internalIp) + "\n" + "/etc/confluent/docker/run" ) .exec(); dockerClient.execStartCmd(execCreateCmdResponse.getId()).exec(new ExecStartResultCallback()).awaitStarted(10, TimeUnit.SECONDS); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_geocode_route); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); mMapView = (MapView) findViewById(R.id.mapView); mMapView.getGraphicsOverlays().add(graphicsOverlay); boolean permissionCheck = ContextCompat.checkSelfPermission(GeocodeRouteActivity.this, permission[0]) == PackageManager.PERMISSION_GRANTED; if (!permissionCheck) { ActivityCompat.requestPermissions(GeocodeRouteActivity.this, permission, requestCode); } else { setupOfflineMap(); } FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { solveRoute(); } }); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_geocode_route); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); mMapView = (MapView) findViewById(R.id.mapView); mMapView.getGraphicsOverlays().add(graphicsOverlay); boolean permissionCheck = ContextCompat.checkSelfPermission(GeocodeRouteActivity.this, permission[0]) == PackageManager.PERMISSION_GRANTED; if (!permissionCheck) { ActivityCompat.requestPermissions(GeocodeRouteActivity.this, permission, requestCode); } else { setupOfflineMap(); } FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { solveRoute(); } }); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); }
Source:
protected List<Map.Entry<Unit, Double>> getMetricEquivalent(double value, @NotNull Unit unit) throws IllegalArgumentException { LinkedList<Map.Entry<Unit, Double>> conversions = new LinkedList<>(); for (Unit metric : metricUnits) { if (unit.equals(metric)) { return null; } if (unit.isCompatible(metric)) { Double converted = unit.getConverterTo(metric).convert(value); conversions.add(new AbstractMap.SimpleImmutableEntry<>(metric, converted)); } } sortByNaturalness(conversions); if (conversions.size() == 0) throw new IllegalArgumentException("Unit " + unit + " is not convertible to any metric unit."); else return conversions; }

Target:
protected List<Map.Entry<Unit, Double>> getMetricEquivalent(double value, @NotNull Unit unit) { LinkedList<Map.Entry<Unit, Double>> conversions = new LinkedList<>(); for (Unit metric : metricUnits) { if (unit.equals(metric)) { return null; } if (unit.isCompatible(metric)) { Double converted = unit.getConverterTo(metric).convert(value); conversions.add(new AbstractMap.SimpleImmutableEntry<>(metric, converted)); } } sortByNaturalness(conversions); if (conversions.size() == 0) { return null; } else { return conversions; } }
Source:
List<String> findLastDonationForDonor(@ModelAttribute("addCollectionForm") CollectedSampleBackingForm form) { CollectedSample collectedSample = form.getCollectedSample(); long diffInDays =0; Date dateofLastDonation = null; List<String> message = new ArrayList<String>(); try{ Donor donor =donorRepository.findDonorById(collectedSample.getDonor().getDonorNumber()); dateofLastDonation = donor.getDateOfLastDonation(); if(dateofLastDonation != null){ Date collectedOnDate = collectedSample.getCollectedOn(); long diff = collectedOnDate.getTime() - dateofLastDonation.getTime(); diffInDays = diff / (24 * 60 * 60 * 1000); SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); message.add(String.valueOf(diffInDays)); message.add(formatter.format(dateofLastDonation).toString()); message.add(formatter.format(collectedOnDate).toString()); } else{ message.add("firstTime"); message.add("Doner is first time donar"); } } catch(NoResultException e){ message.add("notExist"); message.add("Doner does not exist"); } catch(NullPointerException e){ message.add("collectedOnRequired"); message.add("'Collected On' Date is required"); } catch(NumberFormatException e){ message.add("invalideDonor"); message.add("Invalide Donor Number"); } catch(Exception e){ message.add("error"); message.add(e.toString()); } return message; }

Target:
Map<String, String> findLastDonationForDonor(@ModelAttribute("addCollectionForm") CollectedSampleBackingForm form) { CollectedSample collectedSample = form.getCollectedSample(); long diffInDays =0; Date dateofLastDonation = null; List<String> message = new ArrayList<String>(); Map<String, String> m = new HashMap<String, String>(); try{ if(donorRepository.findDonorByNumber(collectedSample.getDonor().getDonorNumber()) != null){ Donor donor = donorRepository.findDonorByNumber(collectedSample.getDonor().getDonorNumber()); if(donor.getDateOfLastDonation() != null){ dateofLastDonation = donor.getDateOfLastDonation(); Date collectedOnDate = collectedSample.getCollectedOn(); long diff = collectedOnDate.getTime() - dateofLastDonation.getTime(); diffInDays = diff / (24 * 60 * 60 * 1000); SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); m.put("diffInDays",String.valueOf(diffInDays)); m.put("dateOfLastDonation",formatter.format(dateofLastDonation).toString()); m.put("collectedOnDate",formatter.format(collectedOnDate).toString()); } } } catch(Exception ex){ ex.printStackTrace(); } return m; }