auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void checkLeaderAndTimelockBlocks() { if (leader().isPresent()) { Preconditions.checkState(areTimeAndLockConfigsAbsent(), "If the leader block is present, then the lock and timestamp server blocks must both be absent."); Preconditions.checkState(!timelock().isPresent(), "If the leader block is present, then the timelock block must be absent."); } checkLeaderBlockHasAtLeastOneServerIfPresent(leader()); if (timelock().isPresent()) { Preconditions.checkState(areTimeAndLockConfigsAbsent(), "If the timelock block is present, then the lock and timestamp blocks must both be absent."); } }

Target:
private void checkLeaderAndTimelockBlocks() { if (leader().isPresent()) { Preconditions.checkState(areTimeAndLockConfigsAbsent(), "If the leader block is present, then the lock and timestamp server blocks must both be absent."); Preconditions.checkState(!timelock().isPresent(), "If the leader block is present, then the timelock block must be absent."); Preconditions.checkState(!leader().get().leaders().isEmpty(), "Leader config must have at least one server."); } if (timelock().isPresent()) { Preconditions.checkState(areTimeAndLockConfigsAbsent(), "If the timelock block is present, then the lock and timestamp blocks must both be absent."); } }
Source:
public Object doWork() { final AllelicPanelOfNormals allelicPoN = allelicPoNFile != null ? AllelicPanelOfNormals.read(allelicPoNFile) : AllelicPanelOfNormals.EMPTY_PON; final AllelicCountCollection acc = new AllelicCountCollection(snpCountsFile); final AlleleFractionSegmenter alleleFractionSegmenter = new AlleleFractionSegmenter(initialNumAFStates, acc, allelicPoN); final ReadCountCollection counts; try { counts = ReadCountCollectionUtils.parse(new File(coverageFile)); } catch (final IOException ex) { throw new UserException.BadInput("could not read input file"); } final List<Double> coverage = Doubles.asList(counts.counts().getColumn(0)); final List<SimpleInterval> targets = counts.targets().stream().map(Target::getInterval).collect(Collectors.toList()); final CopyRatioSegmenter copyRatioSegmenter = new CopyRatioSegmenter(initialNumCRStates, targets, coverage); final JointAFCRSegmenter jointSegmenter = JointAFCRSegmenter.createJointSegmenter(copyRatioSegmenter, alleleFractionSegmenter); final List<Pair<SimpleInterval, AFCRHiddenState>> segmentation = jointSegmenter.findSegments(); final List<ACNVModeledSegment> segments = segmentation.stream().map(pair -> new ACNVModeledSegment(pair.getLeft(), errorlessPosterior(pair.getRight().getLog2CopyRatio()), errorlessPosterior(pair.getRight().getMinorAlleleFraction()))) .collect(Collectors.toList()); SegmentUtils.writeACNVModeledSegmentFile(outputSegmentsFile, segments, new Genome(counts, acc.getCounts())); return "SUCCESS"; }

Target:
public Object doWork() { ParamUtils.isPositive(initialNumAFStates, "Must have at least one allele-fraction state."); ParamUtils.isPositive(initialNumCRStates, "Must have at least one copy-ratio state."); final AllelicPanelOfNormals allelicPoN = allelicPoNFile != null ? AllelicPanelOfNormals.read(allelicPoNFile) : AllelicPanelOfNormals.EMPTY_PON; final AllelicCountCollection acc = new AllelicCountCollection(snpCountsFile); final ReadCountCollection rcc; try { rcc = ReadCountCollectionUtils.parse(new File(coverageFile)); } catch (final IOException ex) { throw new UserException.BadInput("could not read input file"); } final JointAFCRSegmenter jointSegmenter = JointAFCRSegmenter.createJointSegmenter(initialNumCRStates, rcc, initialNumAFStates, acc, allelicPoN); final List<Pair<SimpleInterval, AFCRHiddenState>> segmentation = jointSegmenter.findSegments(); final List<ACNVModeledSegment> segments = segmentation.stream().map(pair -> new ACNVModeledSegment(pair.getLeft(), errorlessPosterior(pair.getRight().getLog2CopyRatio()), errorlessPosterior(pair.getRight().getMinorAlleleFraction()))) .collect(Collectors.toList()); SegmentUtils.writeACNVModeledSegmentFile(outputSegmentsFile, segments, new Genome(rcc, acc.getCounts())); return "SUCCESS"; }
Source:
private void parse() throws IOException { stream.mark(0); try { final byte[] curIdentifier = new byte[IDENTIFIER_LENGTH]; for (int i = 0; i < curIdentifier.length; i++) { curIdentifier[i] = parseByte(); } final String identifier = new String(curIdentifier); setIdentifier(identifier); if (!identifier.equals(GTC_IDENTIFIER)) { throw new PicardException("Invalid identifier '" + identifier + "' for GTC file"); } setFileVersion(parseByte()); setNumberOfEntries(parseInt()); for (InfiniumFileTOC toc : getTableOfContents()) { stream.reset(); readData(stream, toc); } if (numCalls == 0) { numCalls = aaCalls + abCalls + bbCalls; } } finally { stream.close(); } if (allNormalizationIds != null) { normalizeIntensities(); } }

Target:
private void parse() throws IOException { stream.mark(0); try { final byte[] curIdentifier = new byte[IDENTIFIER_LENGTH]; for (int i = 0; i < curIdentifier.length; i++) { curIdentifier[i] = parseByte(); } final String identifier = new String(curIdentifier); setIdentifier(identifier); if (!identifier.equals(GTC_IDENTIFIER)) { throw new PicardException("Invalid identifier '" + identifier + "' for GTC file"); } setFileVersion(parseByte()); setNumberOfEntries(parseInt()); for (InfiniumFileTOC toc : getTableOfContents()) { stream.reset(); readData(stream, toc); } if (numCalls == 0) { numCalls = aaCalls + abCalls + bbCalls; } } finally { stream.close(); } normalizeIntensities(); }
Source:
protected void updateOSValue(final Integer selectedOsId) { Cluster cluster = getModel().getSelectedCluster(); if (cluster != null) { List<Integer> vmOsValues = AsyncDataProvider.getInstance().getOsIds(cluster.getArchitecture()); if (selectedOsId == null || !vmOsValues.contains(selectedOsId)) { updateOSValues(); return; } getModel().getOSType().setSelectedItem(selectedOsId); } }

Target:
protected void updateOSValue(final Integer selectedOsId) { Cluster cluster = getModel().getSelectedCluster(); if (cluster == null) { return; } List<Integer> vmOsValues = AsyncDataProvider.getInstance().getOsIds(cluster.getArchitecture()); if (selectedOsId == null || !vmOsValues.contains(selectedOsId)) { updateOSValues(); return; } getModel().getOSType().setSelectedItem(selectedOsId); }
Source:
public boolean isClosed() { return m_closed == true; }

Target:
public boolean isClosed() { return m_closed; }
Source:
private static void appendAllGroups(Matcher matcher, int findIndex, StringBuilder capture) { for (int i = 1; i <= matcher.groupCount(); i++) { capture.append("") .append(findIndex) .append(".") .append(i) .append(" ") .append(buildGroup(matcher.start(i), matcher.end(i))) .append("\t") .append(matcher.group(i)) .append("\n"); } }

Target:
private static void appendAllGroups(Matcher matcher, int findIndex, StringBuilder capture) { for (int i = 1; i <= matcher.groupCount(); i++) { capture.append("").append(findIndex).append(".").append(i).append(" "); buildGroup(capture, matcher, i); } }
Source:
public static void sortDetailedCoursesByCreationDate(List<CourseDetailsBundle> courses) { courses.sort(Comparator.comparing((CourseDetailsBundle obj) -> obj.course.createdAt)); }

Target:
public static void sortDetailedCoursesByCreationDate(List<CourseDetailsBundle> courses) { courses.sort(Comparator.comparing((CourseDetailsBundle obj) -> obj.course.createdAt).reversed()); }
Source:
public void execute(JobExecutionContext arg0) throws JobExecutionException { LOGGER.info("*****Chart Data Generator is startin now.*****"); SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); List<CertifiedProductFlatSearchResult> certifiedProducts = certifiedProductSearchDAO.getAllCertifiedProducts(); LOGGER.info("Certified Product Count: " + certifiedProducts.size()); analyzeSed(certifiedProducts); analyzeProducts(certifiedProducts); analyzeDevelopers(certifiedProducts); analyzeListingCounts(certifiedProducts); analyzeNonconformity(); LOGGER.info("*****Chart Data Generator is done running.*****"); }

Target:
public void execute(JobExecutionContext arg0) throws JobExecutionException { LOGGER.info("*****Chart Data Generator is starting now.*****"); SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); List<CertifiedProductFlatSearchResult> certifiedProducts = certifiedProductSearchDAO.getAllCertifiedProducts(); LOGGER.info("Certified Product Count: " + certifiedProducts.size()); analyzeSed(certifiedProducts); analyzeProducts(certifiedProducts); analyzeDevelopers(certifiedProducts); analyzeListingCounts(certifiedProducts); analyzeNonconformity(); LOGGER.info("*****Chart Data Generator is done running.*****"); }
Source:
private static void createStream(String streamName, int shardCount, AmazonKinesisClient kinesisClient) { CreateStreamRequest createStreamRequest = new CreateStreamRequest(); createStreamRequest.setStreamName(streamName); createStreamRequest.setShardCount(shardCount); kinesisClient.createStream(createStreamRequest); LOG.info("Stream " + streamName + " created"); }

Target:
private static void createStream(String streamName, int shardCount, AmazonKinesisClient kinesisClient) { CreateStreamRequest createStreamRequest = new CreateStreamRequest(); createStreamRequest.setStreamName(streamName); createStreamRequest.setShardCount(shardCount); kinesisClient.createStream(createStreamRequest); LOG.info("Stream is being created", streamName); }
Source:
protected void publishHelp() { printHelpHeader(); out("Usage: dockstore " + getEntryType().toLowerCase() + " publish --help"); out(" dockstore " + getEntryType().toLowerCase() + " publish"); out(" dockstore " + getEntryType().toLowerCase() + " publish [parameters]"); out(" dockstore " + getEntryType().toLowerCase() + " publish --unpub [parameters]"); out(""); out("Description:"); out(" Publish/unpublish a registered " + getEntryType() + "."); out(" No arguments will list the current and potential " + getEntryType() + "s to share."); out("Required Parameter(s):"); out(" --entry <entry> Complete " + getEntryType() + " path in the Dockstore (ex. quay.io/collaboratory/seqware-bwa-workflow)"); out("Optional Parameter(s):"); out(" --entryname <New" + getEntryType() + "name> " + "New name to give the tool specified by --entry. " + "This will register and publish a new 'copy' of the tool with the given name."); printHelpFooter(); }

Target:
protected void publishHelp() { printHelpHeader(); out("Usage: dockstore " + getEntryType().toLowerCase() + " publish --help"); out(" dockstore " + getEntryType().toLowerCase() + " publish"); out(" dockstore " + getEntryType().toLowerCase() + " publish [parameters]"); out(" dockstore " + getEntryType().toLowerCase() + " publish --unpub [parameters]"); out(""); out("Description:"); out(" Publish/unpublish a registered " + getEntryType() + "."); out(" No arguments will list the current and potential " + getEntryType() + "s to share."); out("Required Parameter(s):"); out(" --entry <entry> Complete " + getEntryType() + " path in the Dockstore (ex. quay.io/collaboratory/seqware-bwa-workflow)"); out("Optional Parameter(s):"); out(" --entryname <New" + getEntryType() + "name> " + "New name to give the tool specified by --entry. " + "This will register and publish a new copy of the tool with the given name."); printHelpFooter(); }
Source:
public void testSimpleTransactionInAnotherThreadContinued() throws IgniteCheckedException { withAllIsolationsAndConcurrencies(new IgniteClosure<Object, Void>() { @Override public Void apply(Object o) { try { simpleTransactionInAnotherThreadContinued(); } catch (Exception ignore) { assert false : "Impossible situation"; } return null; } }); }

Target:
public void testSimpleTransactionInAnotherThreadContinued() throws Exception { runWithAllIsolations(new IgniteCallable<Void>() { @Override public Void call() throws Exception { simpleTransactionInAnotherThreadContinued(); return null; } }); }
Source:
public static void showMessage(Activity activity, int resId, int duration) { showMessage(findBestView(activity), activity.getString(resId), duration); }

Target:
public static void showMessage(Activity activity, int resId, int duration) { showMessage(activity, activity.getString(resId), duration); }
Source:
public FrenchSouthWestProvider(final String authorization) { super(NetworkId.ALPC, authorization); setTimeZone("Europe/Paris"); }

Target:
public FrenchSouthWestProvider(final String authorization) { super(NetworkId.FRENCHSOUTHWEST, authorization); setTimeZone("Europe/Paris"); }
Source:
protected List<String> getCodeFields() { ParameterizedType p = (ParameterizedType) this.getClass().getGenericSuperclass(); System.out.println(p.getActualTypeArguments()[0]); return getProperties(); }

Target:
protected List<String> getCodeFields() { return getProperties(); }
Source:
protected void ExecuteIrsBrokerCommand() { P params = getParameters(); String spUUIDstr = params.getStoragePoolId().toString(); String targetVersion = params.getCompatibilityVersion(); log.info("-- UpgradeStoragePoolVDSCommand::ExecuteIrsBrokerCommand: calling 'upgradeStoragePool' with two new parameters: poolVersion and UUID"); log.infoFormat("-- upgradeStoragePool parameters:\r\n" + "spUUID={0}\r\n" + "version={1}\r\n", spUUIDstr, targetVersion); status = getIrsProxy().upgradeStoragePool(spUUIDstr, targetVersion); ProceedProxyReturnValue(); }

Target:
protected void ExecuteIrsBrokerCommand() { final P params = getParameters(); final String storagePoolId = params.getStoragePoolId().toString(); final String targetVersion = params.getCompatibilityVersion(); log.info("Upgrading storage pool \"" + storagePoolId + "\" to version \"" + targetVersion + "\""); status = getIrsProxy().upgradeStoragePool(storagePoolId, targetVersion); ProceedProxyReturnValue(); }
Source:
private void parseCommentGeneric(String comment) { if (comment == null) return; String[] lines = comment.split("\n"); if (lines.length > 1) { StringBuilder buf = new StringBuilder(comment.length()); for (String line : lines) { int eq = line.indexOf('='); if (eq != -1) { String key = line.substring(0, eq).trim(); String value = line.substring(eq + 1).trim(); addGlobalMeta(key, value); } else if (!line.startsWith("[")) { buf.append(line); buf.append("\n"); } } description = buf.toString(); addGlobalMeta("Comment", description); } }

Target:
private void parseCommentGeneric(String comment) { if (comment == null) return; String[] lines = comment.split("\n"); if (lines.length > 1) { StringBuilder buf = new StringBuilder(comment.length()); for (String line : lines) { int eq = line.indexOf('='); if (eq != -1) { String key = line.substring(0, eq).trim(); String value = line.substring(eq + 1).trim(); addGlobalMeta(key, value); } else if (!line.startsWith("[")) { buf.append(line); buf.append('\n'); } } description = buf.toString(); addGlobalMeta("Comment", description); } }
Source:
public void testEvtOpenPublisherEnum() throws Exception { Winevt.EVT_RPC_LOGIN login = new Winevt.EVT_RPC_LOGIN("localhost", null, null, null, Winevt.EVT_RPC_LOGIN_FLAGS.EvtRpcLoginAuthDefault); EVT_HANDLE session = null; EVT_HANDLE publisherEnumHandle = null; List<String> publisherList = new ArrayList<String>(); try { session = Wevtapi.INSTANCE.EvtOpenSession(Winevt.EVT_LOGIN_CLASS.EvtRpcLogin, login, 0, 0); if (session == null) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } publisherEnumHandle = Wevtapi.INSTANCE.EvtOpenPublisherEnum(session, 0); if (publisherEnumHandle == null) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } Memory buff; while (true) { try { buff = WevtapiUtil.EvtNextPublisherId(publisherEnumHandle); } catch (Win32Exception e) { if (e.getErrorCode() == WinError.ERROR_NO_MORE_ITEMS) { break; } else { throw e; } } publisherList.add(buff.getWideString(0)); } assertThat(publisherList.size() > 0, is(true)); } finally { if (publisherEnumHandle != null) { Wevtapi.INSTANCE.EvtClose(publisherEnumHandle); } if (session != null) { Wevtapi.INSTANCE.EvtClose(session); } } }

Target:
public void testEvtOpenPublisherEnum() throws Exception { Winevt.EVT_RPC_LOGIN login = new Winevt.EVT_RPC_LOGIN("localhost", null, null, null, Winevt.EVT_RPC_LOGIN_FLAGS.EvtRpcLoginAuthDefault); EVT_HANDLE session = null; EVT_HANDLE publisherEnumHandle = null; List<String> publisherList = new ArrayList<String>(); try { session = Wevtapi.INSTANCE.EvtOpenSession(Winevt.EVT_LOGIN_CLASS.EvtRpcLogin, login, 0, 0); if (session == null) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } publisherEnumHandle = Wevtapi.INSTANCE.EvtOpenPublisherEnum(session, 0); if (publisherEnumHandle == null) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } String providerName; while (true) { try { providerName = WevtapiUtil.EvtNextPublisherId(publisherEnumHandle); } catch (Win32Exception e) { if (e.getErrorCode() == WinError.ERROR_NO_MORE_ITEMS) { break; } else { throw e; } } publisherList.add(providerName); } assertThat(publisherList.size() > 0, is(true)); } finally { if (publisherEnumHandle != null) { Wevtapi.INSTANCE.EvtClose(publisherEnumHandle); } if (session != null) { Wevtapi.INSTANCE.EvtClose(session); } } }
Source:
private static Map<String, String> getMergedEnvironment(LaunchConfiguration configuration) throws IOException { Map<String, String> currentEnv = new HashMap<String, String>(EnvironmentUtils.getProcEnvironment()); currentEnv.putAll(configuration.getEnvironment()); return currentEnv; }

Target:
private static Map<String, String> getMergedEnvironment(LaunchConfiguration configuration) throws IOException { Map<String, String> currentEnv = EnvironmentUtils.getProcEnvironment(); currentEnv.putAll(configuration.getEnvironment()); return currentEnv; }
Source:
void upgradeTo(ChannelHandlerContext ctx, FullHttpResponse upgradeResponse) throws Exception; } private final SourceCodec sourceCodec; private final UpgradeCodec upgradeCodec; private boolean upgradeRequested; public HttpClientUpgradeHandler(SourceCodec sourceCodec, UpgradeCodec upgradeCodec, int maxContentLength) { super(maxContentLength); ObjectUtil.checkNotNull(sourceCodec, "sourceCodec"); ObjectUtil.checkNotNull(upgradeCodec, "upgradeCodec"); this.sourceCodec = sourceCodec; this.upgradeCodec = upgradeCodec; }

Target:
void upgradeTo(ChannelHandlerContext ctx, FullHttpResponse upgradeResponse) throws Exception; } private final SourceCodec sourceCodec; private final UpgradeCodec upgradeCodec; private boolean upgradeRequested; public HttpClientUpgradeHandler(SourceCodec sourceCodec, UpgradeCodec upgradeCodec, int maxContentLength) { super(maxContentLength); this.sourceCodec = ObjectUtil.checkNotNull(sourceCodec, "sourceCodec"); this.upgradeCodec = ObjectUtil.checkNotNull(upgradeCodec, "upgradeCodec"); }
Source:
public TreacherousUrge(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{4}{B}"); this.subtype.add(SubType.ARCANE); this.getSpellAbility().addEffect(new TreacherousUrgeEffect()); this.getSpellAbility().addTarget(new TargetOpponent()); }

Target:
public TreacherousUrge(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{4}{B}"); this.getSpellAbility().addEffect(new TreacherousUrgeEffect()); this.getSpellAbility().addTarget(new TargetOpponent()); }
Source:
public HeapKeyedStateBackend<K> build() throws BackendBuildingException { Map<String, StateTable<K, ?, ?>> registeredKVStates = new HashMap<>(); Map<String, HeapPriorityQueueSnapshotRestoreWrapper> registeredPQStates = new HashMap<>(); CloseableRegistry cancelStreamRegistryForBackend = new CloseableRegistry(); HeapSnapshotStrategy<K> snapshotStrategy = initSnapshotStrategy( asynchronousSnapshots, registeredKVStates, registeredPQStates, cancelStreamRegistryForBackend); InternalKeyContext<K> keyContext = new InternalKeyContextImpl<>( keyGroupRange, numberOfKeyGroups ); HeapRestoreOperation<K> restoreOperation = new HeapRestoreOperation<>( restoreStateHandles, keySerializerProvider, userCodeClassLoader, registeredKVStates, registeredPQStates, cancelStreamRegistry, priorityQueueSetFactory, keyGroupRange, numberOfKeyGroups, snapshotStrategy, keyContext); try { restoreOperation.restore(); logger.info("Finish to build heap keyed state-backend."); } catch (Exception e) { throw new BackendBuildingException("Failed when trying to restore heap backend", e); } return new HeapKeyedStateBackend<>( kvStateRegistry, keySerializerProvider.currentSchemaSerializer(), userCodeClassLoader, executionConfig, ttlTimeProvider, cancelStreamRegistryForBackend, keyGroupCompressionDecorator, registeredKVStates, registeredPQStates, localRecoveryConfig, priorityQueueSetFactory, snapshotStrategy, keyContext); }

Target:
public HeapKeyedStateBackend<K> build() throws BackendBuildingException { Map<String, StateTable<K, ?, ?>> registeredKVStates = new HashMap<>(); Map<String, HeapPriorityQueueSnapshotRestoreWrapper> registeredPQStates = new HashMap<>(); CloseableRegistry cancelStreamRegistryForBackend = new CloseableRegistry(); HeapSnapshotStrategy<K> snapshotStrategy = initSnapshotStrategy( asynchronousSnapshots, registeredKVStates, registeredPQStates, cancelStreamRegistryForBackend); InternalKeyContext<K> keyContext = new InternalKeyContextImpl<>( keyGroupRange, numberOfKeyGroups ); HeapRestoreOperation<K> restoreOperation = new HeapRestoreOperation<>( restoreStateHandles, keySerializerProvider, userCodeClassLoader, registeredKVStates, registeredPQStates, cancelStreamRegistry, priorityQueueSetFactory, keyGroupRange, numberOfKeyGroups, snapshotStrategy, keyContext); try { restoreOperation.restore(); logger.info("Finished to build heap keyed state-backend."); } catch (Exception e) { throw new BackendBuildingException("Failed when trying to restore heap backend", e); } return new HeapKeyedStateBackend<>( kvStateRegistry, keySerializerProvider.currentSchemaSerializer(), userCodeClassLoader, executionConfig, ttlTimeProvider, cancelStreamRegistryForBackend, keyGroupCompressionDecorator, registeredKVStates, registeredPQStates, localRecoveryConfig, priorityQueueSetFactory, snapshotStrategy, keyContext); }
Source:
private static void reindexPublishingSearch(Collection collection) throws IOException { info().data("collectionId", collection.getDescription().getId()).log("Reindexing search"); try { long start = System.currentTimeMillis(); List<String> uris = collection.reviewed.uris("*data.json"); for (String uri : uris) { if (isIndexedUri(uri)) { String contentUri = URIUtils.removeLastSegment(uri); reIndexPublishingSearch(contentUri); } } for (PendingDelete pendingDelete : collection.description.getPendingDeletes()) { ContentTreeNavigator.getInstance().search(pendingDelete.getRoot(), node -> { info().data("uri", node.uri).log("Deleting index from publishing search "); pool.submit(() -> { try { Indexer.getInstance().deleteContentIndex(node.type, node.uri); } catch (Exception e) { error().logException(e, "Exception reloading search index:"); } }); }); } info().data("collectionId", collection.getDescription().getId()) .data("timeTaken", (System.currentTimeMillis() - start)) .log("Redindex search completed"); } catch (Exception exception) { error().data("collectionId", collection.getDescription().getId()) .logException(exception, "An error occurred during the search reindex"); ExceptionUtils.printRootCauseStackTrace(exception); } }

Target:
private static void reindexPublishingSearch(Collection collection) throws IOException { info().data("collectionId", collection.getDescription().getId()).log("Reindexing search"); try { long start = System.currentTimeMillis(); List<String> uris = collection.reviewed.uris("*data.json"); for (String uri : uris) { if (isIndexedUri(uri)) { String contentUri = URIUtils.removeLastSegment(uri); reIndexPublishingSearch(contentUri); } } for (PendingDelete pendingDelete : collection.description.getPendingDeletes()) { ContentTreeNavigator.getInstance().search(pendingDelete.getRoot(), node -> { info().data("uri", node.uri).log("Deleting index from publishing search "); pool.submit(() -> { try { Indexer.getInstance().deleteContentIndex(node.type, node.uri); } catch (Exception e) { error().logException(e, "Exception reloading search index:"); } }); }); } info().data("collectionId", collection.getDescription().getId()) .data("timeTaken", (System.currentTimeMillis() - start)) .log("Redindex search completed"); } catch (Exception exception) { error().data("collectionId", collection.getDescription().getId()) .logException(exception, "An error occurred during the search reindex"); } }
Source:
public void processEvent(final CloudTrailEvent event) { List<String> keyNames = CloudtrailEventSupport.containsKeyNames(event.getEventData().getRequestParameters()); if (!CollectionUtils.isEmpty(keyNames)) { violationStore.save(new ViolationStoreDomain(event.getEventData().getAccountId(), event.getEventData().getAwsRegion(), format("KeyPair must be blank, but was %s", keyNames))); } }

Target:
public void processEvent(final CloudTrailEvent event) { List<String> keyNames = containsKeyNames(event.getEventData().getRequestParameters()); if (!CollectionUtils.isEmpty(keyNames)) { violationStore.save(new Violation(getAccountId(event), getRegionAsString(event), format("KeyPair must be blank, but was %s", keyNames))); } }
Source:
public void start(StartContext context) { LOG.info("Querying service is starting."); executor = Executors.newSingleThreadScheduledExecutor(); executor.scheduleAtFixedRate(() -> { Supplier<Node> node = new ActiveServiceSupplier<>(context.getController().getServiceContainer(), SingletonServiceActivator.SINGLETON_SERVICE_NAME); if (node.get() != null) { LOG.infof("Singleton service is running on this (%s) node.", node.get()); } else { LOG.infof("Singleton service is not running on this node."); } }, 5, 5, TimeUnit.SECONDS); }

Target:
public void start(StartContext context) { LOG.info("Querying service is starting."); executor = Executors.newSingleThreadScheduledExecutor(); executor.scheduleAtFixedRate(() -> { Supplier<Node> node = new PassiveServiceSupplier<>(context.getController().getServiceContainer(), SingletonServiceActivator.SINGLETON_SERVICE_NAME); if (node.get() != null) { LOG.infof("Singleton service is running on this (%s) node.", node.get()); } else { LOG.infof("Singleton service is not running on this node."); } }, 5, 5, TimeUnit.SECONDS); }
Source:
private static int queryFlagValue(boolean resolveGroups, boolean resolveGroupsRecursive) { int result = 0; if (resolveGroups) { result |= Authz.QueryFlags.RESOLVE_GROUPS; } if (resolveGroupsRecursive) { result |= Authz.QueryFlags.RESOLVE_GROUPS_RECURSIVE; } return result; }

Target:
private static int queryFlagValue(boolean resolveGroups, boolean resolveGroupsRecursive) { int result = 0; if (resolveGroups) { result |= Authz.QueryFlags.RESOLVE_GROUPS; } if (resolveGroupsRecursive) { result |= Authz.QueryFlags.RESOLVE_GROUPS_RECURSIVE | Authz.QueryFlags.RESOLVE_GROUPS; } return result; }
Source:
public void generatePage_OnBiDimentionalArray_generatesOutput() { setUpWithJson(SAMPLE_JSON); final Feature feature = features.get(1); page = new FeatureReportPage(reportResult, configuration, feature); page.generatePage(); DocumentAssertion document = documentFrom(page.getWebPage()); Output[] outputElements = features.get(1).getElements()[0].getSteps()[7].getOutput(); ArrayList<String> messages = new ArrayList<>(); for (Output outputElement : outputElements) { messages.addAll(Arrays.asList(outputElement.getMessages())); } OutputAssertion output = document.getFeature().getElements()[0].getStepsSection().getSteps()[7].getOutput(); output.hasMessages(messages.toArray(new String[messages.size()])); }

Target:
public void generatePage_OnBiDimentionalArray_generatesOutput() { setUpWithJson(SAMPLE_JSON); final Feature feature = features.get(1); page = new FeatureReportPage(reportResult, configuration, feature); page.generatePage(); DocumentAssertion document = documentFrom(page.getWebPage()); Output[] outputElements = features.get(1).getElements()[0].getSteps()[7].getOutput(); OutputAssertion output = document.getFeature().getElements()[0].getStepsSection().getSteps()[7].getOutput(); output.hasMessages(getMessages(outputElements)); }
Source:
public static QueryableTable getTable(String name) { return new AbstractQueryableTable(Object[].class) { @Override public RelDataType getRowType(RelDataTypeFactory typeFactory) { return typeFactory.builder() .add("TYPE", SqlTypeName.VARCHAR) .add("CODEVALUE", SqlTypeName.VARCHAR) .build(); } @Override public Queryable<String[]> asQueryable(QueryProvider queryProvider, SchemaPlus schema, String tableName) { if (name == null) { return Linq4j.asEnumerable(new String[][]{}).asQueryable(); } return Linq4j.asEnumerable(new String[][]{ new String[]{"HASHCODE", "" + name.hashCode()}, new String[]{"BASE64", Base64.encodeBase64String(name.getBytes(Charset.defaultCharset()))} }).asQueryable(); } }; }

Target:
public static QueryableTable getTable(String name) { return new AbstractQueryableTable(Object[].class) { @Override public RelDataType getRowType(RelDataTypeFactory typeFactory) { return typeFactory.builder() .add("TYPE", SqlTypeName.VARCHAR) .add("CODEVALUE", SqlTypeName.VARCHAR) .build(); } @Override public Queryable<String[]> asQueryable(QueryProvider queryProvider, SchemaPlus schema, String tableName) { if (name == null) { return Linq4j.<String[]>emptyEnumerable().asQueryable(); } return Linq4j.asEnumerable(new String[][]{ new String[]{"HASHCODE", "" + name.hashCode()}, new String[]{"BASE64", Base64.getEncoder().encodeToString(name.getBytes(StandardCharsets.UTF_8))} }).asQueryable(); } }; }
Source:
private boolean occurrenceHasBeenInReviewForMoreThanAWeek(DiseaseOccurrence occ, DateTime modelRunPrepDateTime) { LocalDate createdDate = occ.getCreatedDate().toLocalDate(); LocalDate comparisonDate = createdDate.plusWeeks(1); LocalDate modelRunPrepDate = modelRunPrepDateTime.toLocalDate(); return (comparisonDate.isEqual(modelRunPrepDate) || comparisonDate.isBefore(modelRunPrepDate)); }

Target:
private boolean occurrenceHasBeenInReviewForMoreThanAWeek(DiseaseOccurrence occ, DateTime modelRunPrepDateTime) { LocalDate createdDate = occ.getCreatedDate().toLocalDate(); LocalDate comparisonDate = createdDate.plusWeeks(1); LocalDate modelRunPrepDate = modelRunPrepDateTime.toLocalDate(); return !comparisonDate.isAfter(modelRunPrepDate); }
Source:
public void initialize() { try { logger.debug("Initializing NTP handler for '{}'.", getThing().getUID().toString()); Configuration config = getThing().getConfiguration(); hostname = (String) config.get(PROPERTY_NTP_SERVER); refreshInterval = (BigDecimal) config.get(PROPERTY_REFRESH_INTERVAL); refreshNtp = (BigDecimal) config.get(PROPERTY_REFRESH_NTP); refreshNtpCount = 0; try { timeZone = TimeZone.getTimeZone((String) config.get(PROPERTY_TIMEZONE)); } catch (Exception e) { timeZone = TimeZone.getDefault(); logger.debug("{} using default TZ: {}", getThing().getUID().toString(), timeZone); } try { String localeString = (String) config.get(PROPERTY_LOCALE); locale = new Locale(localeString); } catch (Exception e) { locale = Locale.getDefault(); logger.debug("{} using default locale: {}", getThing().getUID().toString(), locale); } dateTimeChannelUID = new ChannelUID(getThing().getUID(), CHANNEL_DATE_TIME); updateStatus(ThingStatus.OFFLINE); logger.debug( "Initialized NTP handler '{}' with configuration: host '{}', refresh interval {}, timezone {}, locale {}.", getThing().getUID().toString(), hostname, refreshInterval, timeZone, locale); startAutomaticRefresh(); } catch (Exception ex) { String msg = "Error occured while initializing NTP handler: " + ex.getMessage(); logger.error(msg, ex); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, msg); } }

Target:
public void initialize() { try { logger.debug("Initializing NTP handler for '{}'.", getThing().getUID().toString()); Configuration config = getThing().getConfiguration(); hostname = (String) config.get(PROPERTY_NTP_SERVER); refreshInterval = (BigDecimal) config.get(PROPERTY_REFRESH_INTERVAL); refreshNtp = (BigDecimal) config.get(PROPERTY_REFRESH_NTP); refreshNtpCount = 0; try { timeZone = TimeZone.getTimeZone((String) config.get(PROPERTY_TIMEZONE)); } catch (Exception e) { timeZone = TimeZone.getDefault(); logger.debug("{} using default TZ: {}", getThing().getUID().toString(), timeZone); } try { String localeString = (String) config.get(PROPERTY_LOCALE); locale = new Locale(localeString); } catch (Exception e) { locale = Locale.getDefault(); logger.debug("{} using default locale: {}", getThing().getUID().toString(), locale); } dateTimeChannelUID = new ChannelUID(getThing().getUID(), CHANNEL_DATE_TIME); logger.debug( "Initialized NTP handler '{}' with configuration: host '{}', refresh interval {}, timezone {}, locale {}.", getThing().getUID().toString(), hostname, refreshInterval, timeZone, locale); startAutomaticRefresh(); } catch (Exception ex) { String msg = "Error occured while initializing NTP handler: " + ex.getMessage(); logger.error(msg, ex); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, msg); } }
Source:
public void testUpdateOfNestedRepeatedAttributeName() { coll2 = getCollection(NestedRepeatedAttributeName.class, String.class); Calendar cal = Calendar.getInstance(); cal.set(0, 0, 0, 0, 0, 10); Date d_1 = cal.getTime(); cal.set(0, 0, 0, 0, 0, 20); Date d_2 = cal.getTime(); NestedRepeatedAttributeName nested = new NestedRepeatedAttributeName(); nested.inner.timestamp = d_1; nested.timestamp = 30000; coll2.insert(nested); coll2.updateById(nested._id, DBUpdate.set("inner.timestamp", d_2)); NestedRepeatedAttributeName updated = coll2.findOneById(nested._id); assertThat(updated, notNullValue()); assertThat(updated.inner.timestamp, equalTo(d_2)); assertThat(updated.timestamp, equalTo(nested.timestamp)); }

Target:
public void testUpdateOfNestedRepeatedAttributeName() { coll2 = getCollection(NestedRepeatedAttributeName.class, String.class); Date d1 = new Date(10000L); Date d2 = new Date(20000L); NestedRepeatedAttributeName original = new NestedRepeatedAttributeName(); original.inner.timestamp = d1; original.timestamp = 30000; coll2.insert(original); coll2.updateById(original._id, DBUpdate.set("inner.timestamp", d2)); NestedRepeatedAttributeName updated = coll2.findOneById(original._id); assertThat(updated, notNullValue()); assertThat(updated.inner.timestamp, equalTo(d2)); assertThat(updated.timestamp, equalTo(original.timestamp)); }
Source:
public GetRecordsCache createRecordsFetcher(GetRecordsRetrievalStrategy getRecordsRetrievalStrategy, String shardId) { if(dataFetchingStrategy.equals(DataFetchingStrategy.DEFAULT)) { return new BlockingGetRecordsCache(maxRecords, getRecordsRetrievalStrategy, idleMillisBetweenCalls); } else { return new PrefetchGetRecordsCache(maxSize, maxByteSize, maxRecordsCount, maxRecords, getRecordsRetrievalStrategy, Executors.newFixedThreadPool(1, new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat("prefetch-get-records-cache-" + shardId + "-%d") .build()), idleMillisBetweenCalls); } }

Target:
public GetRecordsCache createRecordsFetcher(GetRecordsRetrievalStrategy getRecordsRetrievalStrategy, String shardId) { if(dataFetchingStrategy.equals(DataFetchingStrategy.DEFAULT)) { return new BlockingGetRecordsCache(maxRecords, getRecordsRetrievalStrategy, idleMillisBetweenCalls); } else { return new PrefetchGetRecordsCache(maxPendingProcessRecordsInput, maxByteSize, maxRecordsCount, maxRecords, getRecordsRetrievalStrategy, Executors.newFixedThreadPool(1, new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat("prefetch-cache-" + shardId + "-%04d") .build()), idleMillisBetweenCalls); } }
Source:
protected void doNotify(ClientApplicationEvent event) throws Exception { restTemplate.postForEntity(buildUrl(event), createEvent(event), Void.class); }

Target:
protected void doNotify(ClientApplicationEvent event) throws Exception { restTemplate.exchange(buildUrl(event), HttpMethod.POST, createEvent(event), Void.class); }
Source:
protected int getOverProvisioningFactor() { return Integer.valueOf(Framework.getProperty(WORKMANAGER_OVERPROVISIONING_PROP, DEFAULT_WORKMANAGER_OVERPROVISIONING)); }

Target:
protected int getOverProvisioningFactor() { return Integer.parseInt( Framework.getProperty(WORKMANAGER_OVERPROVISIONING_PROP, DEFAULT_WORKMANAGER_OVERPROVISIONING)); }
Source:
public void scenario1() throws Exception { logger.info("Running scenario1"); final String objA = getRandomPid(); final HttpPut method = new HttpPut(serverAddress + "/" + objA); final FileEntity acl = new FileEntity(new File(classLoader.getResource("acls/01/acl.ttl").getFile())); setAuth(method, "fedoraAdmin"); method.setHeader("Content-type", "text/turtle"); method.setEntity(acl); final HttpResponse response = client.execute(method); final String content = EntityUtils.toString(response.getEntity()); final int status = response.getStatusLine().getStatusCode(); assertEquals("Didn't get a CREATED response! Got content:\n" + content, CREATED.getStatusCode(), status); }

Target:
public void scenario1() throws Exception { logger.info("Running scenario1"); final String objA = getRandomPid(); final HttpPut method = super.putObjMethod("rest/" + objA); final FileEntity acl = new FileEntity(new File(classLoader.getResource("acls/01/acl.ttl").getFile())); setAuth(method, "fedoraAdmin"); method.setHeader("Content-type", "text/turtle"); method.setEntity(acl); try (final CloseableHttpResponse response = super.execute(method)) { assertEquals(CREATED.getStatusCode(), super.getStatus(response)); } }
Source:
public Builder cronSchedule(String cron) { this.type = ScalingPolicyType.SCHEDULE; this.args = Maps.newHashMap(); args.put("cron", cron); return this; }

Target:
public Builder cronSchedule(String cron) { this.type = ScalingPolicyType.SCHEDULE; this.args = ImmutableMap.of("cron", cron); return this; }
Source:
private int determineCurGroupSize(int remaining) { int modified = totalModInstanceCount.get() - remaining; int lastGroupSize = maxActiveGroups.get(maxActiveGroups.size() - 1); LOG.debug("Variable Batch Update progress: instances have been modified, " + "{} instances remain unmodified, and overall instances to be modified.", modified, remaining, totalModInstanceCount.get()); if (rollingForward) { int sum = 0; for (Integer groupSize : maxActiveGroups) { sum += groupSize; if (sum > modified) { return groupSize; } } return lastGroupSize; } else { int curGroupSize = remaining; for (Integer groupSize : maxActiveGroups) { if (curGroupSize <= groupSize) { return curGroupSize; } curGroupSize -= groupSize; } curGroupSize = curGroupSize % lastGroupSize; if (curGroupSize == 0) { return lastGroupSize; } else { return curGroupSize; } } }

Target:
private int determineCurGroupSize(int remaining) { int modified = totalModInstanceCount.get() - remaining; int finalGroupSize = Iterables.getLast(groupSizes); LOG.debug("Variable Batch Update progress: instances have been modified, " + "{} instances remain unmodified, and overall instances to be modified.", modified, remaining, totalModInstanceCount.get()); if (rollingForward) { int sum = 0; for (Integer groupSize : groupSizes) { sum += groupSize; if (sum > modified) { return groupSize; } } return finalGroupSize; } else { int curGroupSize = remaining; for (Integer groupSize : groupSizes) { if (curGroupSize <= groupSize) { return curGroupSize; } curGroupSize -= groupSize; } curGroupSize = curGroupSize % finalGroupSize; if (curGroupSize == 0) { return finalGroupSize; } else { return curGroupSize; } } }
Source:
private String getShortBranchName(Ref headRef) { Ref target = headRef.getTarget(); if (target.getName().equals(headRef.getName())) { ObjectId objectId = target.getObjectId(); if (objectId != null) { return objectId.getName(); } } return Repository.shortenRefName(target.getName()); }

Target:
private String getShortBranchName(Ref headRef) { if (headRef.isSymbolic()) { return Repository.shortenRefName(headRef.getTarget().getName()); } ObjectId id = headRef.getObjectId(); assert (id != null); return id.getName(); }
Source:
private <P, R> JsonElement response(String endpointId, RequestHandler<P, R> handler, JsonObject params, Class<P> paramClass, Class<R> resultClass) { R result; if(paramClass != null) { final P param = DtoFactory.getInstance().createDtoFromJson(params.toString(), paramClass); result = handler.handleRequest(endpointId, param); } else { result = handler.handleRequest(endpointId); } LOG.debug("Dispatch response: " + result); if(result instanceof Void) return new JsonObject(); else if(result instanceof String) { JsonObject response = new JsonObject(); response.addProperty("text", (String)result); return response; } else if(result instanceof Collection) { JsonArray valueArray = new JsonArray(); ((Collection)result).stream().filter(r -> r instanceof JsonSerializable).forEach(r -> { String resultString = DtoFactory.getInstance().toJson(r); valueArray.add(new JsonParser().parse(resultString).getAsJsonObject()); }); return valueArray; } final String resultString = DtoFactory.getInstance().toJson(result); return new JsonParser().parse(resultString).getAsJsonObject(); }

Target:
private <P, R> JsonElement response(String endpointId, RequestHandler<P, R> handler, JsonObject params, Class<P> paramClass, Class<R> resultClass) { final R result; if (paramClass != null) { final P param = DtoFactory.getInstance().createDtoFromJson(params.toString(), paramClass); result = handler.handleRequest(endpointId, param); } else { result = handler.handleRequest(endpointId); } LOG.debug("Dispatch response: ", result); if (result instanceof Void) return new JsonObject(); else if (result instanceof String) { JsonObject response = new JsonObject(); response.addProperty("text", (String)result); return response; } else if (result instanceof Collection) { JsonArray valueArray = new JsonArray(); ((Collection)result).stream().filter(r -> r instanceof JsonSerializable).forEach(r -> { String resultString = DtoFactory.getInstance().toJson(r); valueArray.add(new JsonParser().parse(resultString).getAsJsonObject()); }); return valueArray; } final String resultString = DtoFactory.getInstance().toJson(result); return new JsonParser().parse(resultString).getAsJsonObject(); }
Source:
public HandlerRegistration addValueChangeHandler(final ValueChangeHandler<T> handler) { this.handler = handler; return asSuggestBox().addValueChangeHandler(new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> event) { handler.onValueChange(new ValueChangeEvent<T>(getValue()) { }); } }); }

Target:
public HandlerRegistration addValueChangeHandler(final ValueChangeHandler<T> handler) { return asSuggestBox().addValueChangeHandler(new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> event) { T value = wrap(event.getValue()); if (value != null) { handler.onValueChange(new ValueChangeEvent<T>(wrap(event.getValue())) { }); } } }); }
Source:
private void parseArgv(String[] argv) { boolean gui = false; for(String arg : argv) { if(arg.equals("--gui") || arg.equals("-g")) { gui = true; } else if(arg.equals("--nogui") || arg.equals("-G")) { gui = false; } } if (gui) { createGui(); } }

Target:
private void parseArgv(String[] argv) { boolean gui = false; for(String arg : argv) { if(arg.equals("--gui") || arg.equals("-g")) { gui = true; } else if(arg.equals("--nogui") || arg.equals("-G")) { gui = false; } else if(arg.startsWith("--port=") || arg.startsWith("-p=")) { port = Integer.parseInt(arg.split("=")[1]); } else if(arg.startsWith("--host") || arg.startsWith("-h=")) { host = arg.split("=")[1]; } } if (gui) { createGui(); } }
Source:
StatDetails(List<LatencyStat> latencies) { this.latencies = latencies; }

Target:
StatDetails(List<LatencyStat> latencies) { this.latencies = requireNonNull(latencies); }
Source:
public static BitSize detect() { BitSize bitSize = BitSize.B32; String osArch = System.getProperty("os.arch"); if (osArch.equals("i686_64") || osArch.equals("x86_64") || osArch.equals("amd64") || osArch.equals("ppc64le") ) bitSize = BitSize.B64; return bitSize; }

Target:
public static BitSize detect() { BitSize bitSize = BitSize.B32; String osArch = System.getProperty("os.arch"); if (osArch.equals("i686_64") || osArch.equals("x86_64") || osArch.equals("amd64") || osArch.equals("ppc64le") || osArch.equals("aarch64")) bitSize = BitSize.B64; return bitSize; }
Source:
public CustomerToken getCustomerToken() { final CustomerToken customerToken = customerTokenRef.get(); if (customerToken != null) { return new CustomerToken(customerToken); } else { return null; } }

Target:
public CustomerToken getCustomerToken() { return customerTokenRef.get(); }
Source:
EvalResult evaluate(LDUser user, FeatureStore featureStore) { if (user == null || user.getKey() == null) { return null; } Set<FeatureRequestEvent> prereqEvents = new HashSet<>(); Set<String> visited = new HashSet<>(); return evaluate(user, featureStore, prereqEvents, visited); }

Target:
EvalResult evaluate(LDUser user, FeatureStore featureStore) { if (user == null || user.getKey() == null) { return null; } List<FeatureRequestEvent> prereqEvents = new ArrayList<>(); Set<String> visited = new HashSet<>(); return evaluate(user, featureStore, prereqEvents, visited); }
Source:
public void run() { if (isSynchronizedWithZooKeeper.get() || ! zkClient.isConnected() || ! started.get()) { return; } if (checkVersion.getAndSet(false)) { try { Stat stat = zkClient.getZookeeper().exists(path, null); synchronized (lastStatusVersionMonitor) { if (stat != null && zkClient.getZookeeper().getSessionId() == stat.getEphemeralOwner()) { zkClient.getZookeeper().delete(path, lastStatusVersion); } } } catch (InterruptedException e) { LOG.info("Interruppted"); checkVersion.set(true); } catch (KeeperException e) { LOG.info("exception "+ e.getMessage()); checkVersion.set(true); } } LOG.info("We are out-of-sync, have a zookeeper connection, and are started, trying reclaim: " + path + this); tryClaim(); }

Target:
public void run() { if (isSynchronizedWithZooKeeper.get() || ! zkClient.isConnected() || ! started.get()) { return; } if (checkVersion.getAndSet(false)) { try { synchronized (lastStatusVersionMonitor) { final Stat stat = zkClient.getZookeeper().exists(path, null); if (stat != null && zkClient.getZookeeper().getSessionId() == stat.getEphemeralOwner()) { zkClient.getZookeeper().delete(path, lastStatusVersion); } } } catch (InterruptedException e) { LOG.info("Interrupted"); checkVersion.set(true); } catch (KeeperException e) { LOG.info("exception "+ e.getMessage()); checkVersion.set(true); } } LOG.info("We are out-of-sync, have a zookeeper connection, and are started, trying reclaim: " + path + this); tryClaim(); }
Source:
private static IRecipe addQuartzRecipes(int meta, Item req, Block block, Block stairs, Block slab) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(block), "QQ", "QQ", Character.valueOf('Q'), LibOreDict.QUARTZ[meta])); GameRegistry.addRecipe(new ItemStack(block, 2, 2), "Q", "Q", 'Q', block); GameRegistry.addRecipe(new ItemStack(block, 1, 1), "Q", "Q", 'Q', slab); addStairsAndSlabs(block, 0, stairs, slab); if(req != null) { if(req == Items.coal) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.quartz, 8, meta), "QQQ", "QCQ", "QQQ", 'Q', "gemQuartz", 'C', new ItemStack(req, 1, 1))); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.quartz, 8, meta), "QQQ", "QCQ", "QQQ", 'Q', "gemQuartz", 'C', req)); return BotaniaAPI.getLatestAddedRecipe(); } return null; }

Target:
private static IRecipe addQuartzRecipes(int meta, Item req, Block block, Block stairs, Block slab) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(block), "QQ", "QQ", 'Q', LibOreDict.QUARTZ[meta])); GameRegistry.addRecipe(new ItemStack(block, 2, 2), "Q", "Q", 'Q', block); GameRegistry.addRecipe(new ItemStack(block, 1, 1), "Q", "Q", 'Q', slab); addStairsAndSlabs(block, 0, stairs, slab); if(req != null) { if(req == Items.coal) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.quartz, 8, meta), "QQQ", "QCQ", "QQQ", 'Q', "gemQuartz", 'C', new ItemStack(req, 1, 1))); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.quartz, 8, meta), "QQQ", "QCQ", "QQQ", 'Q', "gemQuartz", 'C', req)); return BotaniaAPI.getLatestAddedRecipe(); } return null; }