auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Optional<Path> getCompilerOutputPath(TargetNode<? extends JvmLibraryArg, ?> targetNode) { BuildTarget buildTarget = targetNode.getBuildTarget(); Path compilerOutputPath = DefaultJavaLibrary.getClassesDir(buildTarget, projectFilesystem); return Optional.ofNullable(compilerOutputPath); }

Target:
public Optional<Path> getCompilerOutputPath(TargetNode<? extends JvmLibraryArg, ?> targetNode) { BuildTarget buildTarget = targetNode.getBuildTarget(); Path compilerOutputPath = DefaultJavaLibrary.getClassesDir(buildTarget, projectFilesystem); return Optional.of(compilerOutputPath); }
Source:
public void init(final IEditorSite site, final IEditorInput input) { AbstractReviewTaskEditorPage.super.init(site, input); IReviewRemoteFactoryProvider factoryProvider = getFactoryProvider(); if (factoryProvider != null) { checkIfModelIsCached(); reviewConsumer = factoryProvider.getReviewFactory().getConsumerForLocalKey(factoryProvider.getRoot(), getTask().getTaskId()); reviewConsumer.addObserver(reviewObserver); reviewConsumer.open(); } }

Target:
public void init(final IEditorSite site, final IEditorInput input) { AbstractReviewTaskEditorPage.super.init(site, input); checkIfModelIsCached(); reviewConsumer = getFactoryProvider().getReviewFactory().getConsumerForLocalKey(getFactoryProvider().getRoot(), getTask().getTaskId()); reviewConsumer.addObserver(reviewObserver); reviewConsumer.open(); }
Source:
public void testPerformAdd_Triple() { GraphWithPerform g = (GraphWithPerform) graphWith( producer.newInstance(), "S P O; S2 P2 O2"); g.getEventManager().register(GL); txnBegin(g); g.performAdd(triple("S3 P3 O3")); txnCommit(g); GL.assertEmpty(); txnRun( g, new Runnable() { @Override public void run() { assertTrue(g.contains(triple("S3 P3 O3"))); }}); }

Target:
public void testPerformAdd_Triple() { GraphWithPerform g = (GraphWithPerform) graphWith( producer.newInstance(), "S P O; S2 P2 O2"); g.getEventManager().register(GL); txnBegin(g); g.performAdd(triple("S3 P3 O3")); txnCommit(g); GL.assertEmpty(); assertTrue(g.contains(triple("S3 P3 O3"))); }
Source:
public void testPropagation() throws Exception { Span span = tracer.buildSpan("root").start(); JaegerSpanContext context = (JaegerSpanContext) span.context(); String traceId = context.getTraceId(); String baggage = "Baggage-" + System.currentTimeMillis(); span.setBaggageItem(BAGGAGE_KEY, baggage); span.setBaggageItem(CUSTOM_BAGGAGE_PARAM_KEY, customBaggage); if (!sampled) { Tags.SAMPLING_PRIORITY.set(span, 0); } tracingContext.pushSpan(span); try { TraceResponse response = callDownstream(forwardEncodings); assertEquals("Only requests with 'pass' baggage should pass", "pass", customBaggage); List<String> encodings = new ArrayList<>(Arrays.asList(forwardEncodings.split(","))); validate(encodings, traceId, baggage, response); if (sampled) { for (int i = 0; i < 100; i++) { if (reporter.getSpans().size() == 4) { break; } Thread.sleep(10); } assertEquals(4, reporter.getSpans().size()); } } catch (ErrorResponseException error) { if ("pass".equals(customBaggage)) { fail("Request with 'pass' baggage must pass but failed with: " + error); } } }

Target:
public void testPropagation() throws Exception { Span span = tracer.buildSpan("root").start(); String traceId = span.context().toTraceId(); String baggage = "Baggage-" + System.currentTimeMillis(); span.setBaggageItem(BAGGAGE_KEY, baggage); span.setBaggageItem(CUSTOM_BAGGAGE_PARAM_KEY, customBaggage); if (!sampled) { Tags.SAMPLING_PRIORITY.set(span, 0); } tracingContext.pushSpan(span); try { TraceResponse response = callDownstream(forwardEncodings); assertEquals("Only requests with 'pass' baggage should pass", "pass", customBaggage); List<String> encodings = new ArrayList<>(Arrays.asList(forwardEncodings.split(","))); validate(encodings, traceId, baggage, response); if (sampled) { for (int i = 0; i < 100; i++) { if (reporter.getSpans().size() == 4) { break; } Thread.sleep(10); } assertEquals(4, reporter.getSpans().size()); } } catch (ErrorResponseException error) { if ("pass".equals(customBaggage)) { fail("Request with 'pass' baggage must pass but failed with: " + error); } } }
Source:
private String initializeDeviceId() { Set<String> invalidIds = getInvalidDeviceIds(); String deviceId = dbHelper.getValue(DEVICE_ID_KEY); String sharedPrefDeviceId = Utils.getStringFromSharedPreferences(context, instanceName, DEVICE_ID_KEY); if (!(Utils.isEmptyString(deviceId) || invalidIds.contains(deviceId))) { if (!deviceId.equals(sharedPrefDeviceId)) { Utils.writeStringToSharedPreferences(context, instanceName, DEVICE_ID_KEY, deviceId); } return deviceId; } if (!(Utils.isEmptyString(sharedPrefDeviceId) || invalidIds.contains(sharedPrefDeviceId))) { dbHelper.insertOrReplaceKeyValue(DEVICE_ID_KEY, sharedPrefDeviceId); return sharedPrefDeviceId; } if (!newDeviceIdPerInstall && useAdvertisingIdForDeviceId && !deviceInfo.isLimitAdTrackingEnabled()) { String advertisingId = deviceInfo.getAdvertisingId(); if (!(Utils.isEmptyString(advertisingId) || invalidIds.contains(advertisingId))) { saveDeviceId(advertisingId); return advertisingId; } } String randomId = deviceInfo.generateUUID() + "R"; saveDeviceId(randomId); return randomId; }

Target:
private String initializeDeviceId() { Set<String> invalidIds = getInvalidDeviceIds(); String deviceId = dbHelper.getValue(DEVICE_ID_KEY); String sharedPrefDeviceId = Utils.getStringFromSharedPreferences(context, instanceName, DEVICE_ID_KEY); if (!(Utils.isEmptyString(deviceId) || invalidIds.contains(deviceId))) { if (!deviceId.equals(sharedPrefDeviceId)) { saveDeviceId(deviceId); } return deviceId; } if (!(Utils.isEmptyString(sharedPrefDeviceId) || invalidIds.contains(sharedPrefDeviceId))) { saveDeviceId(sharedPrefDeviceId); return sharedPrefDeviceId; } if (!newDeviceIdPerInstall && useAdvertisingIdForDeviceId && !deviceInfo.isLimitAdTrackingEnabled()) { String advertisingId = deviceInfo.getAdvertisingId(); if (!(Utils.isEmptyString(advertisingId) || invalidIds.contains(advertisingId))) { saveDeviceId(advertisingId); return advertisingId; } } String randomId = deviceInfo.generateUUID() + "R"; saveDeviceId(randomId); return randomId; }
Source:
public Xid[] recover(int flag) throws XAException { Xid toReturn = null; if ((flag & XAResource.TMSTARTRSCAN) == XAResource.TMSTARTRSCAN) { synchronized(this) { if (scanning) { try { this.wait(); } catch (InterruptedException e) { throw new XAException("Could not wait for in progress scanner"); } } else { scanning = true; } } System.out.println("[" + Thread.currentThread().getName() + "] DummyXAResource (" + serverId + ") RECOVER[XAResource.TMSTARTRSCAN]: " + serverId); if (xid != null) { toReturn = xid; System.out.println("[" + Thread.currentThread().getName() + "] DummyXAResource (" + serverId + ") RECOVERED: " + toReturn); } } if ((flag & XAResource.TMENDRSCAN) == XAResource.TMENDRSCAN) { System.out.println("[" + Thread.currentThread().getName() + "] DummyXAResource (" + serverId + ") RECOVER[XAResource.TMENDRSCAN]: " + serverId); synchronized(this) { if (scanning) { scanning = false; this.notify(); } } } if (flag == XAResource.TMNOFLAGS) { System.out.println("[" + Thread.currentThread().getName() + "] DummyXAResource (" + serverId + ") RECOVER[XAResource.TMENDRSCAN]: " + serverId); } return new Xid[] { toReturn }; }

Target:
public Xid[] recover(int flag) throws XAException { return new Xid[]{xid}; }
Source:
public void ack(Object messageId) { if (!isTestMessageId(messageId)) { delegateSpout.ack(messageId); } else { tuplesToAck--; LOG.info("Received an ack with MessageId: " + messageId + " tuplesToAck=" + tuplesToAck); handleAckedMessage(messageId, pendingMessages.get(messageId)); } emitTerminalIfNeeded(); }

Target:
public void ack(Object messageId) { tuplesToAck--; LOG.info("Received an ack with MessageId: " + messageId + " tuplesToAck=" + tuplesToAck); if (!isTestMessageId(messageId)) { delegateSpout.ack(messageId); } else { handleAckedMessage(messageId, pendingMessages.get(messageId)); } emitTerminalIfNeeded(); }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { IEditorInput editorInput = HandlerUtil.getActiveEditorInput(event); if (editorInput instanceof CompareEditorInput) { configuration = ((CompareEditorInput)editorInput).getCompareConfiguration(); } Shell parent = configuration.getContainer().getWorkbenchPart().getSite().getShell(); FileDialog fileDialog = new FileDialog(parent, SWT.SAVE); String filePath = fileDialog.open(); if (filePath != null) { File file = new File(filePath); if (file.exists()) { MessageDialog messageDialog = new MessageDialog(parent, "File already exists", null, "File \"" + file.toString() + "\" already exists. Do you want to replace the existing one?", MessageDialog.WARNING, DIALOG_BUTTON_LABELS.toArray(new String[0]), 1); int open = messageDialog.open(); if (open == DIALOG_BUTTON_LABELS.indexOf("Replace")) { saveComparison(file); } } else { saveComparison(file); } } return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { IEditorInput editorInput = HandlerUtil.getActiveEditorInput(event); if (editorInput instanceof CompareEditorInput) { configuration = ((CompareEditorInput)editorInput).getCompareConfiguration(); Shell parent = configuration.getContainer().getWorkbenchPart().getSite().getShell(); FileDialog fileDialog = new FileDialog(parent, SWT.SAVE); String filePath = fileDialog.open(); if (filePath != null) { File file = new File(filePath); if (file.exists()) { MessageDialog messageDialog = new MessageDialog(parent, "File already exists", null, "File \"" + file.toString() + "\" already exists. Do you want to replace the existing one?", MessageDialog.WARNING, DIALOG_BUTTON_LABELS.toArray(new String[0]), 1); int open = messageDialog.open(); if (open == DIALOG_BUTTON_LABELS.indexOf("Replace")) { saveComparison(file); } } else { saveComparison(file); } } } return null; }
Source:
protected static MarkupParser createParserWithConfiguration(MarkupLanguageConfiguration configuration) { MarkupLanguage markupLanguage = new AsciiDocLanguage(); if (configuration != null) { markupLanguage.configure(configuration); } MarkupParser parser = new MarkupParser(markupLanguage); return parser; }

Target:
protected static MarkupParser createParserWithConfiguration(MarkupLanguageConfiguration configuration) { MarkupLanguage markupLanguage = new AsciiDocLanguage(); if (configuration != null) { markupLanguage.configure(configuration); } return new MarkupParser(markupLanguage); }
Source:
private void highlightViewOnUiThread() { hideHighlightOnUiThread(); while (true) { View viewToHighlight = mViewToHighlight.get(); if (viewToHighlight != null) { mHighlightDrawable.setBounds(0, 0, viewToHighlight.getWidth(), viewToHighlight.getHeight()); viewToHighlight.getOverlay().add(mHighlightDrawable); mHighlightedView = viewToHighlight; if (mViewToHighlight.compareAndSet(viewToHighlight, null)) { break; } } } }

Target:
private void highlightViewOnUiThread() { final View viewToHighlight = mViewToHighlight.getAndSet(null); if (viewToHighlight == mHighlightedView) { return; } if (mHighlightedView != null) { mHighlightedView.getOverlay().remove(mHighlightDrawable); } if (viewToHighlight != null) { mHighlightDrawable.setColor(mContentColor.get()); mHighlightDrawable.setBounds(0, 0, viewToHighlight.getWidth(), viewToHighlight.getHeight()); viewToHighlight.getOverlay().add(mHighlightDrawable); mHighlightedView = viewToHighlight; } }
Source:
public String format(LogRecord record) { ZonedDateTime timestamp = ZonedDateTime.ofInstant(Instant.ofEpochMilli(record.getMillis()), SYSTEM_ZONE); StringWriter stringWriter = new StringWriter() .append(TIMESTAMP_FORMATTER.format(timestamp)) .append('\t') .append(Level.fromJulLevel(record.getLevel()).name()) .append('\t') .append(Thread.currentThread().getName()) .append('\t') .append(record.getLoggerName()) .append('\t') .append(record.getMessage()); if (record.getThrown() != null) { stringWriter.append('\n'); record.getThrown().printStackTrace(new PrintWriter(stringWriter)); stringWriter.append('\n'); } stringWriter.append('\n'); String message = stringWriter.toString(); return message; }

Target:
public String format(LogRecord record) { ZonedDateTime timestamp = ZonedDateTime.ofInstant(Instant.ofEpochMilli(record.getMillis()), SYSTEM_ZONE); StringWriter stringWriter = new StringWriter() .append(TIMESTAMP_FORMATTER.format(timestamp)) .append('\t') .append(Level.fromJulLevel(record.getLevel()).name()) .append('\t') .append(Thread.currentThread().getName()) .append('\t') .append(record.getLoggerName()) .append('\t') .append(record.getMessage()); if (record.getThrown() != null) { stringWriter.append('\n'); record.getThrown().printStackTrace(new PrintWriter(stringWriter)); stringWriter.append('\n'); } stringWriter.append('\n'); return stringWriter.toString(); }
Source:
public void addLineItem() { ProductFixtures.withTaxedProduct(client(), product -> { final LineItemDraft lineItemDraft = LineItemDraft.of(product, 1, 5); final AddLineItem addLineItem = AddLineItem.of(lineItemDraft); testOrderEditStagedUpdateAction(addLineItem); }); }

Target:
public void addLineItem() { withTaxedProduct(client(), product -> { final LineItemDraft lineItemDraft = LineItemDraft.of(product, 1, 5); final AddLineItem addLineItem = AddLineItem.of(lineItemDraft); testOrderEditStagedUpdateAction(addLineItem); }); }
Source:
private void testAsyncWritesToBuffer() { Buffer buffer = (Buffer) store; int count = TestData.getScaleCount(); for (int i = 0; i < count; ++i) { Write write = null; while (write == null ) { write = TestData.getWriteAdd(); } buffer.insert( write,true ); } }

Target:
private void testAsyncWritesToBuffer() { Buffer buffer = (Buffer) store; int count = TestData.getScaleCount(); for (int i = 0; i < count; ++i) { Write write = null; while (write == null) { write = TestData.getWriteAdd(); } buffer.insert(write, true); } Assert.assertEquals(count, GlobalState.BINARY_QUEUE.size()); }
Source:
static <T> Future<T> ofSupplier(ExecutorService executorService, Supplier<? extends T> computation) { return of(executorService, computation::get); }

Target:
static <T> Future<T> ofSupplier(ExecutorService executorService, Supplier<? extends T> computation) { Objects.requireNonNull(computation, "computation is null"); return of(executorService, computation::get); }
Source:
public void process(final Exchange exchange) throws Exception { final Message in = exchange.getIn(); final Model model = createDefaultModel(); String fcrepoBinaryUri = (String) in.getHeader("CamelFcrepoUri"); Model values = model.read(in.getBody(InputStream.class), null, "Turtle"); ResIterator resources = values.listResourcesWithProperty(RDF.type, Fcrepo4Repository.Binary); try { if (resources.hasNext()) { Resource resource = resources.next(); String binaryMimeType = resource.getProperty(hasMimeType).getObject().toString(); String binaryFcrepoChecksum = resource.getProperty(hasMessageDigest).getObject().toString(); String[] binaryFcrepoChecksumSplit = binaryFcrepoChecksum.split(":"); String binaryPath = idToPath(binaryFcrepoChecksumSplit[2], BINARY_PATH_DEPTH, HASHED_PATH_SIZE); String binaryFullPath = new StringJoiner("") .add(baseBinaryPath) .add(binaryPath) .add(binaryFcrepoChecksumSplit[2]) .toString(); if (Files.exists(Paths.get(binaryFullPath))) { in.setHeader(CdrBinaryPath, binaryFullPath); in.setHeader(CdrBinarySubPath, idToPath(fcrepoBinaryUri, HASHED_PATH_DEPTH, HASHED_PATH_SIZE)); } in.setHeader(CdrBinaryChecksum, binaryFcrepoChecksumSplit[2]); in.setHeader(CdrBinaryMimeType, binaryMimeType); in.setHeader(CdrBinaryUri, fcrepoBinaryUri); } } finally { resources.close(); } }

Target:
public void process(final Exchange exchange) throws Exception { final Message in = exchange.getIn(); final Model model = createDefaultModel(); String fcrepoBinaryUri = (String) in.getHeader("CamelFcrepoUri"); Model values = model.read(in.getBody(InputStream.class), null, "Turtle"); ResIterator resources = values.listResourcesWithProperty(RDF.type, Fcrepo4Repository.Binary); try { if (resources.hasNext()) { Resource resource = resources.next(); String binaryMimeType = resource.getProperty(hasMimeType).getObject().toString(); String binaryFcrepoChecksum = resource.getProperty(hasMessageDigest).getObject().toString(); String[] binaryFcrepoChecksumSplit = binaryFcrepoChecksum.split(":"); String binaryPath = RepositoryPaths .idToPath(binaryFcrepoChecksumSplit[2], BINARY_PATH_DEPTH, HASHED_PATH_SIZE); String binaryFullPath = new StringJoiner("") .add(baseBinaryPath) .add(binaryPath) .add(binaryFcrepoChecksumSplit[2]) .toString(); if (Files.exists(Paths.get(binaryFullPath))) { in.setHeader(CdrBinaryPath, binaryFullPath); } in.setHeader(CdrBinaryChecksum, binaryFcrepoChecksumSplit[2]); in.setHeader(CdrBinaryMimeType, binaryMimeType); in.setHeader(CdrBinaryUri, fcrepoBinaryUri); } } finally { resources.close(); } }
Source:
public static FunctionMetadata removeTypeParameters(FunctionMetadata metadata) { ImmutableList.Builder<TypeSignature> argumentsBuilder = ImmutableList.builder(); for (TypeSignature typeSignature : metadata.getArgumentTypes()) { argumentsBuilder.add(removeTypeParameters(typeSignature)); } if (metadata.getOperatorType().isPresent()) { return new FunctionMetadata( metadata.getOperatorType().get(), argumentsBuilder.build(), metadata.getReturnType(), metadata.getFunctionKind(), metadata.isDeterministic(), metadata.isCalledOnNullInput()); } else { return new FunctionMetadata( metadata.getName(), argumentsBuilder.build(), metadata.getReturnType(), metadata.getFunctionKind(), metadata.isDeterministic(), metadata.isCalledOnNullInput()); } }

Target:
private static FunctionMetadata removeTypeParameters(FunctionMetadata metadata) { ImmutableList.Builder<TypeSignature> argumentsBuilder = ImmutableList.builder(); for (TypeSignature typeSignature : metadata.getArgumentTypes()) { argumentsBuilder.add(removeTypeParameters(typeSignature)); } if (metadata.getOperatorType().isPresent()) { return new FunctionMetadata( metadata.getOperatorType().get(), argumentsBuilder.build(), metadata.getReturnType(), metadata.getFunctionKind(), metadata.isDeterministic(), metadata.isCalledOnNullInput()); } return new FunctionMetadata( metadata.getName(), argumentsBuilder.build(), metadata.getReturnType(), metadata.getFunctionKind(), metadata.isDeterministic(), metadata.isCalledOnNullInput()); }
Source:
public static String getPayloadAsString(CoreEvent event) { return event.getMessage().getPayload().getValue().toString(); }

Target:
public static String getPayloadAsString(CoreEvent event) { TypedValue<?> payload= event.getMessage().getPayload(); if(payload != null && payload.getValue() != null) return payload.getValue().toString(); return null; }
Source:
private String buildRetrieveClaimsUrlJsonBody(String code) throws JsonProcessingException { Map<String, String> body = new HashMap<String, String>() {{ put("grant_type", "authorization_code"); put("code", code); put("client_id", clientId); put("client_secret", clientSecret); put("redirect_uri", callbackURI); }}; ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.writeValueAsString(body); }

Target:
private String buildRetrieveClaimsUrlJsonBody(String code) throws JsonProcessingException { Map<String, String> body = Map.of( "grant_type", "authorization_code", "code", code, "client_id", clientId, "client_secret", clientSecret, "redirect_uri", callbackURI ); ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.writeValueAsString(body); }
Source:
public BoundedContextBuilder addCommandDispatcher(CommandDispatcher<?> commandDispatcher) { checkNotNull(commandDispatcher); commandDispatchers.add(commandDispatcher); return this; }

Target:
public BoundedContextBuilder addCommandDispatcher(CommandDispatcher<?> commandDispatcher) { checkNotNull(commandDispatcher); if (commandDispatcher instanceof Repository) { return add((Repository<?, ?>) commandDispatcher); } commandDispatchers.add(commandDispatcher); return this; }
Source:
private CompletableFuture<CorfuInterClusterReplicationServerNode> startDiscoveryService(ServerContext serverContext) throws Exception { log.info("Start Discovery Service."); CompletableFuture<CorfuInterClusterReplicationServerNode> discoveryServiceCallback = new CompletableFuture<>(); this.clusterManagerAdapter = buildClusterManagerAdapter(serverContext.getPluginConfigFilePath()); replicationDiscoveryService = new CorfuReplicationDiscoveryService(serverContext, clusterManagerAdapter, discoveryServiceCallback); Thread replicationDiscoveryThread = new Thread(replicationDiscoveryService, "discovery-service"); replicationDiscoveryThread.start(); return discoveryServiceCallback; }

Target:
private CompletableFuture<CorfuInterClusterReplicationServerNode> startDiscoveryService(ServerContext serverContext) { log.info("Start Discovery Service."); CompletableFuture<CorfuInterClusterReplicationServerNode> discoveryServiceCallback = new CompletableFuture<>(); this.clusterManagerAdapter = buildClusterManagerAdapter(serverContext.getPluginConfigFilePath()); replicationDiscoveryService = new CorfuReplicationDiscoveryService(serverContext, clusterManagerAdapter, discoveryServiceCallback); Thread replicationDiscoveryThread = new Thread(replicationDiscoveryService, "discovery-service"); replicationDiscoveryThread.start(); return discoveryServiceCallback; }
Source:
public LoginPasswordAuthentication(final String login, final String password) { this.login = notEmpty(login, "login");; this.password = notEmpty(password, "password");; }

Target:
public LoginPasswordAuthentication(final String login, final String password) { this.login = notEmpty(login, "login"); this.password = notEmpty(password, "password"); }
Source:
public HashCode buildHashCode() { final HashCode hc = Const.HASH_FUNCTION().newHasher() .putString(Strings.nullToEmpty(aggregator), Const.UTF8_CHARSET) .putBoolean(infectious_nan) .putBoolean(merge_ids) .putBoolean(full_merge) .hash(); final List<HashCode> hashes = Lists.newArrayListWithCapacity(4); hashes.add(super.buildHashCode()); hashes.add(hc); if (tag_keys != null) { final List<String> keys = Lists.newArrayList(tag_keys); Collections.sort(keys); final Hasher hasher = Const.HASH_FUNCTION().newHasher(); for (final String key : keys) { hasher.putString(key, net.opentsdb.core.Const.UTF8_CHARSET); } hashes.add(hasher.hash()); } if (encoded_tag_keys != null) { final List<byte[]> keys = Lists.newArrayList(encoded_tag_keys); final Hasher hasher = Const.HASH_FUNCTION().newHasher(); for (final byte[] key : keys) { hasher.putInt(key.hashCode()); } hashes.add(hasher.hash()); } return Hashing.combineOrdered(hashes); }

Target:
public HashCode buildHashCode() { final HashCode hc = Const.HASH_FUNCTION().newHasher() .putString(Strings.nullToEmpty(aggregator), Const.UTF8_CHARSET) .putBoolean(infectious_nan) .putBoolean(merge_ids) .putBoolean(full_merge) .hash(); final List<HashCode> hashes = Lists.newArrayListWithCapacity(4); hashes.add(super.buildHashCode()); hashes.add(hc); if (tag_keys != null) { final List<String> keys = Lists.newArrayList(tag_keys); Collections.sort(keys); final Hasher hasher = Const.HASH_FUNCTION().newHasher(); for (final String key : keys) { hasher.putString(key, net.opentsdb.core.Const.UTF8_CHARSET); } hashes.add(hasher.hash()); } return Hashing.combineOrdered(hashes); }
Source:
public void destroy() { this.connectionFactoryMap.forEach((ldap, connectionFactory) -> { connectionFactory.close(); }); }

Target:
public void destroy() { this.connectionFactoryMap.forEach((ldap, connectionFactory) -> connectionFactory.close()); }
Source:
public void doesNotEscapeBase64() throws Exception { String name = secretBase64.getName(); when(aclDAO.getBatchSanitizedSecretsFor(client, ImmutableList.of(name))) .thenReturn(ImmutableList.of(SanitizedSecret.fromSecret(secretBase64))); when(secretController.getSecretsByName(ImmutableList.of(name))) .thenReturn(ImmutableList.of(secretBase64)); List<SecretDeliveryResponse> response = batchSecretDeliveryResource.getBatchSecret(client, BatchSecretRequest.create(ImmutableList.of(secretBase64.getName()))); assertThat(response.get(0).getSecret()).isEqualTo(secretBase64.getSecret()); assertThat(response.size()).isEqualTo(1); }

Target:
public void doesNotEscapeBase64() throws Exception { String name = secretBase64.getName(); when(aclDAO.getBatchSanitizedSecretsFor(client, ImmutableList.of(name))) .thenReturn(ImmutableList.of(SanitizedSecret.fromSecret(secretBase64))); when(clientDAO.getClientByName(client.getName())).thenReturn(Optional.of(client)); when(secretController.getSecretsByName(ImmutableList.of(name))) .thenReturn(ImmutableList.of(secretBase64)); List<SecretDeliveryResponse> response = batchSecretDeliveryResource.getBatchSecret(client, BatchSecretRequest.create(ImmutableList.of(secretBase64.getName()))); assertThat(response.size()).isEqualTo(1); assertThat(response.get(0).getSecret()).isEqualTo(secretBase64.getSecret()); }
Source:
public PantsCompileAllTargetsAction() { super(new PantsGetAllTargets(), new PantsExecuteCompile(), "Compile all targets in project"); }

Target:
public PantsCompileAllTargetsAction() { super("Compile all targets in project"); }
Source:
public static synchronized SyncManager getInstance(UserAccount account, String communityId, SmartStore smartStore) { if (account == null) { account = SalesforceSDKManagerWithSmartStore.getInstance().getUserAccountManager().getCurrentUser(); } if (smartStore == null) { smartStore = SmartSyncSDKManager.getInstance().getSmartStore(account, communityId); } if (UserAccount.INTERNAL_COMMUNITY_ID.equals(communityId)) { communityId = null; } String uniqueId = (account != null ? account.getUserId() : "") + ":" + (communityId != null ? communityId : "") + ":" + smartStore.getDatabase().getPath(); SyncManager instance = INSTANCES.get(uniqueId); if (instance == null) { RestClient restClient = SalesforceSDKManager.getInstance().getClientManager().peekRestClient(account); instance = new SyncManager(smartStore, restClient); INSTANCES.put(uniqueId, instance); } return instance; }

Target:
public static synchronized SyncManager getInstance(UserAccount account, String communityId, SmartStore smartStore) { if (account == null) { account = SalesforceSDKManagerWithSmartStore.getInstance().getUserAccountManager().getCurrentUser(); } if (smartStore == null) { smartStore = SmartSyncSDKManager.getInstance().getSmartStore(account, communityId); } String uniqueId = (account != null ? account.getUserId() : "") + ":" + smartStore.getDatabase().getPath(); SyncManager instance = INSTANCES.get(uniqueId); if (instance == null) { RestClient restClient = SalesforceSDKManager.getInstance().getClientManager().peekRestClient(account); instance = new SyncManager(smartStore, restClient); INSTANCES.put(uniqueId, instance); } return instance; }
Source:
public DefaultTimeSourceService(TimeSourceConfiguration config) { if (config != null) { timeSource = config.getTimeSource(); } else { timeSource = TickingTimeSource.INSTANCE; } }

Target:
public DefaultTimeSourceService(TimeSourceConfiguration config) { if (config != null) { timeSource = config.getTimeSource(); } else { timeSource = SystemTimeSource.INSTANCE; } }
Source:
public Set<String> addSenseBlackList(@Scope(OAuthScope.ADMINISTRATION_READ) final AccessToken accessToken) { Jedis jedis = null; try { jedis = jedisPool.getResource(); return jedis.smembers(BlackListDevicesConfiguration.SENSE_BLACK_LIST_KEY); } catch (JedisDataException e) { if (jedis != null) { jedisPool.returnBrokenResource(jedis); } throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(new JsonError(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), String.format("Failed to get data from redis - %s", e.getMessage()))).build()); } catch (Exception e) { if (jedis != null) { jedisPool.returnBrokenResource(jedis); } throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(new JsonError(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), String.format("Failed to retrieve sense black list because %s", e.getMessage()))).build()); } finally { if (jedis != null) { jedisPool.returnResource(jedis); } } }

Target:
public Set<String> addSenseBlackList(@Scope(OAuthScope.ADMINISTRATION_READ) final AccessToken accessToken) { Jedis jedis = null; try { jedis = jedisPool.getResource(); return jedis.smembers(BlackListDevicesConfiguration.SENSE_BLACK_LIST_KEY); } catch (JedisDataException e) { if (jedis != null) { jedisPool.returnBrokenResource(jedis); jedis = null; } throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(new JsonError(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), String.format("Failed to get data from redis - %s", e.getMessage()))).build()); } catch (Exception e) { if (jedis != null) { jedisPool.returnBrokenResource(jedis); jedis = null; } throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(new JsonError(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), String.format("Failed to retrieve sense black list because %s", e.getMessage()))).build()); } finally { if (jedis != null) { jedisPool.returnResource(jedis); } } }
Source:
private void testJBossWSRuntimeDeletion() { jbossWSRuntimePreferencePage.select(0); jbossWSRuntimePreferencePage.remove(); new WaitUntil(new ShellIsActive("Confirm Runtime Delete")); new PushButton("OK").click(); new WaitWhile(new ShellIsActive("Confirm Runtime Delete")); assertThat(jbossWSRuntimePreferencePage.getAllJBossWSRuntimes().size(), Is.is(0)); }

Target:
private void testJBossWSRuntimeDeletion() { jbossWSRuntimePreferencePage.select(0); jbossWSRuntimePreferencePage.remove(); new DefaultShell("Confirm Runtime Delete"); new PushButton("OK").click(); new WaitWhile(new ShellIsAvailable("Confirm Runtime Delete")); assertThat(jbossWSRuntimePreferencePage.getAllJBossWSRuntimes().size(), Is.is(0)); }
Source:
public Queue<Selectable> createFlowTriggerEventQueue(DatabaseBackupTriggerEvent event) { Queue<Selectable> chain = new ConcurrentLinkedQueue<>(); String selector = DATABASE_BACKUP_EVENT.event(); chain.add(new StackEvent(SaltUpdateEvent.SALT_UPDATE_EVENT.event(), event.getResourceId(), event.accepted())); chain.add(new DatabaseBackupTriggerEvent(selector, event.getResourceId(), event.getBackupLocation(), event.getBackupId())); return chain; }

Target:
public Queue<Selectable> createFlowTriggerEventQueue(DatabaseBackupTriggerEvent event) { Queue<Selectable> chain = new ConcurrentLinkedQueue<>(); chain.add(new StackEvent(SaltUpdateEvent.SALT_UPDATE_EVENT.event(), event.getResourceId(), event.accepted())); chain.add(new DatabaseBackupTriggerEvent(DATABASE_BACKUP_EVENT.event(), event.getResourceId(), event.getBackupLocation(), event.getBackupId())); return chain; }
Source:
public PatchSetAttribute asPatchSetAttribute(final PatchSet patchSet) { PatchSetAttribute p = new PatchSetAttribute(); p.revision = patchSet.getRevision().get(); p.number = Integer.toString(patchSet.getPatchSetId()); p.ref = patchSet.getRefName(); p.uploader = asAccountAttribute(patchSet.getUploader()); p.createdOn = patchSet.getCreatedOn().getTime() / 1000L; try { final ReviewDb db = schema.open(); try { p.parents = new ArrayList<String>(); for (PatchSetAncestor a : db.patchSetAncestors().ancestorsOf( patchSet.getId())) { p.parents.add(a.getAncestorRevision().get()); } p.author = asAccountAttribute(psInfoFactory.get(db, patchSet.getId()) .getAuthor().getAccount()); Change change = db.changes().get(patchSet.getId().getParentKey()); List<Patch> list = patchListCache.get(change, patchSet).toPatchList(patchSet.getId()); for (Patch pe : list) { if (!Patch.COMMIT_MSG.equals(pe.getFileName())) { p.sizeDeletions -= pe.getDeletions(); p.sizeInsertions += pe.getInsertions(); } } } finally { db.close(); } } catch (OrmException e) { log.error("Cannot load patch set data for " + patchSet.getId(), e); } catch (PatchSetInfoNotAvailableException e) { log.error( String.format("Cannot get authorEmail for %s ", patchSet.getId()), e); } catch (PatchListNotAvailableException e) { log.error( String.format("Cannot get deletions and insertions for %s ", patchSet.getId()), e); } return p; }

Target:
public PatchSetAttribute asPatchSetAttribute(final PatchSet patchSet) { PatchSetAttribute p = new PatchSetAttribute(); p.revision = patchSet.getRevision().get(); p.number = Integer.toString(patchSet.getPatchSetId()); p.ref = patchSet.getRefName(); p.uploader = asAccountAttribute(patchSet.getUploader()); p.createdOn = patchSet.getCreatedOn().getTime() / 1000L; final PatchSet.Id pId = patchSet.getId(); try { final ReviewDb db = schema.open(); try { p.parents = new ArrayList<String>(); for (PatchSetAncestor a : db.patchSetAncestors().ancestorsOf( patchSet.getId())) { p.parents.add(a.getAncestorRevision().get()); } p.author = asAccountAttribute( psInfoFactory.get(db, pId).getAuthor().getAccount()); Change change = db.changes().get(pId.getParentKey()); List<Patch> list = patchListCache.get(change, patchSet).toPatchList(pId); for (Patch pe : list) { if (!Patch.COMMIT_MSG.equals(pe.getFileName())) { p.sizeDeletions -= pe.getDeletions(); p.sizeInsertions += pe.getInsertions(); } } } finally { db.close(); } } catch (OrmException e) { log.error("Cannot load patch set data for " + patchSet.getId(), e); } catch (PatchSetInfoNotAvailableException e) { log.error(String.format("Cannot get authorEmail for %s.", pId), e); } catch (PatchListNotAvailableException e) { log.error(String.format("Cannot get size information for %s.", pId), e); } return p; }
Source:
protected RefundsResponse executeFutureBehaviourStrategy() { return getPaymentRefundsService.getLedgerTransactionTransactions(account, paymentId); }

Target:
protected RefundsResponse executeFutureBehaviourStrategy() { return executeLedgerOnlyStrategy(); }
Source:
public GuiltyConscience(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{W}"); this.subtype.add("Aura"); TargetPermanent auraTarget = new TargetCreaturePermanent(); this.getSpellAbility().addTarget(auraTarget); this.getSpellAbility().addEffect(new AttachEffect(Outcome.BoostCreature)); Ability ability = new EnchantAbility(auraTarget.getTargetName()); this.addAbility(ability); this.addAbility(new DealsDamageAttachedTriggeredAbility(Zone.BATTLEFIELD, new DamageAttachedEffect(new NumericSetToEffectValues("that much", "damage")), false)); }

Target:
public GuiltyConscience(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{W}"); this.subtype.add("Aura"); TargetPermanent auraTarget = new TargetCreaturePermanent(); this.getSpellAbility().addTarget(auraTarget); this.getSpellAbility().addEffect(new AttachEffect(Outcome.UnboostCreature)); Ability ability = new EnchantAbility(auraTarget.getTargetName()); this.addAbility(ability); this.addAbility(new DealsDamageAttachedTriggeredAbility(Zone.BATTLEFIELD, new DamageAttachedEffect(new NumericSetToEffectValues("that much", "damage")), false)); }
Source:
public void testFields() { assertNotNull(mapMetaDataModel.getFields()); assertEquals(2, mapMetaDataModel.getFields().size()); final List<DataType> list = new ArrayList<DataType>(); for (int i = mapMetaDataModel.getFields().size(); --i >= 0;) { list.add(mapMetaDataModel.getFields().get(i).getMetaDataModel().getDataType()); } Collections.sort(list); assertTrue(list.get(1).equals(DataType.STRING)); assertTrue(list.get(0).equals(DataType.NUMBER)); }

Target:
public void testFields() { assertNotNull(mapMetaDataModel.getFields()); assertEquals(2, mapMetaDataModel.getFields().size()); Assertions.assertThat(mapMetaDataModel.getFields()).extracting("metaDataModel").extracting("dataType").contains(DataType.STRING); Assertions.assertThat(mapMetaDataModel.getFields()).extracting("metaDataModel").extracting("dataType").contains(DataType.NUMBER); }
Source:
public Boolean getResultAsBoolean() { return JsFunction.RESULT_TYPE_BOOLEAN.equals(resultType) ? (Boolean) resultValue : Boolean.FALSE; }

Target:
public Boolean getResultAsBoolean() { return JsFunction.RESULT_TYPE_BOOLEAN.equals(resultType) ? (Boolean) resultValue : Boolean.TRUE; }
Source:
public RemoteOutcomeParams() { new RemoteOutcomeParams(true, true, true); }

Target:
public RemoteOutcomeParams() { this(true, true, true); }
Source:
public Group createGroup(PerunSession sess, Group parentGroup, Group group) throws GroupExistsException, InternalErrorException, GroupRelationNotAllowed, GroupRelationAlreadyExists { Vo vo = this.getVo(sess, parentGroup); group = getGroupsManagerImpl().createGroup(sess, vo, parentGroup, group); try { parentGroup = createGroupUnion(sess, parentGroup, group, true); } catch (WrongAttributeValueException | WrongReferenceAttributeValueException e) { log.debug("Exception thrown in createGroup method, while it shouldn't be thrown. Cause:{}",e); } catch (GroupNotExistsException e) { throw new ConsistencyErrorException("Database consistency error while creating group: {}",e); } getPerunBl().getAuditer().log(sess, "{} created in as subgroup of {}", group, vo, parentGroup); return group; }

Target:
public Group createGroup(PerunSession sess, Group parentGroup, Group group) throws GroupExistsException, InternalErrorException, GroupRelationNotAllowed, GroupRelationAlreadyExists { Vo vo = this.getVo(sess, parentGroup); group = getGroupsManagerImpl().createGroup(sess, vo, parentGroup, group); try { parentGroup = createGroupUnion(sess, parentGroup, group, true); } catch (WrongAttributeValueException | WrongReferenceAttributeValueException e) { log.error("Exception thrown in createGroup method, while it shouldn't be thrown. Cause:{}",e); } catch (GroupNotExistsException e) { throw new ConsistencyErrorException("Database consistency error while creating group: {}",e); } getPerunBl().getAuditer().log(sess, "{} created in as subgroup of {}", group, vo, parentGroup); return group; }
Source:
private void initHttpClient(String hostUrlString) { try { hostUrl = new URL(hostUrlString); if (hostUrl.getProtocol().equalsIgnoreCase(HTTPS_PROTOCOL)) { URL trustStorePath = new URL(FILE_URL_PREFIX + EngineLocalConfig.getInstance().getPKIExternalTrustStore()); String trustStorePassword = EngineLocalConfig.getInstance().getPKIExternalTrustStorePassword(); boolean enableSniExtension = EngineLocalConfig.getInstance().isEnableSniExtension(); System.setProperty("jsse.enableSNIExtension", String.valueOf(enableSniExtension)); int hostPort = hostUrl.getPort(); if (hostPort == -1) { hostPort = DEFAULT_SECURED_PORT; } Protocol httpsProtocol = new Protocol("https", new AuthSSLProtocolSocketFactory(null, null, trustStorePath, trustStorePassword), hostPort); httpClient.getHostConfiguration().setHost(hostUrl.getHost(), hostPort, httpsProtocol); this.isSecured = true; } else { int hostPort = hostUrl.getPort(); if (hostPort == -1) { hostPort = DEFAULT_PORT; } httpClient.getHostConfiguration().setHost(hostUrl.getHost(), hostPort); } objectMapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); Credentials hostProviderCredentials = new UsernamePasswordCredentials(hostProvider.getUsername(), hostProvider.getPassword()); httpClient.getState().setCredentials(AuthScope.ANY, hostProviderCredentials); httpClient.getState().setAuthenticationPreemptive(true); } catch (MalformedURLException e) { throw new VdcBLLException(VdcBllErrors.PROVIDER_FAILURE, e.getMessage()); } }

Target:
private void initHttpClient(String hostUrlString) { try { URL hostUrl = getUrl(); if (isSecured()) { URL trustStorePath = ExternalTrustStoreInitializer.getTrustStoreUrl(); String trustStorePassword = ExternalTrustStoreInitializer.getTrustStorePassword(); int hostPort = hostUrl.getPort() == -1 ? HttpsURL.DEFAULT_PORT : hostUrl.getPort(); Protocol httpsProtocol = new Protocol(String.valueOf(HttpsURL.DEFAULT_SCHEME), (ProtocolSocketFactory) new AuthSSLProtocolSocketFactory(null, null, trustStorePath, trustStorePassword), hostPort); httpClient.getHostConfiguration().setHost(hostUrl.getHost(), hostPort, httpsProtocol); } else { int hostPort = hostUrl.getPort() == -1 ? HttpURL.DEFAULT_PORT : hostUrl.getPort(); httpClient.getHostConfiguration().setHost(hostUrl.getHost(), hostPort); } objectMapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); Credentials hostProviderCredentials = new UsernamePasswordCredentials(hostProvider.getUsername(), hostProvider.getPassword()); httpClient.getState().setCredentials(AuthScope.ANY, hostProviderCredentials); httpClient.getState().setAuthenticationPreemptive(true); } catch (MalformedURLException e) { throw new VdcBLLException(VdcBllErrors.PROVIDER_FAILURE, e.getMessage()); } }
Source:
public IStatus getProfileDefinitionStatus() { String profilePath = getProfileURI(); if (profilePath == null || profilePath.equalsIgnoreCase("")) { return Status.OK_STATUS; } URI profileURI = URI.createURI(profilePath); ResourceSet resourceSet = Util.createTemporaryResourceSet(); Resource resource = null; try { resource = resourceSet.getResource(profileURI, true); } catch (WrappedException ex) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.ProfileChooserComposite_ProfileStatus_UnavailableResource, ex); } finally { EMFHelper.unload(resourceSet); } if (resource == null) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.ProfileChooserComposite_ProfileStatus_NullResource); } if (resource.getContents().isEmpty()) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.ProfileChooserComposite_ProfileStatus_EmptyResource); } EObject eObject = resource.getContents().get(0); if (!(eObject instanceof Profile)) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.ProfileChooserComposite_ProfileStatus_NotAProfile); } Profile profile = (Profile) eObject; if (!profile.isDefined()) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.ProfileChooserComposite_ProfileStatus_ProfileNotDefined); } return Status.OK_STATUS; }

Target:
public IStatus getProfileDefinitionStatus() { String profilePath = getProfileURI(); URI profileURI = URI.createURI(profilePath); ResourceSet resourceSet = Util.createTemporaryResourceSet(); try { if (profilePath == null || profilePath.equalsIgnoreCase("")) { return Status.OK_STATUS; } Resource resource = null; resource = resourceSet.getResource(profileURI, true); if (resource == null) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.ProfileChooserComposite_ProfileStatus_NullResource); } if (resource.getContents().isEmpty()) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.ProfileChooserComposite_ProfileStatus_EmptyResource); } EObject eObject = resource.getContents().get(0); if (!(eObject instanceof Profile)) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.ProfileChooserComposite_ProfileStatus_NotAProfile); } Profile profile = (Profile) eObject; if (!profile.isDefined()) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.ProfileChooserComposite_ProfileStatus_ProfileNotDefined); } return Status.OK_STATUS; } catch (WrappedException ex) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.ProfileChooserComposite_ProfileStatus_UnavailableResource, ex); } finally { EMFHelper.unload(resourceSet); } }
Source:
public CompletableFuture<Integer> readIntoArray(byte[] res, int offset, int length) { try { System.arraycopy(data, index, res, offset, length); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(); } index += length; return CompletableFuture.completedFuture(length); }

Target:
public CompletableFuture<Integer> readIntoArray(byte[] res, int offset, int length) { System.arraycopy(data, index, res, offset, length); index += length; return CompletableFuture.completedFuture(length); }
Source:
private CsvReader(Path inputPath) throws IOException { mCloser = Closer.create(); Configuration conf = ReadWriterUtils.readNoCacheConf(); mFs = inputPath.getFileSystem(conf); mCloser.register(mFs); CSVProperties props = new CSVProperties.Builder() .hasHeader() .build(); Schema schema; try (InputStream inputStream = open(mFs, inputPath)) { String schemaName = inputPath.getName(); if (schemaName.contains(".")) { schemaName = schemaName.substring(0, schemaName.indexOf(".")); } schema = AvroCSV.inferSchema(schemaName, inputStream, props); mSchema = new CsvSchema(schema); } mReader = new AvroCSVReader<>(open(mFs, inputPath), props, schema, Record.class, false); mCloser.register(mReader); }

Target:
private CsvReader(Path inputPath) throws IOException { mCloser = Closer.create(); try { Configuration conf = ReadWriterUtils.readNoCacheConf(); mFs = mCloser.register(inputPath.getFileSystem(conf)); CSVProperties props = new CSVProperties.Builder() .hasHeader() .build(); Schema schema; try (InputStream inputStream = open(mFs, inputPath)) { String schemaName = inputPath.getName(); if (schemaName.contains(".")) { schemaName = schemaName.substring(0, schemaName.indexOf(".")); } schema = AvroCSV.inferSchema(schemaName, inputStream, props); mSchema = new CsvSchema(schema); } mReader = mCloser.register( new AvroCSVReader<>(open(mFs, inputPath), props, schema, Record.class, false)); } catch (IOException e) { try { mCloser.close(); } catch (IOException ioe) { e.addSuppressed(ioe); } throw e; } }
Source:
public List<Metric> transformScanner(List<MetricScanner> scanners) { if (scanners == null) { throw new MissingDataException("The metric scanners list cannot be null or empty while performing transforms."); } if (scanners.size() != 1) { throw new UnsupportedOperationException("Anomaly DetectionTransform can only be used with one metric."); } MetricScanner scanner = scanners.get(0); if (!scanner.hasNextDP()) { throw new MissingDataException("Metric scanner must contain data points to perform transforms."); } Map<Long, Double> datapoints = fitParametersScanner(scanner); Metric predictions = predictAnomalies(datapoints); Metric predictionsNormalized = normalizePredictions(predictions); List<Metric> resultMetrics = new ArrayList<>(); resultMetrics.add(predictionsNormalized); return resultMetrics; }

Target:
public List<Metric> transformScanner(List<MetricScanner> scanners) { SystemAssert.requireArgument(scanners != null, "The metric scanners list cannot be null or empty while performing transforms."); SystemAssert.requireArgument(scanners.size() == 1, "Anomaly DetectionTransform can only be used with one metric."); MetricScanner scanner = scanners.get(0); SystemAssert.requireArgument(scanner.hasNextDP(), "Metric scanner must contain data points to perform transforms."); Map<Long, Double> datapoints = fitParametersScanner(scanner); Metric predictions = predictAnomalies(datapoints); Metric predictionsNormalized = normalizePredictions(predictions); List<Metric> resultMetrics = new ArrayList<>(); resultMetrics.add(predictionsNormalized); return resultMetrics; }
Source:
public void testJobWithMaxRowsFilter() throws Exception { FilterComponentBuilder<MaxRowsFilter, Category> filter = analysisJobBuilder.addFilter(MaxRowsFilter.class); filter.addInputColumn(analysisJobBuilder.getSourceColumnByName("email")); filter.getComponentInstance().setMaxRows(5); emailTransformerBuilder.setRequirement(filter, Category.VALID); PreviewTransformedDataActionListener action = new PreviewTransformedDataActionListener(null, emailTransformerBuilder); TableModel tableModel = action.call(); assertEquals(5, tableModel.getRowCount()); }

Target:
public void testJobWithMaxRowsFilter() throws Exception { final FilterComponentBuilder<MaxRowsFilter, Category> filter = analysisJobBuilder .addFilter(MaxRowsFilter.class); filter.addInputColumn(analysisJobBuilder.getSourceColumnByName("email")); filter.getComponentInstance().setMaxRows(5); emailTransformerBuilder.setRequirement(filter, Category.VALID); final PreviewTransformedDataActionListener action = new PreviewTransformedDataActionListener(null, emailTransformerBuilder); final TableModel tableModel = action.call(); assertEquals(5, tableModel.getRowCount()); }
Source:
public void postInitialise(Context rootContext) { metrics.initialise(); InjectionHelper.inject(this, rootContext); if (config.getTelemetryConfig().isEnableTelemetry()) { Unstructured systemContextMetric = metrics.getSystemContextMetric().getMetric(); TelemetryUtils.trackMetric(emitter,NAMESPACE_TRACKER,systemContextMetric); } }

Target:
public void postInitialise(Context rootContext) { metrics.initialise(rootContext); addTelemetryLogstashAppender(rootContext); }