auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void exceptionWhileExecutingJob(String nextJobId, Throwable t) { if(t instanceof OptimisticLockingException && !isDebugEnabled()) { logWarn( "006", <START> "Exception while closing command context: To see the full stacktrace set logging level to WARNING.", <END> t.getClass().getSimpleName()); } else { logWarn( "006", "Exception while executing job {}: ", nextJobId, t); } }</code><technical_language>suggestion "Exception while executing job {}: {}. full stacktrace set logging level DEBUG.",</technical_language>

Target:
public void exceptionWhileExecutingJob(String nextJobId, Throwable t) { if(t instanceof OptimisticLockingException && !isDebugEnabled()) { logWarn( "006", "Exception while executing job {}: {}. To see the full stacktrace set logging level to DEBUG.", nextJobId, t.getClass().getSimpleName()); } else { logWarn( "006", "Exception while executing job {}: ", nextJobId, t); } }
Source:
<code><START> static synchronized Iterable<TerminalInfoView> getViews() { <END> return new ArrayList<TerminalInfoView>(views); }</code><technical_language>Visibility missing. Synchronized static return Iterable here? return a List<TerminatlInfoView></technical_language>

Target:
private static synchronized Iterable<TerminalInfoView> getViews() { return new ArrayList<TerminalInfoView>(views); }
Source:
<code>public void testLoadMetadataResources() throws IOException { ZkKeyBuilder keyBuilder = Mockito.mock(ZkKeyBuilder.class); ZkClient mockZkClient = Mockito.mock(ZkClient.class); when(keyBuilder.getJobModelVersionBarrierPrefix()).thenReturn(TEST_BARRIER_ROOT); ZkUtils zkUtils = Mockito.mock(ZkUtils.class); when(zkUtils.getKeyBuilder()).thenReturn(keyBuilder); when(zkUtils.getZkClient()).thenReturn(mockZkClient); when(zkUtils.getJobModel(TEST_JOB_MODEL_VERSION)).thenReturn(jobModel); StartpointManager mockStartpointManager = Mockito.mock(StartpointManager.class); ZkJobCoordinator zkJobCoordinator = Mockito.spy(new ZkJobCoordinator("TEST_PROCESSOR_ID", config, new NoOpMetricsRegistry(), zkUtils)); doReturn(mockStartpointManager).when(zkJobCoordinator).createStartpointManager(any(CoordinatorStreamStore.class)); doReturn(mock(CoordinatorStreamStore.class)).when(zkJobCoordinator).createCoordinatorStreamStore(); <START> doReturn(mock(MetadataResourceUtil.class)).when(zkJobCoordinator).createMetadataResourceUtil(any(JobModel.class)); <END> verifyZeroInteractions(mockStartpointManager); zkJobCoordinator.loadMetadataResources(jobModel); verify(mockStartpointManager).start(); verify(mockStartpointManager).fanOut(any()); verify(mockStartpointManager).stop(); }</code><technical_language>verify createResources called MetadataResourceUtil</technical_language>

Target:
public void testLoadMetadataResources() throws IOException { ZkKeyBuilder keyBuilder = Mockito.mock(ZkKeyBuilder.class); ZkClient mockZkClient = Mockito.mock(ZkClient.class); when(keyBuilder.getJobModelVersionBarrierPrefix()).thenReturn(TEST_BARRIER_ROOT); ZkUtils zkUtils = Mockito.mock(ZkUtils.class); when(zkUtils.getKeyBuilder()).thenReturn(keyBuilder); when(zkUtils.getZkClient()).thenReturn(mockZkClient); when(zkUtils.getJobModel(TEST_JOB_MODEL_VERSION)).thenReturn(jobModel); StartpointManager mockStartpointManager = Mockito.mock(StartpointManager.class); ZkJobCoordinator zkJobCoordinator = Mockito.spy(new ZkJobCoordinator("TEST_PROCESSOR_ID", config, new NoOpMetricsRegistry(), zkUtils)); doReturn(mockStartpointManager).when(zkJobCoordinator).createStartpointManager(any(CoordinatorStreamStore.class)); doReturn(mock(CoordinatorStreamStore.class)).when(zkJobCoordinator).createCoordinatorStreamStore(); MetadataResourceUtil mockMetadataResourceUtil = mock(MetadataResourceUtil.class); doReturn(mockMetadataResourceUtil).when(zkJobCoordinator).createMetadataResourceUtil(any(JobModel.class)); verifyZeroInteractions(mockStartpointManager); zkJobCoordinator.loadMetadataResources(jobModel); verify(mockMetadataResourceUtil).createResources(); verify(mockStartpointManager).start(); verify(mockStartpointManager).fanOut(any()); verify(mockStartpointManager).stop(); }
Source:
<code>public MailboxExecutorImpl(@Nonnull TaskMailbox mailbox, int priority, StreamTaskActionExecutor actionExecutor, MailboxProcessor mailboxProcessor) { <START> this.mailbox = (TaskMailboxImpl) mailbox; <END> this.priority = priority; this.actionExecutor = Preconditions.checkNotNull(actionExecutor); this.mailboxProcessor = mailboxProcessor; }</code><technical_language>revert this change</technical_language>

Target:
public MailboxExecutorImpl(@Nonnull TaskMailbox mailbox, int priority, StreamTaskActionExecutor actionExecutor, MailboxProcessor mailboxProcessor) { this.mailbox = mailbox; this.priority = priority; this.actionExecutor = Preconditions.checkNotNull(actionExecutor); this.mailboxProcessor = mailboxProcessor; }
Source:
<code>public EntityRef createEntityWithoutLifecycleEvents(Iterable<Component> components) { EntityRef entity = create(); <START> <END> String prefabName = null; BlockUri blockUri = null; for (Component component : components) { if (component instanceof EntityInfoComponent) { EntityInfoComponent comp = (EntityInfoComponent) component; prefabName = comp.parentPrefab; if (blockUri != null) break; } else if (component instanceof BlockComponent) { BlockComponent comp = (BlockComponent) component; blockUri = comp.getBlock().getBlockFamily().getURI(); if (prefabName != null) break; } } EntityBeingGenerated event = new EntityBeingGenerated(prefabName, blockUri, components); eventSystem.send(entity, event); components = event.getResultComponents(); for (Component c : components) { store.put(entity.getId(), c); } return entity; }</code><technical_language>Repeated code. combine a single private method</technical_language>

Target:
public EntityRef createEntityWithoutLifecycleEvents(Iterable<Component> components) { EntityRef entity = createAndSendEvent(components); return entity; }
Source:
<code>public static AtlasDbDialogueServiceProvider create( Refreshable<ServerListConfig> timeLockServerListConfig, DialogueClients.ReloadingFactory baseFactory, UserAgent userAgent) { UserAgent versionedAgent = userAgent.addAgent(AtlasDbRemotingConstants.ATLASDB_HTTP_CLIENT_AGENT); Refreshable<Map<String, RemoteServiceConfiguration>> timeLockRemoteConfigurations = timeLockServerListConfig <START> .map(serverListConfig -> ImmutableMap.of( <END> TIMELOCK_SHORT_TIMEOUT, createRemoteServiceConfiguration(versionedAgent, serverListConfig, false), TIMELOCK_LONG_TIMEOUT, createRemoteServiceConfiguration(versionedAgent, serverListConfig, true))); DialogueClients.ReloadingFactory reloadingFactory = decorateForFailoverServices(baseFactory, timeLockRemoteConfigurations).withUserAgent(versionedAgent); return new AtlasDbDialogueServiceProvider(reloadingFactory); }</code><technical_language>Extract a constant function a method a bit more visible this works</technical_language>

Target:
public static AtlasDbDialogueServiceProvider create( Refreshable<ServerListConfig> timeLockServerListConfig, DialogueClients.ReloadingFactory baseFactory, UserAgent userAgent) { UserAgent versionedAgent = userAgent.addAgent(AtlasDbRemotingConstants.ATLASDB_HTTP_CLIENT_AGENT); Refreshable<Map<String, RemoteServiceConfiguration>> timeLockRemoteConfigurations = timeLockServerListConfig .map(serverListConfig -> getServiceConfigurations(versionedAgent, serverListConfig)); DialogueClients.ReloadingFactory reloadingFactory = decorateForFailoverServices(baseFactory, timeLockRemoteConfigurations).withUserAgent(versionedAgent); return new AtlasDbDialogueServiceProvider(reloadingFactory); }
Source:
<code>public static MailMessage formatMessage(long userId, Event event, Position position) { Device device = Context.getIdentityManager().getDeviceById(event.getDeviceId()); VelocityContext velocityContext = new VelocityContext(); velocityContext.put("device", device); velocityContext.put("event", event); if (position != null) { velocityContext.put("position", position); velocityContext.put("speedUnits", ReportUtils.getSpeedUnit(userId)); } if (event.getGeofenceId() != 0) { velocityContext.put("geofence", Context.getGeofenceManager().getGeofence(event.getGeofenceId())); } Template template = null; try { template = Context.getVelocityEngine().getTemplate(event.getType() + ".vm"); } catch (ResourceNotFoundException error) { Log.warning(error); } if (template == null) { <START> template = Context.getVelocityEngine().getTemplate("unknown.vm"); <END> } StringWriter writer = new StringWriter(); template.merge(velocityContext, writer); String subject = (String) velocityContext.get("subject"); return new MailMessage(subject, writer.toString()); }</code><technical_language>I move this catch. is a chance getTemplate returns null</technical_language>

Target:
public static MailMessage formatMessage(long userId, Event event, Position position) { Device device = Context.getIdentityManager().getDeviceById(event.getDeviceId()); VelocityContext velocityContext = new VelocityContext(); velocityContext.put("device", device); velocityContext.put("event", event); if (position != null) { velocityContext.put("position", position); velocityContext.put("speedUnits", ReportUtils.getSpeedUnit(userId)); } if (event.getGeofenceId() != 0) { velocityContext.put("geofence", Context.getGeofenceManager().getGeofence(event.getGeofenceId())); } Template template = null; try { template = Context.getVelocityEngine().getTemplate(event.getType() + ".vm"); } catch (ResourceNotFoundException error) { Log.warning(error); template = Context.getVelocityEngine().getTemplate("unknown.vm"); } StringWriter writer = new StringWriter(); template.merge(velocityContext, writer); String subject = (String) velocityContext.get("subject"); return new MailMessage(subject, writer.toString()); }
Source:
<code>public Date parseInput(FlagContext context) throws InvalidFlagFormat { String input = context.getUserInput(); if("now".equalsIgnoreCase(input)) { return new Date(); } else if("none".equalsIgnoreCase(input)) { <START> return null; <END> } else { DateFormat format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault()); try { return format.parse(input); } catch (ParseException ignored) { String pattern = format instanceof SimpleDateFormat ? ((SimpleDateFormat) format).toLocalizedPattern() : format.format(new Date()); throw new InvalidFlagFormat("Expected input in format: " + pattern); } } }</code><technical_language>/rg flag <region> blah /rg flag <region>blah -e explicitly set null/empty values</technical_language>

Target:
public Instant parseInput(FlagContext context) throws InvalidFlagFormat { String input = context.getUserInput(); if("now".equalsIgnoreCase(input)) { return Instant.now(); } else { try { return Instant.from(FORMATTER.parse(input)); } catch(DateTimeParseException ignored) { throw new InvalidFlagFormat("Expected 'now' or ISO 8601 formatted input."); } } }
Source:
<code>protected void executeCommand() { List<ActionParametersBase> params = hosts.stream() .filter(host -> <START> host.getInterfaces().stream() <END> .anyMatch(hostIf -> !hostIf.getNetworkImplementationDetails().isInSync())) .map(host -> new VdsActionParameters(host.getId())) .collect(Collectors.toList()); runInternalMultipleActions(ActionType.SyncAllHostNetworks, params); setSucceeded(true); }</code><technical_language>Is this attribute populated</technical_language>

Target:
protected void executeCommand() { List<ActionParametersBase> params = vdsIds.stream() .map(VdsActionParameters::new) .collect(Collectors.toList()); runInternalMultipleActions(ActionType.SyncAllHostNetworks, params); setSucceeded(true); }
Source:
<code>public void testOwnerPurge() { try { Connection c = null; Statement stmt = null; try { c = DriverManager.getConnection("jdbc:sqlite:test.db"); SqlHelper.dropTable(c, "TFLedger"); SqlHelper.createTable(c, "TFLedger", new Ledger()); SqlHelper.insertToTable(c, "TFLedger", l); ResultSet rs = SqlHelper.selectFromTable(c, "TFLedger", new String[]{"entity-id"}, new String[]{"ledger_entity_id"}, new Ledger()); byte[] caseBytes = rs.getBytes("commcare_sql_record"); DataInputStream is = new DataInputStream(new ByteArrayInputStream(caseBytes)); Ledger readLedger = new Ledger(); try { PrototypeFactory lPrototypeFactory = new PrototypeFactory(); lPrototypeFactory.addClass(Ledger.class); readLedger.readExternal(is, lPrototypeFactory); } catch(Exception e){ System.out.println("e: " + e); e.printStackTrace(); } c.close(); } catch ( Exception e ) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } } catch (Exception e) { e.printStackTrace(); fail("Unexpected exception " + e.getMessage()); <START> } <END> }</code><technical_language>I need nested catchs</technical_language>

Target:
public void testOwnerPurge() { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; String databaseName = ("test.db"); try { connection = DriverManager.getConnection("jdbc:sqlite:" + databaseName); SqlHelper.dropTable(connection, "TFLedger"); SqlHelper.createTable(connection, "TFLedger", new Ledger()); SqlHelper.insertToTable(connection, "TFLedger", l); preparedStatement = SqlHelper.prepareTableSelectStatement(connection, "TFLedger", new String[]{"entity-id"}, new String[]{"ledger_entity_id"}, new Ledger()); if (preparedStatement == null) { fail("failed to prepare table select query"); } resultSet = preparedStatement.executeQuery(); byte[] caseBytes = resultSet.getBytes("commcare_sql_record"); DataInputStream is = new DataInputStream(new ByteArrayInputStream(caseBytes)); Ledger readLedger = new Ledger(); PrototypeFactory lPrototypeFactory = new PrototypeFactory(); lPrototypeFactory.addClass(Ledger.class); readLedger.readExternal(is, lPrototypeFactory); } catch (Exception e) { e.printStackTrace(); fail("Unexpected exception " + e.getMessage()); } finally{ try { if(preparedStatement != null) { preparedStatement.close(); } if(connection != null) { connection.close(); } if(resultSet != null){ resultSet.close(); } File databaseFile = new File(databaseName); if(databaseFile.exists()){ databaseFile.delete(); } } catch (SQLException e1) { e1.printStackTrace(); } } }
Source:
<code>public int handlesSelection(ISelection selection) { int result = 0; Object sel = SelectionUtils.getSelectedObject(selection); if (sel instanceof GdbLaunch || sel instanceof GDBProcess || sel instanceof IDMVMContext) { <START> result = 2; <END> } updateDebugViewListener(); return result; }</code><technical_language>increase two. give some space for other visualizer in between, 10</technical_language>

Target:
public int handlesSelection(ISelection selection) { int result = 0; Object sel = SelectionUtils.getSelectedObject(selection); if (sel instanceof GdbLaunch || sel instanceof GDBProcess || sel instanceof IDMVMContext) { result = 10; } updateDebugViewListener(); return result; }
Source:
<code>public List<E> findAllWhereFieldEquals(String fieldName, Object fieldEntity, Criterion... criterion) { final boolean isField = EntityUtil.isField(entityClass, fieldName, true); if (!isField) { String errorMsg = String.format( "There is no field '%s' in the type '%s'", fieldName, entityClass.getName() <START> ); <END> throw new IllegalArgumentException(errorMsg); } Criteria criteria = createDistinctRootEntityCriteria(criterion); criteria.add(Restrictions.eq(fieldName, fieldEntity)); return (List<E>) criteria.list(); }</code><technical_language>Message enhanced read e.g. java String errorMsg = String.format( "There is field '%s' in type '%s' accepts instances of '%s'", fieldName, entityClass.getName(), // beware of null, fieldEntity.getClass().getName() );</technical_language>

Target:
public List<E> findAllWhereFieldEquals(String fieldName, Object fieldEntity, Criterion... criterion) { Class<?> fieldEntityType = null; if(fieldEntity != null) { fieldEntityType = fieldEntity.getClass(); } final boolean isField = EntityUtil.isField(entityClass, fieldName, fieldEntityType, true); if (!isField) { String errorMsg = String.format( "There is no field '%s' in the type '%s' that accepts instances of '%s'", fieldName, entityClass.getName(), fieldEntityType.getName() ); throw new IllegalArgumentException(errorMsg); } Criteria criteria = createDistinctRootEntityCriteria(criterion); if(fieldEntity == null) { criteria.add(Restrictions.isNull(fieldName)); } else { criteria.add(Restrictions.eq(fieldName, fieldEntity)); } return (List<E>) criteria.list(); }
Source:
<code>public void testNoCredentialId() { <START> assertNull(this.action.createCredentials(requestContext, getCredentials(), null)); <END> }</code><technical_language>This return null, wrap assertNull</technical_language>

Target:
public void testNoCredentialId() { this.action.createCredentials(requestContext, getCredentials(), null); }
Source:
<code>public void should_parse_virtual_metadata() { KeyspaceMetadata km=session().getCluster().getMetadata().getKeyspace("system_views"); assertThat(km.getTables().size() >= 2); assertThat(km.isVirtual()).isTrue(); <START> assertThat(km.getTable("clients")).isNotNull(); <END> assertThat(km.isDurableWrites()).isFalse(); assertThat(km.getName()).isEqualTo("system_views"); assertThat(km.getUserTypes().size()).isEqualTo(0); assertThat(km.getFunctions().size()).isEqualTo(0); assertThat(km.getMaterializedViews().size()).isEqualTo(0); assertThat(km.getAggregates().size()).isEqualTo(0); assertThat(km.asCQLQuery()).isEqualTo(" "); TableMetadata tm = km.getTable("clients"); assertThat(tm).isNotNull(); assertThat(tm.getName()).isEqualTo("clients"); assertThat(tm.isVirtual()).isTrue(); assertThat(tm.getColumns().size()).isEqualTo(12); assertThat(tm.getIndexes().size()).isEqualTo(0); assertThat(tm.getViews().size()).isEqualTo(0); assertThat(tm.getClusteringColumns().size()).isEqualTo(0); assertThat(tm.getClusteringOrder().size()).isEqualTo(0); assertThat(tm.getId()).isEqualTo( new UUID(0L, 0L)); assertThat(tm.getOptions()).isNull(); assertThat(tm.getKeyspace()).isEqualTo(km); assertThat(tm.asCQLQuery()).isEqualTo(" "); ColumnMetadata cm = tm.getColumn("driver_name"); assertThat(cm).isNotNull(); assertThat(cm.getParent()).isEqualTo(tm); assertThat(cm.getType()).isEqualTo(DataType.text()); assertThat(cm.getName()).isEqualTo("driver_name"); }</code><technical_language>Nit: this is duplicated line 48, I get rid of this line</technical_language>

Target:
public void should_parse_virtual_metadata() { KeyspaceMetadata km = session().getCluster().getMetadata().getKeyspace("system_views"); assertThat(km.getTables().size() >= 2); assertThat(km.isVirtual()).isTrue(); assertThat(km.isDurableWrites()).isFalse(); assertThat(km.getName()).isEqualTo("system_views"); assertThat(km.getUserTypes().size()).isEqualTo(0); assertThat(km.getFunctions().size()).isEqualTo(0); assertThat(km.getMaterializedViews().size()).isEqualTo(0); assertThat(km.getAggregates().size()).isEqualTo(0); assertThat(km.asCQLQuery()).isEqualTo(" "); TableMetadata tm = km.getTable("clients"); assertThat(tm).isNotNull(); assertThat(tm.getName()).isEqualTo("clients"); assertThat(tm.isVirtual()).isTrue(); assertThat(tm.getColumns().size()).isEqualTo(12); assertThat(tm.getIndexes().size()).isEqualTo(0); assertThat(tm.getViews().size()).isEqualTo(0); assertThat(tm.getClusteringColumns().size()).isEqualTo(0); assertThat(tm.getClusteringOrder().size()).isEqualTo(0); assertThat(tm.getId()).isEqualTo(new UUID(0L, 0L)); assertThat(tm.getOptions()).isNull(); assertThat(tm.getKeyspace()).isEqualTo(km); assertThat(tm.asCQLQuery()).isEqualTo(" "); ColumnMetadata cm = tm.getColumn("driver_name"); assertThat(cm).isNotNull(); assertThat(cm.getParent()).isEqualTo(tm); assertThat(cm.getType()).isEqualTo(DataType.text()); assertThat(cm.getName()).isEqualTo("driver_name"); }
Source:
<code>protected void executeQueryCommand() { Set<Guid> haveInvalidAncestor = new HashSet<>(); Function<Guid, DiskImage> getAncestor = (Guid imageId) -> { DiskImage ancestor = diskImageDao.getAncestor(imageId, getUserID(), getParameters().isFiltered()); if (ancestor == null) { haveInvalidAncestor.add(imageId); } return ancestor; }; Map<Guid, DiskImage> haveValidAncestor = getParameters().getIds().stream() .map(guid -> new Pair<>(guid, getAncestor.apply(guid))) .filter(pair -> pair.getSecond() != null) .collect(Collectors.toMap(Pair::getFirst, Pair::getSecond)); if (!haveInvalidAncestor.isEmpty()) { log.warn("Ancestor is missing for the following <START> guid(s): {}", <END> StringUtils.join(haveInvalidAncestor, ',')); } getQueryReturnValue().setReturnValue(haveValidAncestor); }</code><technical_language>images</technical_language>

Target:
protected void executeQueryCommand() { Set<Guid> haveInvalidAncestor = new HashSet<>(); Function<Guid, DiskImage> getAncestor = (Guid imageId) -> { DiskImage ancestor = diskImageDao.getAncestor(imageId, getUserID(), getParameters().isFiltered()); if (ancestor == null) { haveInvalidAncestor.add(imageId); } return ancestor; }; Map<Guid, DiskImage> haveValidAncestor = getParameters().getIds().stream() .map(guid -> new Pair<>(guid, getAncestor.apply(guid))) .filter(pair -> pair.getSecond() != null) .collect(Collectors.toMap(Pair::getFirst, Pair::getSecond)); if (!haveInvalidAncestor.isEmpty()) { log.warn("Ancestor is missing for the following image id(s): {}", StringUtils.join(haveInvalidAncestor, ',')); } getQueryReturnValue().setReturnValue(haveValidAncestor); }
Source:
<code>public double computeFor(ASTAnyTypeDeclaration node, MetricOptions options) { JavaOperationSigMask mask = new JavaOperationSigMask(); mask.restrictRolesTo(Role.METHOD, Role.STATIC); mask.restrictVisibilitiesTo(Visibility.PUBLIC); int functionalMethods = countMatchingOpSigs(node, mask); mask.coverAllRoles(); int totalPublicMethods = countMatchingOpSigs(node, mask); <START> return functionalMethods / (totalPublicMethods + 1.); <END> }</code><technical_language>Is this "+ 1." correct? way, is impossible calculate 100%... want cast double maybe? return functionalMethod / (double)totalPublicMethods;</technical_language>

Target:
public double computeFor(ASTAnyTypeDeclaration node, MetricOptions options) { JavaOperationSigMask mask = new JavaOperationSigMask(); mask.forbid(Role.CONSTRUCTOR, Role.GETTER_OR_SETTER); mask.restrictVisibilitiesTo(Visibility.PUBLIC); int functionalMethods = countMatchingOpSigs(node, mask); mask.coverAllRoles(); int totalPublicMethods = countMatchingOpSigs(node, mask); return functionalMethods / (double) totalPublicMethods; }
Source:
<code>public static void inputBigint(StatisticalDigestState state, long value, long weight, double accuracy) { <START> checkArgument(accuracy > 0 && accuracy < 1, "Percentile accuracy must be exclusively between 0 and 1, was %s", accuracy); <END> checkArgument(weight > 0, "Weight must be positive, was %s", weight); StatisticalDigest digest = getOrCreateQuantileDigest(state, accuracy); state.addMemoryUsage(-digest.estimatedInMemorySizeInBytes()); digest.add(value, weight); state.addMemoryUsage(digest.estimatedInMemorySizeInBytes()); }</code><technical_language>logic in QuantileDigestFunctions. I strong preference sit a separate function not. @tdcmeehan implemented first, do think? Is this a deliberate change</technical_language>

Target:
public static void inputBigint(StatisticalDigestState state, long value, long weight, double accuracy) { StatisticalDigest digest = getOrCreateQuantileDigest(state, verifyAccuracy(accuracy)); state.addMemoryUsage(-digest.estimatedInMemorySizeInBytes()); digest.add(value, verifyWeight(weight)); state.addMemoryUsage(digest.estimatedInMemorySizeInBytes()); }
Source:
<code>public int postEventsFromFile(String file) { try { BufferedReader reader = new BufferedReader( new InputStreamReader( EventReceiverFirehoseTestClient.class.getResourceAsStream( file ) ) <START> ); <END> String s; Collection<Map<String, Object>> events = new ArrayList<Map<String, Object>>(); int totalEventsPosted = 0; while ((s = reader.readLine()) != null) { events.add( (Map<String, Object>) this.jsonMapper.readValue( s, new TypeReference<Map<String, Object>>() { } ) ); ObjectMapper mapper = (totalEventsPosted % 2 == 0) ? jsonMapper : smileMapper; String mediaType = (totalEventsPosted % 2 == 0) ? MediaType.APPLICATION_JSON : SmileMediaTypes.APPLICATION_JACKSON_SMILE; int eventsPosted = postEvents(events, mapper, mediaType); if (eventsPosted != 1) { throw new ISE("Unable to send events to Indexing Service"); } totalEventsPosted += eventsPosted; events = new ArrayList<Map<String, Object>>(); } return totalEventsPosted; } catch (Exception e) { throw Throwables.propagate(e); } }</code><technical_language>this try resources? I reader closed</technical_language>

Target:
public int postEventsFromFile(String file) { try ( BufferedReader reader = new BufferedReader( new InputStreamReader( EventReceiverFirehoseTestClient.class.getResourceAsStream( file ) ) ); ) { String s; Collection<Map<String, Object>> events = new ArrayList<Map<String, Object>>(); int totalEventsPosted = 0; while ((s = reader.readLine()) != null) { events.add( (Map<String, Object>) this.jsonMapper.readValue( s, new TypeReference<Map<String, Object>>() { } ) ); ObjectMapper mapper = (totalEventsPosted % 2 == 0) ? jsonMapper : smileMapper; String mediaType = (totalEventsPosted % 2 == 0) ? MediaType.APPLICATION_JSON : SmileMediaTypes.APPLICATION_JACKSON_SMILE; totalEventsPosted += postEvents(events, mapper, mediaType); ; events = new ArrayList<>(); } if (totalEventsPosted != events.size()) { throw new ISE("All events not posted, expected : %d actual : %d", events.size(), totalEventsPosted); } return totalEventsPosted; } catch (Exception e) { throw Throwables.propagate(e); } }
Source:
<code>public Event updateDeviceState(long deviceId) { DeviceState deviceState = Context.getDeviceManager().getDeviceState(deviceId); if (deviceState == null || deviceState.getMotionState() == null) { return null; } Event result = null; Boolean oldMotion = deviceState.getMotionState(); <START> long currentTime = new Date().getTime(); <END> boolean newMotion = !oldMotion; Position potentialPosition = deviceState.getMotionPosition(); if (potentialPosition != null) { long potentialTime = potentialPosition.getFixTime().getTime() + (newMotion ? tripsConfig.getMinimalTripDuration() : tripsConfig.getMinimalParkingDuration()); if (potentialTime <= currentTime) { String eventType = newMotion ? Event.TYPE_DEVICE_MOVING : Event.TYPE_DEVICE_STOPPED; result = new Event(eventType, potentialPosition.getDeviceId(), potentialPosition.getId()); deviceState.setMotionState(newMotion); deviceState.setMotionPosition(null); } } return result; }</code><technical_language>System.currentTimeMillis() instead</technical_language>

Target:
public Event updateDeviceState(long deviceId) { DeviceState deviceState = Context.getDeviceManager().getDeviceState(deviceId); if (deviceState == null || deviceState.getMotionState() == null) { return null; } Event result = null; Boolean oldMotion = deviceState.getMotionState(); long currentTime = System.currentTimeMillis(); boolean newMotion = !oldMotion; Position motionPosition = deviceState.getMotionPosition(); if (motionPosition != null) { long motionTime = motionPosition.getFixTime().getTime() + (newMotion ? tripsConfig.getMinimalTripDuration() : tripsConfig.getMinimalParkingDuration()); if (motionTime <= currentTime) { String eventType = newMotion ? Event.TYPE_DEVICE_MOVING : Event.TYPE_DEVICE_STOPPED; result = new Event(eventType, motionPosition.getDeviceId(), motionPosition.getId()); deviceState.setMotionState(newMotion); deviceState.setMotionPosition(null); } } return result; }
Source:
<code>public static DescriptorMap register(DescriptorMap map) { Class<?> supportFragmentClass = FragmentApi.tryGetSupportFragmentClass(); if (supportFragmentClass != null) { <START> LogUtil.i("Registering support Fragment descriptor"); <END> map.register(supportFragmentClass, sInstance); } Class<?> fragmentClass = FragmentApi.tryGetFragmentClass(); if (fragmentClass != null) { LogUtil.i("Registering Fragment descriptor"); map.register(fragmentClass, sInstance); } return map; }</code><technical_language>This .d. .i log in caller application default</technical_language>

Target:
public static DescriptorMap register(DescriptorMap map) { Class<?> supportFragmentClass = FragmentApi.tryGetSupportFragmentClass(); if (supportFragmentClass != null) { LogUtil.d("Registering support Fragment descriptor"); map.register(supportFragmentClass, new FragmentDescriptor()); } Class<?> fragmentClass = FragmentApi.tryGetFragmentClass(); if (fragmentClass != null) { LogUtil.d("Registering Fragment descriptor"); map.register(fragmentClass, new FragmentDescriptor()); } return map; }
Source:
<code>public void generateTargetFile(MotechEvent event) { LOGGER.debug(event.toString()); if(Boolean.valueOf(settingsFacade.getProperty(generateJhFile))) { LOGGER.info("boolean:"+Boolean.valueOf(settingsFacade.getProperty(generateJhFile))); TargetFileNotification[] tfn = generateObdFiles(); if (tfn != null) { ScpHelper scpHelper = new ScpHelper(settingsFacade); for(TargetFileNotification t: tfn) { try { scpHelper.scpObdToRemote(t.getFileName()); } catch (ExecException e) { String error = String.format("Error copying target file %s: %s", t.getFileName(), e.getMessage()); LOGGER.error(error,e); fileAuditRecordDataService.create(new FileAuditRecord( FileType.TARGET_FILE, t.getFileName(), false, error, <START> null, <END> null )); alert(t.getFileName(), "targetFileName", error); return; } sendNotificationRequest(t); } } } else { TargetFileNotification tfn = generateTargetFile(); if (tfn != null) { ScpHelper scpHelper = new ScpHelper(settingsFacade); try { scpHelper.scpObdToRemote(tfn.getFileName()); } catch (ExecException e) { String error = String.format("Error copying target file %s: %s", tfn.getFileName(), e.getMessage()); LOGGER.error(error,e); fileAuditRecordDataService.create(new FileAuditRecord( FileType.TARGET_FILE, tfn.getFileName(), false, error, null, null )); alert(tfn.getFileName(), "targetFileName", error); return; } sendNotificationRequest(tfn); } } }</code><technical_language>code duplicate please abstract out single method params</technical_language>

Target:
public void generateTargetFile(MotechEvent event) { LOGGER.debug(event.toString()); HashMap<String, TargetFileNotification> tfn = generateTargetFile(Boolean.valueOf(settingsFacade.getProperty(generateJhFile))); if (tfn != null) { ScpHelper scpHelper = new ScpHelper(settingsFacade); for(TargetFileNotification t: tfn.values()) { try { scpHelper.scpObdToRemote(t.getFileName()); } catch (ExecException e) { String error = String.format("Error copying target file %s: %s", t.getFileName(), e.getMessage()); LOGGER.error(error,e); fileAuditRecordDataService.create(new FileAuditRecord( FileType.TARGET_FILE, t.getFileName(), false, error, null, null )); alert(t.getFileName(), "targetFileName", error); return; } sendNotificationRequest(t); } } }
Source:
<code>protected void <START> removeDetachedView(@NonNull <END> View child, boolean animate) { if ((animate && child.getAnimation() != null) || (mTransitioningFragmentViews != null && mTransitioningFragmentViews.contains(child))) { addDisappearingFragmentView(child); } super.removeDetachedView(child, animate); }</code><technical_language>this called removeView() for example? end adding view mDisappearingFragmentChildren. this is place needs added</technical_language>

Target:
protected void removeDetachedView(@NonNull View child, boolean animate) { if (child != mHoldView) { if (animate) { addDisappearingFragmentView(child); } super.removeDetachedView(child, animate); } }
Source:
<code>public void restorePreMothballInfo(Unit unit, Campaign campaign) { if (tech != null) { unit.setTech(tech); } for (Person driver : drivers) { <START> if (driver.getStatus().isActive() && driver.getUnit() == null) { <END> unit.addDriver(driver); } } for (Person gunner : gunners) { if (gunner.getStatus().isActive() && ((gunner.getUnit() == null) || (gunner.getUnit() == unit))) { unit.addGunner(gunner); } } for (Person crew : vesselCrew) { if (crew.getStatus().isActive() && crew.getUnit() == null) { unit.addVesselCrew(crew); } } if (techOfficer != null && techOfficer.getStatus().isActive() && techOfficer.getUnit() == null) { unit.setTechOfficer(techOfficer); } if (navigator != null && navigator.getStatus().isActive() && navigator.getUnit() == null) { unit.setNavigator(navigator); } if (campaign.getForce(forceID) != null) { campaign.addUnitToForce(unit, forceID); } unit.resetEngineer(); }</code><technical_language>suggestion if (driver.getStatus().isActive() && (driver.getUnit() == null)) {</technical_language>

Target:
public void restorePreMothballInfo(Unit unit, Campaign campaign) { if (tech != null) { unit.setTech(tech); } for (Person driver : drivers) { if (driver.getStatus().isActive() && (driver.getUnit() == null)) { unit.addDriver(driver); } } for (Person gunner : gunners) { if (gunner.getStatus().isActive() && ((gunner.getUnit() == null) || (gunner.getUnit() == unit))) { unit.addGunner(gunner); } } for (Person crew : vesselCrew) { if (crew.getStatus().isActive() && (crew.getUnit() == null)) { unit.addVesselCrew(crew); } } if ((techOfficer != null) && (techOfficer.getStatus().isActive()) && (techOfficer.getUnit() == null)) { unit.setTechOfficer(techOfficer); } if ((navigator != null) && (navigator.getStatus().isActive()) && (navigator.getUnit() == null)) { unit.setNavigator(navigator); } if (campaign.getForce(forceID) != null) { campaign.addUnitToForce(unit, forceID); } unit.resetEngineer(); }
Source:
<code>private ICoreEndpointService getEndpointService() { BundleContext ctx = Activator.ctx; try { ServiceReference<?>[] refs = ctx.getAllServiceReferences(ICoreEndpointService.class.getName(), null); if (refs != null) { for (ServiceReference<?> ref : refs) { ICoreEndpointService plugin = (ICoreEndpointService) ctx.getService(ref); return plugin; } } } catch (InvalidSyntaxException e) { e.printStackTrace(); return null; } <START> return null; <END> }</code><technical_language>is this injected component? Is construction time</technical_language>

Target:
private ICoreEndpointService getEndpointService() { BundleContext ctx = Activator.ctx; try { ServiceReference<?>[] refs = ctx.getAllServiceReferences(ICoreEndpointService.class.getName(), null); if (refs != null) { for (ServiceReference<?> ref : refs) { ICoreEndpointService plugin = (ICoreEndpointService) ctx.getService(ref); return plugin; } } } catch (InvalidSyntaxException e) { LOG.error("Couldn't fetch ICoreEndpointService instance", e); } return null; }
Source:
<code>private Set<String> parseFileNames(String input) { Set<String> names = new HashSet<>(); <START> names.addAll(Stream.of(input.split(",")).map(String::trim).collect(Collectors.toList())); <END> return names; }</code><technical_language>this skip empty strings</technical_language>

Target:
private static Set<String> parseFileNames(String input) { Set<String> names = new HashSet<>(); names.addAll(Stream.of(input.split(",")).map(String::trim).collect(Collectors.toList())); return names; }
Source:
<code>public void run() { listBox = new ChosenValueListBox<CarBrand>(getRenderer(), new ProvidesKey<CarBrand>() { @Override public Object getKey(final CarBrand item) { return item == null ? null : item.name(); } }, options); final List<CarBrand> acceptableValues = Lists.newArrayList(CarBrand.values()); <START> if (addNullValue) { <END> acceptableValues.add(0, null); } listBox.setAcceptableValues(acceptableValues); if (!listBox.isAccepted(CarBrand.AUDI)) { throw new AssertionError("Audi is acceptable value"); } RootPanel.get().add(listBox); }</code><technical_language>remove 63,64,65, addNullValue is false</technical_language>

Target:
public void run() { listBox = new ChosenValueListBox<CarBrand>(RENDERER, new ProvidesKey<CarBrand>() { @Override public Object getKey(final CarBrand item) { return item == null ? null : item.name(); } }, options); final List<CarBrand> acceptableValues = Lists.newArrayList(CarBrand.values()); listBox.setAcceptableValues(acceptableValues); if (!listBox.isAccepted(CarBrand.AUDI)) { throw new AssertionError("Audi is acceptable value"); } RootPanel.get().add(listBox); }
Source:
<code>private int applyBinaryOperation( final int firstValue, final String operationDescription, final int secondValue) { switch (operationDescription) { case "plus": return firstValue + secondValue; case "minus": return firstValue - secondValue; case "multiplied by": return firstValue * secondValue; case "divided by": return firstValue / secondValue; <START> case "raised to the power": <END> return (int) Math.pow(firstValue, secondValue); default: throw new IllegalArgumentException("This branch should never be executed."); } }</code><technical_language>I a complete solution in example code. So, it, please</technical_language>

Target:
private int applyBinaryOperation( final int firstValue, final String operationDescription, final int secondValue) { switch (operationDescription) { case "plus": return firstValue + secondValue; case "minus": return firstValue - secondValue; case "multiplied by": return firstValue * secondValue; case "divided by": return firstValue / secondValue; default: throw new IllegalArgumentException("This branch should never be executed."); } }
Source:
<code>AffinityResourceDefinition(PathElement path) { <START> super(path, UndertowExtension.getResolver(Constants.HANDLER, Constants.AFFINITY, path.getValue()), new ReloadRequiredAddStepHandler(), new ReloadRequiredRemoveStepHandler()); <END> }</code><technical_language>mistaken, need reload server, restart services of parent resource. leverage RestartParentResourceRegistration for this</technical_language>

Target:
AffinityResourceDefinition(PathElement path) { super(path, UndertowExtension.getResolver(Constants.HANDLER, Constants.AFFINITY, path.getValue())); }
Source:
<code>public static void refreshTreeSelection(TreeViewer viewer, int offset, IDocument document) { ITreeContentProvider contentProvider = (ITreeContentProvider) viewer.getContentProvider(); Object[] objects = contentProvider.getElements(null); SymbolInformation bestSymbol = null; int level = 0; while (objects != null && objects.length > 0) { SymbolInformation nextChild = null; for (Object object : objects) { <START> if (object instanceof SymbolInformation) { <END> SymbolInformation symbol = (SymbolInformation) object; if (isOffsetInSymbolRange(offset, symbol, document)) { nextChild = symbol; objects = contentProvider.getChildren(symbol); break; } } } if (nextChild == null) break; level++; bestSymbol = nextChild; } if (bestSymbol != null) { final int finalLevel = level; final SymbolInformation finalBestSymbol = bestSymbol; Display.getDefault().asyncExec(() -> { viewer.expandToLevel(finalLevel); viewer.setSelection(new StructuredSelection(finalBestSymbol), true); }); } }</code><technical_language>worth checking object adapted SymbolInformation. SymbolInformation symbol = object instanceof SymbolInformation ? (SymbolInformation)object : Adpaters.adapt(object, SymbolInformation.class); if (symbol != null) { ..</technical_language>

Target:
public static void refreshTreeSelection(TreeViewer viewer, int offset, IDocument document) { ITreeContentProvider contentProvider = (ITreeContentProvider) viewer.getContentProvider(); Object[] objects = contentProvider.getElements(null); SymbolInformation bestSymbol = null; int level = 0; while (objects != null && objects.length > 0) { SymbolInformation nextChild = null; for (Object object : objects) { SymbolInformation symbol = object instanceof SymbolInformation ? (SymbolInformation) object : Adapters.adapt(object, SymbolInformation.class); if (symbol != null) { if (isOffsetInSymbolRange(offset, symbol, document)) { nextChild = symbol; objects = contentProvider.getChildren(symbol); break; } } } if (nextChild == null) break; level++; bestSymbol = nextChild; } if (bestSymbol != null) { final int finalLevel = level; final SymbolInformation finalBestSymbol = bestSymbol; Display.getDefault().asyncExec(() -> { viewer.expandToLevel(finalLevel); viewer.setSelection(new StructuredSelection(finalBestSymbol), true); }); } }
Source:
<code>private void loginToStore(String userName, String password) throws Exception { <START> setKeyStoreProperties(); <END> apiStoreClient = new APIStoreRestClient(storeURL); apiStoreClient.login(userName, password); }</code><technical_language>remove this this is done in base class</technical_language>

Target:
private void loginToStore(String userName, String password) throws Exception { apiStoreClient = new APIStoreRestClient(storeURL); apiStoreClient.login(userName, password); }
Source:
<code>static void verifyCanContinueOnException(CosmosException ex) { <START> if (ex == null) { <END> return; } if (ex instanceof PartitionKeyRangeGoneException) { throw ex; } if (ex instanceof PartitionKeyRangeIsSplittingException) { throw ex; } if (ex instanceof PartitionIsMigratingException) { throw ex; } String value = ex.getResponseHeaders().get(HttpConstants.HttpHeaders.REQUEST_VALIDATION_FAILURE); if (Strings.isNullOrWhiteSpace(value)) { return; } Integer result = Integers.tryParse(value); if (result != null && result == 1) { throw ex; } return; }</code><technical_language>this null check</technical_language>

Target:
static void verifyCanContinueOnException(CosmosException ex) { if (ex instanceof PartitionKeyRangeGoneException) { throw ex; } if (ex instanceof PartitionKeyRangeIsSplittingException) { throw ex; } if (ex instanceof PartitionIsMigratingException) { throw ex; } String value = ex.getResponseHeaders().get(HttpConstants.HttpHeaders.REQUEST_VALIDATION_FAILURE); if (Strings.isNullOrWhiteSpace(value)) { return; } Integer result = Integers.tryParse(value); if (result != null && result == 1) { throw ex; } return; }
Source:
<code><START> private Show(String name) { <END> this.name = name; }</code><technical_language>Modifier 'private' is redundant for Enum constructor - needs removed</technical_language>

Target:
Show(String name) { this.name = name; }
Source:
<code>private void handleDestroyStoragePoolCommand() { try { runVdsCommand(VDSCommandType.DestroyStoragePool, new IrsBaseVDSCommandParameters(getStoragePool().getId())); } catch (VdcBLLException e) { try { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { runVdsCommand(VDSCommandType.SpmStopOnIrs, new SpmStopOnIrsVDSCommandParameters(getStoragePool().getId())); return null; } }); } catch (Exception e1) { <START> log.error("Failed destroy storage pool with id '{}' and after that failed to stop spm because of {}", <END> getStoragePoolId(), e1.getMessage()); log.debug("Exception", e1); } throw e; } }</code><technical_language>s/ of/:/</technical_language>

Target:
private void handleDestroyStoragePoolCommand() { try { runVdsCommand(VDSCommandType.DestroyStoragePool, new IrsBaseVDSCommandParameters(getStoragePool().getId())); } catch (VdcBLLException e) { try { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { runVdsCommand(VDSCommandType.SpmStopOnIrs, new SpmStopOnIrsVDSCommandParameters(getStoragePool().getId())); return null; } }); } catch (Exception e1) { log.error("Failed destroy storage pool with id '{}' and after that failed to stop spm: {}", getStoragePoolId(), e1.getMessage()); log.debug("Exception", e1); } throw e; } }
Source:
<code>public void write(final Kryo kryo, final Output output, final Cipher object) { <START> if (object.getProvider() != null && !"BC".equals(object.getProvider().getName())) { <END> String msg = String.format("Serialization is only " + "supported for ciphers from the BouncyCastle provider. " + "Actual provider: %s", object.getProvider().getName()); throw new UnsupportedOperationException(msg); } final Object cryptoPerm = readField(cryptoPermField, object); kryo.writeObjectOrNull(output, cryptoPerm, cryptoAllPermissionClass); kryo.writeClassAndObject(output, readField(exmechField, object)); kryo.writeClassAndObject(output, readField(firstServiceField, object)); kryo.writeClassAndObject(output, readField(firstSpiField, object)); output.writeBoolean((Boolean)readField(initializedField, object)); kryo.writeClassAndObject(output, readField(lockField, object)); final int opmode = (int)readField(opmodeField, object); output.writeInt(opmode, true); Provider provider = (Provider)readField(providerField, object); output.writeString(provider.getName()); kryo.writeClassAndObject(output, readField(serviceIteratorField, object)); final Object spi = readField(spiField, object); kryo.writeClassAndObject(output, spi); output.writeString((String)readField(transformationField, object)); kryo.writeClassAndObject(output, readField(transformsField, object)); output.flush(); }</code><technical_language>Is a (maybe package private) constant compared instead</technical_language>

Target:
public void write(final Kryo kryo, final Output output, final Cipher object) { if (object.getProvider() != null && !BouncyCastleProvider.PROVIDER_NAME .equals(object.getProvider().getName())) { String msg = String.format("Serialization is only " + "supported for ciphers from the BouncyCastle provider. " + "Actual provider: %s", object.getProvider().getName()); throw new UnsupportedOperationException(msg); } final Object cryptoPerm = readField(cryptoPermField, object); kryo.writeObjectOrNull(output, cryptoPerm, cryptoAllPermissionClass); kryo.writeClassAndObject(output, readField(exmechField, object)); kryo.writeClassAndObject(output, readField(firstServiceField, object)); kryo.writeClassAndObject(output, readField(firstSpiField, object)); output.writeBoolean((Boolean)readField(initializedField, object)); kryo.writeClassAndObject(output, readField(lockField, object)); final int opmode = (int)readField(opmodeField, object); output.writeInt(opmode, true); Provider provider = (Provider)readField(providerField, object); output.writeString(provider.getName()); kryo.writeClassAndObject(output, readField(serviceIteratorField, object)); final Object spi = readField(spiField, object); kryo.writeClassAndObject(output, spi); output.writeString((String)readField(transformationField, object)); kryo.writeClassAndObject(output, readField(transformsField, object)); output.flush(); }
Source:
<code>public void cancel(InterpreterContext context) { SparkInterpreter sparkInterpreter = getSparkInterpreter(); sparkInterpreter.cancel(context); try { <START> interrupt(); <END> } catch (IOException e) { e.printStackTrace(); } }</code><technical_language>I In case of Spark job is running, need wait sparkInterpreter.cancel(context) call interrupt. In case of Spark job is running, interrupt() need called. do think</technical_language>

Target:
public void cancel(InterpreterContext context) { SparkInterpreter sparkInterpreter = getSparkInterpreter(); sparkInterpreter.cancel(context); try { interrupt(); } catch (IOException e) { logger.error("Error", e); } }
Source:
<code>public void setOAuthHeader(MessageContext messageContext) throws OAuthException { String token; try { token = TokenCache.getInstance().getToken(id, new Callable<String>() { @Override public String call() throws OAuthException, IOException { return OAuthClient.generateToken(tokenApiUrl, buildTokenRequestPayload(), getEncodedCredentials()); } }); } catch (ExecutionException e) { throw new OAuthException(e); <START> } <END> setAuthorizationHeader(messageContext, token); }</code><technical_language>extract this a method called getToken</technical_language>

Target:
public void setOAuthHeader(MessageContext messageContext) throws OAuthException { setAuthorizationHeader(messageContext, getToken()); }