auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>static void fetchInputAndOutputStreamPartitions(JobGraph jobGraph, StreamManager streamManager) { Set<StreamEdge> existingStreams = new HashSet<>(); existingStreams.addAll(jobGraph.getInputStreams()); <START> existingStreams.addAll(jobGraph.getOutputStreams()); <END> Multimap<String, String> systemToStreams = HashMultimap.create(); Map<String, StreamEdge> streamToStreamEdge = new HashMap<>(); for (StreamEdge streamEdge : existingStreams) { SystemStream systemStream = streamEdge.getSystemStream(); String stream = systemStream.getStream(); systemToStreams.put(systemStream.getSystem(), stream); streamToStreamEdge.put(stream, streamEdge); } for (String system : systemToStreams.keySet()) { Collection<String> streams = systemToStreams.get(system); Map<String, Integer> streamToPartitionCount = streamManager.getStreamPartitionCounts(system, new HashSet<>(streams)); for (Map.Entry<String, Integer> entry : streamToPartitionCount.entrySet()) { String stream = entry.getKey(); Integer partitionCount = entry.getValue(); streamToStreamEdge.get(stream).setPartitionCount(partitionCount); log.info("Fetched partition count value of for stream {}", partitionCount, stream); } } }</code><technical_language>effectively un-nesting lookup in this map one-level. Previously, map of [streamName -> streamEdge] per-system. appears changed this a single-map of [streamName -> streamEdge].. Do present issues read streamName systems? a concrete example LinkedIn: imagine reading stream - PageViewEvent "tracking" "aggregate-tracking" Kafka clusters. "system-level" scope considered streams treated 2 distinct - StreamEdges</technical_language>

Target:
static void fetchInputAndOutputStreamPartitions(JobGraph jobGraph, StreamManager streamManager) { Set<StreamEdge> existingStreams = new HashSet<>(); existingStreams.addAll(jobGraph.getInputStreams()); existingStreams.addAll(jobGraph.getOutputStreams()); Multimap<String, StreamEdge> systemToStreamEdges = HashMultimap.create(); for (StreamEdge streamEdge : existingStreams) { String system = streamEdge.getSystemStream().getSystem(); systemToStreamEdges.put(system, streamEdge); } for (String system : systemToStreamEdges.keySet()) { Collection<StreamEdge> streamEdges = systemToStreamEdges.get(system); Map<String, StreamEdge> streamToStreamEdge = new HashMap<>(); for (StreamEdge streamEdge : streamEdges) { streamToStreamEdge.put(streamEdge.getSystemStream().getStream(), streamEdge); } Set<String> streams = streamToStreamEdge.keySet(); Map<String, Integer> streamToPartitionCount = streamManager.getStreamPartitionCounts(system, streams); for (Map.Entry<String, Integer> entry : streamToPartitionCount.entrySet()) { String stream = entry.getKey(); Integer partitionCount = entry.getValue(); streamToStreamEdge.get(stream).setPartitionCount(partitionCount); log.info("Fetched partition count value for stream {}", partitionCount, stream); } } }
Source:
<code>public void testToString() throws CalendarParserException { Assert.assertTrue(invoke("toString") instanceof EvalError); Assert.assertEquals(invoke("toString", (Object) null), "null"); Assert.assertEquals(invoke("toString", Long.valueOf(100)),"100"); Assert.assertEquals(invoke("toString", Double.valueOf(100.0)),"100.0"); Assert.assertEquals(invoke("toString", Double.valueOf(100.0),"%.0f"),"100"); String expectedDate = "2013-06-01T00:00:00Z"; Assert.assertEquals(invoke("toString", CalenderParser.parseAsOffsetDateTime("2013-06-01")), expectedDate); <START> Assert.assertEquals(invoke("toString", CalenderParser.parseAsOffsetDateTime("2013-06-01"),"yyyy-MM-dd"),expectedDate); <END> }</code><technical_language>This test is incorrect (L122). Assert.assertEquals(invoke("toString", CalenderParser.parseAsOffsetDateTime("2013-06-01"),"yyyy-MM-dd"),"2013-06-01");</technical_language>

Target:
public void testToString() throws CalendarParserException { Assert.assertTrue(invoke("toString") instanceof EvalError); Assert.assertEquals(invoke("toString", (Object) null), "null"); Assert.assertEquals(invoke("toString", Long.valueOf(100)),"100"); Assert.assertEquals(invoke("toString", Double.valueOf(100.0)),"100.0"); Assert.assertEquals(invoke("toString", Double.valueOf(100.0),"%.0f"),"100"); String inputDate = "2013-06-01"; Assert.assertEquals(invoke("toString", CalendarParser.parseAsOffsetDateTime(inputDate)), "01-Jun-2013"); Assert.assertEquals(invoke("toString", CalendarParser.parseAsOffsetDateTime(inputDate), "yyyy-MM-dd"), "2013-06-01"); Assert.assertEquals(invoke("toString", CalendarParser.parseAsOffsetDateTime(inputDate), "yyyy/dd/MM"), "2013/01/06"); Assert.assertEquals(invoke("toString", CalendarParser.parseAsOffsetDateTime(inputDate), "yyyy-MMM"), "2013-Jun"); Assert.assertEquals(invoke("toString", CalendarParser.parseAsOffsetDateTime(inputDate), "yyyy-MM-dd hh:mm:ss"), "2013-06-01 12:00:00"); String inputDateTime = "2013-06-01 13:12:11"; Assert.assertEquals(invoke("toString", CalendarParser.parseAsOffsetDateTime(inputDateTime)), "01-Jun-2013"); Assert.assertEquals(invoke("toString", CalendarParser.parseAsOffsetDateTime(inputDateTime), "yyyy-MM-dd"), "2013-06-01"); Assert.assertEquals(invoke("toString", CalendarParser.parseAsOffsetDateTime(inputDateTime), "yyyy-MM-dd hh:mm:ss"),"2013-06-01 01:12:11"); Assert.assertEquals(invoke("toString", CalendarParser.parseAsOffsetDateTime(inputDateTime), "yyyy-MM-dd HH:mm:ss"),"2013-06-01 13:12:11"); }
Source:
<code>private static Boolean checkCacheForMatches(String inputText, TypeReferenceLocation location) { <START> String key = location + "_" + inputText; <END> Boolean cachedResult = (Boolean) resultsCache.get(key); Long lookupCount = cacheLookupCount.incrementAndGet(); Long hitCount = cacheHitCount.get(); if (cachedResult != null) { hitCount = cacheHitCount.incrementAndGet(); } if (lookupCount % 100000L == 0) { long hitPercentage = Math.round(((double) hitCount / (double) lookupCount) * 100); LOG.info("There have been " + lookupCount + " lookups with " + hitCount + " hits, for a hit percentage of: " + hitPercentage); } return cachedResult; }</code><technical_language>Suggest turning this a method call consistent / easier keys used/created</technical_language>

Target:
private static Boolean checkCacheForMatches(String inputText, TypeReferenceLocation location) { String key = getCacheKey(location, inputText); Boolean cachedResult = (Boolean) resultsCache.get(key); Long lookupCount = cacheLookupCount.incrementAndGet(); Long hitCount = cacheHitCount.get(); if (cachedResult != null) { hitCount = cacheHitCount.incrementAndGet(); } if (lookupCount % 100000L == 0) { long hitPercentage = Math.round(((double) hitCount / (double) lookupCount) * 100); LOG.info("There have been " + lookupCount + " lookups with " + hitCount + " hits, for a hit percentage of: " + hitPercentage); } return cachedResult; }
Source:
<code>public final Response toResponse(T exception) { String exceptionMessage = Objects.toString(exception.getMessage()); String errorId = UUID.randomUUID().toString(); StatusType status = this.getStatus(exception); if (status.getFamily().equals(Response.Status.Family.CLIENT_ERROR)) { log.info("Error handling request {}", errorId, exception); } else { <START> log.error("Error handling request {}", errorId, exception); <END> } ResponseBuilder builder = Response.status(status); try { final SerializableError error; if (includeStackTrace) { StackTraceElement[] stackTrace = exception.getStackTrace(); error = SerializableError.of(exceptionMessage, exception.getClass(), Arrays.asList(stackTrace)); } else { error = SerializableError.of("Refer to the server logs with this errorId: " + errorId, exception.getClass()); } builder.type(MediaType.APPLICATION_JSON); String json = MAPPER.writeValueAsString(error); builder.entity(json); } catch (RuntimeException | JsonProcessingException e) { log.warn("Unable to translate exception to json for request {}", errorId, e); builder = Response.status(status); builder.type(MediaType.TEXT_PLAIN); builder.entity(exceptionMessage); } return builder.build(); }</code><technical_language>Is a reason include actual status code a safe arg? I realize get request log, this more useful context here, in addition error ID</technical_language>

Target:
public final Response toResponse(T exception) { String exceptionMessage = Objects.toString(exception.getMessage()); String errorId = UUID.randomUUID().toString(); StatusType status = this.getStatus(exception); if (status.getFamily().equals(Response.Status.Family.CLIENT_ERROR)) { log.info("Error handling request {}", SafeArg.of("errorId", errorId), exception); } else { log.error("Error handling request {}", SafeArg.of("errorId", errorId), exception); } ResponseBuilder builder = Response.status(status); try { final SerializableError error; if (includeStackTrace) { StackTraceElement[] stackTrace = exception.getStackTrace(); error = SerializableError.of(exceptionMessage, exception.getClass(), Arrays.asList(stackTrace)); } else { error = SerializableError.of("Refer to the server logs with this errorId: " + errorId, exception.getClass()); } builder.type(MediaType.APPLICATION_JSON); String json = MAPPER.writeValueAsString(error); builder.entity(json); } catch (RuntimeException | JsonProcessingException e) { log.warn("Unable to translate exception to json for request {}", SafeArg.of("errorId", errorId), e); builder = Response.status(status); builder.type(MediaType.TEXT_PLAIN); builder.entity(exceptionMessage); } return builder.build(); }
Source:
<code>public void asyncWriteWithPersistWaitTime() throws Exception { AlluxioURI filePath = new AlluxioURI(PathUtils.uniqPath()); createTwoBytesFile(mFileSystem, filePath, 2000); <START> CommonUtils.sleepMs(500); <END> IntegrationTestUtils .checkPersistStateAndWaitForPersist(sLocalAlluxioClusterResource, mFileSystem, filePath, 2); }</code><technical_language>if shorten intervals for cluster, shorten this? Or, line do wait anyways? If so, this line do anything</technical_language>

Target:
public void asyncWriteWithPersistWaitTime() throws Exception { AlluxioURI filePath = new AlluxioURI(PathUtils.uniqPath()); createTwoBytesFile(mFileSystem, filePath, 2000); IntegrationTestUtils .checkPersistStateAndWaitForPersist(sLocalAlluxioClusterResource, mFileSystem, filePath, 2); }
Source:
<code>public void appendTo(ExpressionBuilder builder, boolean useQuotes) { <START> appendTo(builder, QuoteMethod.ALWAYS); <END> }</code><technical_language>if useQuotes else NEVER</technical_language>

Target:
public void appendTo(ExpressionBuilder builder, boolean useQuotes) { appendTo(builder, useQuotes ? QuoteMethod.ALWAYS : QuoteMethod.NEVER); }
Source:
<code>public void navigate() { FinderNavigation navigation; if (ConfigUtils.isDomain()) { navigation = new FinderNavigation(browser, DomainConfigEntryPoint.class); navigation.step(FinderNames.CONFIGURATION, FinderNames.PROFILES) .step(FinderNames.PROFILE, ConfigUtils.getDefaultProfile()) <START> .step(FinderNames.SUBSYSTEM, "EE"); <END> } else { navigation = new FinderNavigation(browser, StandaloneConfigEntryPoint.class); navigation.step(FinderNames.CONFIGURATION, FinderNames.SUBSYSTEMS) .step(FinderNames.SUBSYSTEM, "EE"); } navigation.selectRow().invoke(FinderNames.VIEW); Application.waitUntilVisible(); }</code><technical_language>This step is for standalone domain ;-)</technical_language>

Target:
public void navigate() { FinderNavigation navigation; if (ConfigUtils.isDomain()) { navigation = new FinderNavigation(browser, DomainConfigEntryPoint.class) .step(FinderNames.CONFIGURATION, FinderNames.PROFILES) .step(FinderNames.PROFILE, ConfigUtils.getDefaultProfile()); } else { navigation = new FinderNavigation(browser, StandaloneConfigEntryPoint.class) .step(FinderNames.CONFIGURATION, FinderNames.SUBSYSTEMS); } navigation.step(FinderNames.SUBSYSTEM, "EE") .selectRow() .invoke(FinderNames.VIEW); Application.waitUntilVisible(); }
Source:
<code>public DocComparator.Difference<Object> compareNodesWithFallback(DBObject oldDoc,DBObject newDoc) throws Exception { <START> while(true) { <END> try { return compareNodes(oldDoc,newDoc); } catch(DocComparator.DuplicateArrayIdentity dai) { LOGGER.debug("Duplicate ID:{}"); Path p=dai.getPath(); ignoredIdentities.add(getArray(p)); LOGGER.debug("Ignored paths:{}",ignoredIdentities); } catch(DocComparator.InvalidArrayIdentity iai) { LOGGER.debug("Invalid ID:{}"); Path p=iai.getPath(); ignoredIdentities.add(getArray(p)); LOGGER.debug("Ignored paths:{}",ignoredIdentities); } } }</code><technical_language>a for avoid infinite loop in case is wrong loop logic? throw exception if reaches 1000 so</technical_language>

Target:
public DocComparator.Difference<Object> compareNodesWithFallback(DBObject oldDoc,DBObject newDoc) throws Exception { int n=getArrayIdentities().size()+1; for(int i=0;i<n;i++) { try { return compareNodes(oldDoc,newDoc); } catch(DocComparator.DuplicateArrayIdentity dai) { LOGGER.warn("Duplicate array element id for doc._id:{}, field:{}",oldDoc.get("_id"),dai.getPath()); Path p=dai.getPath(); ignoredIdentities.add(getArray(p)); LOGGER.debug("Ignored paths:{}",ignoredIdentities); } catch(DocComparator.InvalidArrayIdentity iai) { LOGGER.warn("Invalid array element id for doc._id:{}, field:{}",oldDoc.get("_id"),iai.getPath()); Path p=iai.getPath(); ignoredIdentities.add(getArray(p)); LOGGER.debug("Ignored paths:{}",ignoredIdentities); } } throw new RuntimeException("Cannot compute document diffs even with ignored identities:"+ignoredIdentities); }
Source:
<code><START> public void testCustomSerializerWithSerializableSillyManagementExample() throws IOException { <END> ManagementContext mgmt = LocalManagementContextForTests.newInstance(); try { ObjectMapper mapper = BrooklynJacksonJsonProvider.newPrivateObjectMapper(mgmt); SillyClassWithManagementContext silly = new SillyClassWithManagementContext("123", mgmt); log.info("silly is: "+silly); String sillyS = mapper.writeValueAsString(silly); log.info("silly json is: "+sillyS); SillyClassWithManagementContext silly2 = mapper.readValue(sillyS, SillyClassWithManagementContext.class); log.info("silly2 is: "+silly2); Assert.assertEquals(silly.id, silly2.id); } finally { Entities.destroyAll(mgmt); } }</code><technical_language>Personal preference: test methods throws Exception. testing compiler, reduce amount of refactoring do in future. more concise</technical_language>

Target:
public void testCustomSerializerWithSerializableSillyManagementExample() throws Exception { ManagementContext mgmt = LocalManagementContextForTests.newInstance(); try { ObjectMapper mapper = BrooklynJacksonJsonProvider.newPrivateObjectMapper(mgmt); SillyClassWithManagementContext silly = new SillyClassWithManagementContext("123", mgmt); log.info("silly is: "+silly); String sillyS = mapper.writeValueAsString(silly); log.info("silly json is: "+sillyS); SillyClassWithManagementContext silly2 = mapper.readValue(sillyS, SillyClassWithManagementContext.class); log.info("silly2 is: "+silly2); Assert.assertEquals(silly.id, silly2.id); } finally { Entities.destroyAll(mgmt); } }
Source:
<code>private boolean unplugPassthroughNics() { if (passthroughNicsUnplugged) { return true; } <START> passthroughNicsUnplugged = true; <END> List<ActivateDeactivateVmNicParameters> parametersList = createActivateDeactivateVmNicParameters( getAllVmPassthroughNics(), PlugAction.UNPLUG); log.debug("About to call with parameters: {}", VdcActionType.ActivateDeactivateVmNic, Arrays.toString(parametersList.toArray())); for (ActivateDeactivateVmNicParameters parameter : parametersList) { VdcReturnValueBase returnValue = runInternalAction(VdcActionType.ActivateDeactivateVmNic, parameter); if (!returnValue.getSucceeded()) { returnValue.getValidationMessages().forEach(this::addValidationMessage); return false; } } return true; }</code><technical_language>aware of rerun implications, say, nics unplugged unplug attempt. #266 location for setting this variable</technical_language>

Target:
private boolean unplugPassthroughNics() { if (passthroughNicsUnplugged) { return true; } List<ActivateDeactivateVmNicParameters> parametersList = createActivateDeactivateVmNicParameters( getAllVmPassthroughNics(), PlugAction.UNPLUG); log.debug("About to call with parameters: {}", VdcActionType.ActivateDeactivateVmNic, Arrays.toString(parametersList.toArray())); for (ActivateDeactivateVmNicParameters parameter : parametersList) { VdcReturnValueBase returnValue = runInternalAction(VdcActionType.ActivateDeactivateVmNic, parameter); if (!returnValue.getSucceeded()) { returnValue.getValidationMessages().forEach(this::addValidationMessage); return false; } } passthroughNicsUnplugged = true; return true; }
Source:
<code>public FunctionImplementationType getFunctionImplementationType() { <START> checkState(LANGUAGE_TO_IMPLEMENTATION_MAP.containsKey(routineCharacteristics.getLanguage()), "Does not support language %s", routineCharacteristics.getLanguage()); <END> return LANGUAGE_TO_IMPLEMENTATION_MAP.get(routineCharacteristics.getLanguage()); }</code><technical_language>nit: language is supported: %s</technical_language>

Target:
public FunctionImplementationType getFunctionImplementationType() { checkState(LANGUAGE_TO_IMPLEMENTATION_MAP.containsKey(routineCharacteristics.getLanguage()), "Language is not supported: %s", routineCharacteristics.getLanguage()); return LANGUAGE_TO_IMPLEMENTATION_MAP.get(routineCharacteristics.getLanguage()); }
Source:
<code>public void createManagementNetworkIfRequired() { if (host == null) { return; } final String managementNetworkName = resolveManagementNetworkName(); final String hostManagementNetworkAddress = resolveHostManagementNetworkAddress(managementNetworkName); final String hostIp = NetworkUtils.getHostByIp(host, log); <START> if (hostManagementNetworkAddress != null && hostManagementNetworkAddress.equals(hostIp)) { log.info("The management network '{}' is already configured on host '{}'", managementNetworkName, host.getName()); <END> return; } if (!FeatureSupported.setupManagementNetwork(host.getVdsGroupCompatibilityVersion())) { log.warn("Cluster of host '{}' does not support normalize management network feature", host.getName()); return; } VdsNetworkInterface nic = findNicToSetupManagementNetwork(); if (nic == null) { return; } List<VdsNetworkInterface> interfaces = filterBondsWithoutSlaves(host.getInterfaces()); if (interfaces.contains(nic)) { nic.setNetworkName(managementNetworkName); configureManagementNetwork(createSetupNetworkParams(interfaces)); } else { final AuditLogableBase event = createEvent(); event.addCustomValue("InterfaceName", nic.getName()); auditLogDirector.log(event, AuditLogType.INVALID_INTERFACE_FOR_MANAGEMENT_NETWORK_CONFIGURATION, NETWORK_CONFIG_LOG_ERR); throw new NetworkConfiguratorException(MANAGEMENET_NETWORK_CONFIG_ERR); } }</code><technical_language>message match check. pls separate checking mmanagement network name IP check</technical_language>

Target:
public void createManagementNetworkIfRequired() { if (host == null) { return; } final String managementNetworkName = resolveManagementNetworkName(); final String hostManagementNetworkAddress = resolveHostManagementNetworkAddress(managementNetworkName); final String hostIp = NetworkUtils.getHostByIp(host); if (hostManagementNetworkAddress != null && hostManagementNetworkAddress.equals(hostIp)) { log.info("The management network '{}' is already configured on host '{}'", managementNetworkName, host.getName()); return; } if (!FeatureSupported.setupManagementNetwork(host.getVdsGroupCompatibilityVersion())) { log.warn("Cluster of host '{}' does not support normalize management network feature", host.getName()); return; } VdsNetworkInterface nic = findNicToSetupManagementNetwork(); if (nic == null) { return; } List<VdsNetworkInterface> interfaces = filterBondsWithoutSlaves(host.getInterfaces()); if (interfaces.contains(nic)) { nic.setNetworkName(managementNetworkName); configureManagementNetwork(createSetupNetworkParams(interfaces)); } else { final AuditLogableBase event = createEvent(); event.addCustomValue("InterfaceName", nic.getName()); auditLogDirector.log(event, AuditLogType.INVALID_INTERFACE_FOR_MANAGEMENT_NETWORK_CONFIGURATION, NETWORK_CONFIG_LOG_ERR); throw new NetworkConfiguratorException(MANAGEMENET_NETWORK_CONFIG_ERR); } }
Source:
<code>public void initRepo() throws Exception { src = session.createDocumentModel("/", "src", "Folder"); src.setPropertyValue("dc:title", "Source"); src = session.createDocument(src); session.save(); src = session.getDocument(src.getRef()); when(administratorGroupsProvider.getAdministratorsGroups()).thenReturn( Collections.singletonList("administrators")); <START> DocumentModel testUser = userManager.getBareUserModel(); <END> testUser.setProperty("user", "username", "existingUser"); testUserId = userManager.createUser(testUser).getId(); }</code><technical_language>mocked userManager.getUserModel method avoid requiring PlatformFeature, creating deleting a user</technical_language>

Target:
public void initRepo() throws Exception { src = session.createDocumentModel("/", "src", "Folder"); src.setPropertyValue("dc:title", "Source"); src = session.createDocument(src); session.save(); src = session.getDocument(src.getRef()); when(userManager.getUserModel("existingUser")).thenReturn(new DocumentModelImpl("user")); when(userManager.getGroup("existingGroup")).thenReturn(new NuxeoGroupImpl("existingGroup")); when(administratorGroupsProvider.getAdministratorsGroups()).thenReturn( Collections.singletonList("administrators")); }
Source:
<code>public static Properties getConfiguration(String filename) { Properties props = new Properties(); InputStream in = null; <START> try { <END> in = ClientUtils.class.getClassLoader().getResourceAsStream(filename); } catch (Exception e) { } finally { try { props.load(in); if(in != null) { in.close(); } } catch (IOException ioe) { } } return props; }</code><technical_language>try resources Input stream is closed automatically</technical_language>

Target:
public static Properties getConfiguration(String filename) { Properties props = new Properties(); try (InputStream in = ClientUtils.class.getClassLoader().getResourceAsStream(filename)) { props.load(in); } catch (IOException e) { logger.error(e.getMessage(), e); } return props; }
Source:
<code>protected void updateSearchField() { if (!isNew() && !isAnyMappingChanged()) { return; } StringBuilder contentBuilder = new StringBuilder(); this.getDescriptor() .getProperties() .stream() .filter(p -> p.getAnnotation(SearchContent.class).isPresent()) .map(p -> p.getValue(this)) <START> .filter(Objects::nonNull) <END> .forEach(obj -> addContent(contentBuilder, obj)); searchField = contentBuilder.toString(); }</code><technical_language>filter for Strings::isFilled here</technical_language>

Target:
protected void updateSearchField() { if (!isNew() && !isAnyMappingChanged()) { return; } StringBuilder contentBuilder = new StringBuilder(); this.getDescriptor() .getProperties() .stream() .filter(p -> p.getAnnotation(SearchContent.class).isPresent()) .map(p -> p.getValue(this)) .filter(Strings::isFilled) .forEach(obj -> addContent(contentBuilder, obj)); searchField = contentBuilder.toString(); }
Source:
<code>public HashedWheelTimer( ThreadFactory threadFactory, long tickDuration, TimeUnit unit, int ticksPerWheel, boolean leakDetection, long maxPendingTimeouts) { if (threadFactory == null) { throw new NullPointerException("threadFactory"); } if (unit == null) { throw new NullPointerException("unit"); } if (tickDuration <= 0) { throw new IllegalArgumentException("tickDuration must be greater than 0: " + tickDuration); } if (ticksPerWheel <= 0) { throw new IllegalArgumentException("ticksPerWheel must be greater than 0: " + ticksPerWheel); } wheel = createWheel(ticksPerWheel); mask = wheel.length - 1; long duration = unit.toNanos(tickDuration); if (duration >= Long.MAX_VALUE / wheel.length) { throw new IllegalArgumentException(String.format( "tickDuration: %d (expected: 0 < tickDuration in nanos < %d", tickDuration, Long.MAX_VALUE / wheel.length)); } if (duration < MILLISECOND_NANOS) { if (logger.isWarnEnabled()) { <START> logger.warn(String.format("Configured tickDuration %d smaller then %d, using 1ms.", <END> tickDuration, MILLISECOND_NANOS)); } this.tickDuration = MILLISECOND_NANOS; } else { this.tickDuration = duration; } workerThread = threadFactory.newThread(worker); leak = leakDetection || !workerThread.isDaemon() ? leakDetector.track(this) : null; this.maxPendingTimeouts = maxPendingTimeouts; if (INSTANCE_COUNTER.incrementAndGet() > INSTANCE_COUNT_LIMIT && WARNED_TOO_MANY_INSTANCES.compareAndSet(false, true)) { reportTooManyInstances(); } }</code><technical_language>@szhnet replace %ds {}s</technical_language>

Target:
public HashedWheelTimer( ThreadFactory threadFactory, long tickDuration, TimeUnit unit, int ticksPerWheel, boolean leakDetection, long maxPendingTimeouts) { if (threadFactory == null) { throw new NullPointerException("threadFactory"); } if (unit == null) { throw new NullPointerException("unit"); } if (tickDuration <= 0) { throw new IllegalArgumentException("tickDuration must be greater than 0: " + tickDuration); } if (ticksPerWheel <= 0) { throw new IllegalArgumentException("ticksPerWheel must be greater than 0: " + ticksPerWheel); } wheel = createWheel(ticksPerWheel); mask = wheel.length - 1; long duration = unit.toNanos(tickDuration); if (duration >= Long.MAX_VALUE / wheel.length) { throw new IllegalArgumentException(String.format( "tickDuration: %d (expected: 0 < tickDuration in nanos < %d", tickDuration, Long.MAX_VALUE / wheel.length)); } if (duration < MILLISECOND_NANOS) { if (logger.isWarnEnabled()) { logger.warn("Configured tickDuration smaller then {}, using 1ms.", tickDuration, MILLISECOND_NANOS); } this.tickDuration = MILLISECOND_NANOS; } else { this.tickDuration = duration; } workerThread = threadFactory.newThread(worker); leak = leakDetection || !workerThread.isDaemon() ? leakDetector.track(this) : null; this.maxPendingTimeouts = maxPendingTimeouts; if (INSTANCE_COUNTER.incrementAndGet() > INSTANCE_COUNT_LIMIT && WARNED_TOO_MANY_INSTANCES.compareAndSet(false, true)) { reportTooManyInstances(); } }
Source:
<code>public static <T extends ToolInstallation> void installTool(Jenkins jenkins, Class<T> type, String name, String version) { waitForUpdates(jenkins, type); <START> jenkins.getPluginManager().checkForUpdates(); <END> ConfigurablePageObject tools = ensureConfigPage(jenkins); T maven = addTool(jenkins, type); maven.name.set(name); maven.installVersion(version); tools.save(); }</code><technical_language>This is called in method waitForUpdates(). Is needed twice</technical_language>

Target:
public static <T extends ToolInstallation> void installTool(Jenkins jenkins, Class<T> type, String name, String version) { waitForUpdates(jenkins, type); ConfigurablePageObject tools = ensureConfigPage(jenkins); T toolInstallation = addTool(jenkins, type); toolInstallation.name.set(name); if(version != null) { toolInstallation.installVersion(version); } tools.save(); }
Source:
<code>protected void updatePosition(final CharacterMovementComponent movementComp, final CharacterStateEvent state, CharacterMoveInputEvent input, EntityRef entity) { switch (state.getMode()) { <START> case GHOSTING: <END> ghost(movementComp, state, input, entity); break; case SWIMMING: swim(movementComp, state, input, entity); break; case WALKING: walk(movementComp, state, input, entity); break; case CLIMBING: climb(movementComp, state, input, entity); break; default: walk(movementComp, state, input, entity); break; } }</code><technical_language>A (if in todo) - movement modes broken out separate classes installed in a map (EnumMap). character mover 2 distinct phases - updating state running movement. A couple of underlying methods live moveUp sweep need move CharacterCollider class similar</technical_language>

Target:
private void updatePosition(final CharacterMovementComponent movementComp, final CharacterStateEvent state, CharacterMoveInputEvent input, EntityRef entity) { switch (state.getMode()) { case GHOSTING: ghost(movementComp, state, input, entity); break; case SWIMMING: swim(movementComp, state, input, entity); break; case WALKING: walk(movementComp, state, input, entity); break; case CLIMBING: climb(movementComp, state, input, entity); break; default: walk(movementComp, state, input, entity); break; } }
Source:
<code>public void applyParameters(Material program) { super.applyParameters(program); DisplayResolutionDependentFBOs displayResolutionDependentFBOs = CoreRegistry.get(DisplayResolutionDependentFBOs.class); int texId = 0; GL13.glActiveTexture(GL13.GL_TEXTURE0 + texId); <START> displayResolutionDependentFBOs.bindFboColorTexture(new ResourceUrn("engine:sceneFinal")); <END> program.setInt("texSceneFinal", texId, true); }</code><technical_language>ResourceUrn a static final field please</technical_language>

Target:
public void applyParameters(Material program) { super.applyParameters(program); DisplayResolutionDependentFBOs displayResolutionDependentFBOs = CoreRegistry.get(DisplayResolutionDependentFBOs.class); int texId = 0; GL13.glActiveTexture(GL13.GL_TEXTURE0 + texId); displayResolutionDependentFBOs.bindFboColorTexture(FINAL_BUFFER); program.setInt("texSceneFinal", texId, true); }
Source:
<code>protected Set<IEclipsePreferences> getThemeRelatedPreferences() { if (prefs == null) { prefs = new HashSet<>(); <START> final IExtensionRegistry registry = Platform.getExtensionRegistry(); <END> IConfigurationElement[] elements = registry .getConfigurationElementsFor("org.eclipse.e4.ui.css.swt.theme"); Set<String> bundleIDs = new HashSet<>(); for (IConfigurationElement element : elements) { try { String nameSpace = element.getNamespaceIdentifier(); if (nameSpace != null) { bundleIDs.add(nameSpace); } } catch (InvalidRegistryObjectException e) { Activator.log(LogService.LOG_ERROR, e.getMessage(), e); } } elements = registry.getConfigurationElementsFor("org.eclipse.ui.themes"); for (IConfigurationElement element : elements) { try { String nameSpace = element.getNamespaceIdentifier(); if (nameSpace != null) { bundleIDs.add(nameSpace); } } catch (InvalidRegistryObjectException e) { Activator.log(LogService.LOG_ERROR, e.getMessage(), e); } } for (String bundleId : bundleIDs) { if (bundleId != null) { prefs.add(InstanceScope.INSTANCE.getNode(bundleId)); } } } return prefs; }</code><technical_language>This logic worked fine for me. suggest removing redundant code loop, this: --------- Set<String> bundleIDs = new HashSet<>(); String[] themeRelatedExtensionPoints = { "org.eclipse.e4.ui.css.swt.theme", "org.eclipse.ui.themes" }; for (String extensionPoint : themeRelatedExtensionPoints) { IConfigurationElement[] elements = registry.getConfigurationElementsFor(extensionPoint); for (IConfigurationElement element : elements) { try { String nameSpace = element.getNamespaceIdentifier(); if (nameSpace != null) { bundleIDs.add(nameSpace); } } catch (InvalidRegistryObjectException e) { Activator.log(LogService.LOG_ERROR, e.getMessage(), e); } } } ----</technical_language>

Target:
protected Set<IEclipsePreferences> getThemeRelatedPreferences() { if (prefs == null) { prefs = new HashSet<>(); final IExtensionRegistry registry = Platform.getExtensionRegistry(); Set<String> bundleIDs = new HashSet<>(); String[] themeRelatedExtensionPoints = { "org.eclipse.e4.ui.css.swt.theme", "org.eclipse.ui.themes" }; for (String extensionPoint : themeRelatedExtensionPoints) { IConfigurationElement[] elements = registry.getConfigurationElementsFor(extensionPoint); for (IConfigurationElement element : elements) { try { String nameSpace = element.getNamespaceIdentifier(); if (nameSpace != null) { bundleIDs.add(nameSpace); } } catch (InvalidRegistryObjectException e) { Activator.log(LogService.LOG_ERROR, e.getMessage(), e); } } } for (String bundleId : bundleIDs) { if (bundleId != null) { prefs.add(InstanceScope.INSTANCE.getNode(bundleId)); } } } return prefs; }
Source:
<code>public void createContainers(String path) throws Exception; public SyncBuilder sync(); public RemoveWatchesBuilder watches(); public Listenable<ConnectionStateListener> getConnectionStateListenable(); public Listenable<CuratorListener> getCuratorListenable(); public Listenable<UnhandledErrorListener> getUnhandledErrorListenable(); @Deprecated public CuratorFramework nonNamespaceView(); public CuratorFramework usingNamespace(String newNamespace); public String getNamespace(); public CuratorZookeeperClient getZookeeperClient(); @Deprecated public EnsurePath newNamespaceAwareEnsurePath(String path); @Deprecated public void clearWatcherReferences(Watcher watcher); public boolean blockUntilConnected(int maxWaitTime, TimeUnit units) throws InterruptedException; public void blockUntilConnected() throws InterruptedException; public WatcherRemoveCuratorFramework newWatcherRemoveCuratorFramework(); public ConnectionStateErrorPolicy getConnectionStateErrorPolicy(); public QuorumVerifier getCurrentConfig(); SchemaSet getSchemaSet(); boolean isZk34CompatibilityMode(); <START> default void postSafeNotify(Object monitorHolder) <END> { runSafe(() -> { synchronized(monitorHolder) { monitorHolder.notifyAll(); } }); }</code><technical_language>Thinking future... return a CompletableFuture? This caller a chance eventually operation executed</technical_language>

Target:
public void createContainers(String path) throws Exception; public SyncBuilder sync(); public RemoveWatchesBuilder watches(); public Listenable<ConnectionStateListener> getConnectionStateListenable(); public Listenable<CuratorListener> getCuratorListenable(); public Listenable<UnhandledErrorListener> getUnhandledErrorListenable(); @Deprecated public CuratorFramework nonNamespaceView(); public CuratorFramework usingNamespace(String newNamespace); public String getNamespace(); public CuratorZookeeperClient getZookeeperClient(); @Deprecated public EnsurePath newNamespaceAwareEnsurePath(String path); @Deprecated public void clearWatcherReferences(Watcher watcher); public boolean blockUntilConnected(int maxWaitTime, TimeUnit units) throws InterruptedException; public void blockUntilConnected() throws InterruptedException; public WatcherRemoveCuratorFramework newWatcherRemoveCuratorFramework(); public ConnectionStateErrorPolicy getConnectionStateErrorPolicy(); public QuorumVerifier getCurrentConfig(); SchemaSet getSchemaSet(); boolean isZk34CompatibilityMode(); default CompletableFuture<Void> postSafeNotify(Object monitorHolder) { return runSafe(() -> { synchronized(monitorHolder) { monitorHolder.notifyAll(); } }); }
Source:
<code>public ActionForward viewDescriptionCurricularPlan(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { String degreeCurricularPlanID = RequestUtils.getAndSetStringToRequest(request, "degreeCurricularPlanID"); DegreeCurricularPlan degreeCurricularPlan = FenixFramework.getDomainObject(degreeCurricularPlanID); if (degreeCurricularPlan == null) { addErrorMessage(request, "noDegreeCurricularPlan", "error.coordinator.chosenDegree"); return new ActionForward(mapping.getInput()); } request.setAttribute("degreeCurricularPlan", degreeCurricularPlan); request.setAttribute( "degreeCurricularPlanDescription", <START> new LocalizedString().with(Locale.ENGLISH, degreeCurricularPlan.getDescriptionEn()).with(new Locale("pt", "PT"), <END> degreeCurricularPlan.getDescription())); return mapping.findForward("viewDescriptionCurricularPlan"); }</code><technical_language>MultiLanguageString.en MultiLanguageString.pt access 'well known' locales</technical_language>

Target:
public ActionForward viewDescriptionCurricularPlan(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { String degreeCurricularPlanID = RequestUtils.getAndSetStringToRequest(request, "degreeCurricularPlanID"); DegreeCurricularPlan degreeCurricularPlan = FenixFramework.getDomainObject(degreeCurricularPlanID); if (degreeCurricularPlan == null) { addErrorMessage(request, "noDegreeCurricularPlan", "error.coordinator.chosenDegree"); return new ActionForward(mapping.getInput()); } request.setAttribute("degreeCurricularPlan", degreeCurricularPlan); request.setAttribute( "degreeCurricularPlanDescription", new LocalizedString().with(MultiLanguageString.en, degreeCurricularPlan.getDescriptionEn()).with( MultiLanguageString.pt, degreeCurricularPlan.getDescription())); return mapping.findForward("viewDescriptionCurricularPlan"); }
Source:
<code>void testDescribe() { for (String region : ec2Api.getConfiguredRegions()) { Set<SecurityGroup> allResults = client.describeSecurityGroupsInRegion(region); assertNotNull(allResults); if (allResults.size() >= 1) { final SecurityGroup group = getLast(allResults); ImmutableSet<SecurityGroup> expected = FluentIterable.from(allResults) .filter(new Predicate<SecurityGroup>() { @Override public boolean apply(SecurityGroup in) { return group.getName().equals(in.getName()); } }).toSet(); ImmutableSet<SecurityGroup> result = ImmutableSet.copyOf(client.describeSecurityGroupsInRegion(region, group.getName())); <START> assertTrue(expected.containsAll(result)); <END> } } }</code><technical_language>Add message</technical_language>

Target:
void testDescribe() { for (String region : ec2Api.getConfiguredRegions()) { Set<SecurityGroup> allResults = client.describeSecurityGroupsInRegion(region); assertNotNull(allResults); if (!allResults.isEmpty()) { final SecurityGroup group = getLast(allResults); ImmutableSet<SecurityGroup> expected = FluentIterable.from(allResults) .filter(new Predicate<SecurityGroup>() { @Override public boolean apply(SecurityGroup in) { return group.getName().equals(in.getName()); } }).toSet(); ImmutableSet<SecurityGroup> result = ImmutableSet.copyOf(client.describeSecurityGroupsInRegion(region, group.getName())); assertTrue(expected.containsAll(result), "group(s) for name not found"); } } }
Source:
<code>public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException, OperationCanceledException { pm.subTask(Messages.RenameModelChange_LoadingEMF); pm.subTask(Messages.RenameModelChange_DaveDirtyEditor); openedEditors = new ArrayList<IMultiDiagramEditor>(); Display.getDefault().syncExec(new Runnable() { public void run() { IMultiDiagramEditor[] multiEditors = EditorUtils.getRelatedEditors(oldFile); if(multiEditors != null && multiEditors.length > 0) { for(IMultiDiagramEditor editor : multiEditors) { if(editor.isDirty()) { editor.doSave(new NullProgressMonitor()); } openedEditors.add(editor); } } } }); pm.worked(10); resourceSet = new ModelSet(); try { ModelsReader reader = new ModelsReader(); reader.readModel(resourceSet); resourceSet.loadModels(oldFile); for(IResource r : impacted) { if(r instanceof IFile) { IFile file = (IFile)r; try { resourceSet.getResource(URI.createPlatformResourceURI(file.getFullPath().toString(), true), true); } catch (Exception e) { } } } URI stashOldFile = SashUtils.getSashStateLocationURI(oldFile); if(stashOldFile != null) { <START> resourceSet.getResource(stashOldFile, true); <END> } } catch (Exception e) { Activator.log.error(e); } try { EcoreUtil.resolveAll(resourceSet); } catch (Exception ex) { } pm.worked(4); domain = resourceSet.getTransactionalEditingDomain(); return manageResourceSet(pm, resourceSet); }</code><technical_language>in PapyrusCopyFilesAndFoldersOperation, this fails exception for a legacy model *.sash resource in workspace metadata. exception is logged, refactoring fails another exception I abort it: org.eclipse.emf.ecore.resource.impl.ResourceSetImpl$1DiagnosticWrappedException: java.net.MalformedURLException: unknown protocol: pathmap</technical_language>

Target:
public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException, OperationCanceledException { pm.subTask(Messages.RenameModelChange_LoadingEMF); pm.subTask(Messages.RenameModelChange_DaveDirtyEditor); openedEditors = new ArrayList<IMultiDiagramEditor>(); Display.getDefault().syncExec(new Runnable() { public void run() { IMultiDiagramEditor[] multiEditors = EditorUtils.getRelatedEditors(oldFile); if(multiEditors != null && multiEditors.length > 0) { for(IMultiDiagramEditor editor : multiEditors) { if(editor.isDirty()) { editor.doSave(new NullProgressMonitor()); } openedEditors.add(editor); } } } }); pm.worked(10); resourceSet = new ModelSet(); try { ModelsReader reader = new ModelsReader(); reader.readModel(resourceSet); resourceSet.loadModels(oldFile); for(IResource r : impacted) { if(r instanceof IFile) { IFile file = (IFile)r; try { resourceSet.getResource(URI.createPlatformResourceURI(file.getFullPath().toString(), true), true); } catch (Exception e) { } } } } catch (Exception e) { Activator.log.error(e); } try { EcoreUtil.resolveAll(resourceSet); } catch (Exception ex) { } pm.worked(4); domain = resourceSet.getTransactionalEditingDomain(); return manageResourceSet(pm, resourceSet); }
Source:
<code>public Optional<PlanNode> apply(PlanNode node, Lookup lookup, PlanNodeIdAllocator idAllocator, SymbolAllocator symbolAllocator, Session session) { if (!(node instanceof ProjectNode)) { return Optional.empty(); } ProjectNode parent = (ProjectNode) node; PlanNode child = lookup.resolve(parent.getSource()); if (!(child instanceof MarkDistinctNode)) { return Optional.empty(); } MarkDistinctNode markDistinctNode = (MarkDistinctNode) child; Optional<List<Symbol>> prunedOutputs = pruneInputs(child.getOutputSymbols(), parent.getAssignments().getExpressions()); if (!prunedOutputs.isPresent()) { return Optional.empty(); } if (prunedOutputs.get().stream().noneMatch(markDistinctNode.getMarkerSymbol()::equals)) { return Optional.of( node.replaceChildren(ImmutableList.of(markDistinctNode.getSource()))); } Set<Symbol> requiredInputs = Streams.concat( prunedOutputs.get().stream() .filter(symbol -> !symbol.equals(markDistinctNode.getMarkerSymbol())), markDistinctNode.getDistinctSymbols().stream(), markDistinctNode.getHashSymbol().map(Stream::of).orElse(Stream.empty())) .collect(toImmutableSet()); return Optional.of( <START> node.replaceChildren(ImmutableList.of( <END> markDistinctNode.replaceChildren(ImmutableList.of( restrictOutputs(idAllocator, markDistinctNode.getSource(), requiredInputs)))))); }</code><technical_language>nit: parent instead of node for consistency markDistinctNode below</technical_language>

Target:
public Optional<PlanNode> apply(PlanNode node, Lookup lookup, PlanNodeIdAllocator idAllocator, SymbolAllocator symbolAllocator, Session session) { ProjectNode parent = (ProjectNode) node; PlanNode child = lookup.resolve(parent.getSource()); if (!(child instanceof MarkDistinctNode)) { return Optional.empty(); } MarkDistinctNode markDistinctNode = (MarkDistinctNode) child; Optional<List<Symbol>> prunedOutputs = pruneInputs(child.getOutputSymbols(), parent.getAssignments().getExpressions()); if (!prunedOutputs.isPresent()) { return Optional.empty(); } if (!prunedOutputs.get().contains(markDistinctNode.getMarkerSymbol())) { return Optional.of( node.replaceChildren(ImmutableList.of(markDistinctNode.getSource()))); } Set<Symbol> requiredInputs = Streams.concat( prunedOutputs.get().stream() .filter(symbol -> !symbol.equals(markDistinctNode.getMarkerSymbol())), markDistinctNode.getDistinctSymbols().stream(), markDistinctNode.getHashSymbol().map(Stream::of).orElse(Stream.empty())) .collect(toImmutableSet()); return restrictOutputs(idAllocator, markDistinctNode.getSource(), requiredInputs) .map(prunedMarkDistinctSource -> parent.replaceChildren(ImmutableList.of( markDistinctNode.replaceChildren(ImmutableList.of( prunedMarkDistinctSource))))); }
Source:
<code><START> private ImmutableDruidDataSource getDataSource(final String dataSourceName) <END> { List<ImmutableDruidDataSource> dataSources = serverInventoryView .getInventory() .stream() .map(server -> server.getDataSource(dataSourceName)) .filter(Objects::nonNull) .map(DruidDataSource::toImmutableDruidDataSource) .collect(Collectors.toList()); if (dataSources.isEmpty()) { return null; } Map<String, DataSegment> segmentMap = Maps.newHashMap(); for (ImmutableDruidDataSource dataSource : dataSources) { Iterable<DataSegment> segments = dataSource.getSegments(); for (DataSegment segment : segments) { segmentMap.put(segment.getIdentifier(), segment); } } return new DruidDataSource( dataSourceName, ImmutableMap.of() ).addSegments(segmentMap).toImmutableDruidDataSource(); }</code><technical_language>Annotate @Nullable</technical_language>

Target:
private ImmutableDruidDataSource getDataSource(final String dataSourceName) { List<ImmutableDruidDataSource> dataSources = serverInventoryView .getInventory() .stream() .map(server -> server.getDataSource(dataSourceName)) .filter(Objects::nonNull) .map(DruidDataSource::toImmutableDruidDataSource) .collect(Collectors.toList()); if (dataSources.isEmpty()) { return null; } Map<String, DataSegment> segmentMap = Maps.newHashMap(); for (ImmutableDruidDataSource dataSource : dataSources) { Iterable<DataSegment> segments = dataSource.getSegments(); for (DataSegment segment : segments) { segmentMap.put(segment.getIdentifier(), segment); } } return new ImmutableDruidDataSource( dataSourceName, ImmutableMap.of(), ImmutableMap.copyOf(segmentMap) ); }
Source:
<code>public Single<List<Media>> getMediaListForUser(String userName) { return responseToMediaList( <START> continuationStore.containsKey("user_" + userName) ? <END> mediaInterface.getMediaListForUser(userName, 10, continuationStore.get("user_" + userName)) : mediaInterface.getMediaListForUser(userName, 10, Collections.emptyMap()), "user_" + userName); }</code><technical_language>this is a bit hard eyes, moving ternary method call? mediaInterface.getMediaListForUser( username, 10, continuationStore.hasUser ? continuation.getUser : emptyMap() )</technical_language>

Target:
public Single<List<Media>> getMediaListForUser(String userName) { Map<String, String> continuation = continuationStore.containsKey("user_" + userName) ? continuationStore.get("user_" + userName) : Collections.emptyMap(); return responseToMediaList(mediaInterface .getMediaListForUser(userName, 10, continuation), "user_" + userName); }