auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public ILaunchDescriptor getDescriptor(Object element) { if (element instanceof ILaunchConfiguration) { ILaunchConfiguration config = (ILaunchConfiguration) element; try { if( config.getType().isPublic()) { DefaultLaunchDescriptor descriptor = descriptors.get(config); if (descriptor == null) { descriptor = new DefaultLaunchDescriptor(this, config); descriptors.put(config, descriptor); } return descriptor; } } catch(CoreException ce) { ce.printStackTrace(); } catch(NullPointerException npe) { npe.printStackTrace(); } } return null; }

Target:
public ILaunchDescriptor getDescriptor(Object element) { if (element instanceof ILaunchConfiguration) { ILaunchConfiguration config = (ILaunchConfiguration) element; try { if( config.getType().isPublic() && !(config.getAttribute(ILaunchManager.ATTR_PRIVATE, false))) { DefaultLaunchDescriptor descriptor = descriptors.get(config); if (descriptor == null) { descriptor = new DefaultLaunchDescriptor(this, config); descriptors.put(config, descriptor); } return descriptor; } } catch(CoreException ce) { Activator.log(ce.getStatus()); } catch(NullPointerException npe) { npe.printStackTrace(); } } return null; }
Source:
static private Class<?> getReturnType(Method method) { if (isSuspend(method)) { return getSuspendReturnType(method).resolve(); } else { return method.getReturnType(); } }

Target:
static private Class<?> getReturnType(Method method) { if (isSuspend(method)) { final Class<?> returnType = getSuspendReturnType(method).resolve(); Assert.notNull(returnType, "returnType cannot be null"); return returnType; } else { return method.getReturnType(); } }
Source:
private String createHeader(Detail shortDetail) { EvaluationContext context = mSession.getEvaluationContext(); DetailField[] fields = shortDetail.getFields(); StringBuilder row = new StringBuilder(); int i = 0; for(DetailField field : fields) { Object o = field.getHeader().evaluate(context); String s; if(!(o instanceof String)) { s = ""; } else { s = (String)o; } int widthHint = SCREEN_WIDTH / fields.length; try { widthHint = Integer.parseInt(field.getHeaderWidthHint()); } catch(Exception e) { } addPaddedStringToBuilder(row, s, widthHint); i++; if(i != fields.length) { row.append(" | "); } } return row.toString(); }

Target:
private String createHeader(Detail shortDetail) { EvaluationContext context = mSession.getEvaluationContext(); DetailField[] fields = shortDetail.getFields(); StringBuilder row = new StringBuilder(); int i = 0; for (DetailField field : fields) { String s = field.getHeader().evaluate(context); int widthHint = SCREEN_WIDTH / fields.length; try { widthHint = Integer.parseInt(field.getHeaderWidthHint()); } catch (Exception e) { } addPaddedStringToBuilder(row, s, widthHint); i++; if (i != fields.length) { row.append(" | "); } } return row.toString(); }
Source:
public MyFacesInjectionProvider() { if (StartupContext.getInjectionContainer() != null) { this.injectionContainer = StartupContext.getInjectionContainer(); } }

Target:
public MyFacesInjectionProvider() { this.injectionContainer = StartupContext.getInjectionContainer(); }
Source:
public void register(final InstanceInfo info) throws Exception { long expiryTime = System.currentTimeMillis() + info.getLeaseInfo().getRenewalIntervalInSecs() * 1000; batchingDispatcher.process( "register#" + info.getId(), new InstanceReplicationTask(targetHost, Action.Register, info, null, true) { public HttpResponse<Void> execute() { return replicationClient.register(info); } }, expiryTime ); }

Target:
public void register(final InstanceInfo info) throws Exception { long expiryTime = System.currentTimeMillis() + info.getLeaseInfo().getRenewalIntervalInSecs() * 1000; batchingDispatcher.process( taskId("register", info), new InstanceReplicationTask(targetHost, Action.Register, info, null, true) { public HttpResponse<Void> execute() { return replicationClient.register(info); } }, expiryTime ); }
Source:
public void submit(Statement statement, QueryExecution queryExecution, SelectionContext<C> selectionContext, Executor executor) { checkState(configurationManager.get() != null, "configurationManager not set"); int activeWorkerCount = getActiveWorkerCount(); if (!acceptQueries.get() && !shouldQueueQueriesWithInsufficientWorkers) { if (nanosSince(initialNanos).compareTo(initializationTimeout) < 0 && activeWorkerCount < initializationRequiredWorkers) { queryExecution.fail(new PrestoException(SERVER_STARTING_UP, String.format("Cluster is still initializing, there are insufficient active worker nodes (%s) to run query. Waiting for (%s) active worker nodes.", activeWorkerCount, initializationRequiredWorkers))); } acceptQueries.set(true); } createGroupIfNecessary(selectionContext, executor); groups.get(selectionContext.getResourceGroupId()).run(queryExecution, shouldQueueQueries()); }

Target:
public void submit(Statement statement, QueryExecution queryExecution, SelectionContext<C> selectionContext, Executor executor) { checkState(configurationManager.get() != null, "configurationManager not set"); int activeWorkerCount = getActiveWorkerCount(); if (!acceptQueries.get() && !shouldPendQueriesUntilScaleout()) { if (nanosSince(initialNanos).compareTo(initializationTimeout) < 0 && activeWorkerCount < initializationRequiredWorkers) { queryExecution.fail(new PrestoException(SERVER_STARTING_UP, String.format("Cluster is still initializing, there are insufficient active worker nodes (%s) to run query. Waiting for (%s) active worker nodes.", activeWorkerCount, initializationRequiredWorkers))); } acceptQueries.set(true); } createGroupIfNecessary(selectionContext, executor); groups.get(selectionContext.getResourceGroupId()).run(queryExecution, shouldPendQueriesUntilScaleout()); }
Source:
public static @Nullable PercentType toColorTemperaturePercentType(State lightState) { ColorMode colorMode = lightState.getColorMode(); if (colorMode != null && !colorMode.equals(ColorMode.CT)) { return null; } int percent = (int) Math .round(((lightState.getColorTemperature() - MIN_COLOR_TEMPERATURE) * 100.0) / COLOR_TEMPERATURE_RANGE); return new PercentType(restrictToBounds(percent)); }

Target:
public static PercentType toColorTemperaturePercentType(State lightState) { int percent = (int) Math .round(((lightState.getColorTemperature() - MIN_COLOR_TEMPERATURE) * 100.0) / COLOR_TEMPERATURE_RANGE); return new PercentType(restrictToBounds(percent)); }
Source:
default Collation asc() { return Collation.of(Matchers.extract(this).path(), Ordering.Direction.ASCENDING); }

Target:
default Ordering asc() { return Collation.of(Matchers.extract(this).path(), Ordering.Direction.ASCENDING); }
Source:
public FormValidation doReloadTypes(@QueryParameter String credential, @AncestorInPath AbstractProject project) { if (project == null) { if (!project.hasPermission(Jenkins.ADMINISTER)) { return FormValidation.ok(); } } else if (!project.hasPermission(Item.EXTENDED_READ) && !project.hasPermission(CredentialsProvider.USE_ITEM)) { return FormValidation.ok(); } project.checkPermission(AbstractProject.CONFIGURE); Credential overridingcredential = RepositoryUtils.retrieveOverridingCredentialFromProject(project); try { DeployitServer deployitServer = RepositoryUtils.getDeployitServer(credential, overridingcredential, project); if (null == deployitServer) return error("Server not found for credential."); deployitServer.reload(); return ok("Types reloaded from XL Deploy version " + deployitServer.getServerInfo().getVersion() + " at " + deployitServer.getBooterConfig().getUrl()); } catch (DeployitPluginException ex) { return error(String.format("Unable to reload types. Cause: %s.", ex.getMessage())); } }

Target:
public FormValidation doReloadTypes(@QueryParameter String credential, @AncestorInPath AbstractProject project) { project.checkPermission(Jenkins.ADMINISTER); Credential overridingcredential = RepositoryUtils.retrieveOverridingCredentialFromProject(project); try { DeployitServer deployitServer = RepositoryUtils.getDeployitServer(credential, overridingcredential, project); if (null == deployitServer) return error("Server not found for credential."); deployitServer.reload(); return ok("Types reloaded from XL Deploy version " + deployitServer.getServerInfo().getVersion() + " at " + deployitServer.getBooterConfig().getUrl()); } catch (DeployitPluginException ex) { return error(String.format("Unable to reload types. Cause: %s.", ex.getMessage())); } }
Source:
public void apply(EntitySpec<?> entitySpec, String nodeId, ToscaApplication toscaApplication) { final Iterable<String> artifacts = getToscaFacade().getArtifacts(nodeId, toscaApplication); if (Iterables.isEmpty(artifacts)) { return; } final Map<String, String> filesToCopy = MutableMap.of(); for (String artifactId : artifacts) { Optional<Path> optionalResourcesRootPath = getToscaFacade().getArtifactPath(nodeId, toscaApplication, artifactId); if(!optionalResourcesRootPath.isPresent()) { continue; } BrooklynDslDeferredSupplier deferredRunDir = BrooklynDslCommon.attributeWhenReady("run.dir"); entitySpec.configure(SoftwareProcess.SHELL_ENVIRONMENT.subKey(artifactId), deferredRunDir); try { Files.walkFileTree(optionalResourcesRootPath.get(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { filesToCopy.put(file.toAbsolutePath().toString(), file.getFileName().toString()); return FileVisitResult.CONTINUE; } }); } catch (IOException e) { LOG.warn("Cannot parse CSAR resources", e); } } entitySpec.configure(SoftwareProcess.RUNTIME_FILES, filesToCopy); }

Target:
public void apply(EntitySpec<?> entitySpec, String nodeId, ToscaApplication toscaApplication) { final Iterable<String> artifacts = getToscaFacade().getArtifacts(nodeId, toscaApplication); if (Iterables.isEmpty(artifacts)) { return; } final Map<String, String> filesToCopy = MutableMap.of(); for (final String artifactId : artifacts) { Optional<Path> optionalResourcesRootPath = getToscaFacade().getArtifactPath(nodeId, toscaApplication, artifactId); if(!optionalResourcesRootPath.isPresent()) { continue; } BrooklynDslDeferredSupplier deferredRunDir = (BrooklynDslDeferredSupplier) BrooklynDslCommon.formatString("%s/%s", BrooklynDslCommon.attributeWhenReady("run.dir"), artifactId); entitySpec.configure(SoftwareProcess.SHELL_ENVIRONMENT.subKey(artifactId), deferredRunDir); try { Files.walkFileTree(optionalResourcesRootPath.get(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { filesToCopy.put(file.toAbsolutePath().toString(), artifactId + "/" + file.getFileName().toString()); return FileVisitResult.CONTINUE; } }); } catch (IOException e) { LOG.warn("Cannot parse CSAR resources", e); } } entitySpec.configure(SoftwareProcess.RUNTIME_FILES, filesToCopy); }
Source:
public Object next() { Object obj = null; if (hasNext) { hasNext = false; obj = "THE_ROW"; } return obj; }

Target:
public Object next() { if (!hasNext) { throw new NoSuchElementException("no more rows"); } hasNext = false; return "THE_ROW"; }
Source:
private void window() { state.startWindow(); Runnable windowWorker = new Runnable() { @Override public void run() { try { containerMetrics.windows().inc(); ReadableCoordinator coordinator = new ReadableCoordinator(task.taskName()); long startTime = clock.nanoTime(); task.window(coordinator); containerMetrics.windowNs().update(clock.nanoTime() - startTime); double lowerBoundForWindowTriggerTimeInMs = containerMetrics.windowNs().getSnapshot().getAverage() / 1e6; if (windowMs <= lowerBoundForWindowTriggerTimeInMs) { log.warn( "Window might potentially starve process method." + " Consider increasing the window interval to something greater than ms", (long) lowerBoundForWindowTriggerTimeInMs); } coordinatorRequests.update(coordinator); state.doneWindow(); } catch (Throwable t) { log.error("Task window failed", task.taskName(), t); abort(t); } finally { log.trace("Task window completed", task.taskName()); resume(); } } }; if (threadPool != null) { log.trace("Task window on the thread pool", task.taskName()); threadPool.submit(windowWorker); } else { log.trace("Task window on the run loop thread", task.taskName()); windowWorker.run(); } }

Target:
private void window() { state.startWindow(); Runnable windowWorker = new Runnable() { @Override public void run() { try { containerMetrics.windows().inc(); ReadableCoordinator coordinator = new ReadableCoordinator(task.taskName()); long startTime = clock.nanoTime(); task.window(coordinator); containerMetrics.windowNs().update(clock.nanoTime() - startTime); long lowerBoundForWindowTriggerTimeInMs = TimeUnit.NANOSECONDS .toMillis((long) containerMetrics.windowNs().getSnapshot().getAverage()); if (windowMs <= lowerBoundForWindowTriggerTimeInMs) { log.warn( "window() call might potentially starve process calls." + " Consider setting task.window.ms > ms", lowerBoundForWindowTriggerTimeInMs); } coordinatorRequests.update(coordinator); state.doneWindow(); } catch (Throwable t) { log.error("Task window failed", task.taskName(), t); abort(t); } finally { log.trace("Task window completed", task.taskName()); resume(); } } }; if (threadPool != null) { log.trace("Task window on the thread pool", task.taskName()); threadPool.submit(windowWorker); } else { log.trace("Task window on the run loop thread", task.taskName()); windowWorker.run(); } }
Source:
public void sendEvents() { log.debug("Committing ActiveMQ transaction"); try { ClientSession session = this.getClientSession(); session.commit(); session.close(); } catch (Exception e) { log.error("Error committing ActiveMQ transaction", e); } }

Target:
public void sendEvents() { log.debug("Committing ActiveMQ transaction"); try (ClientSession session = this.getClientSession()) { session.commit(); } catch (Exception e) { log.error("Error committing ActiveMQ transaction", e); } }
Source:
public static void main(String[] args) { List<Trade> trades = ImmutableList.of(createTrade()); List<Column> columns = ImmutableList.of( Column.of(Measure.PRESENT_VALUE)); MarketDataBuilder marketDataBuilder = MarketDataBuilder.ofResource(MARKET_DATA_RESOURCE_ROOT); CalculationRules rules = CalculationRules.builder() .pricingRules(OpenGammaPricingRules.standard()) .marketDataRules(marketDataBuilder.rules()) .reportingRules(ReportingRules.empty()) .build(); Map<LocalDate, Map<RateCurveId, Curve>> historicalCurves = marketDataBuilder.loadAllRatesCurves(); List<LocalDate> scenarioDates = new ArrayList<LocalDate>(historicalCurves.keySet()); scenarioDates.sort(null); ScenarioDefinition historicalScenarios = buildHistoricalScenarios(historicalCurves, scenarioDates); LocalDate valuationDate = LocalDate.of(2015, 4, 23); BaseMarketData snapshot = marketDataBuilder.buildSnapshot(valuationDate); CalculationEngine engine = ExampleEngine.create(); Results results = engine.calculate(trades, columns, rules, snapshot, historicalScenarios); ScenarioResult<?> scenarioValuations = (ScenarioResult<?>) results.get(0, 0).getValue(); outputPnl(scenarioDates, scenarioValuations); }

Target:
public static void main(String[] args) { List<Trade> trades = ImmutableList.of(createTrade()); List<Column> columns = ImmutableList.of( Column.of(Measure.PRESENT_VALUE)); MarketDataBuilder marketDataBuilder = MarketDataBuilder.ofResource(MARKET_DATA_RESOURCE_ROOT); CalculationRules rules = CalculationRules.builder() .pricingRules(OpenGammaPricingRules.standard()) .marketDataRules(marketDataBuilder.rules()) .build(); SortedMap<LocalDate, Map<RateCurveId, Curve>> historicalCurves = marketDataBuilder.loadAllRatesCurves(); List<LocalDate> scenarioDates = new ArrayList<LocalDate>(historicalCurves.keySet()); ScenarioDefinition historicalScenarios = buildHistoricalScenarios(historicalCurves, scenarioDates); LocalDate valuationDate = LocalDate.of(2015, 4, 23); BaseMarketData snapshot = marketDataBuilder.buildSnapshot(valuationDate); CalculationEngine engine = ExampleEngine.create(); Results results = engine.calculate(trades, columns, rules, snapshot, historicalScenarios); ScenarioResult<?> scenarioValuations = (ScenarioResult<?>) results.get(0, 0).getValue(); outputPnl(scenarioDates, scenarioValuations); }
Source:
public byte[] get(NamedKey key) { byte[] result = null; try (ResourceHolder<ShardedJedis> clientHolder = supplier.get()) { final ShardedJedis jedis = clientHolder.get(); final byte[] itemKey = CacheImplUtils.computeKeyHash(prefix, key).getBytes(); final byte[] serialized = jedis.get(itemKey); if (serialized != null) { result = deserialize(key, serialized); hitCount.incrementAndGet(); } else { missCount.incrementAndGet(); } } catch (IOException ex) { throw Throwables.propagate(ex); } catch (JedisConnectionException ex) { if (isTimeout(ex)) { timeoutCount.incrementAndGet(); } throw Throwables.propagate(ex); } catch (JedisException | LZ4Exception ex) { errorCount.incrementAndGet(); log.warn(ex, "Error getting cache item"); return null; } return result; }

Target:
public byte[] get(NamedKey key) { byte[] result = null; try (ResourceHolder<ShardedJedis> clientHolder = supplier.get()) { final ShardedJedis jedis = clientHolder.get(); final byte[] itemKey = CacheImplUtils.computeKeyHash(prefix, key).getBytes(); final byte[] serialized = jedis.get(itemKey); if (serialized != null) { result = deserialize(key, serialized); hitCount.incrementAndGet(); } else { missCount.incrementAndGet(); } } catch (IOException | JedisException | LZ4Exception ex) { this.countException(ex); log.warn(ex, "Error getting cache item"); } return result; }
Source:
public void init_module_relative_import() { String code = String.join(System.getProperty("line.separator"), "from .. import fn", "fn()", "class A: pass"); FileInput fileInput = new PythonTreeMaker().fileInput(PythonParser.create().parse(code)); PythonFile pythonFile = Mockito.mock(PythonFile.class, "__init__.py"); when(pythonFile.fileName()).thenReturn("__init__.py"); PythonVisitorContext context = new PythonVisitorContext(fileInput, pythonFile, null, "foo.bar"); fileInput = context.rootTree(); CallExpression callExpression = (CallExpression) getAllDescendant(fileInput, tree -> tree.is(Tree.Kind.CALL_EXPR)).get(0); assertThat(callExpression.calleeSymbol().fullyQualifiedName()).isEqualTo("fn"); ClassDef classDef = (ClassDef) getAllDescendant(fileInput, tree -> tree.is(Tree.Kind.CLASSDEF)).get(0); assertThat(classDef.name().symbol().fullyQualifiedName()).isEqualTo("foo.bar.A"); }

Target:
public void init_module_relative_import() { String code = String.join(System.getProperty("line.separator"), "from .. import fn", "fn()", "class A: pass"); FileInput fileInput = new PythonTreeMaker().fileInput(PythonParser.create().parse(code)); PythonFile pythonFile = Mockito.mock(PythonFile.class, "__init__.py"); when(pythonFile.fileName()).thenReturn("__init__.py"); PythonVisitorContext context = new PythonVisitorContext(fileInput, pythonFile, null, "foo.bar"); fileInput = context.rootTree(); CallExpression callExpression = (CallExpression) getAllDescendant(fileInput, tree -> tree.is(Tree.Kind.CALL_EXPR)).get(0); assertThat(callExpression.calleeSymbol().fullyQualifiedName()).isEqualTo("foo.fn"); ClassDef classDef = (ClassDef) getAllDescendant(fileInput, tree -> tree.is(Tree.Kind.CLASSDEF)).get(0); assertThat(classDef.name().symbol().fullyQualifiedName()).isEqualTo("foo.bar.A"); }
Source:
int limit(Long limit) { if (limit != null) { parallelism = Math.min(parallelism, limit.intValue() / 1000); } return Math.max(1, parallelism); }

Target:
int limit(Long limit) { if (limit != null) { parallelism = Math.min(parallelism, (int) (limit / 1000)); } return Math.max(1, parallelism); }
Source:
private Mono<Document> tryUpdateDocument(AsyncDocumentClient client, String collectionUri, Document document, int index) { BridgeInternal.setProperty(document, "regionId", index); BridgeInternal.setProperty(document, "regionEndpoint", client.getReadEndpoint()); RequestOptions options = new RequestOptions(); options.setIfMatchEtag(document.getETag()); return client.replaceDocument(document.getSelfLink(), document, null).onErrorResume(e -> { if (hasDocumentClientException(e, 412)) { return Mono.empty(); } return Mono.error(e); }).map(ResourceResponse::getResource); }

Target:
private Mono<Document> tryUpdateDocument(AsyncDocumentClient client, String collectionUri, Document document, int index) { BridgeInternal.setProperty(document, "regionId", index); BridgeInternal.setProperty(document, "regionEndpoint", client.getReadEndpoint()); RequestOptions options = new RequestOptions(); options.setIfMatchETag(document.getETag()); return client.replaceDocument(document.getSelfLink(), document, null).onErrorResume(e -> { if (hasDocumentClientException(e, 412)) { return Mono.empty(); } return Mono.error(e); }).map(ResourceResponse::getResource); }
Source:
public void tag(final TagParams params) throws ImageNotFoundException, IOException { String sourceImage = params.getImage(); String targetImage = params.getRepository(); String tag = params.getTag(); if (sourceImage.contains(":")) { tag = sourceImage.split(":")[1]; sourceImage = sourceImage.split(":")[0]; } else if (isNullOrEmpty(tag)) { tag = "latest"; } String sourceImageWithTag; try { String sourceImageTagName = KubernetesStringUtils.getTagNameFromRepoString(sourceImage); ImageStreamTag existingTag = getImageStreamTagFromRepo(sourceImageTagName); sourceImageWithTag = existingTag.getTag().getFrom().getName(); } catch (IOException e) { sourceImageWithTag = String.format("%s:%s", sourceImage, tag); } String imageStreamTagName = KubernetesStringUtils.getImageStreamTagName(sourceImageWithTag, targetImage); createImageStreamTag(sourceImageWithTag, imageStreamTagName); }

Target:
public void tag(final TagParams params) throws ImageNotFoundException, IOException { String paramsSourceImage = params.getImage(); String targetImage = params.getRepository(); String paramsTag = params.getTag(); String sourceImage = KubernetesStringUtils.stripTagFromPullSpec(paramsSourceImage); String tag = KubernetesStringUtils.getTagNameFromPullSpec(paramsSourceImage); if (isNullOrEmpty(tag)) { tag = !isNullOrEmpty(paramsTag) ? paramsTag : "latest"; } String sourceImageWithTag; try { String sourceImageTagName = KubernetesStringUtils.convertPullSpecToTagName(sourceImage); ImageStreamTag existingTag = getImageStreamTagFromRepo(sourceImageTagName); sourceImageWithTag = existingTag.getTag().getFrom().getName(); } catch (IOException e) { sourceImageWithTag = String.format("%s:%s", sourceImage, tag); } String imageStreamTagName = KubernetesStringUtils.createImageStreamTagName(sourceImageWithTag, targetImage); createImageStreamTag(sourceImageWithTag, imageStreamTagName); }
Source:
public String toString() { if (rate == (long) rate) { return pair + " " + Long.toString((long) rate); } return pair + " " + Double.toString(rate); }

Target:
public String toString() { return pair + " " + (DoubleMath.isMathematicalInteger(rate) ? Long.toString((long) rate) : Double.toString(rate)); }
Source:
NatsConnectionWriter(NatsConnection connection) { this.connection = connection; this.running = new AtomicBoolean(false); this.reconnectMode = new AtomicBoolean(false); this.startStopLock = new ReentrantLock(); this.stopped = new CompletableFuture<>(); ((CompletableFuture<Boolean>)this.stopped).complete(Boolean.TRUE); int bufSize = connection.getOptions().getBufferSize(); this.sendBuffer = new byte[bufSize]; this.maxAccumulate = 1000; outgoing = new MessageQueue(true, (int) (5 * maxAccumulate)); reconnectOutgoing = new MessageQueue(true, 0); }

Target:
NatsConnectionWriter(NatsConnection connection) { this.connection = connection; this.running = new AtomicBoolean(false); this.reconnectMode = new AtomicBoolean(false); this.startStopLock = new ReentrantLock(); this.stopped = new CompletableFuture<>(); ((CompletableFuture<Boolean>)this.stopped).complete(Boolean.TRUE); int bufSize = connection.getOptions().getBufferSize(); this.sendBuffer = new byte[bufSize]; outgoing = new MessageQueue(true, Options.MAX_MESSAGES_IN_OUTGOING_QUEUE); reconnectOutgoing = new MessageQueue(true, 0); }
Source:
PRED_change_owner_1(Term a1, Operation n) { arg1 = a1; cont = n; }

Target:
public PRED_change_owner_1(Term a1, Operation n) { arg1 = a1; cont = n; }
Source:
public ILocationConfiguratorPlugin newInstance(String locationType) { if (BrooklynOrchestratorFactory.BROOKLYN.equals(locationType)) { return applicationContext.getBean(BrooklynLocationConfigurer.class); } return new ILocationConfiguratorPlugin() { @Override public List<PluginArchive> pluginArchives() { return new ArrayList<>(); } @Override public List<String> getResourcesTypes() { return new ArrayList<>(); } @Override public Map<String, MatchingConfiguration> getMatchingConfigurations() { return new HashMap<>(); } @Override public List<LocationResourceTemplate> instances(ILocationResourceAccessor resourceAccessor) { return null; } }; }

Target:
public ILocationConfiguratorPlugin newInstance(String locationType) { if (BrooklynOrchestratorFactory.BROOKLYN.equals(locationType)) { return applicationContext.getBean(BrooklynLocationConfigurer.class); } return new ILocationConfiguratorPlugin() { @Override public List<PluginArchive> pluginArchives() { return Collections.emptyList(); } @Override public List<String> getResourcesTypes() { return Collections.emptyList(); } @Override public Map<String, MatchingConfiguration> getMatchingConfigurations() { return Collections.emptyMap(); } @Override public List<LocationResourceTemplate> instances(ILocationResourceAccessor resourceAccessor) { return Collections.emptyList(); } }; }
Source:
private boolean checkServiceDeployed(String response, int numTasks, boolean useMarathonServices) { JSONObject deployment = new JSONObject(response); JSONArray tasks = (JSONArray) deployment.get("tasks"); int numTasksRunning = 0; for (int i = 0; i < tasks.length(); i++) { if (useMarathonServices) { numTasksRunning = tasks.getJSONObject(i).get("status").equals("RUNNING") ? (numTasksRunning + 1) : numTasksRunning; } else if (!useMarathonServices) { numTasksRunning = tasks.getJSONObject(i).get("state").equals("TASK_RUNNING") ? (numTasksRunning + 1) : numTasksRunning; } } return numTasksRunning == numTasks ? true : false; }

Target:
private boolean checkServiceDeployed(String response, int numTasks, boolean useMarathonServices) { JSONObject deployment = new JSONObject(response); JSONArray tasks = (JSONArray) deployment.get("tasks"); int numTasksRunning = 0; for (int i = 0; i < tasks.length(); i++) { if (useMarathonServices) { numTasksRunning = tasks.getJSONObject(i).get("status").equals("RUNNING") ? (numTasksRunning + 1) : numTasksRunning; } else { numTasksRunning = tasks.getJSONObject(i).get("state").equals("TASK_RUNNING") ? (numTasksRunning + 1) : numTasksRunning; } } return numTasksRunning == numTasks; }
Source:
private int skipIndefiniteLengthContents() throws BerDataValueFormatException { boolean prevZeroByte = false; int bytesRead = 0; while (true) { if (!mBuf.hasRemaining()) { throw new BerDataValueFormatException( "Truncated indefinite-length contents: " + bytesRead + " bytes read"); } int b = mBuf.get(); bytesRead++; if (bytesRead < 0) { throw new BerDataValueFormatException("Indefinite-length contents too long"); } if (b == 0) { if (prevZeroByte) { return bytesRead - 2; } prevZeroByte = true; continue; } else { prevZeroByte = false; } } }

Target:
private int skipIndefiniteLengthContents() throws BerDataValueFormatException { boolean prevZeroByte = false; int bytesRead = 0; while (true) { if (!mBuf.hasRemaining()) { throw new BerDataValueFormatException( "Truncated indefinite-length contents: " + bytesRead + " bytes read"); } int b = mBuf.get(); bytesRead++; if (bytesRead < 0) { throw new BerDataValueFormatException("Indefinite-length contents too long"); } if (b == 0) { if (prevZeroByte) { return bytesRead - 2; } prevZeroByte = true; } else { prevZeroByte = false; } } }
Source:
private static boolean isValid(long value, long minValue, long maxValue, long increment) { return minValue <= value && maxValue >= value && maxValue > minValue && increment != 0 && Math.abs(increment) + Long.MIN_VALUE < maxValue - minValue + Long.MIN_VALUE; }

Target:
private static boolean isValid(long value, long minValue, long maxValue, long increment) { return minValue <= value && maxValue >= value && maxValue > minValue && increment != 0 && Math.abs(increment) + Long.MIN_VALUE <= maxValue - minValue + Long.MIN_VALUE; }
Source:
protected void runWork() throws WorkCompletedException { if (securityIntegration.getSecurityContext() != null && ((CallbackImpl) workManager.getCallbackSecurity()).isElytronEnabled()) ((ElytronSecurityContext) securityIntegration.getSecurityContext()).runWork(() -> { try { WildflyWorkWrapper.super.runWork(); } catch (WorkCompletedException e) { ROOT_LOGGER.error(e.getLocalizedMessage()); } }); else super.runWork(); }

Target:
protected void runWork() throws WorkCompletedException { if (securityIntegration.getSecurityContext() != null && ((CallbackImpl) workManager.getCallbackSecurity()).isElytronEnabled()) ((ElytronSecurityContext) securityIntegration.getSecurityContext()).runWork(() -> { try { WildflyWorkWrapper.super.runWork(); } catch (WorkCompletedException e) { ConnectorLogger.ROOT_LOGGER.unexceptedWorkerCompletionError(e.getLocalizedMessage(),e); } }); else super.runWork(); }
Source:
void forceRefresh(M model) { if (model instanceof SearchableListModel) { UICommand lastExecutedCommand = model.getLastExecutedCommand(); if (lastExecutedCommand != null && !lastExecutedCommand.getIsCancel()) { SearchableListModel searchableList = (SearchableListModel) model; searchableList.getForceRefreshCommand().execute(); } } }

Target:
void forceRefresh(M model) { if (model instanceof SearchableListModel) { UICommand lastExecutedCommand = model.getLastExecutedCommand(); if (lastExecutedCommand != null && !lastExecutedCommand.getIsCancel()) { SearchableListModel searchableList = (SearchableListModel) model; searchableList.forceRefresh(); } } }
Source:
public void readLedgerMetadata(final long ledgerId, final GenericCallback<LedgerMetadata> readCb) { final String key = ledgerId2Key(ledgerId); MetastoreCallback<Versioned<Value>> msCallback = new MetastoreCallback<Versioned<Value>>() { @Override public void complete(int rc, Versioned<Value> value, Object ctx) { if (MSException.Code.NoKey.getCode() == rc) { LOG.error("No ledger metadata found for ledger " + ledgerId + " : ", MSException.create(MSException.Code.get(rc), "No key " + key + " found.")); readCb.operationComplete(BKException.Code.NoSuchLedgerExistsException, null); return; } if (MSException.Code.OK.getCode() != rc) { LOG.error("Could not read metadata for ledger " + ledgerId + " : ", MSException.create(MSException.Code.get(rc), "Failed to get key " + key)); readCb.operationComplete(BKException.Code.MetaStoreException, null); return; } LedgerMetadata metadata; try { metadata = LedgerMetadata .parseConfig(value.getValue().getField(META_FIELD), value.getVersion(),null); } catch (IOException e) { LOG.error("Could not parse ledger metadata for ledger " + ledgerId + " : ", e); readCb.operationComplete(BKException.Code.MetaStoreException, null); return; } readCb.operationComplete(BKException.Code.OK, metadata); } }; ledgerTable.get(key, this, msCallback, ALL_FIELDS); }

Target:
public void readLedgerMetadata(final long ledgerId, final GenericCallback<LedgerMetadata> readCb) { final String key = ledgerId2Key(ledgerId); MetastoreCallback<Versioned<Value>> msCallback = new MetastoreCallback<Versioned<Value>>() { @Override public void complete(int rc, Versioned<Value> value, Object ctx) { if (MSException.Code.NoKey.getCode() == rc) { LOG.error("No ledger metadata found for ledger " + ledgerId + " : ", MSException.create(MSException.Code.get(rc), "No key " + key + " found.")); readCb.operationComplete(BKException.Code.NoSuchLedgerExistsException, null); return; } if (MSException.Code.OK.getCode() != rc) { LOG.error("Could not read metadata for ledger " + ledgerId + " : ", MSException.create(MSException.Code.get(rc), "Failed to get key " + key)); readCb.operationComplete(BKException.Code.MetaStoreException, null); return; } LedgerMetadata metadata; try { metadata = LedgerMetadata .parseConfig(value.getValue().getField(META_FIELD), value.getVersion(), Optional.<Long>absent()); } catch (IOException e) { LOG.error("Could not parse ledger metadata for ledger " + ledgerId + " : ", e); readCb.operationComplete(BKException.Code.MetaStoreException, null); return; } readCb.operationComplete(BKException.Code.OK, metadata); } }; ledgerTable.get(key, this, msCallback, ALL_FIELDS); }
Source:
public void process(final ElasticJob elasticJob, final JobConfiguration jobConfig, final JobFacade jobFacade, final ShardingContext shardingContext) { System.out.println(jobConfig.getProps().getProperty(PrintJobProperties.CONTENT_KEY)); }

Target:
public void process(final ElasticJob elasticJob, final JobConfiguration jobConfig, final JobFacade jobFacade, final ShardingContext shardingContext) { log.info(jobConfig.getProps().getProperty(PrintJobProperties.CONTENT_KEY)); }
Source:
public void testConjunction() { int v = 100; int v2 = v + 2 + 100; ConcreteIntPredicate conjunction = gt(v).and(lt(v2)); assertTrue(conjunction.test(150)); assertFalse(conjunction.test(Integer.MAX_VALUE)); assertFalse(conjunction.test(Integer.MIN_VALUE)); assertEquals(gt(v).and(lt(v2)), conjunction); assertEquals(gt(v).and(lt(v2)).hashCode(), conjunction.hashCode()); assertNotEquals(gt(v).and(lt(v2 + 1)), conjunction); assertNotEquals(gt(v).and(lt(v2 + 1)).hashCode(), conjunction.hashCode()); assertEquals(conjunction.toString(), "> " + v + " and " + "< " + v2); }

Target:
public void testConjunction() { int v = 100; int v2 = v + 2 + 100; ConcreteIntPredicate conjunction = gt(v).and(lt(v2)); assertTrue(conjunction.test(150)); assertFalse(conjunction.test(Integer.MAX_VALUE)); assertFalse(conjunction.test(Integer.MIN_VALUE)); assertEquals(gt(v).and(lt(v2)), conjunction); assertEquals(gt(v).and(lt(v2)).hashCode(), conjunction.hashCode()); assertNotEquals(gt(v).and(lt(v2 + 1)), conjunction); assertEquals(conjunction.toString(), "> " + v + " and " + "< " + v2); }
Source:
public boolean isDomainXmlEnabledForVds(Guid vdsId) { return FeatureSupported.isDomainXMLSupported(getVdsManager(vdsId).getCompatibilityVersion()); }

Target:
private boolean isDomainXmlEnabledForVds(Guid vdsId) { return FeatureSupported.isDomainXMLSupported(getVdsManager(vdsId).getCompatibilityVersion()); }
Source:
public final Authentication getAuthentication() { if (!isEmpty()) { final String principalId = this.chainedAuthentication.get(0).getPrincipal().getId(); final MutablePrincipal compositePrincipal = new MutablePrincipal(principalId); final Map<String, Object> authenticationAttribues = new Hashtable<String, Object>(); for (final Authentication authn : this.chainedAuthentication) { final Principal authenticatedPrincipal = authn.getPrincipal(); compositePrincipal.getAttributes().putAll(authenticatedPrincipal.getAttributes()); for (final String attrName : authn.getAttributes().keySet()) { if (!authenticationAttribues.containsKey(attrName)) { authenticationAttribues.put(attrName, authn.getAttributes().get(attrName)); } else { final Object oldValue = authenticationAttribues.remove(attrName); final Collection<Object> listOfValues = MultiFactorUtils.convertValueToCollection(oldValue); listOfValues.add(authn.getAttributes().get(attrName)); authenticationAttribues.put(attrName, listOfValues); } } } return new DefaultCompositeAuthentication(compositePrincipal, authenticationAttribues); } return null; }

Target:
public final Authentication getAuthentication() { if (!isEmpty()) { final String principalId = this.chainedAuthentication.get(0).getPrincipal().getId(); final MutablePrincipal compositePrincipal = new MutablePrincipal(principalId); final Map<String, Object> authenticationAttributes = new Hashtable<String, Object>(); for (final Authentication authn : this.chainedAuthentication) { final Principal authenticatedPrincipal = authn.getPrincipal(); compositePrincipal.getAttributes().putAll(authenticatedPrincipal.getAttributes()); for (final String attrName : authn.getAttributes().keySet()) { if (!authenticationAttributes.containsKey(attrName)) { authenticationAttributes.put(attrName, authn.getAttributes().get(attrName)); } else { final Object oldValue = authenticationAttributes.remove(attrName); final Collection<Object> listOfValues = MultiFactorUtils.convertValueToCollection(oldValue); listOfValues.add(authn.getAttributes().get(attrName)); authenticationAttributes.put(attrName, listOfValues); } } } return new DefaultCompositeAuthentication(compositePrincipal, authenticationAttributes); } return null; }
Source:
private gov.hhs.fha.nhinc.common.nhinccommonproxy.RespondingGatewayProvideAndRegisterDocumentSetSecuredRequestType createRequestForNhin( RespondingGatewayProvideAndRegisterDocumentSetSecuredRequestType request) { gov.hhs.fha.nhinc.common.nhinccommonproxy.RespondingGatewayProvideAndRegisterDocumentSetSecuredRequestType nhinRequest = new gov.hhs.fha.nhinc.common.nhinccommonproxy.RespondingGatewayProvideAndRegisterDocumentSetSecuredRequestType(); nhinRequest.setNhinTargetSystem(getTargetSystemTypeFromCommunity(getNhinTargetHomeCommunity(request))); nhinRequest.setProvideAndRegisterDocumentSetRequest(request.getProvideAndRegisterDocumentSetRequest()); return nhinRequest; }

Target:
createRequestForNhin(RespondingGatewayProvideAndRegisterDocumentSetSecuredRequestType request) { gov.hhs.fha.nhinc.common.nhinccommonproxy.RespondingGatewayProvideAndRegisterDocumentSetSecuredRequestType nhinRequest = new gov.hhs.fha.nhinc.common.nhinccommonproxy.RespondingGatewayProvideAndRegisterDocumentSetSecuredRequestType(); nhinRequest.setNhinTargetSystem(getMessageGeneratorUtils().convertFirstToNhinTargetSystemType( request.getNhinTargetCommunities())); nhinRequest.setProvideAndRegisterDocumentSetRequest(request.getProvideAndRegisterDocumentSetRequest()); return nhinRequest; }
Source:
private void setDiskProfilesList(List<DiskProfile> diskProfiles) { if (diskProfiles != null && !diskProfiles.isEmpty()) { getDiskProfile().setItems(diskProfiles); } Guid defaultProfileId = (getDisk() != null && isExistingDisk() && getDisk().getDiskStorageType() == DiskStorageType.IMAGE) ? ((DiskImage) getDisk()).getDiskProfileId() : null; if (defaultProfileId != null) { for (DiskProfile profile : diskProfiles) { if (profile.getId().equals(defaultProfileId)) { getDiskProfile().setSelectedItem(profile); return; } } DiskProfile diskProfile = new DiskProfile(); diskProfile.setId(defaultProfileId); if (getDisk() != null) { diskProfile.setName(getDiskImage().getDiskProfileName()); } diskProfiles.add(diskProfile); getDiskProfile().setItems(diskProfiles); getDiskProfile().setSelectedItem(diskProfile); } }

Target:
private void setDiskProfilesList(List<DiskProfile> diskProfiles) { if (diskProfiles != null && !diskProfiles.isEmpty()) { getDiskProfile().setItems(diskProfiles); } Guid defaultProfileId = (getDisk() != null && !getIsNew() && getDisk().getDiskStorageType() == DiskStorageType.IMAGE) ? ((DiskImage) getDisk()).getDiskProfileId() : null; if (defaultProfileId != null) { for (DiskProfile profile : diskProfiles) { if (profile.getId().equals(defaultProfileId)) { getDiskProfile().setSelectedItem(profile); return; } } DiskProfile diskProfile = new DiskProfile(); diskProfile.setId(defaultProfileId); if (getDisk() != null) { diskProfile.setName(getDiskImage().getDiskProfileName()); } diskProfiles.add(diskProfile); getDiskProfile().setItems(diskProfiles); getDiskProfile().setSelectedItem(diskProfile); } }
Source:
private String[] calculateGroupsTouseConsideringValuesAndGroupValues(Class<? extends ITestOrConfiguration> annotationClass, String[] groups) { ITestOrConfiguration annotation = getAnnotationFinder().findAnnotation(getConstructorOrMethod(), annotationClass); if (groups == null || groups.length == 0) { groups = null != annotation ? annotation.getGroups() : null; } return groups; }

Target:
private String[] calculateGroupsTouseConsideringValuesAndGroupValues(Class<? extends ITestOrConfiguration> annotationClass, String[] groups) { if (groups == null || groups.length == 0) { ITestOrConfiguration annotation = getAnnotationFinder().findAnnotation(getConstructorOrMethod(), annotationClass); groups = null != annotation ? annotation.getGroups() : null; } return groups; }
Source:
@VisibleForTesting void waitForBytesToFree(long minBytes, long startTimeMs) { try { logger.debug("Waiting for " + (usedMemoryBytes + minBytes - maxMemoryBytes) + " bytes to be free " + startTimeMs); long remainingWaitTimeMs = maxWaitMs - (System.currentTimeMillis() - startTimeMs); if (remainingWaitTimeMs <= 0) { throw new InsufficientMemoryException("Requested memory of " + minBytes + " bytes could not be allocated. Using memory of " + usedMemoryBytes + " bytes from global pool of " + maxMemoryBytes + " bytes after waiting for " + maxWaitMs + "ms."); } sync.wait(remainingWaitTimeMs); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new RuntimeException("Interrupted allocation of " + minBytes + " bytes", ie); } }

Target:
void waitForBytesToFree(long minBytes, long startTimeMs) { try { logger.debug("Waiting for " + (usedMemoryBytes + minBytes - maxMemoryBytes) + " bytes to be free " + startTimeMs); long remainingWaitTimeMs = maxWaitMs - (System.currentTimeMillis() - startTimeMs); if (remainingWaitTimeMs <= 0) { throw new InsufficientMemoryException("Requested memory of " + minBytes + " bytes could not be allocated. Using memory of " + usedMemoryBytes + " bytes from global pool of " + maxMemoryBytes + " bytes after waiting for " + maxWaitMs + "ms."); } sync.wait(remainingWaitTimeMs); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new RuntimeException("Interrupted allocation of " + minBytes + " bytes", ie); } }
Source:
public void run() { List<TaskResult> results = new ArrayList<TaskResult>(); for (String task : myTasks) { TaskResult taskResult = new TaskResult(); taskResult.myTaskName = task; taskResult.myIsSuccess = true; long loopStartTime = System.currentTimeMillis(); try { Class taskClass; taskClass = Runner.class.getClassLoader().loadClass(task); if (!BaseTask.class.isAssignableFrom(taskClass)) { throw new InvalidClassException("Invalid class " + task + ". It is not a subclass of " + BaseTask.class.getName() + "."); } BaseTask baseTask = (BaseTask)taskClass.getConstructor().newInstance(new Object[]{}); baseTask.setProjectNavigationUtil(myNavigationUtil); baseTask.setTaskContext(myTaskContext); try { if (!baseTask.setup()) { throw new Exception("Setup failed for task " + baseTask.getClass().getCanonicalName() + "."); } long taskStartTime = System.currentTimeMillis(); taskResult.myIsSuccess = baseTask.run(); taskResult.myRunningTime = System.currentTimeMillis() - taskStartTime; } finally { baseTask.teardown(); } } catch (Exception e) { taskResult.myIsSuccess = false; taskResult.myException = e.toString(); taskResult.myStackTraceElements = e.getStackTrace(); e.printStackTrace(); } taskResult.myTotalTime = System.currentTimeMillis() - loopStartTime; } myAllResults.add(results); for (TaskResult result : results) { myLastResults.put(result.myTaskName, result); } }

Target:
public void run() { List<TaskResult> results = new ArrayList<TaskResult>(); for (String task : myTasks) { TaskResult taskResult = new TaskResult(); taskResult.myTaskName = task; taskResult.myIsSuccess = true; long loopStartTime = System.currentTimeMillis(); try { Class taskClass; taskClass = Runner.class.getClassLoader().loadClass(task); if (!BaseTask.class.isAssignableFrom(taskClass)) { throw new InvalidClassException("Invalid class " + task + ". It is not a subclass of " + BaseTask.class.getName() + "."); } BaseTask baseTask = (BaseTask)taskClass.getConstructor().newInstance(new Object[]{}); baseTask.setProjectNavigationUtil(myNavigationUtil); baseTask.setTaskContext(myTaskContext); try { baseTask.setup(); long taskStartTime = System.currentTimeMillis(); taskResult.myIsSuccess = baseTask.run(); taskResult.myRunningTime = System.currentTimeMillis() - taskStartTime; } finally { baseTask.teardown(); } } catch (Exception e) { taskResult.myIsSuccess = false; taskResult.myException = e.toString(); taskResult.myStackTraceElements = e.getStackTrace(); e.printStackTrace(); } taskResult.myTotalTime = System.currentTimeMillis() - loopStartTime; } myAllResults.add(results); for (TaskResult result : results) { myLastResults.put(result.myTaskName, result); } }
Source:
boolean copyObject(BaseObject srcObj, BaseObject trgObj, boolean set) { boolean hasChanged = false; if (srcObj != trgObj) { Set<String> srcProps = srcObj.getPropertyList(); Set<String> trgProps = new HashSet<>(trgObj.getPropertyList()); for (String name : srcProps) { Object srcVal = modelAccess.getProperty(srcObj, name); Object trgVal = modelAccess.getProperty(trgObj, name); if (!Objects.equal(srcVal, trgVal)) { if (set) { modelAccess.setProperty(trgObj, name, srcVal); } hasChanged = true; LOGGER.trace("for doc '{}' field '{}' changed from '{}' to '{}'", trgObj.getDocumentReference(), name, trgVal, srcVal); } trgProps.remove(name); } for (String name : trgProps) { if (set) { trgObj.removeField(name); } hasChanged = true; LOGGER.trace("for doc '{}' field '{}' set to null", trgObj.getDocumentReference(), name); } } return hasChanged; }

Target:
boolean copyObject(BaseObject srcObj, BaseObject trgObj, boolean set) { boolean hasChanged = false; if (srcObj != trgObj) { Set<String> srcProps = srcObj.getPropertyList(); Set<String> trgProps = new HashSet<>(trgObj.getPropertyList()); for (String name : srcProps) { Object srcVal = modelAccess.getProperty(srcObj, name); Object trgVal = modelAccess.getProperty(trgObj, name); if (!Objects.equal(srcVal, trgVal)) { if (set) { modelAccess.setProperty(trgObj, name, srcVal); } hasChanged = true; LOGGER.trace("copyObject - for doc '{}' field '{}' changed from '{}' to '{}'", trgObj.getDocumentReference(), name, trgVal, srcVal); } trgProps.remove(name); } for (String name : trgProps) { if (set) { trgObj.removeField(name); } hasChanged = true; LOGGER.trace("copyObject - for doc '{}' field '{}' set to null", trgObj.getDocumentReference(), name); } } else { LOGGER.warn("copyObject - skipped because identical reference: {}", srcObj); } return hasChanged; }
Source:
private Map<HivePartitionName, PartitionStatistics> loadPartitionColumnStatistics(Iterable<? extends HivePartitionName> keys) { SetMultimap<HiveTableName, HivePartitionName> tablePartitions = stream(keys) .collect(toImmutableSetMultimap(HivePartitionName::getHiveTableName, key -> key)); ImmutableMap.Builder<HivePartitionName, PartitionStatistics> result = ImmutableMap.builder(); tablePartitions.keySet().forEach(table -> { Set<String> partitionNames = tablePartitions.get(table).stream() .map(HivePartitionName::getPartitionName) .collect(toImmutableSet()); Map<String, PartitionStatistics> partitionStatistics = delegate.getPartitionStatistics(table.getDatabaseName(), table.getTableName(), partitionNames); for (String partitionName : partitionNames) { verify(partitionStatistics.containsKey(partitionName), "the result doesn't contain statistics for partition %s", partitionName); result.put(HivePartitionName.partition(table, partitionName), partitionStatistics.get(partitionName)); } }); return result.build(); }

Target:
private Map<HivePartitionName, PartitionStatistics> loadPartitionColumnStatistics(Iterable<? extends HivePartitionName> keys) { SetMultimap<HiveTableName, HivePartitionName> tablePartitions = stream(keys) .collect(toImmutableSetMultimap(HivePartitionName::getHiveTableName, key -> key)); ImmutableMap.Builder<HivePartitionName, PartitionStatistics> result = ImmutableMap.builder(); tablePartitions.keySet().forEach(table -> { Set<String> partitionNames = tablePartitions.get(table).stream() .map(HivePartitionName::getPartitionName) .collect(toImmutableSet()); Map<String, PartitionStatistics> partitionStatistics = delegate.getPartitionStatistics(table.getDatabaseName(), table.getTableName(), partitionNames); for (String partitionName : partitionNames) { if (!partitionStatistics.containsKey(partitionName)) { throw new PrestoException(HIVE_PARTITION_DROPPED_DURING_QUERY, "Statistics result does not contain entry for partition: " + partitionName); } result.put(HivePartitionName.partition(table, partitionName), partitionStatistics.get(partitionName)); } }); return result.build(); }