auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testPostWithUnsupportedRetryAndFailureWhileBodyIsSent() throws IOException { AtomicInteger count = new AtomicInteger(1); HttpRequestFactory reqFactory = m_client.getHttpRequestFactory(); HttpRequest req = reqFactory.buildPostRequest(new GenericUrl(m_server.getContextUrl() + "retry"), new HttpContent() { @Override public void writeTo(OutputStream out) throws IOException { System.out.println("POST write body " + count); if (count.getAndIncrement() < 2) { out.write("ba".getBytes()); throw new SocketException("TEST:cannot write"); } out.write("bar".getBytes()); } @Override public boolean retrySupported() { return false; } @Override public String getType() { return "text/plain;charset=UTF-8"; } @Override public long getLength() throws IOException { return 3; } }); req.setThrowExceptionOnExecuteError(false); req.execute(); }

Target:
public void testPostWithUnsupportedRetryAndFailureWhileBodyIsSent() throws IOException { AtomicInteger count = new AtomicInteger(1); HttpRequestFactory reqFactory = m_client.getHttpRequestFactory(); HttpRequest req = reqFactory.buildPostRequest(new GenericUrl(m_server.getContextUrl() + "retry"), new HttpContent() { @Override public void writeTo(OutputStream out) throws IOException { if (count.getAndIncrement() < 2) { out.write("ba".getBytes()); throw new SocketException("TEST:cannot write"); } out.write("bar".getBytes()); } @Override public boolean retrySupported() { return false; } @Override public String getType() { return "text/plain;charset=UTF-8"; } @Override public long getLength() throws IOException { return 3; } }); req.getHeaders().set(CORRELATION_ID, "03"); try { req.execute(); } catch (org.apache.http.client.ClientProtocolException e) { for (int i = 0; i < 100 && Servlet.doPostError == null; i++) { SleepUtil.sleepSafe(100, TimeUnit.MILLISECONDS); } assertEquals(Arrays.asList("03"), Servlet.doPostLog); assertNotNull(Servlet.doPostError); assertEquals(ProcessingException.class, Servlet.doPostError.getClass()); assertEquals(org.eclipse.jetty.io.EofException.class, Servlet.doPostError.getCause().getClass()); return; } fail("Expected to fail"); }
Source:
public Deferred<List<TSMeta>> getTSMetas() { if (metric == null || metric.length < 0) { throw new IllegalArgumentException("Missing metric UID"); } if (tags == null) { throw new IllegalArgumentException("Tag map was null"); } final Scanner scanner = getScanner(); scanner.setQualifier(TSMeta.COUNTER_QUALIFIER()); final Deferred<List<TSMeta>> results = new Deferred<List<TSMeta>>(); final List<TSMeta> tsmetas = new ArrayList<TSMeta>(); final List<Deferred<TSMeta>> tsmeta_group = new ArrayList<Deferred<TSMeta>>(); final class TSMetaGroupCB implements Callback<Object, ArrayList<TSMeta>> { @Override public List<TSMeta> call(ArrayList<TSMeta> ts) throws Exception { for (TSMeta tsm: ts) { if (tsm != null) { tsmetas.add(tsm); } } results.callback(tsmetas); return null; } } final class ScannerCB implements Callback<Object, ArrayList<ArrayList<KeyValue>>> { public Object scan() { return scanner.nextRows().addCallback(this); } @Override public Object call(final ArrayList<ArrayList<KeyValue>> rows) throws Exception { try { if (rows == null) { Deferred.group(tsmeta_group).addCallback(new TSMetaGroupCB()); return null; } for (final ArrayList<KeyValue> row : rows) { final byte[] tsuid = row.get(0).key(); tsmeta_group.add(TSMeta.getTSMeta(tsdb, UniqueId.uidToString(tsuid))); } return scan(); } catch (Exception e) { results.callback(e); return null; } } } new ScannerCB().scan(); return results; }

Target:
public Deferred<List<TSMeta>> getTSMetas() { if (metric == null || metric.length < 0) { throw new IllegalArgumentException("Missing metric UID"); } if (tags == null) { throw new IllegalArgumentException("Tag map was null"); } final Scanner scanner = getScanner(); scanner.setQualifier(TSMeta.META_QUALIFIER()); final Deferred<List<TSMeta>> results = new Deferred<List<TSMeta>>(); final List<TSMeta> tsmetas = new ArrayList<TSMeta>(); final List<Deferred<TSMeta>> tsmeta_group = new ArrayList<Deferred<TSMeta>>(); final class TSMetaGroupCB implements Callback<Object, ArrayList<TSMeta>> { @Override public List<TSMeta> call(ArrayList<TSMeta> ts) throws Exception { for (TSMeta tsm: ts) { if (tsm != null) { tsmetas.add(tsm); } } results.callback(tsmetas); return null; } } final class ScannerCB implements Callback<Object, ArrayList<ArrayList<KeyValue>>> { public Object scan() { return scanner.nextRows().addCallback(this); } @Override public Object call(final ArrayList<ArrayList<KeyValue>> rows) throws Exception { try { if (rows == null) { Deferred.group(tsmeta_group).addCallback(new TSMetaGroupCB()); return null; } for (final ArrayList<KeyValue> row : rows) { tsmeta_group.add(TSMeta.parseFromColumn(tsdb, row.get(0), true)); } return scan(); } catch (Exception e) { results.callback(e); return null; } } } new ScannerCB().scan(); return results; }
Source:
if (t == null) { try { Class<?> clazz = Class.forName("androidx.test.InstrumentationRegistry"); Object context = clazz.getDeclaredMethod("getTargetContext").invoke(clazz); t = (File) context.getClass().getMethod("getCacheDir").invoke(context); } catch (Throwable ignored) { } }

Target:
if (t == null) { t = getCacheDirFromInstrumentationRegistry("android.support.test.InstrumentationRegistry"); }
Source:
public XmlConfigBuilder(XmlConfigLocator locator) { if (locator == null) { locator = new XmlConfigLocator(); locator.locateEveryWhere(); } this.in = locator.getIn(); this.configurationFile = locator.getConfigurationFile(); this.configurationUrl = locator.getConfigurationUrl(); }

Target:
public XmlConfigBuilder(XmlConfigLocator locator) { if (locator == null) { locator = new XmlConfigLocator(); locator.locateEverywhere(); } this.in = locator.getIn(); this.configurationFile = locator.getConfigurationFile(); this.configurationUrl = locator.getConfigurationUrl(); }
Source:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append("{ \"event\" : "); if (event != null) { builder.append("\""); } builder.append(event); if (event != null) { builder.append("\""); } builder.append(", "); builder.append("\"id\" : "); if (id != null) { builder.append("\""); } builder.append(id); if (id != null) { builder.append("\""); } builder.append(", \"data\" : "); builder.append(data); builder.append("}"); return builder.toString(); }

Target:
public String toString() { return this.specName; }
Source:
public void testParseXmlWithNonBMPCharacters() { FormInstance model = null; try { model = FormLoadingUtils.loadFormInstance(formPath); IDataPayload payload = new XFormSerializingVisitor().createSerializedPayload(model); assertTrue(payload instanceof ByteArrayPayload); assertTrue(payload.getPayloadType() == IDataPayload.PAYLOAD_TYPE_XML); ByteArrayInputStream is = (ByteArrayInputStream)payload.getPayloadStream(); try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); dBuilder.parse(is); } catch (Exception e) { fail(e.getMessage()); } } catch (IOException e) { fail("Unable to load form at " + formPath); } catch (InvalidStructureException e) { fail("Form at " + formPath + " has an invalid structure."); } }

Target:
public void testParseXmlWithNonBMPCharacters() { FormInstance model = null; try { model = FormLoadingUtils.loadFormInstance(formPath); IDataPayload payload = new XFormSerializingVisitor().createSerializedPayload(model); assertTrue(payload instanceof ByteArrayPayload); assertTrue(payload.getPayloadType() == IDataPayload.PAYLOAD_TYPE_XML); ByteArrayInputStream is = (ByteArrayInputStream)payload.getPayloadStream(); try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); dBuilder.parse(is); } catch (Exception e) { e.printStackTrace(); fail("Xml parsing failed with exception: " + e.getMessage()); } } catch (IOException e) { fail("Unable to load form at " + formPath); } catch (InvalidStructureException e) { fail("Form at " + formPath + " has an invalid structure."); } }
Source:
public String getValue(String key) { if (key.equals("compression.s2c") || key.equals("compression.c2s")) { String foo = findValue(key); if (foo == null || foo.equals("no")) return "none,zlib@openssh.com,zlib"; return "zlib@openssh.com,zlib,none"; } return findValue(key); }

Target:
public String getValue(String key) { if (key.equals("compression.s2c") || key.equals("compression.c2s")) { String foo = findValue(key); if (foo == null || foo.equals("no")) { return "none,zlib@openssh.com,zlib"; } return "zlib@openssh.com,zlib,none"; } return findValue(key); }
Source:
public void shouldGenerateRepartitionTopicWhenNameIsNotSpecified() throws ExecutionException, InterruptedException { final long timestamp = System.currentTimeMillis(); sendEvents( timestamp, Arrays.asList( new KeyValue<>(1, "A"), new KeyValue<>(2, "B") ) ); final StreamsBuilder builder = new StreamsBuilder(); builder.stream(inputTopic, Consumed.with(Serdes.Integer(), Serdes.String())) .selectKey((key, value) -> key.toString()) .repartition(Repartitioned.with(Serdes.String(), Serdes.String())) .to(outputTopic); startStreams(builder); validateReceivedMessages( new StringDeserializer(), new StringDeserializer(), Arrays.asList( new KeyValue<>("1", "A"), new KeyValue<>("2", "B") ) ); final String topology = builder.build().describe().toString(); assertEquals(1, countOccurrencesInTopology(topology, "Sink: .*-repartition")); }

Target:
public void shouldGenerateRepartitionTopicWhenNameIsNotSpecified() throws Exception { final long timestamp = System.currentTimeMillis(); sendEvents( timestamp, Arrays.asList( new KeyValue<>(1, "A"), new KeyValue<>(2, "B") ) ); final StreamsBuilder builder = new StreamsBuilder(); builder.stream(inputTopic, Consumed.with(Serdes.Integer(), Serdes.String())) .selectKey((key, value) -> key.toString()) .repartition(Repartitioned.with(Serdes.String(), Serdes.String())) .to(outputTopic); startStreams(builder); validateReceivedMessages( new StringDeserializer(), new StringDeserializer(), Arrays.asList( new KeyValue<>("1", "A"), new KeyValue<>("2", "B") ) ); final String topology = builder.build().describe().toString(); assertEquals(1, countOccurrencesInTopology(topology, "Sink: .*-repartition")); }
Source:
public Vector shuffle(Factory factory) { double[] vector = new double[length]; for (int i = 0; i < length; i++) { vector[i] = get(i); } Random rnd = new Random(); for (int i = vector.length - 1; i >= 0; i--) { int index = rnd.nextInt(i + 1); double a = vector[index]; vector[index] = vector[i]; vector[i] = a; } return factory().createVector(vector); }

Target:
public Vector shuffle(Factory factory) { ensureFactoryIsNotNull(factory); Vector vector = copy(factory); Random rnd = new Random(); for (int i = 0; i < length; i++) { int rand = rnd.nextInt(length - i) + i; double a = vector.get(rand); vector.set(rand, vector.get(i)); vector.set(i, a); } return vector; }
Source:
private void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { LoggerUtils.logErrorWithStackTrace(IsisLog.getLogger(getClass()), e.getMessage(), e); } }

Target:
private void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { LoggerUtils.logErrorWithStackTrace(LOG, e.getMessage(), e); } }
Source:
public List<Class> getSupportedTypes() { return new ArrayList<>(Arrays.asList(byte.class, Byte.class)); }

Target:
public List<Class> getSupportedTypes() { return Arrays.asList(byte.class, Byte.class); }
Source:
private boolean isNullOrEmpty(CharSequence actual) { return (actual == null || actual.length() == 0); }

Target:
private boolean isNullOrEmpty(CharSequence actual) { return actual == null || actual.length() == 0; }
Source:
protected void processListener(MethodRabbitListenerEndpoint endpoint, RabbitListener rabbitListener, Object bean, Object adminTarget, String beanName) { String id = rabbitListener.id(); if (StringUtils.hasText(id)) { if (this.attributes.getBoolean("spy")) { Object spy = Mockito.spy(bean); this.listeners.put(id, spy); super.processListener(endpoint, rabbitListener, spy, adminTarget, beanName); return; } else { try { ProxyFactoryBean pfb = new ProxyFactoryBean(); pfb.setProxyTargetClass(true); pfb.setTarget(bean); CaptureAdvice advice = new CaptureAdvice(); pfb.addAdvice(advice); Object advised = pfb.getObject(); this.listenerCapture.put(id, advice); super.processListener(endpoint, rabbitListener, advised, adminTarget, beanName); return; } catch (Exception e) { logger.error("Failed to proxy @RabbitListener with id: " + id); } } } else { logger.info("The test harness can only proxy @RabbitListeners with an 'id' attribute"); } super.processListener(endpoint, rabbitListener, bean, adminTarget, beanName); }

Target:
protected void processListener(MethodRabbitListenerEndpoint endpoint, RabbitListener rabbitListener, Object bean, Object adminTarget, String beanName) { Object proxy = bean; String id = rabbitListener.id(); if (StringUtils.hasText(id)) { if (this.attributes.getBoolean("spy")) { proxy = Mockito.spy(proxy); this.listeners.put(id, proxy); } if (this.attributes.getBoolean("capture")) { try { ProxyFactoryBean pfb = new ProxyFactoryBean(); pfb.setProxyTargetClass(true); pfb.setTarget(proxy); CaptureAdvice advice = new CaptureAdvice(); pfb.addAdvice(advice); proxy = pfb.getObject(); this.listenerCapture.put(id, advice); } catch (Exception e) { logger.error("Failed to proxy @RabbitListener with id: " + id); } } } else { logger.info("The test harness can only proxy @RabbitListeners with an 'id' attribute"); } super.processListener(endpoint, rabbitListener, proxy, adminTarget, beanName); }
Source:
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException { final AccountManager am = AccountManager.get(mContext); String authToken = am.peekAuthToken(account, authTokenType); if (TextUtils.isEmpty(authToken)) { return getLoginBundledIntent(response, account.type, authTokenType, false); } final Bundle result = new Bundle(); result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type); result.putString(AccountManager.KEY_AUTHTOKEN, authToken); return result; }

Target:
public Bundle getAuthToken( AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException { AccountManager am = AccountManager.get(context); String authToken = am.peekAuthToken(account, authTokenType); if (TextUtils.isEmpty(authToken)) { return getLoginBundledIntent(response, account.type, authTokenType, false); } final Bundle result = new Bundle(); result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type); result.putString(AccountManager.KEY_AUTHTOKEN, authToken); return result; }
Source:
public static void addLocationExtension(Activity activity, MediaFeedData item) { Map<String, Object> extensions = ensureExtensions(activity); if(item.getLocation() != null) { Map<String, Object> coordinates = new HashMap<String, Object>(); coordinates.put("type", "Point"); coordinates.put("coordinates", "[" + item.getLocation().getLatitude() + "," + item.getLocation().getLongitude() + "]"); extensions.put("coordinates", coordinates); } }

Target:
public static void addLocationExtension(Activity activity, MediaFeedData item) { Map<String, Object> extensions = ensureExtensions(activity); if(item.getLocation() != null) { Map<String, Object> coordinates = new HashMap<String, Object>(); coordinates.put("type", "Point"); coordinates.put("coordinates", "[" + item.getLocation().getLongitude() + "," + item.getLocation().getLatitude() + "]"); extensions.put("coordinates", coordinates); } }
Source:
private static void validatePath(String path) { CommonHelper.assertNotBlank("path", path); if (!path.startsWith("/")) { final String msg = "Excluded path must begin with a /"; logger.error(msg); throw new TechnicalException(msg); } }

Target:
private static void validatePath(String path) { CommonHelper.assertNotBlank("path", path); if (!path.startsWith("/")) { throw new TechnicalException("Excluded path must begin with a /"); } }
Source:
void setActive(boolean isActive) { CallbackToFutureAdapter.Completer<Void> completerToSetException = null; boolean shouldResetDefault = false; synchronized (mActiveLock) { if (mIsActive == isActive) { return; } mIsActive = isActive; if (!mIsActive) { synchronized (mCompleterLock) { if (mPendingZoomRatioCompleter != null) { completerToSetException = mPendingZoomRatioCompleter; mPendingZoomRatioCompleter = null; } } shouldResetDefault = true; } } if (shouldResetDefault) { setZoomRatioInternal(DEFAULT_ZOOM_RATIO, true); } if (completerToSetException != null) { completerToSetException .setException(new OperationCanceledException("Camera is not active.")); } }

Target:
void setActive(boolean isActive) { CallbackToFutureAdapter.Completer<Void> completerToSetException = null; boolean shouldResetDefault = false; synchronized (mActiveLock) { if (mIsActive == isActive) { return; } mIsActive = isActive; if (!mIsActive) { synchronized (mCompleterLock) { if (mPendingZoomRatioCompleter != null) { completerToSetException = mPendingZoomRatioCompleter; mPendingZoomRatioCompleter = null; mPendingZoomCropRegion = null; } } shouldResetDefault = true; } } if (shouldResetDefault) { setLiveDataValue(mZoomRatioLiveData, DEFAULT_ZOOM_RATIO); setLiveDataValue(mZoomPercentageLiveData, 0f); mCamera2CameraControl.setCropRegion(null); } if (completerToSetException != null) { completerToSetException .setException(new OperationCanceledException("Camera is not active.")); } }
Source:
private void loadScript(ScriptWrapper scriptW, boolean adaptOldValues) { SessionScript script = getScriptInterface(scriptW); if (script == null) { log.warn( "The script " + scriptW.getName() + " does not properly implement the Session Script interface."); warnAndResetPanel( Constant.messages.getString( "session.method.script.dialog.error.text.interface", scriptW.getName())); return; } try { String[] requiredParams = script.getRequiredParamsNames(); String[] optionalParams = script.getOptionalParamsNames(); Map<String, String> oldValues = null; if (adaptOldValues && dynamicFieldsPanel != null) { oldValues = dynamicFieldsPanel.getFieldValues(); if (log.isDebugEnabled()) log.debug("Trying to adapt old values: " + oldValues); } this.dynamicFieldsPanel = new DynamicFieldsPanel(requiredParams, optionalParams); this.loadedScript = scriptW; if (adaptOldValues && oldValues != null) this.dynamicFieldsPanel.bindFieldValues(oldValues); this.dynamicContentPanel.removeAll(); this.dynamicContentPanel.add(dynamicFieldsPanel, BorderLayout.CENTER); this.dynamicContentPanel.revalidate(); } catch (Exception e) { getScriptsExtension().handleScriptException(scriptW, e); log.error("Error while calling session management script", e); warnAndResetPanel( Constant.messages.getString( "session.method.script.dialog.error.text.loading", ExceptionUtils.getRootCauseMessage(e))); } }

Target:
private void loadScript(ScriptWrapper scriptW, boolean adaptOldValues) { SessionScript script = getScriptInterface(scriptW); if (script == null) { LOG.warn( "The script " + scriptW.getName() + " does not properly implement the Session Script interface."); warnAndResetPanel( Constant.messages.getString( "session.method.script.dialog.error.text.interface", scriptW.getName())); return; } try { String[] requiredParams = script.getRequiredParamsNames(); String[] optionalParams = script.getOptionalParamsNames(); Map<String, String> oldValues = null; if (adaptOldValues && dynamicFieldsPanel != null) { oldValues = dynamicFieldsPanel.getFieldValues(); if (LOG.isDebugEnabled()) { LOG.debug("Trying to adapt old values: " + oldValues); } } this.dynamicFieldsPanel = new DynamicFieldsPanel(requiredParams, optionalParams); this.loadedScript = scriptW; if (adaptOldValues && oldValues != null) { this.dynamicFieldsPanel.bindFieldValues(oldValues); } this.dynamicContentPanel.removeAll(); this.dynamicContentPanel.add(dynamicFieldsPanel, BorderLayout.CENTER); this.dynamicContentPanel.revalidate(); } catch (Exception e) { getScriptsExtension().handleScriptException(scriptW, e); LOG.error("Error while calling session management script", e); warnAndResetPanel( Constant.messages.getString( "session.method.script.dialog.error.text.loading", ExceptionUtils.getRootCauseMessage(e))); } }
Source:
public Set<Territory> getNeighborsByMovementCost( final Territory territory, final Unit unit, final BigDecimal movementLeft, final Predicate<Territory> cond) { Preconditions.checkArgument( movementLeft.compareTo(BigDecimal.ZERO) >= 0, "MovementLeft must be non-negative: " + movementLeft); if (movementLeft.compareTo(BigDecimal.ZERO) == 0) { return Collections.emptySet(); } final Set<Territory> start = getNeighbors(territory, cond); if (movementLeft.compareTo(BigDecimal.ONE) <= 0) { return start; } final Set<Territory> neighbors = getNeighbors(start, new HashSet<>(start), movementLeft.intValue() - 1, cond); neighbors.remove(territory); return neighbors; }

Target:
public Set<Territory> getNeighborsByMovementCost( final Territory territory, final Unit unit, final BigDecimal movementLeft, final Predicate<Territory> cond) { Preconditions.checkNotNull(unit); Preconditions.checkArgument( movementLeft.compareTo(BigDecimal.ZERO) >= 0, "MovementLeft must be non-negative: " + movementLeft); if (movementLeft.compareTo(BigDecimal.ZERO) == 0) { return Collections.emptySet(); } final Set<Territory> neighbors = getNeighbors(territory, cond); if (movementLeft.compareTo(BigDecimal.ONE) <= 0) { return neighbors; } final Set<Territory> result = getNeighbors(neighbors, new HashSet<>(neighbors), movementLeft.intValue() - 1, cond); result.remove(territory); return result; }
Source:
private CPMProducer getProducer() throws CPMException { if (this.cpmProducer == null || this.cpmProducer.isClosed()) { log.debug("Creating new CPM producer for job message dispatch..."); CPMSession session = this.getSession(); CPMProducerConfig config = session.createProducerConfig(); this.cpmProducer = session.createProducer(config); log.debug("Created new CPM producer: {}", this.cpmProducer); } return this.cpmProducer; }

Target:
private synchronized CPMProducer getProducer() throws CPMException { if (this.cpmProducer == null || this.cpmProducer.isClosed()) { log.debug("Creating new CPM producer for job message dispatch..."); CPMSession session = this.getSession(); CPMProducerConfig config = session.createProducerConfig(); this.cpmProducer = session.createProducer(config); log.debug("Created new CPM producer: {}", this.cpmProducer); } return this.cpmProducer; }
Source:
private void doDefinition(WebService.NewAction action) { action.setDescription("Search for a collection of relevant rules matching a specified query.<br/>" + "Since 5.5, following fields in the response have been deprecated :" + "<ul>" + "<li>\"effortToFixDescription\" becomes \"gapDescription\"</li>" + "<li>\"debtRemFnCoeff\" becomes \"remFnGapMultiplier\"</li>" + "<li>\"defaultDebtRemFnCoeff\" becomes \"defaultRemFnGapMultiplier\"</li>" + "<li>\"debtRemFnOffset\" becomes \"remFnBaseEffort\"</li>" + "<li>\"defaultDebtRemFnOffset\" becomes \"defaultRemFnBaseEffort\"</li>" + "<li>\"debtOverloaded\" becomes \"remFnOverloaded\"</li>" + "</ul>" + "In 7.1, a new field 'scope' has been added to the response.") .setResponseExample(getClass().getResource("search-example.json")) .setSince("4.4") .setHandler(this); defineRuleSearchParameters(action); }

Target:
private void doDefinition(WebService.NewAction action) { action.setDescription("Search for a collection of relevant rules matching a specified query.<br/>" + "Since 5.5, following fields in the response have been deprecated :" + "<ul>" + "<li>\"effortToFixDescription\" becomes \"gapDescription\"</li>" + "<li>\"debtRemFnCoeff\" becomes \"remFnGapMultiplier\"</li>" + "<li>\"defaultDebtRemFnCoeff\" becomes \"defaultRemFnGapMultiplier\"</li>" + "<li>\"debtRemFnOffset\" becomes \"remFnBaseEffort\"</li>" + "<li>\"defaultDebtRemFnOffset\" becomes \"defaultRemFnBaseEffort\"</li>" + "<li>\"debtOverloaded\" becomes \"remFnOverloaded\"</li>" + "</ul>") .setResponseExample(getClass().getResource("search-example.json")) .setSince("4.4") .setHandler(this); defineRuleSearchParameters(action); }
Source:
public void watch(PodActionHandler handler) throws InfrastructureException { handlers.add(handler); if (watch == null) { try (OpenShiftClient client = clientFactory.create()) { final Watcher<Pod> watcher = new Watcher<Pod>() { @Override public void eventReceived(Action action, Pod pod) { handlers.forEach(h -> h.handle(action, pod)); } @Override public void onClose(KubernetesClientException ignored) }; watch = client.pods().inNamespace(namespace).watch(watcher); } catch (KubernetesClientException ex) { throw new InfrastructureException(ex.getMessage()); } } }

Target:
public void watch(PodActionHandler handler) throws InfrastructureException { if (watch == null) { final Watcher<Pod> watcher = new Watcher<Pod>() { @Override public void eventReceived(Action action, Pod pod) { handlers.forEach(h -> h.handle(action, pod)); } @Override public void onClose(KubernetesClientException ignored) }; try (OpenShiftClient client = clientFactory.create()) { watch = client.pods().inNamespace(namespace).watch(watcher); } catch (KubernetesClientException ex) { throw new InfrastructureException(ex.getMessage()); } } handlers.add(handler); }
Source:
protected static VariantContext flipIndel(final VariantContext source, final LiftOver liftOver, final ReferenceSequence referenceSequence) { if (!source.isBiallelic()) return null; final Locatable target = getFlippedLocation(source, liftOver); if (target == null) return null; final Map<Allele, Allele> reverseComplementAlleleMap = new HashMap<>(10); reverseComplementAlleleMap.clear(); final List<Allele> alleles = new ArrayList<>(); for (final Allele oldAllele : source.getAlleles()) { final String alleleWithoutHead = oldAllele.getBaseString().substring(1, oldAllele.length()); final char refBase = (char) referenceSequence.getBases()[target.getStart() - 1]; final Allele fixedAllele = Allele.create(refBase + SequenceUtil.reverseComplement(alleleWithoutHead), oldAllele.isReference()); alleles.add(fixedAllele); reverseComplementAlleleMap.put(oldAllele, fixedAllele); } VariantContextBuilder builder = new VariantContextBuilder(source.getSource(), target.getContig(), target.getStart(), target.getEnd(), alleles); builder.id(source.getID()); builder.attributes(source.getAttributes()); builder.genotypes(fixGenotypes(source.getGenotypes(), reverseComplementAlleleMap)); builder.filters(source.getFilters()); builder.log10PError(source.getLog10PError()); return leftAlignVariant(builder.make(), referenceSequence); }

Target:
protected static VariantContext flipIndel(final VariantContext source, final LiftOver liftOver, final ReferenceSequence referenceSequence) { if (!source.isBiallelic()) return null; final Interval originalLocus = new Interval(source.getContig(), source.getStart(), source.getEnd()); final Locatable target = liftOver.liftOver(originalLocus); if (target == null) return null; final boolean addToStart = target.getStart() > 1; final Map<Allele, Allele> reverseComplementAlleleMap = new HashMap<>(2); reverseComplementAlleleMap.clear(); final List<Allele> alleles = new ArrayList<>(); for (final Allele oldAllele : source.getAlleles()) { final StringBuilder alleleBuilder = new StringBuilder(target.getEnd() - target.getStart() + 1); if (addToStart) alleleBuilder.append((char) referenceSequence.getBases()[target.getStart() - 2]); alleleBuilder.append(SequenceUtil.reverseComplement(oldAllele.getBaseString().substring(1, oldAllele.length()))); if (!addToStart) alleleBuilder.append((char) referenceSequence.getBases()[target.getEnd() - 1]); final Allele fixedAllele = Allele.create(alleleBuilder.toString(), oldAllele.isReference()); alleles.add(fixedAllele); reverseComplementAlleleMap.put(oldAllele, fixedAllele); } final VariantContextBuilder builder = new VariantContextBuilder(source.getSource(), target.getContig(), target.getStart() - (addToStart ? 1 : 0), target.getEnd() - (addToStart ? 1 : 0), alleles); builder.id(source.getID()); builder.attributes(source.getAttributes()); builder.genotypes(fixGenotypes(source.getGenotypes(), reverseComplementAlleleMap)); builder.filters(source.getFilters()); builder.log10PError(source.getLog10PError()); return leftAlignVariant(builder.make(), referenceSequence); }
Source:
Promise<List<JSITDefinitions>> loadDMNDefinitions() { final List<JSITDefinitions> otherDefinitions = new Vector<>(); return contentService.getFilteredItems(DMN_FILES_PATTERN).then(list -> { final List<Promise<JSITDefinitions>> fileLoadPromises = new ArrayList<>(); for (final String file : list) { final Promise<JSITDefinitions> promise = loadDefinitionFromFile(file, otherDefinitions); fileLoadPromises.add(promise); } return promises.all(fileLoadPromises.toArray(new Promise[]{})).then(v -> promises.resolve(otherDefinitions)); }); }

Target:
Promise<Map<String, JSITDefinitions>> loadDMNDefinitions() { return contentService.getFilteredItems(DMN_FILES_PATTERN, ResourceListOptions.assetFolder()) .then(list -> { if (list.length == 0) { return promises.resolve(Collections.emptyMap()); } else { final Map<String, JSITDefinitions> otherDefinitions = new ConcurrentHashMap<>(); return promises.all(Arrays.asList(list), (String file) -> loadDefinitionFromFile(file, otherDefinitions)) .then(v -> promises.resolve(otherDefinitions)); } }); }
Source:
public long getRetainedBytes() { return INSTANCE_SIZE + pageDataSink.getRetainedSizeInBytes(); }

Target:
public long getRetainedBytes() { return INSTANCE_SIZE + retainedBytes + dataSink.getRetainedSizeInBytes(); }
Source:
private void startCleanup() throws DotHibernateException { try { HibernateUtil.startTransaction(); cleanUpOrphanRelationships(); HibernateUtil.commitTransaction(); FixAssetsProcessStatus.setErrorsFixed(modifiedData.size()); } catch (DotHibernateException e1) { Logger.error(this, "Unable to clean orphaned relationships.", e1); HibernateUtil.rollbackTransaction(); modifiedData.clear(); } catch (SQLException e2) { Logger.error(this, "There was an unexpected problem with cleaning up relationship in Database.", e2); HibernateUtil.rollbackTransaction(); modifiedData.clear(); } finally { flushCacheRegions(); } }

Target:
private void startCleanup() throws DotDataException { try { cleanUpOrphanRelationships(); FixAssetsProcessStatus.setErrorsFixed(modifiedData.size()); } catch (SQLException | DotHibernateException e1) { Logger.error(this, "There was an unexpected problem with cleaning up relationship in Database.", e1); modifiedData.clear(); } }
Source:
private void verifyPackChecksum(long position, MessageDigest md, DfsReader ctx) throws IOException { if (md != null) { byte[] buf = new byte[20]; byte[] actHash = md.digest(); if (ctx.copy(this, position, buf, 0, 20) != 20) { setInvalid(); throw new IOException(MessageFormat.format( JGitText.get().packfileIsTruncated, getPackName())); } if (!Arrays.equals(actHash, buf)) { setInvalid(); throw new IOException(MessageFormat.format( JGitText.get().packfileCorruptionDetected, getPackName())); } } }

Target:
private void verifyPackChecksum(long position, MessageDigest md, DfsReader ctx) throws IOException { if (md != null) { byte[] buf = new byte[20]; byte[] actHash = md.digest(); if (ctx.copy(this, position, buf, 0, 20) != 20) throw packfileIsTruncated(); if (!Arrays.equals(actHash, buf)) { invalid = true; throw new IOException(MessageFormat.format( JGitText.get().packfileCorruptionDetected, getPackName())); } } }
Source:
private void addEntriesToPane(FlowPane pane, Collection<? extends BibEntryType> entries) { for (BibEntryType entryType : entries) { Button entryButton = new Button(entryType.getType().getDisplayName()); entryButton.setUserData(entryType); entryButton.setOnAction(event -> setEntryTypeForReturnAndClose(Optional.of(entryType))); pane.getChildren().add(entryButton); String description = getDescription(entryType); if (StringUtil.isNotBlank(description)) { Tooltip tooltip = new Tooltip(); tooltip.setText(description); entryButton.setTooltip(tooltip); } } }

Target:
private void addEntriesToPane(FlowPane pane, Collection<? extends BibEntryType> entries) { for (BibEntryType entryType : entries) { Button entryButton = new Button(entryType.getType().getDisplayName()); entryButton.setUserData(entryType); entryButton.setOnAction(event -> setEntryTypeForReturnAndClose(Optional.of(entryType))); pane.getChildren().add(entryButton); EntryType selectedType = entryType.getType(); String description = getDescription(selectedType); if (StringUtil.isNotBlank(description)) { Screen currentScreen = Screen.getPrimary(); double maxWidth = currentScreen.getBounds().getWidth(); Tooltip tooltip = new Tooltip(description); tooltip.setMaxWidth((maxWidth * 2) / 3); tooltip.setWrapText(true); entryButton.setTooltip(tooltip); } } }
Source:
private Trigger createTrigger(Server server) throws ParseException { int runPeriod = configuration.getRunPeriod(); Trigger trigger; if (server.getCronExpression() != null && CronExpression.isValidExpression(server.getCronExpression())) { CronTrigger cTrigger = new CronTrigger(); cTrigger.setCronExpression(server.getCronExpression()); trigger = cTrigger; } else { if (server.getRunPeriodSeconds() != null) { runPeriod = server.getRunPeriodSeconds(); } trigger = TriggerUtils.makeSecondlyTrigger(runPeriod); } trigger.setName(server.getHost() + ":" + server.getPort() + "-" + Long.toString(System.nanoTime()) + "-" + UUID.randomUUID().toString().substring(0, 8)); trigger.setStartTime(computeSpreadStartDate(runPeriod)); return trigger; }

Target:
private Trigger createTrigger(Server server) throws ParseException { int runPeriod = configuration.getRunPeriod(); Trigger trigger; if (server.getCronExpression() != null && CronExpression.isValidExpression(server.getCronExpression())) { CronTrigger cTrigger = new CronTrigger(); cTrigger.setCronExpression(server.getCronExpression()); trigger = cTrigger; } else { if (server.getRunPeriodSeconds() != null) { runPeriod = server.getRunPeriodSeconds(); } trigger = TriggerUtils.makeSecondlyTrigger(runPeriod); } trigger.setName(server.getHost() + ":" + server.getPort() + "-" + Long.toString(System.nanoTime()) + "-" + Long.toHexString(random.nextLong())); trigger.setStartTime(computeSpreadStartDate(runPeriod)); return trigger; }
Source:
private int severityForElapsedTime(long nanoTime) { final int severity; if (job.isUser() && isCanceledHitCount == 0 && options.alwaysReportNonCancelableUserJobAsError()) { severity = IStatus.ERROR; } else if (nanoTime >= options.errorThreshold()) { severity = IStatus.ERROR; } else if (nanoTime >= options.warningThreshold()) { severity = IStatus.WARNING; } else if (!job.isSystem() && options.doNotReportNonCancelableFastSystemJob()) { severity = IStatus.INFO; } else { severity = IStatus.OK; } return severity; }

Target:
private int severityForElapsedTime(long nanoTime) { final int severity; if (job.isUser() && isCanceledHitCount == 0 && options.alwaysReportNonCancelableUserJobAsError()) { severity = IStatus.ERROR; } else if (nanoTime >= options.errorThreshold()) { severity = IStatus.ERROR; } else if (nanoTime >= options.warningThreshold()) { severity = IStatus.WARNING; } else { severity = IStatus.OK; } return severity; }
Source:
public void prepareToRead(RecordReader recordReader, PigSplit pigSplit) throws IOException { RecordReaderValueIterator<Key, EventWritable> rri = new RecordReaderValueIterator<Key, EventWritable>(recordReader); Iterable<Event> xformed = Iterables.transform(ImmutableList.copyOf(rri), new GettableTransform<Event>()); itr = new TupleStoreIterator<Event>(xformed); }

Target:
public void prepareToRead(RecordReader recordReader, PigSplit pigSplit) throws IOException { RecordReaderValueIterator<Key, EventWritable> rri = new RecordReaderValueIterator<Key, EventWritable>(recordReader); Iterator<Event> xformed = Iterators.transform(rri, new GettableTransform<Event>()); itr = new TupleStoreIterator<Event>(xformed); }
Source:
private void setVdsmNamesInVdsInterfaces(Network network, List<VdsNetworkInterface> interfaces) { List<VdsNetworkInterface> interfacesToUpdate = new LinkedList<>(); interfaces.stream().filter(iface -> Objects.equals(iface.getNetworkName(), network.getName())).forEach(iface -> { iface.setNetworkName(network.getVdsmName()); interfacesToUpdate.add(iface); }); for (VdsNetworkInterface iface : interfaces) { if (Objects.equals(iface.getNetworkName(), network.getName())) { iface.setNetworkName(network.getVdsmName()); interfacesToUpdate.add(iface); } } interfaceDao.massUpdateInterfacesForVds(interfacesToUpdate); }

Target:
private void setVdsmNamesInVdsInterfaces(Network network, List<VdsNetworkInterface> interfaces) { List<VdsNetworkInterface> interfacesToUpdate = new LinkedList<>(); interfaces.stream().filter(iface -> Objects.equals(iface.getNetworkName(), network.getName())).forEach(iface -> { iface.setNetworkName(network.getVdsmName()); interfacesToUpdate.add(iface); }); interfaceDao.massUpdateInterfacesForVds(interfacesToUpdate); }
Source:
public void testListips() throws InterruptedException { List<ServerIp> ips = serverApi().listIps(currentServer.id()); currentIP = ips.get(0); assertNotNull(ips); assertFalse(ips.isEmpty()); Assert.assertTrue(ips.size() > 0); }

Target:
public void testListips() throws InterruptedException { List<ServerIp> ips = serverApi().listIps(currentServer.id()); currentIP = ips.get(0); assertNotNull(ips); Assert.assertTrue(ips.size() > 0); }
Source:
private JarEntry getRealFileEntry(JarFile jar, String file) { String realFile = file.replaceAll("\\.html$", ".md"); JarEntry entry = jar.getJarEntry(realFile); return entry; }

Target:
private JarEntry getRealFileEntry(JarFile jar, String file) { return jar.getJarEntry(file.replaceAll("\\.html$", ".md")); }
Source:
void onEditMode(@SuppressWarnings("unused") ClickEvent e) { fileTableMode = FileTable.Mode.EDIT; refreshFileTable(); editMode.setVisible(false); reply.setVisible(false); addFile.setVisible(true); reviewMode.setVisible(true); }

Target:
void onEditMode(@SuppressWarnings("unused") ClickEvent e) { fileTableMode = FileTable.Mode.EDIT; refreshFileTable(); editMode.setVisible(false); addFile.setVisible(true); reviewMode.setVisible(true); }
Source:
public void test_of_CurrencyCurrencyDouble() { FxRate test = FxRate.of(GBP, USD, 1.5d); assertEquals(test.getPair(), CurrencyPair.of(GBP, USD)); assertEquals(test.getRate(), 1.5d, TOLERANCE); assertEquals(test.toString(), "GBP/USD 1.5"); }

Target:
public void test_of_CurrencyCurrencyDouble() { FxRate test = FxRate.of(GBP, USD, 1.5d); assertEquals(test.getPair(), CurrencyPair.of(GBP, USD)); assertEquals(test.getRate(), 1.5d, 0); assertEquals(test.toString(), "GBP/USD 1.5"); }
Source:
public void testMathFunctions1() throws Exception { doTest(readFile("/streamline-udf-math1.json"), getTuple()); new Verifications() { { String streamId; Tuple anchor; List<List<Object>> tuples = new ArrayList<>(); mockCollector.emit(streamId = withCapture(), anchor = withCapture(), withCapture(tuples)); Assert.assertEquals(1, tuples.size()); Assert.assertEquals("POWER 1024.0 ABS 1.0 MOD 0 SQRT 1.4142135623730951 LN 0.6931471805599453" + " LOG10 0.3010299956639812 EXP 7.38905609893065 CEIL 2.0 FLOOR 1.0", ((StreamlineEvent)(tuples.get(0).get(0))).get("body")); } }; }

Target:
public void testMathFunctions1() throws Exception { doTest(readFile("/streamline-udf-math1.json"), getTuple()); new Verifications() { { String streamId; Tuple anchor; List<List<Object>> tuples = new ArrayList<>(); double delta = .0001; mockCollector.emit(streamId = withCapture(), anchor = withCapture(), withCapture(tuples)); Assert.assertEquals(1, tuples.size()); String res[] = (((StreamlineEvent)(tuples.get(0).get(0))).get("body")).toString().split(" "); Assert.assertEquals("POWER", res[0]); Assert.assertEquals(1024.0, Double.valueOf(res[1]), delta); Assert.assertEquals("ABS", res[2]); Assert.assertEquals(1.0, Double.valueOf(res[3]), delta); Assert.assertEquals("MOD", res[4]); Assert.assertEquals(0, Double.valueOf(res[5]), delta); Assert.assertEquals("SQRT", res[6]); Assert.assertEquals(1.4142135623730951, Double.valueOf(res[7]), delta); Assert.assertEquals("LN", res[8]); Assert.assertEquals(0.6931471805599453, Double.valueOf(res[9]), delta); Assert.assertEquals("LOG10", res[10]); Assert.assertEquals(0.3010299956639812, Double.valueOf(res[11]), delta); Assert.assertEquals("EXP", res[12]); Assert.assertEquals(7.38905609893065, Double.valueOf(res[13]), delta); Assert.assertEquals("CEIL", res[14]); Assert.assertEquals(2.0, Double.valueOf(res[15]), delta); Assert.assertEquals("FLOOR", res[16]); Assert.assertEquals(1.0, Double.valueOf(res[17]), delta); } }; }
Source:
public void testSerialize() { Set<Property> props = new HashSet<Property>(); Property prop1 = new Property(); prop1.setName("testProp1"); prop1.setValue("testValue1"); prop1.setType(PropertyType.Text); props.add(prop1); ProducerInfo pi = new ProducerInfo(); pi.setId("testId"); pi.setProperties(props); pi.setTimestamp(System.currentTimeMillis()); ProducerInfo result = null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(pi); oos.flush(); oos.close(); baos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); result = (ProducerInfo) ois.readObject(); bais.close(); ois.close(); } catch (Exception e) { e.printStackTrace(); fail("Failed to serialize: " + e); } assertNotNull(result); assertEquals(result, pi); }

Target:
public void testSerialize() { Set<Property> props = new HashSet<Property>(); Property prop1 = new Property(); prop1.setName("testProp1"); prop1.setValue("testValue1"); prop1.setType(PropertyType.Text); props.add(prop1); Property prop2 = new Property(); prop2.setName("testProp2"); prop2.setValue("testValue2"); prop2.setType(PropertyType.Number); props.add(prop2); ProducerInfo pi = new ProducerInfo(); pi.setId("testId"); pi.setDuration(500); pi.setFragmentId("fragId"); pi.setHostAddress("hostAddr"); pi.setHostName("hostName"); pi.setMultipleConsumers(true); pi.setSourceOperation("sourceOp"); pi.setSourceUri("sourceUri"); pi.setProperties(props); pi.setTimestamp(System.currentTimeMillis()); ProducerInfo result = null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(pi); oos.flush(); oos.close(); baos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); result = (ProducerInfo) ois.readObject(); bais.close(); ois.close(); } catch (Exception e) { e.printStackTrace(); fail("Failed to serialize: " + e); } assertNotNull(result); assertEquals(result, pi); }
Source:
private void write(TempFile tempFile, Type writerType, List<String> data) throws IOException { OrcWriter writer = new OrcWriter(new OutputStreamOrcDataSink(new FileOutputStream(tempFile.getFile())), com.google.common.collect.ImmutableList.of(STRUCT_COL_NAME), com.google.common.collect.ImmutableList.of(writerType), ORC, NONE, new OrcWriterOptions().withStripeMinSize(new DataSize(0, MEGABYTE)) .withStripeMaxSize(new DataSize(32, MEGABYTE)) .withStripeMaxRowCount(ORC_STRIPE_SIZE) .withRowGroupMaxRowCount(ORC_ROW_GROUP_SIZE) .withDictionaryMaxMemory(new DataSize(32, MEGABYTE)), ImmutableMap.of(), HIVE_STORAGE_TIME_ZONE, true, OrcWriteValidation.OrcWriteValidationMode.BOTH, new OrcWriterStats()); Block[] fieldBlocks = new Block[data.size()]; int entries = 10; boolean[] rowIsNull = new boolean[entries]; Arrays.fill(rowIsNull, false); BlockBuilder blockBuilder = TEST_DATA_TYPE.createBlockBuilder(null, entries); for (int i = 0; i < data.size(); i++) { byte[] bytes = data.get(i).getBytes(); for (int j = 0; j < entries; j++) { blockBuilder .writeBytes(Slices.wrappedBuffer(bytes, 0, bytes.length), 0, bytes.length); blockBuilder.closeEntry(); } fieldBlocks[i] = blockBuilder.build(); blockBuilder = blockBuilder.newBlockBuilderLike(null); } Block rowBlock = RowBlock.fromFieldBlocks(rowIsNull, fieldBlocks); writer.write(new Page(rowBlock)); writer.close(); }

Target:
private void write(TempFile tempFile, Type writerType, List<String> data) throws IOException { OrcWriter writer = new OrcWriter( new OutputStreamOrcDataSink( new FileOutputStream(tempFile.getFile())), ImmutableList.of(STRUCT_COL_NAME), ImmutableList.of(writerType), ORC, NONE, new OrcWriterOptions().withStripeMinSize(new DataSize(0, MEGABYTE)).withStripeMaxSize(new DataSize(32, MEGABYTE)).withStripeMaxRowCount(ORC_STRIPE_SIZE) .withRowGroupMaxRowCount(ORC_ROW_GROUP_SIZE).withDictionaryMaxMemory(new DataSize(32, MEGABYTE)), ImmutableMap.of(), HIVE_STORAGE_TIME_ZONE, true, BOTH, new OrcWriterStats()); Block[] fieldBlocks = new Block[data.size()]; int entries = 10; boolean[] rowIsNull = new boolean[entries]; Arrays.fill(rowIsNull, false); BlockBuilder blockBuilder = TEST_DATA_TYPE.createBlockBuilder(null, entries); for (int i = 0; i < data.size(); i++) { byte[] bytes = data.get(i).getBytes(); for (int j = 0; j < entries; j++) { blockBuilder.writeBytes(Slices.wrappedBuffer(bytes), 0, bytes.length); blockBuilder.closeEntry(); } fieldBlocks[i] = blockBuilder.build(); blockBuilder = blockBuilder.newBlockBuilderLike(null); } Block rowBlock = RowBlock.fromFieldBlocks(rowIsNull, fieldBlocks); writer.write(new Page(rowBlock)); writer.close(); }
Source:
public void testNotifyCheckpointComplete() throws Exception { TestTaskStateManager stateManager = new TestTaskStateManager(); MockEnvironment mockEnvironment = MockEnvironment.builder().setTaskStateManager(stateManager).build(); SubtaskCheckpointCoordinator subtaskCheckpointCoordinator = new MockSubtaskCheckpointCoordinatorBuilder() .setEnvironment(mockEnvironment) .build(); long checkpointId = 42L; { boolean success = subtaskCheckpointCoordinator.notifyCheckpointComplete(checkpointId, mock(OperatorChain.class), () -> true); assertTrue(success); assertEquals(checkpointId, stateManager.getNotifiedCompletedCheckpointId()); } long newCheckpointId = checkpointId + 1; { boolean success = subtaskCheckpointCoordinator.notifyCheckpointComplete(newCheckpointId, mock(OperatorChain.class), () -> false); assertFalse(success); assertEquals(newCheckpointId, stateManager.getNotifiedCompletedCheckpointId()); } }

Target:
public void testNotifyCheckpointComplete() throws Exception { TestTaskStateManager stateManager = new TestTaskStateManager(); MockEnvironment mockEnvironment = MockEnvironment.builder().setTaskStateManager(stateManager).build(); SubtaskCheckpointCoordinator subtaskCheckpointCoordinator = new MockSubtaskCheckpointCoordinatorBuilder() .setEnvironment(mockEnvironment) .build(); final OperatorChain<?, ?> operatorChain = new OperatorChain<>( new MockStreamTaskBuilder(new DummyEnvironment()).build(), new NonRecordWriter<>()); long checkpointId = 42L; { subtaskCheckpointCoordinator.notifyCheckpointComplete(checkpointId, operatorChain, () -> true); assertEquals(checkpointId, stateManager.getNotifiedCompletedCheckpointId()); } long newCheckpointId = checkpointId + 1; { subtaskCheckpointCoordinator.notifyCheckpointComplete(newCheckpointId, operatorChain, () -> false); assertEquals(newCheckpointId, stateManager.getNotifiedCompletedCheckpointId()); } }
Source:
public void aNotBTest() { int lgK = 4; IntegerSummary.Mode a1Mode = IntegerSummary.Mode.AlwaysOne; IntegerSketch a1Sk1 = new IntegerSketch(lgK, a1Mode); IntegerSketch a1Sk2 = null; AnotB<IntegerSummary> anotb = new AnotB<>(); for (int i = 0; i < 5; i++) { a1Sk1.update(i, 1); } anotb.update(a1Sk1, a1Sk2); anotb.getResult(); }

Target:
public void aNotBTest() { int lgK = 4; int u = 5; IntegerSummary.Mode a1Mode = IntegerSummary.Mode.AlwaysOne; IntegerSketch a1Sk1 = new IntegerSketch(lgK, a1Mode); IntegerSketch a1Sk2 = null; AnotB<IntegerSummary> anotb = new AnotB<>(); for (int i = 0; i < u; i++) { a1Sk1.update(i, 1); } anotb.update(a1Sk1, a1Sk2); CompactSketch<IntegerSummary> cSk = anotb.getResult(); assertEquals((int)cSk.getEstimate(), u); }