auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Collection<Metric> poll(int size, long maxWaitMillis) throws InterruptedException { Preconditions.checkArgument(size > 0); long timeout = System.currentTimeMillis() + maxWaitMillis; do { synchronized (this) { final Metric first = queue.poll(); if (first != null) { final Collection<Metric> metrics = new ArrayList<>(size); metrics.add(first); while (metrics.size() < size) { final Metric m = queue.poll(); if (m == null) { log.debug("No more metrics in queue, retrieved metrics", metrics.size()); break; } metrics.add(m); } for (final Map.Entry<String,Long> e : clientCounts(metrics).entrySet()) { incrementPerClientBacklog(e.getKey(), - e.getValue()); } return metrics; } } Thread.sleep(1); } while (System.currentTimeMillis() < timeout); log.debug("Unable to retrieve a single element after max wait"); return Collections.emptyList(); }

Target:
public Collection<Metric> poll(int size, long maxWaitMillis) throws InterruptedException { Preconditions.checkArgument(size > 0); final Metric first = queue.poll(maxWaitMillis, TimeUnit.MILLISECONDS); if (first == null) { log.debug("Unable to retrieve a single element after max wait"); return Collections.emptyList(); } final Collection<Metric> metrics = new ArrayList<>(size); metrics.add(first); while (metrics.size() < size) { final Metric m = queue.poll(); if (m == null) { log.debug("No more metrics in queue, retrieved metrics", metrics.size()); break; } metrics.add(m); } for (final Multiset.Entry<String> e : clientCounts(metrics).entrySet()) { perClientBacklog.addAndGet(e.getElement(), - e.getCount()); } perClientBacklog.removeAllZeros(); return metrics; }
Source:
public String[] getArray(String key) { if(key.contains("ethiopian")){ return context.getResources().getStringArray(R.array.ethiopian_months); } else if(key.contains("nepali")){ return context.getResources().getStringArray(R.array.nepali_months); } throw new Resources.NotFoundException("Couldn't find Android array for key " + key); }

Target:
public String[] getArray(String key) { int resourceId = context.getResources().getIdentifier(key, "array", context.getPackageName()); if (resourceId == 0) { throw new RuntimeException("Localized array data for '" + key + "' not found"); } return context.getResources().getStringArray(resourceId); }
Source:
void testShouldRunRxTransactionFunctionExampleReactor() throws Exception { try ( RxTransactionFunctionExample example = new RxTransactionFunctionExample( uri, USER, PASSWORD ) ) { try ( Session session = neo4j.driver().session() ) { session.run( "UNWIND ['Infinity Gauntlet', 'Mjölnir'] AS item " + "CREATE (:Product {id: 0, title: item})" ); } StdIOCapture stdIOCapture = new StdIOCapture(); CountDownLatch latch = new CountDownLatch( 1 ); try ( AutoCloseable ignore = stdIOCapture.capture() ) { Mono.from( example.printAllProductsReactor() ) .doAfterTerminate( () -> latch.countDown() ) .subscribe( summary -> assertEquals( StatementType.READ_ONLY, summary.statementType() ) ); } latch.await( 1, TimeUnit.MINUTES ); Set<String> capturedOutput = new HashSet<>( stdIOCapture.stdout() ); assertEquals( new HashSet<>( asList( "Infinity Gauntlet", "Mjölnir" ) ), capturedOutput ); } }

Target:
void testShouldRunRxTransactionFunctionExampleReactor() throws Exception { try ( RxTransactionFunctionExample example = new RxTransactionFunctionExample( uri, USER, PASSWORD ) ) { try ( Session session = neo4j.driver().session() ) { session.run( "UNWIND ['Infinity Gauntlet', 'Mjölnir'] AS item " + "CREATE (:Product {id: 0, title: item})" ); } StdIOCapture stdIOCapture = new StdIOCapture(); CountDownLatch latch = new CountDownLatch( 1 ); try ( AutoCloseable ignore = stdIOCapture.capture() ) { example.printAllProductsReactor() .single() .doAfterTerminate( () -> latch.countDown() ) .subscribe( summary -> assertEquals( StatementType.READ_ONLY, summary.statementType() ) ); } latch.await( 1, TimeUnit.MINUTES ); Set<String> capturedOutput = new HashSet<>( stdIOCapture.stdout() ); assertEquals( new HashSet<>( asList( "Infinity Gauntlet", "Mjölnir" ) ), capturedOutput ); } }
Source:
public void test_service_registry(){ Cluster cluster = Cluster.joinAwait(); Transport transport = Transport.bindAwait(); ServicesConfig services = ServicesConfig.empty(); ServiceProcessor serviceProcessor = new AnnotationServiceProcessor(); ServiceRegistryImpl registry = new ServiceRegistryImpl(cluster, transport, services, serviceProcessor); try{ new ServiceRegistryImpl(null, transport, services, serviceProcessor); } catch (Exception ex){ assertEquals(ex.toString(), "java.lang.IllegalArgumentException: cluster can't be null"); } try{ new ServiceRegistryImpl(cluster, null, services, serviceProcessor); } catch (Exception ex){ assertEquals(ex.toString(), "java.lang.IllegalArgumentException: transport can't be null"); } try{ new ServiceRegistryImpl(cluster, transport, null, serviceProcessor); } catch (Exception ex){ assertEquals(ex.toString(), "java.lang.IllegalArgumentException: services can't be null"); } try{ new ServiceRegistryImpl(cluster, transport, services, null); } catch (Exception ex){ assertEquals(ex.toString(), "java.lang.IllegalArgumentException: serviceProcessor can't be null"); } }

Target:
public void test_service_registry() { Cluster cluster = Cluster.joinAwait(); ServicesConfig services = ServicesConfig.empty(); ServiceProcessor serviceProcessor = new AnnotationServiceProcessor(); ServiceCommunicator sender = new ClusterServiceCommunicator(cluster); ServiceRegistryImpl registry = new ServiceRegistryImpl(cluster, sender, services, serviceProcessor); assertTrue(registry.services().isEmpty()); cluster.shutdown(); }
Source:
public OpenOrders getOpenOrders(OpenOrdersParams params) throws IOException { try { if (params instanceof OpenOrdersParamCurrencyPair == false) { throw new CurrencyPairNotValidException("CurrencyPair is must be provided to get open orders."); } OpenOrdersParamCurrencyPair pairParams = (OpenOrdersParamCurrencyPair) params; CurrencyPair pair = pairParams.getCurrencyPair(); if (pair == null) { throw new CurrencyPairNotValidException("CurrencyPair is must be provided to get open orders."); } List<LatokenOrder> latokenOpenOrders = getLatokenOpenOrders(pair, Integer.MAX_VALUE); return LatokenAdapters.adaptOpenOrders(latokenOpenOrders); } catch (LatokenException e) { throw LatokenErrorAdapter.adapt(e); } }

Target:
public OpenOrders getOpenOrders(OpenOrdersParams params) throws IOException { try { if (params instanceof OpenOrdersParamCurrencyPair == false) { throw new ExchangeException("CurrencyPair is must be provided to get open orders."); } OpenOrdersParamCurrencyPair pairParams = (OpenOrdersParamCurrencyPair) params; CurrencyPair pair = pairParams.getCurrencyPair(); if (pair == null) { throw new ExchangeException("CurrencyPair is must be provided to get open orders."); } List<LatokenOrder> latokenOpenOrders = getLatokenOpenOrders(pair, Integer.MAX_VALUE); return LatokenAdapters.adaptOpenOrders(this.exchange, latokenOpenOrders); } catch (LatokenException e) { throw LatokenErrorAdapter.adapt(e); } }
Source:
private List<Object> search(Class<?> entityClass, FilterExpression filterExpression, Optional<Sorting> sorting, Optional<Pagination> pagination) { Query query; try { query = filterExpression.accept(new FilterExpressionToLuceneQuery(em, entityClass)); } catch (IllegalArgumentException e) { throw new InvalidPredicateException(e.getMessage()); } FullTextQuery fullTextQuery = em.createFullTextQuery(query, entityClass); if (mustSort(sorting, entityClass)) { fullTextQuery = fullTextQuery.setSort(buildSort(sorting.get(), entityClass)); } if (pagination.isPresent()) { fullTextQuery = fullTextQuery.setMaxResults(pagination.get().getLimit()); fullTextQuery = fullTextQuery.setFirstResult(pagination.get().getOffset()); } List<Object[]> results = fullTextQuery .setProjection(ProjectionConstants.THIS) .getResultList(); if (pagination.isPresent() && pagination.get().isGenerateTotals()) { pagination.get().setPageTotals(fullTextQuery.getResultSize()); } if (results.isEmpty()) { return new ArrayList<>(); } return results.stream() .map((result) -> { return result[0]; }).collect(Collectors.toList()); }

Target:
private List<Object> search(Class<?> entityClass, FilterExpression filterExpression, Optional<Sorting> sorting, Optional<Pagination> pagination) { Query query; try { query = filterExpression.accept(new FilterExpressionToLuceneQuery(em, entityClass)); } catch (IllegalArgumentException e) { throw new InvalidPredicateException(e.getMessage()); } FullTextQuery fullTextQuery = em.createFullTextQuery(query, entityClass); if (mustSort(sorting, entityClass)) { fullTextQuery = fullTextQuery.setSort(buildSort(sorting.get(), entityClass)); } if (pagination.isPresent()) { fullTextQuery = fullTextQuery.setMaxResults(pagination.get().getLimit()); fullTextQuery = fullTextQuery.setFirstResult(pagination.get().getOffset()); } List<Object[]> results = fullTextQuery .setProjection(ProjectionConstants.THIS) .getResultList(); if (pagination.isPresent() && pagination.get().isGenerateTotals()) { pagination.get().setPageTotals(fullTextQuery.getResultSize()); } if (results.isEmpty()) { return Collections.emptyList(); } return results.stream() .map((result) -> { return result[0]; }).collect(Collectors.toList()); }
Source:
public static boolean isJunctionOrSymlink(File file) throws IOException { return (file.exists() && (Kernel32.FILE_ATTRIBUTE_REPARSE_POINT & getWin32FileAttributes(file)) != 0); }

Target:
public static boolean isJunctionOrSymlink(File file) throws IOException { return Util.isSymlink(file); }
Source:
private synchronized void logMostLikelyMissedJobs(List<JobDescriptor> jobs) { Date now = new Date(); jobs.stream() .map(jobDescriptor -> ((JobDescriptorImpl) jobDescriptor).getInternal()) .filter(job -> job.getJobDeadline().isPresent()) .filter(job -> { Date deadline = getEffectiveDeadline(job); Date expeFinish = getEffectiveExpectedExecutionTime(job, now); return deadline.compareTo(expeFinish) < 0; }) .forEach(job -> { if (!alreadyNotified.contains(job.getId())) { final Date expectedFinishingTime = getEffectiveExpectedExecutionTime(job, now); final Date effectiveDeadline = getEffectiveDeadline(job); LOGGER.warn(String.format("Job[id=%s] will most likely miss its deadline (expected finish: %s, after deadline: %s)", job.getId().value(), expectedFinishingTime, effectiveDeadline)); new JobMostLikelyMissedEmailNotification(job, expectedFinishingTime, effectiveDeadline).checkAndSend(); alreadyNotified.add(job.getId()); } }); }

Target:
private synchronized void logMostLikelyMissedJobs(List<JobDescriptor> jobs) { Date now = new Date(); jobs.stream() .map(jobDescriptor -> ((JobDescriptorImpl) jobDescriptor).getInternal()) .filter(job -> job.getJobDeadline().isPresent()) .filter(job -> job.getJobInfo().getStartTime() < 0) .filter(job -> { Date deadline = getEffectiveDeadline(job); Date expeFinish = getEffectiveExpectedExecutionTime(job, now); return deadline.compareTo(expeFinish) < 0; }) .forEach(job -> { if (!alreadyNotified.contains(job.getId())) { final Date expectedFinishingTime = getEffectiveExpectedExecutionTime(job, now); final Date effectiveDeadline = getEffectiveDeadline(job); LOGGER.warn(String.format("Job[id=%s] will most likely miss its deadline (expected finish: %s, after deadline: %s)", job.getId().value(), expectedFinishingTime, effectiveDeadline)); new JobMostLikelyMissedEmailNotification(job, expectedFinishingTime, effectiveDeadline).checkAndSend(); alreadyNotified.add(job.getId()); } }); }
Source:
protected IStatus onePing(IServer server, Map<String, String> env) throws PollingException, IOException, TimeoutException { String[] args = new String[] { CDKConstants.VAGRANT_CMD_STATUS }; String vagrantcmdloc = MinishiftBinaryUtility.getMinishiftLocation(server); try { String[] lines = VagrantLaunchUtility.callMachineReadable( vagrantcmdloc, args, getWorkingDirectory(server), env); IStatus stat = parseOutput(lines); if( stat.isOK()) { checkOpenShiftHealth(server, 4000); return stat; } else { return stat; } } catch (VagrantTimeoutException vte) { List<String> inLines = vte.getInLines(); if (inLines != null) { String[] asArr = (String[]) inLines.toArray(new String[inLines.size()]); IStatus stat = parseOutput(asArr); if( stat.isOK()) { checkOpenShiftHealth(server, 4000); } else { return stat; } } CDKCoreActivator.pluginLog().logError("Unable to successfully complete a call to vagrant status. ", vte); throw vte; } }

Target:
protected IStatus onePing(IServer server, Map<String, String> env) throws PollingException, IOException, TimeoutException { String[] args = new String[] { CDKConstants.VAGRANT_CMD_STATUS }; String vagrantcmdloc = MinishiftBinaryUtility.getMinishiftLocation(server); try { String[] lines = CDKLaunchUtility.callMachineReadable( vagrantcmdloc, args, getWorkingDirectory(server), env); IStatus stat = parseOutput(lines); if( stat.isOK()) { checkOpenShiftHealth(server, 4000); return stat; } else { return stat; } } catch (CommandTimeoutException vte) { List<String> inLines = vte.getInLines(); if (inLines != null) { String[] asArr = (String[]) inLines.toArray(new String[inLines.size()]); IStatus stat = parseOutput(asArr); if( stat.isOK()) { checkOpenShiftHealth(server, 4000); } else { return stat; } } CDKCoreActivator.pluginLog().logError("Unable to successfully complete a call to vagrant status. ", vte); throw vte; } }
Source:
public ArrayList<VdcActionParametersBase> buildParameters(List<VdsNetworkInterface> nics) { Set<Guid> nonUpdateableHosts = new HashSet<>(); ArrayList<VdcActionParametersBase> parameters = new ArrayList<>(); boolean vlanNetwork = NetworkUtils.isVlan(network); for (VdsNetworkInterface nic : nics) { SetupNetworksParameters setupNetworkParams = createSetupNetworksParameters(nic.getVdsId()); VdsNetworkInterface nicToConfigure = getNicToConfigure(setupNetworkParams.getInterfaces(), nic.getId()); if (nicToConfigure == null) { continue; } if (network.getName().equals(nicToConfigure.getNetworkName())) { nicToConfigure.setNetworkName(null); } else if (vlanNetwork) { VdsNetworkInterface vlan = getVlanDevice(setupNetworkParams, nicToConfigure); if (vlan == null) { nonUpdateableHosts.add(nic.getVdsId()); } else { setupNetworkParams.getInterfaces().remove(vlan); } } else { nonUpdateableHosts.add(nic.getVdsId()); continue; } parameters.add(setupNetworkParams); } reportNonUpdateableHosts(nonUpdateableHosts); return parameters; }

Target:
public ArrayList<VdcActionParametersBase> buildParameters(List<VdsNetworkInterface> nics) { Set<Guid> nonUpdateableHosts = new HashSet<>(); ArrayList<VdcActionParametersBase> parameters = new ArrayList<>(); boolean vlanNetwork = NetworkUtils.isVlan(network); for (VdsNetworkInterface nic : nics) { SetupNetworksParameters setupNetworkParams = createSetupNetworksParameters(nic.getVdsId()); VdsNetworkInterface nicToConfigure = getNicToConfigure(setupNetworkParams.getInterfaces(), nic.getId()); if (network.getName().equals(nicToConfigure.getNetworkName())) { nicToConfigure.setNetworkName(null); } else if (vlanNetwork) { VdsNetworkInterface vlan = getVlanDevice(setupNetworkParams.getInterfaces(), nicToConfigure); if (vlan == null) { nonUpdateableHosts.add(nic.getVdsId()); } else { setupNetworkParams.getInterfaces().remove(vlan); } } else { nonUpdateableHosts.add(nic.getVdsId()); continue; } parameters.add(setupNetworkParams); } reportNonUpdateableHosts(nonUpdateableHosts); return parameters; }
Source:
public void scheduleWithFixedDelay(Object instance, String methodName, Class<?>[] inputTypes, Object[] inputParams, long initialDelay, long taskDelay, TimeUnit timeUnit) { executor.scheduleWithFixedDelay(getRunnable(instance, methodName), initialDelay, taskDelay, TimeUnit.SECONDS); }

Target:
public void scheduleWithFixedDelay(Object instance, String methodName, Class<?>[] inputTypes, Object[] inputParams, long initialDelay, long taskDelay, TimeUnit timeUnit) { executor.scheduleWithFixedDelay(getRunnable(instance, methodName, inputTypes, inputParams), initialDelay, taskDelay, TimeUnit.SECONDS); }
Source:
public void close() throws IOException { }

Target:
public void close() throws IOException { this.iis = null; }
Source:
private void parseInvalidationCache(XMLExtendedStreamReader reader, ConfigurationBuilderHolder holder, boolean template) throws XMLStreamException { String name = reader.getAttributeValue(null, Attribute.NAME.getLocalName()); String extend = reader.getAttributeValue(null, Attribute.EXTENDS.getLocalName()); ConfigurationBuilder builder = getConfigurationBuilder(holder, name, template, extend); CacheMode baseCacheMode = CacheMode.INVALIDATION_SYNC; builder.clustering().cacheMode(baseCacheMode); for (int i = 0; i < reader.getAttributeCount(); i++) { String value = replaceProperties(reader.getAttributeValue(i)); Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case KEY_PARTITIONER_FACTORY: { builder.clustering().hash().keyPartitionerFactory(Util.getInstance(value, holder.getClassLoader())); break; } default: { this.parseClusteredCacheAttribute(reader, i, attribute, value, builder, baseCacheMode); } } } while (reader.hasNext() && (reader.nextTag() != XMLStreamConstants.END_ELEMENT)) { Element element = Element.forName(reader.getLocalName()); switch (element) { default: { this.parseCacheElement(reader, element, holder); } } } }

Target:
private void parseInvalidationCache(XMLExtendedStreamReader reader, ConfigurationBuilderHolder holder, boolean template) throws XMLStreamException { String name = reader.getAttributeValue(null, Attribute.NAME.getLocalName()); String extend = reader.getAttributeValue(null, Attribute.EXTENDS.getLocalName()); ConfigurationBuilder builder = getConfigurationBuilder(holder, name, template, extend); CacheMode baseCacheMode = CacheMode.INVALIDATION_SYNC; builder.clustering().cacheMode(baseCacheMode); for (int i = 0; i < reader.getAttributeCount(); i++) { String value = replaceProperties(reader.getAttributeValue(i)); Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case KEY_PARTITIONER: { builder.clustering().hash().keyPartitioner(Util.getInstance(value, holder.getClassLoader())); break; } default: { this.parseClusteredCacheAttribute(reader, i, attribute, value, builder, baseCacheMode); } } } while (reader.hasNext() && (reader.nextTag() != XMLStreamConstants.END_ELEMENT)) { Element element = Element.forName(reader.getLocalName()); switch (element) { default: { this.parseCacheElement(reader, element, holder); } } } }
Source:
protected boolean deploymentsDiffer(DeploymentEntity deployment, DeploymentEntity saved) { if (deploymentBuilder.hasProjectManifestSet()) { if (!deployment.getProjectReleaseVersion().equals(saved.getProjectReleaseVersion())) { return true; } else { return !deploymentBuilder.getEnforcedAppVersion().equals(saved.getVersion()); } } else { if (deployment.getResources() == null || saved.getResources() == null) { return true; } Map<String, ResourceEntity> resources = deployment.getResources(); Map<String, ResourceEntity> savedResources = saved.getResources(); for (String resourceName : resources.keySet()) { ResourceEntity savedResource = savedResources.get(resourceName); if (savedResource == null) { return true; } if (!savedResource.isGenerated()) { ResourceEntity resource = resources.get(resourceName); byte[] bytes = resource.getBytes(); byte[] savedBytes = savedResource.getBytes(); if (!Arrays.equals(bytes, savedBytes)) { return true; } } } return false; } }

Target:
protected boolean deploymentsDiffer(DeploymentEntity deployment, DeploymentEntity saved) { if (deploymentBuilder.hasEnforcedAppVersion()) { return deploymentsDifferWhenEnforcedAppVersionIsSet(saved); } else if (deploymentBuilder.hasProjectManifestSet()) { return deploymentsDifferWhenProjectManifestIsSet(deployment, saved); } else { return deploymentsDifferDefault(deployment, saved); } }
Source:
public final Iterable<Row> evaluate(TransactionContext txnCtx, Input<List<Object>>[] arguments) { int numCols = arguments.length; Object[] cells = new Object[numCols]; RowN row = new RowN(cells); Iterator<Object>[] iteratorsPerColumn = iteratorsFrom(arguments); return () -> new Iterator<>() { @Override public boolean hasNext() { for (Iterator<Object> it : iteratorsPerColumn) { if (it.hasNext()) { return true; } } return false; } @Override public Row next() { if (!hasNext()) { throw new NoSuchElementException("No more rows"); } for (int i = 0; i < iteratorsPerColumn.length; i++) { Iterator<Object> iterator = iteratorsPerColumn[i]; cells[i] = iterator.hasNext() ? iterator.next() : null; } return row; } }; }

Target:
public final Iterable<Row> evaluate(TransactionContext txnCtx, Input<List<Object>>[] arguments) { return new ColumnOrientedRowsIterator(() -> iteratorsFrom(arguments)); }
Source:
private void parseCommandLineAndGetKillJobParameters(String[] args) throws IOException, YarnException { GnuParser parser = new GnuParser(); CommandLine cli; try { cli = parser.parse(options, args); parametersHolder = ParametersHolder.createWithCmdLine(cli, Command.KILL_JOB); parametersHolder.updateParameters(clientContext); } catch (ParseException e) { printUsages(); } }

Target:
private void parseCommandLineAndGetKillJobParameters(String[] args) throws IOException, YarnException { GnuParser parser = new GnuParser(); CommandLine cli; try { cli = parser.parse(options, args); parametersHolder = ParametersHolder.createWithCmdLine(cli, Command.KILL_JOB); parametersHolder.updateParameters(clientContext); } catch (ParseException e) { LOG.error(("Error parsing command-line options: " + e.getMessage())); printUsages(); } }
Source:
protected Map<Verify, Object> getArguments(ContainerRequestContext requestContext, Method method) { Map<Verify, Object> argMap = new LinkedHashMap<>(); Annotation[][] annotations = annotationLocator.getParameterAnnotations(method); Map<String, List<String>> pathParams = null; Map<String, List<String>> queryParams = null; Map<String, List<String>> headers = null; for (int i = 0; i < annotations.length; ++i) { Verify verify = null; Object value = null; for (Annotation annotation : annotations[i]) { if (annotation instanceof Verify) { verify = (Verify) annotation; } else { List<String> values = null; if (annotation instanceof PathParam) { if (pathParams == null) { pathParams = requestContext.getUriInfo().getPathParameters(true); } values = pathParams.get(((PathParam) annotation).value()); } else if (annotation instanceof QueryParam) { if (queryParams == null) { queryParams = requestContext.getUriInfo().getQueryParameters(true); } values = queryParams.get(((QueryParam) annotation).value()); } else if (annotation instanceof HeaderParam) { if (headers == null) { headers = requestContext.getHeaders(); } values = headers.get(((HeaderParam) annotation).value()); } if (values != null) { value = values.size() > 1 ? values : values.get(0); } } } if (verify != null) { if (!verify.nullable() && value == null) { throw new IllegalStateException("Null passed to a non-nullable Verify annotation."); } log.debug("ASSIGNING VALUE TO VERIFIED ARG: => {}", verify, value); argMap.put(verify, value); } } return argMap; }

Target:
protected Map<Verify, Object> getArguments(ContainerRequestContext requestContext, Method method) { Map<Verify, Object> argMap = new LinkedHashMap<>(); Annotation[][] annotations = annotationLocator.getParameterAnnotations(method); Map<String, List<String>> pathParams = null; Map<String, List<String>> queryParams = null; Map<String, List<String>> headers = null; for (int i = 0; i < annotations.length; ++i) { Verify verify = null; Object value = null; for (Annotation annotation : annotations[i]) { if (annotation instanceof Verify) { verify = (Verify) annotation; } else { List<String> values = null; if (annotation instanceof PathParam) { if (pathParams == null) { pathParams = requestContext.getUriInfo().getPathParameters(true); } values = pathParams.get(((PathParam) annotation).value()); } else if (annotation instanceof QueryParam) { if (queryParams == null) { queryParams = requestContext.getUriInfo().getQueryParameters(true); } values = queryParams.get(((QueryParam) annotation).value()); } else if (annotation instanceof HeaderParam) { if (headers == null) { headers = requestContext.getHeaders(); } values = headers.get(((HeaderParam) annotation).value()); } if (values != null) { value = values.size() > 1 ? values : values.get(0); } } } if (verify != null) { if (!verify.nullable() && value == null) { throw new IllegalStateException("Null passed to a non-nullable Verify annotation."); } argMap.put(verify, value); } } return argMap; }
Source:
public String docs() { return "boolean {locationArray} Returns the command in the Command Block at the given location."; }

Target:
public String docs() { return "string {locationArray} Returns the command string in the Command Block at the given location."; }
Source:
public ClusterSearchShardsResponse getSearchShards(String index, ElasticsearchTableDescription tableDescription) { TransportClient client = clients.get(tableDescription.getClusterName()); verify(client != null); ClusterSearchShardsRequest request = new ClusterSearchShardsRequest(index); return client.admin().cluster().searchShards(request).actionGet(timeout.toMillis()); }

Target:
public ClusterSearchShardsResponse getSearchShards(String index, ElasticsearchTableDescription tableDescription) { TransportClient client = clients.get(tableDescription.getClusterName()); verify(client != null, "TransportClient should not be null"); ClusterSearchShardsRequest request = new ClusterSearchShardsRequest(index); return client.admin() .cluster() .searchShards(request) .actionGet(timeout.toMillis()); }
Source:
protected void updateLocation(final IGeoData geo) { try { boolean repaintRequired = false; if (overlayPosition == null && mapView != null) { overlayPosition = mapView.createAddPositionOverlay(activity); } if ((overlayPosition != null && geo.getLocation() != null) && overlayPosition != null) { overlayPosition.setCoordinates(geo.getLocation()); } if (geo.getCoords() != null) { if (followMyLocation) { myLocationInMiddle(geo); } else { repaintRequired = true; } } if (!Settings.isUseCompass() || geo.getSpeed() > 5) { overlayPosition.setHeading(geo.getBearing()); repaintRequired = true; } if (repaintRequired && mapView != null) { mapView.repaintRequired(overlayPosition); } } catch (Exception e) { Log.w("Failed to update location."); } }

Target:
protected void updateLocation(final IGeoData geo) { try { boolean repaintRequired = false; if (overlayPosition == null && mapView != null) { overlayPosition = mapView.createAddPositionOverlay(activity); } if ((overlayPosition != null && geo.getLocation() != null)) { overlayPosition.setCoordinates(geo.getLocation()); } if (geo.getCoords() != null) { if (followMyLocation) { myLocationInMiddle(geo); } else { repaintRequired = true; } } if (!Settings.isUseCompass() || geo.getSpeed() > 5) { overlayPosition.setHeading(geo.getBearing()); repaintRequired = true; } if (repaintRequired && mapView != null) { mapView.repaintRequired(overlayPosition); } } catch (Exception e) { Log.w("Failed to update location."); } }
Source:
public PaxosLeaderElectionService build() { return new PaxosLeaderElectionService( proposer, knowledge, potentialLeadersToHosts, acceptors, learners, executor, pingRateMs, randomWaitBeforeProposingLeadershipMs, noQuorumMaxDelayMs, leaderPingResponseWaitMs, eventRecorder); }

Target:
public PaxosLeaderElectionService build() { Preconditions.checkState(randomWaitBeforeProposingLeadershipMs >= 0, "randomWaitBeforeProposingLeadershipMs should be positive; was " + randomWaitBeforeProposingLeadershipMs); Preconditions.checkState(noQuorumMaxDelayMs >= 0, "noQuorumMaxDelayMs should be positive; was " + noQuorumMaxDelayMs); return new PaxosLeaderElectionService( proposer, knowledge, potentialLeadersToHosts, acceptors, learners, executor, pingRateMs, randomWaitBeforeProposingLeadershipMs, noQuorumMaxDelayMs, leaderPingResponseWaitMs, eventRecorder); }
Source:
public DockerInternalRuntime getRuntime() throws InfrastructureException { List<ContainerInfo> runningContainers = containers.find(identity); if (runningContainers.isEmpty()) { return runtimeFactory.create(this); } DockerInternalRuntime runtime = runtimeFactory.create(this, runningContainers); try { consistencyChecker.check(environment, runtime); } catch (ValidationException x) { LOG.warn("Runtime '{}:{}' will be stopped as it is not consistent with its configuration. " + "The problem: {}", identity.getWorkspaceId(), identity.getEnvName(), x.getMessage()); stopAsync(runtime); throw new InfrastructureException(x.getMessage(), x); } return runtime; }

Target:
public DockerInternalRuntime getRuntime() throws InfrastructureException { List<ContainerListEntry> runningContainers = containers.find(identity); if (runningContainers.isEmpty()) { return runtimeFactory.create(this); } DockerInternalRuntime runtime = runtimeFactory.create(this, runningContainers); try { consistencyChecker.check(environment, runtime); runtime.checkServers(); } catch (InfrastructureException | ValidationException x) { LOG.warn("Runtime '{}:{}' will be stopped as it is not consistent with its configuration. " + "The problem: {}", identity.getWorkspaceId(), identity.getEnvName(), x.getMessage()); stopAsync(runtime); throw new InfrastructureException(x.getMessage(), x); } return runtime; }
Source:
int nextStreamId() { int n; int o; do { o = streamId; n = o + 2; } while (!STREAM_ID.compareAndSet(this, o, n)); return n; }

Target:
int nextStreamId() { return STREAM_ID.addAndGet(this, 2); }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PatternDruidPredicateFactory that = (PatternDruidPredicateFactory) o; return Objects.equals(extractionFn, that.extractionFn) && Objects.equals(pattern, that.pattern); }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PatternDruidPredicateFactory that = (PatternDruidPredicateFactory) o; return Objects.equals(extractionFn, that.extractionFn) && Objects.equals(pattern.toString(), that.pattern.toString()); }
Source:
public static String getFrom() { String from = null; final StaplerRequest request = Stapler.getCurrentRequest(); if (request.getSession(false) != null) { from = (String) request.getSession().getAttribute("from"); } if (from == null) { from = request.getParameter("from"); } final String requestURI = request.getRequestURI(); if (from == null && requestURI != null && requestURI.compareTo("/loginError") != 0 && requestURI.compareTo("/login") != 0) { from = requestURI; } if (from == null || from.trim().isEmpty()) { from = "/"; } try { from = java.net.URLEncoder.encode(from, "UTF-8"); } catch (UnsupportedEncodingException e) { from = "/"; } return from; }

Target:
public static String getFrom() { String from = null, returnValue = null; final StaplerRequest request = Stapler.getCurrentRequest(); if (request != null && request.getSession(false) != null) { from = (String) request.getSession().getAttribute("from"); } else if (request != null) { from = request.getParameter("from"); } if (from == null && request != null && request.getRequestURI() != null && !request.getRequestURI().equals("/loginError") && !request.getRequestURI().equals("/login")) { from = request.getRequestURI(); } if (StringUtils.isBlank(from)) { from = "/"; } from.trim(); try { returnValue = java.net.URLEncoder.encode(from, "UTF-8"); } catch (UnsupportedEncodingException e) { } return StringUtils.isBlank(returnValue) ? "/" : returnValue; }
Source:
public void loadSegment(DataSegment segment, LoadPeonCallback callback) { synchronized (lock) { if (stopped) { log.warn( "Server[%s] failed to load segment[%s] because load queue peon is stopped.", serverId, segment.getIdentifier() ); callback.execute(); return; } SegmentHolder holder = segmentsToLoad.get(segment); if (holder == null) { log.info("Server[%s] to load segment[%s] queued.", serverId, segment.getIdentifier()); segmentsToLoad.put(segment, new LoadSegmentHolder(segment, callback)); processingExecutor.execute(this::doSegmentManagement); } else { holder.addCallback(callback); } } }

Target:
public void loadSegment(DataSegment segment, LoadPeonCallback callback) { synchronized (lock) { if (stopped) { log.warn( "Server[%s] cannot load segment[%s] because load queue peon is stopped.", serverId, segment.getIdentifier() ); callback.execute(); return; } SegmentHolder holder = segmentsToLoad.get(segment); if (holder == null) { log.info("Server[%s] to load segment[%s] queued.", serverId, segment.getIdentifier()); segmentsToLoad.put(segment, new LoadSegmentHolder(segment, callback)); processingExecutor.execute(this::doSegmentManagement); } else { holder.addCallback(callback); } } }
Source:
public void shouldNotBeConfiguredIfUsernameAndPasswordAreNull() throws Exception { boolean isConfigured = notConfiguredInstance.isConfigured(); assertThat(isConfigured, is(false)); }

Target:
public void shouldNotBeConfiguredIfUsernameAndPasswordAreNull() { boolean isConfigured = notConfiguredInstance.isConfigured(); assertThat(isConfigured, is(false)); }
Source:
private Map<String, Pair<String, String>> getSharedLocksForVmDisk() { Map<String, Pair<String, String>> sharedLocks = new HashMap<>(); if (vmsForDisk != null) { for (Pair<VM, VmDevice> vmForDisk : vmsForDisk) { sharedLocks.put(vmForDisk.getFirst().getId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.VM, EngineMessage.ACTION_TYPE_FAILED_VM_IS_LOCKED)); } } return sharedLocks; }

Target:
private Map<String, Pair<String, String>> getSharedLocksForVmDisk() { Map<String, Pair<String, String>> lockMap = new HashMap<>(); if (getDiskImage() != null) { List<Pair<VM, VmDevice>> vmsForDisk = vmDao.getVmsWithPlugInfo(getDiskImage().getId()); if (!vmsForDisk.isEmpty()) { for (Pair<VM, VmDevice> pair : vmsForDisk) { lockMap.put(pair.getFirst().getId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.VM, EngineMessage.ACTION_TYPE_FAILED_VM_IS_LOCKED)); } } } return lockMap; }
Source:
private void load(AlluxioURI filePath, int replication) throws IOException, AlluxioException { URIStatus status = mFileSystem.getStatus(filePath); if (status.isFolder()) { ListStatusPOptions options = ListStatusPOptions.newBuilder().setRecursive(true).build(); mFileSystem.listStatusInStream(filePath, options).forEach( uriStatus -> { if (!uriStatus.isFolder()) { addJob(uriStatus, replication); } }); } else { addJob(status, replication); } }

Target:
private void load(AlluxioURI filePath, int replication) throws IOException, AlluxioException { ListStatusPOptions options = ListStatusPOptions.newBuilder().setRecursive(true).build(); mFileSystem.iterateStatus(filePath, options, uriStatus -> { if (!uriStatus.isFolder()) { addJob(uriStatus, replication); } }); }
Source:
public void saveStateShouldThrowIllegalArgumentExceptionWhenStateIsNull() { given(statesRepository.save(stateEntity)).willThrow(IllegalArgumentException.class); statesService.saveState(null, FIRST_ID); }

Target:
public void saveStateShouldThrowIllegalArgumentExceptionWhenStateIsNull() { statesService.saveState(null, FIRST_ID); }
Source:
void submitComments( Run<?, ?> build, PrintStream logger, String jenkinsRootUrl, List<JiraIssue> issues, JiraSession session, boolean useWikiStyleComments, boolean recordScmChanges, String groupVisibility, String roleVisibility) throws RestClientException { List<JiraIssue> copy = new ArrayList<JiraIssue>(issues); for (JiraIssue issue : copy) { logger.println(Messages.Updater_Updating(issue.id)); try { session.addComment( issue.id, createComment(build, useWikiStyleComments, jenkinsRootUrl, recordScmChanges, issue), groupVisibility, roleVisibility ); if(!labels.isEmpty()) session.addLabels(issue.id, labels); } catch (RestClientException e) { if (e.getStatusCode().or(0).equals(404)) { logger.println(issue.id + " - JIRA issue not found. Dropping comment from update queue."); } if (e.getStatusCode().or(0).equals(403)) { logger.println(issue.id + " - Jenkins JIRA user does not have permissions to comment on this issue. Preserving comment for future update."); continue; } if (e.getStatusCode().or(0).equals(401)) { logger.println(issue.id + " - Jenkins JIRA authentication problem. Preserving comment for future update."); continue; } logger.println(Messages.Updater_FailedToCommentOnIssue(issue.id)); logger.println(e.getLocalizedMessage()); } issues.remove(issue); } }

Target:
void submitComments( Run<?, ?> build, PrintStream logger, String jenkinsRootUrl, List<JiraIssue> issues, JiraSession session, boolean useWikiStyleComments, boolean recordScmChanges, String groupVisibility, String roleVisibility) throws RestClientException { List<JiraIssue> copy = new ArrayList<JiraIssue>(issues); for (JiraIssue issue : copy) { logger.println(Messages.Updater_Updating(issue.id)); try { session.addComment( issue.id, createComment(build, useWikiStyleComments, jenkinsRootUrl, recordScmChanges, issue), groupVisibility, roleVisibility ); if (!labels.isEmpty()) { session.addLabels(issue.id, labels); } } catch (RestClientException e) { if (e.getStatusCode().or(0).equals(404)) { logger.println(issue.id + " - JIRA issue not found. Dropping comment from update queue."); } if (e.getStatusCode().or(0).equals(403)) { logger.println(issue.id + " - Jenkins JIRA user does not have permissions to comment on this issue. Preserving comment for future update."); continue; } if (e.getStatusCode().or(0).equals(401)) { logger.println(issue.id + " - Jenkins JIRA authentication problem. Preserving comment for future update."); continue; } logger.println(Messages.Updater_FailedToCommentOnIssue(issue.id)); logger.println(e.getLocalizedMessage()); } issues.remove(issue); } }
Source:
public static String getGroupIdsFromUser(DirectoryUser directoryUser) { StringBuilder sb = new StringBuilder(); Set<DirectoryGroup> groupsSet = new HashSet<DirectoryGroup>(); flatGroups(groupsSet, directoryUser.getGroups()); List<DirectoryGroup> groupsList = new ArrayList<DirectoryGroup>(groupsSet); Collections.sort(groupsList, new Comparator<DirectoryGroup>() { @Override public int compare(DirectoryGroup o1, DirectoryGroup o2) { return o1.getId().compareTo(o2.getId()) != 0 ? o1.getId().compareTo(o2.getId()) : o1.getDirectoryName().compareTo(o2.getDirectoryName()); } }); DbGroupDAO dao = DbFacade.getInstance().getDbGroupDao(); if (groupsSet != null) { boolean first = true; for (DirectoryGroup group : groupsSet) { DbGroup dbGroup = dao.getByExternalId(group.getDirectoryName(), group.getId()); if (!first) { sb.append(","); } else { first = false; } sb.append(dbGroup != null ? dbGroup.getId() : Guid.Empty); } } return sb.toString(); }

Target:
public static String getGroupIdsFromUser(DirectoryUser directoryUser) { StringBuilder sb = new StringBuilder(); Set<DirectoryGroup> groupsSet = new HashSet<DirectoryGroup>(); flatGroups(groupsSet, directoryUser.getGroups()); List<DirectoryGroup> groupsList = new ArrayList<DirectoryGroup>(groupsSet); Collections.sort(groupsList, new Comparator<DirectoryGroup>() { @Override public int compare(DirectoryGroup o1, DirectoryGroup o2) { return o1.getId().compareTo(o2.getId()) != 0 ? o1.getId().compareTo(o2.getId()) : o1.getDirectoryName().compareTo(o2.getDirectoryName()); } }); DbGroupDAO dao = DbFacade.getInstance().getDbGroupDao(); if (groupsSet != null) { boolean first = true; for (DirectoryGroup group : groupsList) { DbGroup dbGroup = dao.getByExternalId(group.getDirectoryName(), group.getId()); if (!first) { sb.append(","); } else { first = false; } sb.append(dbGroup != null ? dbGroup.getId() : Guid.Empty); } } return sb.toString(); }
Source:
public static ClientInfo getClientInfo() { info.setSdkVersion(config.getSdkVersion()); return info; }

Target:
public static ClientInfo getClientInfo() { return info; }
Source:
public void editTitleTest() throws Exception { String title = "new title"; document.addContent(new Element("mods", MODS_V3_NS) .addContent(new Element("titleInfo", MODS_V3_NS) .addContent(new Element("title", MODS_V3_NS).setText("original title")))); when(binaryObj.getBinaryStream()).thenReturn(convertDocumentToStream(document)); service.editTitle(agent, pid, title); verify(operationsMessageSender).sendUpdateDescriptionOperation(anyString(), pidsCaptor.capture()); Collection<PID> pids = pidsCaptor.getValue(); assertEquals(pids.size(), 1); assertTrue(pids.contains(pid)); }

Target:
public void editTitleTest() throws Exception { String title = "new title"; document.addContent(new Element("mods", MODS_V3_NS) .addContent(new Element("titleInfo", MODS_V3_NS) .addContent(new Element("title", MODS_V3_NS).setText("original title")))); when(binaryObj.getBinaryStream()).thenReturn(convertDocumentToStream(document)); service.editTitle(agent, pid, title); verify(operationsMessageSender).sendUpdateDescriptionOperation(anyString(), pidsCaptor.capture()); Collection<PID> pids = pidsCaptor.getValue(); assertEquals(1, pids.size()); assertTrue(pids.contains(pid)); Document updatedDoc = getUpdatedDescriptionDocument(); assertTrue(hasTitleValue(updatedDoc, title)); }
Source:
protected void broadcastPrepare(TxInvocationContext context, PrepareCommand command) { try { boolean async = cacheConfiguration.clustering().cacheMode() == CacheMode.REPL_ASYNC; rpcManager.invokeRemotely(null, command, rpcManager.getDefaultRpcOptions(!async)); } finally { transactionRemotelyPrepared(context); } }

Target:
protected void broadcastPrepare(TxInvocationContext context, PrepareCommand command) { try { boolean sync = cacheConfiguration.clustering().cacheMode().isSynchronous(); rpcManager.invokeRemotely(null, command, rpcManager.getDefaultRpcOptions(sync)); } finally { transactionRemotelyPrepared(context); } }
Source:
private void moveVdsToUp(VDS vds) { vds.setNonOperationalReason(null); DbFacade.getInstance().getVdsDynamicDao().update(vds.getDynamicData()); HostStoragePoolParametersBase tempVar = new HostStoragePoolParametersBase(vds); Backend.getInstance().runInternalAction(VdcActionType.InitVdsOnUp, tempVar); }

Target:
private void moveVdsToUp(VDS vds) { trustedVdses.add(vds.getId()); vds.setStatus(VDSStatus.Up); DbFacade.getInstance().getVdsDynamicDao().update(vds.getDynamicData()); }
Source:
protected void quitDefaultWebDriver() { if (driver != null) { try { driver.get("about:config"); driver.quit(); } finally { driver = null; } } }

Target:
protected void quitDefaultWebDriver() { if (driver != null) { try { driver.quit(); } finally { driver = null; } } }
Source:
public ResponseEntity<String> delete(@PathVariable("id") Long id) { try { userUtil.extractLoggedAppUserFromDatabase(); Counterparty counterparty = counterpartyDao.findOne(id); if(counterparty == null){ throw new NotFoundException("Counterparty not found"); } counterpartyDao.delete(id); counterpartyDao.flush(); } catch (EmptyResultDataAccessException emptyResultDataAccessException) { throw new NotFoundException(emptyResultDataAccessException.getMessage()); } return new ResponseEntity<>("Counterparty deleted", HttpStatus.NO_CONTENT); }

Target:
public ResponseEntity<String> delete(@PathVariable("id") Long id) { try { userUtil.extractLoggedAppUserFromDatabase(); Counterparty counterparty = counterpartyDao.findOne(id); if(counterparty == null){ throw new NotFoundException("Counterparty not found"); } AppUser loggedUser = userUtil.extractLoggedAppUserFromDatabase(); if(loggedUser.getUserId() != counterparty.getUser().getUserId()){ throw new BadRequestException("Bad request!"); } counterpartyDao.delete(id); counterpartyDao.flush(); } catch (EmptyResultDataAccessException emptyResultDataAccessException) { throw new NotFoundException(emptyResultDataAccessException.getMessage()); } return new ResponseEntity<>("Counterparty deleted", HttpStatus.NO_CONTENT); }
Source:
public void acceptsNoContentLengthOnClosedConnection() throws Exception { final String text = "Close Test"; final ByteArrayOutputStream output = new ByteArrayOutputStream(); final ServerSocket server = new ServerSocket(0); try { new Thread( new Runnable() { @Override public void run() { try { new BkBasic(new TkText(text)).accept( server.accept() ); } catch (final IOException exception) { throw new IllegalStateException(exception); } } } ).start(); final Socket socket = new Socket( server.getInetAddress(), server.getLocalPort() ); try { socket.getOutputStream().write( Joiner.on(BkBasicTest.CRLF).join( BkBasicTest.POST, BkBasicTest.HOST, "Connection: Close", "", BkBasicTest.HELLO_WORLD ).getBytes() ); final InputStream input = socket.getInputStream(); final byte[] buffer = new byte[4096]; for (int count = input.read(buffer); count != -1; count = input.read(buffer)) { output.write(buffer, 0, count); } } finally { socket.close(); } } finally { server.close(); } MatcherAssert.assertThat( output.toString(), Matchers.containsString(text) ); }

Target:
public void acceptsNoContentLengthOnClosedConnection() throws Exception { final String text = "Close Test"; final ByteArrayOutputStream output = new ByteArrayOutputStream(); final ServerSocket server = new ServerSocket(0); final String greetings = "Hi everyone"; try { new Thread( new Runnable() { @Override public void run() { try { new BkBasic(new TkText(text)).accept( server.accept() ); } catch (final IOException exception) { throw new IllegalStateException(exception); } } } ).start(); final Socket socket = new Socket( server.getInetAddress(), server.getLocalPort() ); try { socket.getOutputStream().write( Joiner.on(BkBasicTest.CRLF).join( BkBasicTest.POST, BkBasicTest.HOST, "Connection: Close", "", greetings ).getBytes() ); final InputStream input = socket.getInputStream(); final byte[] buffer = new byte[4096]; for (int count = input.read(buffer); count != -1; count = input.read(buffer)) { output.write(buffer, 0, count); } } finally { socket.close(); } } finally { server.close(); } MatcherAssert.assertThat( output.toString(), Matchers.containsString(text) ); }