auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void processDataOrChildChange(WatchedEvent event, long notificationTime) { final String path = event.getPath(); final boolean pathExists = event.getType() != EventType.NodeDeleted; if (EventType.NodeDeleted == event.getType()) { LOG.info("event delelete:" + event.getPath()); } if (event.getType() == EventType.NodeChildrenChanged || event.getType() == EventType.NodeCreated || event.getType() == EventType.NodeDeleted) { Set<IZkChildListener> childListeners = _childListener.get(path); if (childListeners != null && !childListeners.isEmpty()) { fireChildChangedEvents(path, childListeners, pathExists); } } if (event.getType() == EventType.NodeDataChanged || event.getType() == EventType.NodeDeleted || event.getType() == EventType.NodeCreated) { Set<IZkDataListenerEntry> listeners = _dataListener.get(path); if (listeners != null && !listeners.isEmpty()) { fireDataChangedEvents(event.getPath(), listeners, OptionalLong.of(notificationTime), pathExists); } } }

Target:
private void processDataOrChildChange(WatchedEvent event, long notificationTime) { final String path = event.getPath(); final boolean pathExists = event.getType() != EventType.NodeDeleted; if (EventType.NodeDeleted == event.getType()) { LOG.debug("Event NodeDeleted: {}", event.getPath()); } if (event.getType() == EventType.NodeChildrenChanged || event.getType() == EventType.NodeCreated || event.getType() == EventType.NodeDeleted) { Set<IZkChildListener> childListeners = _childListener.get(path); if (childListeners != null && !childListeners.isEmpty()) { fireChildChangedEvents(path, childListeners, pathExists); } } if (event.getType() == EventType.NodeDataChanged || event.getType() == EventType.NodeDeleted || event.getType() == EventType.NodeCreated) { Set<IZkDataListenerEntry> listeners = _dataListener.get(path); if (listeners != null && !listeners.isEmpty()) { fireDataChangedEvents(event.getPath(), listeners, OptionalLong.of(notificationTime), pathExists); } } }
Source:
public ByteStreamSplitValuesWriter(int elementSizeInBytes, int initialCapacity, int pageSize, ByteBufferAllocator allocator) { this.numStreams = elementSizeInBytes; this.elementSizeInBytes = elementSizeInBytes; this.byteStreams = new CapacityByteArrayOutputStream[elementSizeInBytes]; final int capacityPerStream = (pageSize + this.numStreams - 1) / this.numStreams; final int initialCapacityPerStream = (initialCapacity + this.numStreams - 1) / this.numStreams; for (int i = 0; i < this.numStreams; ++i) { this.byteStreams[i] = new CapacityByteArrayOutputStream( initialCapacityPerStream, capacityPerStream, allocator); } }

Target:
public ByteStreamSplitValuesWriter(int elementSizeInBytes, int initialCapacity, int pageSize, ByteBufferAllocator allocator) { if (elementSizeInBytes <= 0) { throw new ParquetEncodingException(String.format("Element byte size is invalid: %d", elementSizeInBytes)); } this.numStreams = elementSizeInBytes; this.elementSizeInBytes = elementSizeInBytes; this.byteStreams = new CapacityByteArrayOutputStream[elementSizeInBytes]; final int capacityPerStream = (pageSize + this.numStreams - 1) / this.numStreams; final int initialCapacityPerStream = (initialCapacity + this.numStreams - 1) / this.numStreams; for (int i = 0; i < this.numStreams; ++i) { this.byteStreams[i] = new CapacityByteArrayOutputStream( initialCapacityPerStream, capacityPerStream, allocator); } }
Source:
public static void setSchemaClass(Job job, Class clazz) { SchemaUtils.setSchemaClass(SchemaUtils.Type.Input, job, clazz); }

Target:
public static void setSchemaClass(Job job, Class clazz) { SchemaUtils.setSchemaClass(PojoType.Input, job, clazz); }
Source:
public void updated(Dictionary<String, ?> config) throws ConfigurationException { logger.debug("Plex binding updated"); if (config != null) { PlexConnection connection = new PlexConnection(); Enumeration<String> keys = config.keys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); if ("service.pid".equals(key)) continue; String value = ((String) config.get(key)).trim(); if ("host".equals(key)) connection.setHost(value); else if ("port".equals(key)) connection.setPort(Integer.valueOf(value)); else if ("refresh".equals(key)) if (StringUtils.isNumeric(value)) refreshInterval = Integer.valueOf(value); else logger.warn("Non-numeric refresh interval {}, using default {}", value, refreshInterval); } logger.debug("Plex config, server at {}:{}", connection.getHost(), connection.getPort()); if (!StringUtils.isEmpty(connection.getHost())) { connector = new PlexConnector(connection, new PlexUpdateReceivedCallback() { @Override public void updateReceived(PlexSession session) { processUpdateRecevied(session); } @Override public void serverListUpdated(MediaContainer container) { processServerList(container); } }); connector.start(); setInitialState(); setProperlyConfigured(true); } else { logger.warn("No host IP configured for Plex binding"); } } }

Target:
public void updated(Dictionary<String, ?> config) throws ConfigurationException { logger.debug("Plex binding updated"); if (config != null) { PlexConnectionProperties connectionProperties = new PlexConnectionProperties(); Enumeration<String> keys = config.keys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); if ("service.pid".equals(key)) continue; String value = ((String) config.get(key)).trim(); if ("host".equals(key)) connectionProperties.setHost(value); else if ("port".equals(key)) connectionProperties.setPort(Integer.valueOf(value)); else if ("refresh".equals(key)) if (StringUtils.isNumeric(value)) refreshInterval = Integer.valueOf(value); else logger.warn("Non-numeric refresh interval {}, using default {}", value, refreshInterval); } logger.debug("Plex config, server at {}:{}", connectionProperties.getHost(), connectionProperties.getPort()); if (!StringUtils.isEmpty(connectionProperties.getHost())) { connect(connectionProperties); setProperlyConfigured(true); } else { logger.warn("No host IP configured for Plex binding"); } } }
Source:
public void testRuntime() throws Exception { setProperty(); KernelServicesBuilder builder = createKernelServicesBuilder(UndertowSubsystem100TestCase.RUNTIME) .setSubsystemXml(getSubsystemXml()); KernelServices mainServices = builder.build(); testRuntime(mainServices, virtualHostName, flag); testRuntimeOther(mainServices); }

Target:
public void testRuntime() throws Exception { setProperty(); KernelServicesBuilder builder = createKernelServicesBuilder(AbstractUndertowSubsystemTestCase.RUNTIME) .setSubsystemXml(getSubsystemXml()); KernelServices mainServices = builder.build(); testRuntime(mainServices, virtualHostName, flag); testRuntimeOther(mainServices); }
Source:
void doClear(RegionEventImpl regionEvent, boolean cacheWrite) { String lockName = CLEAR_OPERATION + partitionedRegion.getName(); long clearStartTime = 0; try { acquireDistributedClearLock(lockName); clearStartTime = System.nanoTime(); assignAllPrimaryBuckets(); if (cacheWrite) { invokeCacheWriter(regionEvent); } boolean acquireClearLockForNotification = (partitionedRegion.hasAnyClientsInterested() || partitionedRegion.hasListener()); if (acquireClearLockForNotification) { obtainLockForClear(regionEvent); } try { Set<Integer> bucketsCleared = clearRegion(regionEvent); if (partitionedRegion.getTotalNumberOfBuckets() != bucketsCleared.size()) { String message = "Unable to clear all the buckets from the partitioned region " + partitionedRegion.getName() + ", either data (buckets) moved or member departed."; logger.warn(message + " expected to clear number of buckets: " + partitionedRegion.getTotalNumberOfBuckets() + " actual cleared: " + bucketsCleared.size()); throw new PartitionedRegionPartialClearException(message); } } finally { if (acquireClearLockForNotification) { releaseLockForClear(regionEvent); } } } finally { releaseDistributedClearLock(lockName); if (partitionedRegion.getCachePerfStats() != null) { CachePerfStats stats = partitionedRegion.getRegionCachePerfStats(); if (stats != null) { partitionedRegion.getRegionCachePerfStats() .incPartitionedRegionClearTotalDuration(System.nanoTime() - clearStartTime); } } } }

Target:
void doClear(RegionEventImpl regionEvent, boolean cacheWrite) { String lockName = CLEAR_OPERATION + partitionedRegion.getName(); long clearStartTime = 0; try { acquireDistributedClearLock(lockName); clearStartTime = System.nanoTime(); assignAllPrimaryBuckets(); if (cacheWrite) { invokeCacheWriter(regionEvent); } boolean acquireClearLockForNotification = (partitionedRegion.hasAnyClientsInterested() || partitionedRegion.hasListener()); if (acquireClearLockForNotification) { obtainLockForClear(regionEvent); } try { Set<Integer> bucketsCleared = clearRegion(regionEvent); if (partitionedRegion.getTotalNumberOfBuckets() != bucketsCleared.size()) { String message = "Unable to clear all the buckets from the partitioned region " + partitionedRegion.getName() + ", either data (buckets) moved or member departed."; logger.warn(message + " expected to clear number of buckets: " + partitionedRegion.getTotalNumberOfBuckets() + " actual cleared: " + bucketsCleared.size()); throw new PartitionedRegionPartialClearException(message); } } finally { if (acquireClearLockForNotification) { releaseLockForClear(regionEvent); } } } finally { releaseDistributedClearLock(lockName); CachePerfStats stats = partitionedRegion.getRegionCachePerfStats(); if (stats != null) { partitionedRegion.getRegionCachePerfStats() .incPartitionedRegionClearTotalDuration(System.nanoTime() - clearStartTime); } } }
Source:
public static void testMergeLocalUserModifiedCoordsAndServerSideModified() { final Geocache stored = new Geocache(); stored.setGeocode("GC12345"); stored.setUserModifiedCoords(true); stored.setCoords(new Geopoint(40.0, 8.0)); final Waypoint originalStored = new Waypoint("ORIGINAL", WaypointType.ORIGINAL, false); originalStored.setCoords(new Geopoint(42.0, 10.0)); stored.addOrChangeWaypoint(originalStored, false); saveFreshCacheToDB(stored); final Geocache download = new Geocache(); download.setGeocode("GC12345"); download.setCoords(new Geopoint(41.0, 9.0)); final Waypoint originalDownloaded = new Waypoint("ORIGINAL", WaypointType.ORIGINAL, false); originalDownloaded.setCoords(new Geopoint(43.0, 11.0)); download.addOrChangeWaypoint(originalDownloaded, false); download.setUserModifiedCoords(true); download.gatherMissingFrom(stored); assertThat(download.hasUserModifiedCoords()).as("merged user modified").isEqualTo(true); assertThat(download.getCoords()).as("merged coordinates").isEqualTo(new Geopoint(41.0, 9.0)); assertThat(download.getWaypoints()).as("merged waypoints size").hasSize(1); assertThat(download.getOriginalWaypoint().getCoords()).as("merged original wp").isEqualTo(new Geopoint(43.0, 11.0)); }

Target:
public static void testMergeLocalUserModifiedCoordsAndServerSideModified() { final Geocache stored = new Geocache(); stored.setGeocode("GC12345"); stored.setUserModifiedCoords(true); stored.setCoords(new Geopoint(40.0, 8.0)); final Waypoint originalStored = new Waypoint("ORIGINAL", WaypointType.ORIGINAL, false); originalStored.setCoords(new Geopoint(42.0, 10.0)); stored.addOrChangeWaypoint(originalStored, false); saveFreshCacheToDB(stored); final Geocache download = new Geocache(); download.setGeocode("GC12345"); download.setCoords(new Geopoint(41.0, 9.0)); final Waypoint originalDownloaded = new Waypoint("ORIGINAL", WaypointType.ORIGINAL, false); originalDownloaded.setCoords(new Geopoint(43.0, 11.0)); download.addOrChangeWaypoint(originalDownloaded, false); download.setUserModifiedCoords(true); download.gatherMissingFrom(stored); assertThat(download.hasUserModifiedCoords()).as("merged user modified").isEqualTo(true); assertThat(download.getCoords()).as("merged coordinates").isEqualTo(new Geopoint(41.0, 9.0)); assertThat(download.getWaypoints()).as("merged waypoints").hasSize(1); assertThat(download.getOriginalWaypoint().getCoords()).as("merged original wp").isEqualTo(new Geopoint(43.0, 11.0)); }
Source:
public Expr visitAlterTable(Context context, Stack<Expr> stack, AlterTable expr) throws TajoException { if (expr.getAlterTableOpType() == AlterTableOpType.ADD_PARTITION) { context.state.addVerification(new UnsupportedException("ADD PARTITION")); } return expr; }

Target:
public Expr visitAlterTable(Context context, Stack<Expr> stack, AlterTable expr) throws TajoException { if (expr.getAlterTableOpType() == AlterTableOpType.ADD_PARTITION) { context.state.addVerification(new NotImplementedException("ADD PARTITION")); } return expr; }
Source:
MetaParamsInternalMetadata(NumericVersion numericVersion, SimpleClusteredVersion clusteredVersion, long created, long lastUsed, long lifespan, long maxIdle) { this.params = new MetaParams(MetaParams.EMPTY_ARRAY, 0); this.params.add(new MetaEntryVersion(numericVersion == null ? clusteredVersion : numericVersion)); if (created > -1) params.add(new MetaCreated(created)); if (lastUsed > -1) params.add(new MetaLastUsed(lastUsed)); if (lifespan > -1) params.add(new MetaLifespan(lifespan)); if (maxIdle > -1) params.add(new MetaMaxIdle(maxIdle)); }

Target:
MetaParamsInternalMetadata(NumericVersion numericVersion, SimpleClusteredVersion clusteredVersion, long created, long lastUsed, long lifespan, long maxIdle) { this.params = new MetaParams(MetaParams.EMPTY_ARRAY, 0); if (numericVersion != null || clusteredVersion != null) { this.params.add(new MetaEntryVersion(numericVersion == null ? clusteredVersion : numericVersion)); } if (created > -1) params.add(new MetaCreated(created)); if (lastUsed > -1) params.add(new MetaLastUsed(lastUsed)); if (lifespan > -1) params.add(new MetaLifespan(lifespan)); if (maxIdle > -1) params.add(new MetaMaxIdle(maxIdle)); }
Source:
void savePOMFile() { String projectPath = ((genProject.getLocation()).toFile()).getAbsolutePath(); try { File file = new File(projectPath + "\\pom.xml"); FileWriter pomFileWriter= new FileWriter(file); new MavenXpp3Writer().write(pomFileWriter, pomFileModel ); pomFileWriter.close(); } catch (IOException e) { e.printStackTrace(); } }

Target:
void savePOMFile() { String projectPath = ((genProject.getLocation()).toFile()).getAbsolutePath(); try { File file = new File(projectPath + "/pom.xml"); FileWriter pomFileWriter = new FileWriter(file); new MavenXpp3Writer().write(pomFileWriter, pomFileModel); pomFileWriter.close(); } catch (IOException e) { e.printStackTrace(); } }
Source:
public void setUp() throws Exception { if (Display.getCurrent() != null) { log.warn("SWTBot test needs to run in a non-UI thread.\n" + "Make sure that \"Run in UI thread\" is unchecked in your launch configuration or that useUIThread is set to false in the pom.xml"); } }

Target:
protected void setUp() throws Exception { if (Display.getCurrent() != null) { fail("SWTBot test needs to run in a non-UI thread.\n" + "Make sure that \"Run in UI thread\" is unchecked in your launch configuration or that useUIThread is set to false in the pom.xml"); } }
Source:
public void setLinkedId(final String linkedId) { if (this.linkedId != null) { CommonHelper.assertNotNull("linkedId", linkedId); } this.linkedId = linkedId; }

Target:
public void setLinkedId(final String linkedId) { this.linkedId = linkedId; }
Source:
public void afterPropertiesSet() throws Exception { Matcher matcher = NO_SYNCHRONIZATION_PATTERN.matcher(root); if (matcher.matches()) { registry = new ResourceModuleRegistry(root, true); ((ResourceModuleRegistry)registry).afterPropertiesSet(); logger.info("Custom modules will be written directly to {}", root); } else { String localRoot = "file:" + Files.createTempDirectory("spring-xd-custom-modules"); ResourceModuleRegistry local = new ResourceModuleRegistry(localRoot, true); local.afterPropertiesSet(); ResourceModuleRegistry remote = new ResourceModuleRegistry(root, true); remote.afterPropertiesSet(); registry = new SynchronizingModuleRegistry(remote, local); logger.info("Custom modules will be written at and kept in synch locally at {}", root, localRoot); } }

Target:
public void afterPropertiesSet() throws Exception { Matcher matcher = NO_SYNCHRONIZATION_PATTERN.matcher(root); if (matcher.matches()) { registry = new WritableResourceModuleRegistry(root); ((WritableResourceModuleRegistry)registry).afterPropertiesSet(); logger.info("Custom modules will be written directly to {}", root); } else { String localRoot = "file:" + Files.createTempDirectory("spring-xd-custom-modules"); WritableResourceModuleRegistry local = new WritableResourceModuleRegistry(localRoot); local.afterPropertiesSet(); WritableResourceModuleRegistry remote = new WritableResourceModuleRegistry(root); remote.afterPropertiesSet(); registry = new SynchronizingModuleRegistry(remote, local); logger.info("Custom modules will be written at and kept in synch locally at {}", root, localRoot); } }
Source:
private String convertQuakemlToString(Quakeml message) throws Exception{ return formatConverter.getString(message,validate); }

Target:
private String convertQuakemlToString(Quakeml message) throws Exception{ return fixRawQuakeml(formatConverter.getString(message,validate)); }
Source:
public Optional<PlanNodeStatsEstimate> doCalculate(FilterNode node, StatsProvider statsProvider, Lookup lookup, Session session, TypeProvider types) { PlanNodeStatsEstimate sourceStats = statsProvider.getStats(node.getSource()); PlanNodeStatsEstimate estimate = filterStatsCalculator.filterStats(sourceStats, node.getPredicate(), session, types); if (isDefaultFilterFactorEnabled(session) && estimate.isOutputRowCountUnknown()) { estimate = estimate.mapOutputRowCount(unknownRowCount -> sourceStats.getOutputRowCount() * UNKNOWN_FILTER_COEFFICIENT); } return Optional.of(estimate); }

Target:
public Optional<PlanNodeStatsEstimate> doCalculate(FilterNode node, StatsProvider statsProvider, Lookup lookup, Session session, TypeProvider types) { PlanNodeStatsEstimate sourceStats = statsProvider.getStats(node.getSource()); PlanNodeStatsEstimate estimate = filterStatsCalculator.filterStats(sourceStats, node.getPredicate(), session, types); if (isDefaultFilterFactorEnabled(session) && estimate.isOutputRowCountUnknown()) { estimate = sourceStats.mapOutputRowCount(sourceRowCount -> sourceStats.getOutputRowCount() * UNKNOWN_FILTER_COEFFICIENT); } return Optional.of(estimate); }
Source:
public DilutionDto updateDilution(@PathVariable Long dilutionId, @RequestBody DilutionDto dilutionDto) throws IOException { if (dilutionDto == null) { log.error( "Received null dilutionDto from front end; cannot convert to Dilution. Something likely went wrong in the JS DTO conversion."); throw new RestException("Cannot convert null to Dilution", Status.BAD_REQUEST); } LibraryDilution dilution = Dtos.to(dilutionDto); dilution.setCreator(securityStore.getUserByFullName(dilutionDto.getDilutionUserName())); dilution.setId(dilutionId); dilutionService.update(dilution); return getDilution(dilutionId); }

Target:
public DilutionDto updateDilution(@PathVariable Long dilutionId, @RequestBody DilutionDto dilutionDto) throws IOException { if (dilutionDto == null) { log.error( "Received null dilutionDto from front end; cannot convert to Dilution. Something likely went wrong in the JS DTO conversion."); throw new RestException("Cannot convert null to Dilution", Status.BAD_REQUEST); } LibraryDilution dilution = Dtos.to(dilutionDto); dilution.setId(dilutionId); dilutionService.update(dilution); return getDilution(dilutionId); }
Source:
public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) { KeycloakTransaction tx = Resteasy.getContextData(KeycloakTransaction.class); if (tx != null && tx.isActive()) { if (tx.getRollbackOnly()) { tx.rollback(); } else { if (!(containerResponseContext.getEntity() instanceof java.util.stream.Stream)) { tx.commit(); } else if (tx instanceof SupportsPostponedCommit) { ((SupportsPostponedCommit) tx).postponeCommit(); } else { throw new RuntimeException(tx.getClass() + " doesn't support postponed commit."); } } } }

Target:
public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) { KeycloakTransaction tx = Resteasy.getContextData(KeycloakTransaction.class); if (tx != null && tx.isActive()) { if (tx.getRollbackOnly()) { tx.rollback(); } else if ((containerResponseContext.getEntity() instanceof java.util.stream.Stream) && tx instanceof SupportsPostponedCommit) { ((SupportsPostponedCommit) tx).postponeCommit(); } else { tx.commit(); } } }
Source:
public boolean init( StepMetaInterface stepMetaInterface, StepDataInterface stepDataInterface ) { boolean init = super.init( stepMetaInterface, stepDataInterface ); Preconditions.checkNotNull( stepMetaInterface ); mqttConsumerMeta = (MQTTConsumerMeta) stepMetaInterface; RowMeta rowMeta = new RowMeta(); try { mqttConsumerMeta.getFields( rowMeta, getStepname(), null, null, this, repository, metaStore ); } catch ( KettleStepException e ) { logger.error( getString( PKG, "MQTTInput.Error.FailureGettingFields" ), e ); } window = new FixedTimeStreamWindow<>( subtransExecutor, rowMeta, getDuration(), getBatchSize() ); try { source = new MQTTStreamSource( environmentSubstitute( mqttConsumerMeta.getMqttServer() ), Arrays.asList( environmentSubstitute( mqttConsumerMeta.getTopics().toArray( new String[]{} ) ) ), Integer.parseInt( environmentSubstitute( mqttConsumerMeta.getQos() ) ), this ); } catch ( NumberFormatException e ) { log.logError( BaseMessages.getString( PKG, "MQTT.Error.QOS", environmentSubstitute( mqttConsumerMeta.getQos() ) ) ); return false; } return init; }

Target:
public boolean init( StepMetaInterface stepMetaInterface, StepDataInterface stepDataInterface ) { boolean init = super.init( stepMetaInterface, stepDataInterface ); Preconditions.checkNotNull( stepMetaInterface ); mqttConsumerMeta = (MQTTConsumerMeta) stepMetaInterface; RowMeta rowMeta = new RowMeta(); try { mqttConsumerMeta.getFields( rowMeta, getStepname(), null, null, this, repository, metaStore ); } catch ( KettleStepException e ) { logger.error( getString( PKG, "MQTTInput.Error.FailureGettingFields" ), e ); } window = new FixedTimeStreamWindow<>( subtransExecutor, rowMeta, getDuration(), getBatchSize() ); try { final List<String> topics = mqttConsumerMeta.getTopics(); source = new MQTTStreamSource( environmentSubstitute( mqttConsumerMeta.getMqttServer() ), Arrays.asList( environmentSubstitute( topics.toArray( new String[ topics.size() ] ) ) ), Integer.parseInt( environmentSubstitute( mqttConsumerMeta.getQos() ) ), this ); } catch ( NumberFormatException e ) { log.logError( BaseMessages.getString( PKG, "MQTT.Error.QOS", environmentSubstitute( mqttConsumerMeta.getQos() ) ) ); return false; } return init; }
Source:
protected String getColorByProgress(int progress) { return progress < 70 ? "#669966" : progress < 95 ? "#FF9900" : "#FF0000"; }

Target:
protected String getColorByProgress(int progress) { if (progress < 70) { return ProgressBarColors.GREEN.asCode(); } else if (progress < 95) { return ProgressBarColors.ORANGE.asCode(); } else { return ProgressBarColors.RED.asCode(); } }
Source:
public List<String> imageSearch(String searchText) { List<String> resultUrls = new ArrayList<String>(); try { String url = "<LINK_0>search?lr=lang_" + Runtime.getInstance().getLocaleTag() + "&site=imghp&tbm=isch&source=hp&q=" + searchText + "&gws_rd=cr"; String filename = URLEncoder.encode(searchText, StandardCharsets.UTF_8.toString()); Document doc = Jsoup.connect(url).userAgent(USER_AGENT).referrer("<LINK_0>").get(); String html = doc.toString(); resultUrls = extractImageRefs(html); System.out.println("number of results: " + resultUrls.size()); for (String imageUrl : resultUrls) { invoke("publishImage", imageUrl); } invoke("publishImages", resultUrls); } catch (Exception e) { error("parsing image threw", e); } return resultUrls; }

Target:
public List<String> imageSearch(String searchText) { List<String> resultUrls = new ArrayList<String>(); try { String url = "<LINK_0>search?lr=lang_" + locale.getTag() + "&site=imghp&tbm=isch&source=hp&q=" + searchText + "&gws_rd=cr"; String filename = URLEncoder.encode(searchText, StandardCharsets.UTF_8.toString()); Document doc = Jsoup.connect(url).userAgent(USER_AGENT).referrer("<LINK_0>").get(); String html = doc.toString(); resultUrls = extractImageRefs(html); System.out.println("number of results: " + resultUrls.size()); for (String imageUrl : resultUrls) { invoke("publishImage", imageUrl); } invoke("publishImages", resultUrls); } catch (Exception e) { error("parsing image threw", e); } return resultUrls; }
Source:
private void joinAll() throws InterruptedException { if (!threads.isEmpty()) { for (Thread thread : threads) { thread.join(); } } }

Target:
private void joinAll() throws InterruptedException { for (Thread thread : threads) { thread.join(); } }
Source:
public synchronized void onWorkerDeleted(final String workerId) { workerClockMap.remove(workerId); if (minimumClockWorkers.contains(workerId)) { minimumClockWorkers.remove(workerId); if (minimumClockWorkers.size() == 0) { globalMinimumClock = workerClockMap.isEmpty() ? 0 : Collections.min(workerClockMap.values()); broadcastGlobalMinimumClock(); } } }

Target:
public synchronized void onWorkerDeleted(final String workerId) { workerClockMap.remove(workerId); if (minimumClockWorkers.remove(workerId)) { if (minimumClockWorkers.size() == 0) { globalMinimumClock = workerClockMap.isEmpty() ? INITIAL_GLOBAL_MINIMUM_CLOCK : Collections.min(workerClockMap.values()); broadcastGlobalMinimumClock(); } } }
Source:
public void testEntityInfo_VersionDoesNotExist(){ assertFalse(new FakeMetadata().checkVersionExists("fake", "1.0")); }

Target:
public void testEntityInfo_VersionDoesNotExist(){ assertFalse(new FakeMetadata().checkVersionExists("fake", "1.0.0")); }
Source:
public SinkFormat<SerializationSchema<RowData>> createSinkFormat( DynamicTableFactory.Context context, ReadableConfig formatOptions) { validateFormatOptions(formatOptions); return new SinkFormat<SerializationSchema<RowData>>() { @Override public SerializationSchema<RowData> createSinkFormat( DynamicTableSink.Context context, DataType consumedDataType) { final RowType rowType = (RowType) consumedDataType.getLogicalType(); final CsvRowDataSerializationSchema.Builder schemaBuilder = new CsvRowDataSerializationSchema.Builder(rowType); configureSerializationSchema(formatOptions, schemaBuilder); return schemaBuilder.build(); } @Override public ChangelogMode getChangelogMode() { return ChangelogMode.insertOnly(); } }; }

Target:
public SinkFormat<SerializationSchema<RowData>> createSinkFormat( DynamicTableFactory.Context context, ReadableConfig formatOptions) { FactoryUtil.validateFactoryOptions(this, formatOptions); validateFormatOptions(formatOptions); return new SinkFormat<SerializationSchema<RowData>>() { @Override public SerializationSchema<RowData> createSinkFormat( DynamicTableSink.Context context, DataType consumedDataType) { final RowType rowType = (RowType) consumedDataType.getLogicalType(); final CsvRowDataSerializationSchema.Builder schemaBuilder = new CsvRowDataSerializationSchema.Builder(rowType); configureSerializationSchema(formatOptions, schemaBuilder); return schemaBuilder.build(); } @Override public ChangelogMode getChangelogMode() { return ChangelogMode.insertOnly(); } }; }
Source:
private String tagsToString(final Set<String> tags) { final StringBuilder stringBuilder = new StringBuilder(); if (!tags.isEmpty()) { final ArrayList<String> sortedTags = new ArrayList<>(tags); sortedTags.sort(Comparator.naturalOrder()); for (int i = 0; i < sortedTags.size(); i++) { stringBuilder.append(sortedTags.get(i)); if (i < sortedTags.size() - 1) { stringBuilder.append(','); } } } return stringBuilder.toString(); }

Target:
String tagsToString(final Set<String> tags) { final ArrayList<String> sortedTags = new ArrayList<>(tags == null ? Collections.emptySet() : tags); sortedTags.sort(Comparator.naturalOrder()); final String joinedString = StringUtils.join(sortedTags, ','); return StringUtils.replaceAll(StringUtils.replaceAll(joinedString, "\'", "\\\'"), "\"", "\\\""); }
Source:
public ClientProcess() throws RemoteException { super(); this.isAlive = true; this.serverAlive = true; this.logger = Logger.getLogger(ClientProcess.class.getName()); logger.log(Level.INFO, "Starting client"); }

Target:
public ClientProcess() throws RemoteException { super(); this.isAlive = true; this.serverAlive = false; this.logger = Logger.getLogger(ClientProcess.class.getName()); logger.log(Level.INFO, "Starting client"); }
Source:
public void setNameExpression(Expression nameExpression) { System.out.println("Setting2 " + nameExpression); this.nameExpression = nameExpression; }

Target:
public void setNameExpression(Expression nameExpression) { this.nameExpression = nameExpression; }
Source:
public String getText(Object element) { String str = ""; if (element instanceof SpecfileSection) { SpecfileSection specfileSection = (SpecfileSection) element; str = specfileSection.toString(); } else if (element instanceof Specfile) { str = ((Specfile) element).getName(); } else if (element instanceof SpecfilePackageContainer) { str = Messages.SpecfileLabelProvider_0; } else if (element instanceof SpecfilePreamble){ str = Messages.SpecfileLabelProvider_1; } else if (element instanceof SpecfileElement) { SpecfileElement specfileElement = (SpecfileElement) element; str = specfileElement.getName(); } else if (element instanceof String) { str = (String) element; } else if (element instanceof SpecfilePackage) { str = ((SpecfilePackage) element).getName(); } return str.trim(); }

Target:
public String getText(Object element) { String str = ""; if (element instanceof SpecfileSection) { SpecfileSection specfileSection = (SpecfileSection) element; str = specfileSection.toString(); } else if (element instanceof Specfile) { str = ((Specfile) element).getName(); } else if (element instanceof SpecfilePackageContainer) { str = Messages.SpecfileLabelProvider_0; } else if (element instanceof SpecfilePreamble){ str = Messages.SpecfileLabelProvider_1; } else if (element instanceof SpecfileElement) { SpecfileElement specfileElement = (SpecfileElement) element; str = specfileElement.getName(); } else if (element instanceof String) { str = (String) element; } else if (element instanceof SpecfilePackage) { str = ((SpecfilePackage) element).getName(); } return filterMacros(str.trim()); }
Source:
public ServiceDefinition introspectServiceInterface(Class<?> serviceInterface) { Service serviceAnnotation = serviceInterface.getAnnotation(Service.class); checkArgument(serviceAnnotation != null, "Not a service interface: %s", serviceInterface); String serviceName = resolveServiceName(serviceInterface, serviceAnnotation); Map<String, Method> methods = new HashMap<>(); for (Method method : serviceInterface.getMethods()) { if (method.isAnnotationPresent(ServiceMethod.class)) { ServiceMethod methodAnnotation = method.getAnnotation(ServiceMethod.class); String methodName = resolveMethodName(method, methodAnnotation); if (methods.containsKey(methodName)) { throw new IllegalStateException("Service method with name '" + methodName + "' already exists"); } methods.put(methodName, method); } } ServiceDefinition serviceDefinition = new ServiceDefinition(serviceInterface, serviceName, Collections.unmodifiableMap(methods)); return serviceDefinition; }

Target:
public ServiceDefinition introspectServiceInterface(Class<?> serviceInterface) { Service serviceAnnotation = serviceInterface.getAnnotation(Service.class); checkArgument(serviceAnnotation != null, "Not a service interface: %s", serviceInterface); String serviceName = resolveServiceName(serviceInterface, serviceAnnotation); Map<String, Method> methods = Arrays.stream(serviceInterface.getMethods()) .filter(method -> method.isAnnotationPresent(ServiceMethod.class)) .collect(Collectors.toMap(method -> { ServiceMethod methodAnnotation = method.getAnnotation(ServiceMethod.class); return resolveMethodName(method, methodAnnotation); }, Function.identity())); return new ServiceDefinition(serviceInterface, serviceName, Collections.unmodifiableMap(methods)); }
Source:
public SignatureKeyManager( @Named("che.auth.signature_key_size") int keySize, @Named("che.auth.signature_key_algorithm") String algorithm, EventService eventService, SignatureKeyDao signatureKeyDao) { this.keySize = keySize; this.algorithm = algorithm; this.eventService = eventService; this.signatureKeyDao = signatureKeyDao; this.workspaceEventsSubscriber = new EventSubscriber<WorkspaceStatusEvent>() { @Override public void onEvent(WorkspaceStatusEvent event) { switch (event.getStatus()) { case STOPPED: try { cachedPair.remove(event.getWorkspaceId()); signatureKeyDao.remove(event.getWorkspaceId()); } catch (ServerException e) { LOG.error(e.getLocalizedMessage(), e); } break; default: } } }; }

Target:
public SignatureKeyManager( @Named("che.auth.signature_key_size") int keySize, @Named("che.auth.signature_key_algorithm") String algorithm, EventService eventService, SignatureKeyDao signatureKeyDao) { this.keySize = keySize; this.algorithm = algorithm; this.eventService = eventService; this.signatureKeyDao = signatureKeyDao; this.cachedPair = CacheBuilder.newBuilder() .maximumSize(100) .expireAfterAccess(2, TimeUnit.HOURS) .build( new CacheLoader<String, KeyPair>() { @Override public KeyPair load(String key) throws Exception { return loadKeyPair(key); } }); this.workspaceEventsSubscriber = new EventSubscriber<WorkspaceStatusEvent>() { @Override public void onEvent(WorkspaceStatusEvent event) { if (event.getStatus() == STOPPED) { removeKeyPair(event.getWorkspaceId()); } } }; }
Source:
public static void updateActivity(Channel channel, Activity activity, String channelId) throws ActivitySerializerException { try { activity.setProvider(getProvider()); Actor actor = new Actor(); activity.setVerb("post"); actor.setId("id:youtube:"+channel.getId()); actor.setSummary(channel.getSnippet().getDescription()); actor.setDisplayName(channel.getSnippet().getTitle()); Image image = new Image(); image.setUrl(channel.getSnippet().getThumbnails().getHigh().getUrl()); actor.setImage(image); actor.setUrl("<LINK_0>" + channel.getId()); Map<String, Object> actorExtensions = Maps.newHashMap(); actorExtensions.put("followers", channel.getStatistics().getSubscriberCount()); actorExtensions.put("posts", channel.getStatistics().getVideoCount()); actor.setAdditionalProperty("extensions", actorExtensions); activity.setActor(actor); Map<String, Object> extensions = Maps.newHashMap(); extensions.put("youtube", channel); activity.setAdditionalProperty("extensions", extensions); } catch (Throwable t) { throw new ActivitySerializerException(t); } }

Target:
public static void updateActivity(Channel channel, Activity activity, String channelId) throws ActivitySerializerException { try { activity.setProvider(getProvider()); activity.setVerb("post"); activity.setActor(createActorForChannel(channel)); Map<String, Object> extensions = Maps.newHashMap(); extensions.put("youtube", channel); activity.setAdditionalProperty("extensions", extensions); } catch (Throwable t) { throw new ActivitySerializerException(t); } }
Source:
public String getTranslatedFamilyName() { String[] transNames = familyName.split("/"); if (transNames != null && transNames.length > 0) { IComponentsFactory factory = ComponentsFactoryProvider.getInstance(); String translated = factory.getFamilyTranslation(this, "FAMILY." + transNames[0].replace(" ", "_")); translatedFamilyName = translated + "/DB Common"; } return translatedFamilyName; }

Target:
public String getTranslatedFamilyName() { String[] transNames = familyName.split("/"); IComponentsFactory factory = ComponentsFactoryProvider.getInstance(); if (transNames != null && transNames.length > 0) { StringBuffer stringBuffer = new StringBuffer(); for (String toTranslate : transNames) { String translated = factory.getFamilyTranslation(this, "FAMILY." + toTranslate.replace(" ", "_")); if (translated.startsWith("!!")) { if (stringBuffer.length() > 0) { stringBuffer.append("/"); } stringBuffer.append(toTranslate); } else { if (stringBuffer.length() > 0) { stringBuffer.append("/"); } stringBuffer.append(translated); } } translatedFamilyName = stringBuffer.toString(); } return translatedFamilyName; }
Source:
private static int upgradeTextBoxProperties(Map<String, JSONValue> componentProperties, int srcCompVersion) { if (srcCompVersion < 2) { srcCompVersion = 2; } if (srcCompVersion < 3) { handlePropertyRename(componentProperties, "Alignment", "TextAlignment"); srcCompVersion = 3; } if (srcCompVersion < 4) { componentProperties.put("MultiLine", new ClientJsonString("True")); srcCompVersion = 4; } if (srcCompVersion < 5) { srcCompVersion = 5; } if (scrCompVersion < 6) { srcCompVersion = 6; } return srcCompVersion; }

Target:
private static int upgradeTextBoxProperties(Map<String, JSONValue> componentProperties, int srcCompVersion) { if (srcCompVersion < 2) { srcCompVersion = 2; } if (srcCompVersion < 3) { handlePropertyRename(componentProperties, "Alignment", "TextAlignment"); srcCompVersion = 3; } if (srcCompVersion < 4) { componentProperties.put("MultiLine", new ClientJsonString("True")); srcCompVersion = 4; } if (srcCompVersion < 5) { srcCompVersion = 5; } if (srcCompVersion < 6) { srcCompVersion = 6; } return srcCompVersion; }
Source:
public Laplace(double mean, double diversity) { fixedMean = true; setMean(new Double(mean)); fixedDiversity = true; setDiversity(new Double(diversity)); }

Target:
public Laplace(double mean, double diversity) { expectMeanAsArg = false; setMean(mean); expectDiversityAsArg = false; setDiversity(diversity); }
Source:
@Test public void completableSuccess200() { server.enqueue(new MockResponse().setBody("Hi")); try { service.completable().await(); assertThat(true); } catch (RuntimeException e) { fail(); } }

Target:
@Test public void completableSuccess200() { server.enqueue(new MockResponse().setBody("Hi")); service.completable().await(); }
Source:
public void runAndCollect(Runnable runnable) { IObservable[] collected = ObservableTracker.runAndCollect(runnable); for (IObservable element : collected) addObservable(element); }

Target:
public void runAndCollect(Runnable runnable) { IObservable[] collected = ObservableTracker.runAndCollect(runnable); for (IObservable observable : collected) addObservable(observable); }
Source:
public static Builder builder() { return new Builder() { List<Destination> fmb = new ArrayList<>(); @Override public Builder loadFileTo(String fileName, RangeType rangeType, Text startRow, Text endRow) { fmb.add(new Destination(fileName, rangeType, copy(startRow), copy(endRow))); return this; } @Override public Builder loadFileTo(String fileName, RangeType rangeType, byte[] startRow, byte[] endRow) { fmb.add(new Destination(fileName, rangeType, copy(startRow), copy(endRow))); return this; } @Override public Builder loadFileTo(String fileName, RangeType rangeType, CharSequence startRow, CharSequence endRow) { fmb.add(new Destination(fileName, rangeType, copy(startRow), copy(endRow))); return this; } @Override public Builder addPlan(LoadPlan plan) { fmb.addAll(plan.getDestinations()); return this; } @Override public LoadPlan build() { return new LoadPlan(Collections.unmodifiableList(fmb)); } }; }

Target:
public static Builder builder() { return new Builder() { ImmutableList.Builder<Destination> fmb = ImmutableList.builder(); @Override public Builder loadFileTo(String fileName, RangeType rangeType, Text startRow, Text endRow) { fmb.add(new Destination(fileName, rangeType, copy(startRow), copy(endRow))); return this; } @Override public Builder loadFileTo(String fileName, RangeType rangeType, byte[] startRow, byte[] endRow) { fmb.add(new Destination(fileName, rangeType, copy(startRow), copy(endRow))); return this; } @Override public Builder loadFileTo(String fileName, RangeType rangeType, CharSequence startRow, CharSequence endRow) { fmb.add(new Destination(fileName, rangeType, copy(startRow), copy(endRow))); return this; } @Override public Builder addPlan(LoadPlan plan) { fmb.addAll(plan.getDestinations()); return this; } @Override public LoadPlan build() { return new LoadPlan(fmb.build()); } }; }
Source:
public IndexDiffData(IndexDiff indexDiff) { added.addAll(indexDiff.getAdded()); changed.addAll(indexDiff.getChanged()); removed.addAll(indexDiff.getRemoved()); missing.addAll(indexDiff.getMissing()); modified.addAll(indexDiff.getModified()); untracked.addAll(indexDiff.getUntracked()); conflicts.addAll(indexDiff.getConflicting()); changedFileResources = null; makeSetsUnmodifiable(); }

Target:
public IndexDiffData(IndexDiff indexDiff) { added = Collections.unmodifiableSet(new HashSet<String>(indexDiff .getAdded())); changed = Collections.unmodifiableSet(new HashSet<String>(indexDiff .getChanged())); removed = Collections.unmodifiableSet(new HashSet<String>(indexDiff .getRemoved())); missing = Collections.unmodifiableSet(new HashSet<String>(indexDiff .getMissing())); modified = Collections.unmodifiableSet(new HashSet<String>(indexDiff .getModified())); untracked = Collections.unmodifiableSet(new HashSet<String>(indexDiff .getUntracked())); conflicts = Collections.unmodifiableSet(new HashSet<String>(indexDiff .getConflicting())); changedFileResources = null; }
Source:
public ExtendedInMemoryUserDetailsManager myUserDetailsService() { ExtendedInMemoryUserDetailsManager extendedInMemoryUserDetailsManager = new ExtendedInMemoryUserDetailsManager(); List<GrantedAuthority> salaboyAuthorities = new ArrayList<>(); salaboyAuthorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_USER")); salaboyAuthorities.add(new SimpleGrantedAuthority("GROUP_activitiTeam")); salaboyAuthorities.add(new SimpleGrantedAuthority("GROUP_developers")); extendedInMemoryUserDetailsManager.createUser(new User("salaboy", "password", salaboyAuthorities)); List<GrantedAuthority> adminAuthorities = new ArrayList<>(); adminAuthorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_ADMIN")); extendedInMemoryUserDetailsManager.createUser(new User("admin", "password", adminAuthorities)); List<GrantedAuthority> garthAuthorities = new ArrayList<>(); garthAuthorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_USER")); garthAuthorities.add(new SimpleGrantedAuthority("GROUP_doctor")); extendedInMemoryUserDetailsManager.createUser(new User("garth", "password", garthAuthorities)); return extendedInMemoryUserDetailsManager; }

Target:
public UserDetails myUserDetailsService() { ExtendedInMemoryUserDetailsManager extendedInMemoryUserDetailsManager = new ExtendedInMemoryUserDetailsManager(); List<GrantedAuthority> salaboyAuthorities = new ArrayList<>(); salaboyAuthorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_USER")); salaboyAuthorities.add(new SimpleGrantedAuthority("GROUP_activitiTeam")); salaboyAuthorities.add(new SimpleGrantedAuthority("GROUP_developers")); extendedInMemoryUserDetailsManager.createUser(new User("salaboy", "password", salaboyAuthorities)); List<GrantedAuthority> adminAuthorities = new ArrayList<>(); adminAuthorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_ADMIN")); extendedInMemoryUserDetailsManager.createUser(new User("admin", "password", adminAuthorities)); List<GrantedAuthority> garthAuthorities = new ArrayList<>(); garthAuthorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_USER")); garthAuthorities.add(new SimpleGrantedAuthority("GROUP_doctor")); extendedInMemoryUserDetailsManager.createUser(new User("garth", "password", garthAuthorities)); return (UserDetails) extendedInMemoryUserDetailsManager; }
Source:
private void serializeLocalBookieConfig(ServerConfiguration localBookieConfig, String fileName) throws IOException { File localBookiesConfigDir = new File(localBookieConfig.getLocalBookiesConfigDirName()); File localBookieConfFile = new File(localBookiesConfigDir, fileName); if (localBookieConfFile.exists() && !localBookieConfFile.delete()) { throw new IOException( "Unable to delete the existing LocalBookieConfigFile - " + localBookieConfFile.getAbsolutePath()); } if (!localBookieConfFile.createNewFile()) { throw new IOException("Unable to create new File - " + localBookieConfFile.getAbsolutePath()); } PrintWriter writer = new PrintWriter(localBookieConfFile); Iterator<String> keys = localBookieConfig.getKeys(); try { while (keys.hasNext()) { String key = keys.next().toString(); String[] values = localBookieConfig.getStringArray(key); StringBuilder concatenatedValue = new StringBuilder(values[0]); for (int i = 1; i < values.length; i++) { concatenatedValue.append("," + values[i]); } writer.println(key + "=" + concatenatedValue.toString()); } } finally { writer.flush(); writer.close(); } }

Target:
private void serializeLocalBookieConfig(ServerConfiguration localBookieConfig, String fileName) throws IOException { File localBookieConfFile = new File(localBookiesConfigDir, fileName); if (localBookieConfFile.exists() && !localBookieConfFile.delete()) { throw new IOException( "Unable to delete the existing LocalBookieConfigFile - " + localBookieConfFile.getAbsolutePath()); } if (!localBookieConfFile.createNewFile()) { throw new IOException("Unable to create new File - " + localBookieConfFile.getAbsolutePath()); } Iterator<String> keys = localBookieConfig.getKeys(); try (PrintWriter writer = new PrintWriter(localBookieConfFile, "UTF-8")) { while (keys.hasNext()) { String key = keys.next().toString(); String[] values = localBookieConfig.getStringArray(key); StringBuilder concatenatedValue = new StringBuilder(values[0]); for (int i = 1; i < values.length; i++) { concatenatedValue.append("," + values[i]); } writer.println(key + "=" + concatenatedValue.toString()); } } }
Source:
public SelfReferencingURLMapper(final String localFedoraServer, final MigrationIDMapper idMapper) { this.contentPatterns = new ArrayList<Pattern>(); this.contentPatterns.add(parsePattern(OLD_DS_CONTENT_URL_PATTERN, localFedoraServer)); this.contentPatterns.add(parsePattern(NEW_DS_CONTENT_URL_PATTERN, localFedoraServer)); this.idMapper = idMapper; this.invalidPattern = parsePattern("http://{local-fedora-server}/fedora/.*", localFedoraServer); }

Target:
public SelfReferencingURLMapper(final String localFedoraServer, final MigrationIDMapper idMapper) { this.contentPatterns = new ArrayList<>(); this.contentPatterns.add(parsePattern(OLD_DS_CONTENT_URL_PATTERN, localFedoraServer)); this.contentPatterns.add(parsePattern(NEW_DS_CONTENT_URL_PATTERN, localFedoraServer)); this.idMapper = idMapper; this.invalidPattern = parsePattern("http://{local-fedora-server}/fedora/.*", localFedoraServer); }