auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public List<RuntimeException> validate(ResourceInfo resource, boolean isNew) { if ( isNull(resource.getName()) ) { throw new NullPointerException( "Resource name must not be null"); } <START> if ( isNull(resource.getNativeName()) && !(resource instanceof CoverageInfo && ((CoverageInfo)resource).getNativeCoverageName() != null)) { <END> throw new NullPointerException( "Resource native name must not be null"); } if ( resource.getStore() == null ) { throw new IllegalArgumentException( "Resource must be part of a store"); } if ( resource.getNamespace() == null ) { throw new IllegalArgumentException( "Resource must be part of a namespace"); } StoreInfo store = resource.getStore(); ResourceInfo existing = getResourceByStore( store, resource.getName(), ResourceInfo.class); if ( existing != null && !existing.getId().equals( resource.getId() ) ) { String msg = "Resource named '"+resource.getName()+"' already exists in store: '"+ store.getName()+"'"; throw new IllegalArgumentException( msg ); } NamespaceInfo namespace = resource.getNamespace(); existing = getResourceByName( namespace, resource.getName(), ResourceInfo.class); if ( existing != null && !existing.getId().equals( resource.getId() ) ) { String msg = "Resource named '"+resource.getName()+"' already exists in namespace: '"+ namespace.getPrefix()+"'"; throw new IllegalArgumentException( msg ); } validateKeywords(resource.getKeywords()); return postValidate(resource, isNew); }</code><technical_language>I a reason... for life of me, I recall one. check Daniele Monday</technical_language>

Target:
public ValidationResult validate(ResourceInfo resource, boolean isNew) { if ( isNull(resource.getName()) ) { throw new NullPointerException( "Resource name must not be null"); } if ( isNull(resource.getNativeName()) && !(resource instanceof CoverageInfo && ((CoverageInfo)resource).getNativeCoverageName() != null)) { throw new NullPointerException( "Resource native name must not be null"); } if ( resource.getStore() == null ) { throw new IllegalArgumentException( "Resource must be part of a store"); } if ( resource.getNamespace() == null ) { throw new IllegalArgumentException( "Resource must be part of a namespace"); } StoreInfo store = resource.getStore(); ResourceInfo existing = getResourceByStore( store, resource.getName(), ResourceInfo.class); if ( existing != null && !existing.getId().equals( resource.getId() ) ) { String msg = "Resource named '"+resource.getName()+"' already exists in store: '"+ store.getName()+"'"; throw new IllegalArgumentException( msg ); } NamespaceInfo namespace = resource.getNamespace(); existing = getResourceByName( namespace, resource.getName(), ResourceInfo.class); if ( existing != null && !existing.getId().equals( resource.getId() ) ) { String msg = "Resource named '"+resource.getName()+"' already exists in namespace: '"+ namespace.getPrefix()+"'"; throw new IllegalArgumentException( msg ); } validateKeywords(resource.getKeywords()); return postValidate(resource, isNew); }
Source:
<code>public TimeSeriesKey<K> fromBytes(byte[] timeSeriesKeyBytes) { ByteBuffer buf = ByteBuffer.wrap(timeSeriesKeyBytes); int keySize = timeSeriesKeyBytes.length - TIMESTAMP_SIZE - SEQNUM_SIZE; K key = null; if (keySize != 0) { byte[] keyBytes = new byte[keySize]; buf.get(keyBytes); key = keySerde.fromBytes(keyBytes); } long timeStamp = buf.getLong(); <START> long seqNum = buf.getLong(); <END> return new TimeSeriesKey(key, timeStamp, seqNum); }</code><technical_language>This relies version 0. Safer do right now. Q: happen if version match field in class? throw here</technical_language>

Target:
public TimeSeriesKey<K> fromBytes(byte[] timeSeriesKeyBytes) { ByteBuffer buf = ByteBuffer.wrap(timeSeriesKeyBytes); int keySize = timeSeriesKeyBytes.length - TIMESTAMP_SIZE - SEQNUM_SIZE; K key = null; if (keySize != 0) { byte[] keyBytes = new byte[keySize]; buf.get(keyBytes); key = keySerde.fromBytes(keyBytes); } long timeStamp = buf.getLong(); long seqNum = buf.getLong(); long version = seqNum & ~SEQUENCE_NUM_MASK; if (version != 0) { throw new SamzaException("Version is not zero. Sequence number: " + seqNum); } return new TimeSeriesKey(key, timeStamp, seqNum); }
Source:
<code>public Opt<Identity> enter(final Request req) throws IOException { <START> Opt<Identity> retValue = null; <END> for (final Pass pass : this.passes) { retValue = pass.enter(req); if (retValue.has()) { break; } } if (retValue == null) { retValue = new Opt.Empty<Identity>(); } return retValue; }</code><technical_language>@antonini please name user, initialize Opt.Empty</technical_language>

Target:
public Opt<Identity> enter(final Request req) throws IOException { Opt<Identity> user = new Opt.Empty<Identity>(); for (final Pass pass : this.passes) { user = pass.enter(req); if (user.has()) { break; } } return user; }
Source:
<code>public Action[] getActions(boolean popup) { List<Action> actions = new ArrayList<>(); actions.add(new NewWindowViewAction( NbBundle.getMessage(this.getClass(), "VirtualDirectoryNode.getActions.viewInNewWin.text"), this)); actions.add(null); actions.add(ExtractAction.getInstance()); actions.add(null); if (this.content.isDataSource()) { <START> actions.add(new FileSearchAction( <END> Bundle.ImageNode_getActions_openFileSearchByAttr_text())); actions.add(new AbstractAction( Bundle.VirtualDirectoryNode_action_runIngestMods_text()) { @Override public void actionPerformed(ActionEvent e) { final RunIngestModulesDialog ingestDialog = new RunIngestModulesDialog(Collections.<Content>singletonList(content)); ingestDialog.display(); } }); } actions.addAll(ContextMenuExtensionPoint.getActions()); return actions.toArray(new Action[0]); }</code><technical_language>I verified want ability run ingest modules non-data source virtual directories. Please remove isDataSource check</technical_language>

Target:
public Action[] getActions(boolean popup) { List<Action> actions = new ArrayList<>(); actions.add(new NewWindowViewAction( NbBundle.getMessage(this.getClass(), "VirtualDirectoryNode.getActions.viewInNewWin.text"), this)); actions.add(null); actions.add(ExtractAction.getInstance()); actions.add(null); actions.add(new FileSearchAction( Bundle.ImageNode_getActions_openFileSearchByAttr_text())); actions.add(new AbstractAction( Bundle.VirtualDirectoryNode_action_runIngestMods_text()) { @Override public void actionPerformed(ActionEvent e) { final RunIngestModulesDialog ingestDialog = new RunIngestModulesDialog(Collections.<Content>singletonList(content)); ingestDialog.display(); } }); actions.addAll(ContextMenuExtensionPoint.getActions()); return actions.toArray(new Action[0]); }
Source:
<code>private Message<?> pruneHeaders(Message<?> message) { Map<String, Object> headersToEmbed = new HashMap<>(); <START> message.getHeaders().forEach((k, v) -> { <END> if (this.headerPatterns.stream().anyMatch(p -> p.matcher(k).matches())) { headersToEmbed.put(k, v); } }); return new MutableMessage<>(message.getPayload(), headersToEmbed); }</code><technical_language>java Stream<Pattern> patternStream = this.headerPatterns.stream(); Map<String, Object> headersToEmbed = message.getHeaders() .entrySet() .stream() .filter(e -> patternStream.anyMatch(p -> p.matcher(e.getKey()).matches())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); ? I this.headerPatterns.stream() a property, too. avoid extra Stream object for message</technical_language>

Target:
private Message<?> pruneHeaders(Message<?> message) { Map<String, Object> headersToEmbed = message.getHeaders().entrySet().stream() .filter(e -> this.headerPatterns.stream().anyMatch(p -> this.caseSensitive ? PatternMatchUtils.simpleMatch(p, e.getKey()) : PatternMatchUtils.simpleMatch(p.toLowerCase(), e.getKey().toLowerCase()))) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); return new MutableMessage<>(message.getPayload(), headersToEmbed); }
Source:
<code>public static void main(String[] args) { int port; if (args.length == 0) { System.err.println("You must specify a port number."); System.exit(1); } port = Integer.parseInt(args[0]); GatewayServer gatewayServer = new GatewayServer(null, port); gatewayServer.start(); int listening_port = gatewayServer.getListeningPort(); System.out.println("" + listening_port); BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); try { stdin.readLine(); System.exit(0); } catch (java.io.IOException e) { <START> System.exit(0); <END> } }</code><technical_language>I guess if pipe is broken, return code 1</technical_language>

Target:
public static void main(String[] args) { int port; boolean dieOnBrokenPipe = false; String usage = "usage: [--die-on-broken-pipe] port"; if (args.length == 0) { System.err.println(usage); System.exit(1); } else if (args.length == 2) { if (!args[0].equals("--die-on-broken-pipe")) { System.err.println(usage); System.exit(1); } dieOnBrokenPipe = true; } port = Integer.parseInt(args[args.length - 1]); GatewayServer gatewayServer = new GatewayServer(null, port); gatewayServer.start(); int listening_port = gatewayServer.getListeningPort(); System.out.println("" + listening_port); if (dieOnBrokenPipe) { BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); try { stdin.readLine(); System.exit(0); } catch (java.io.IOException e) { System.exit(1); } } }
Source:
<code>public PipelinedSubpartitionView createReadView(BufferAvailabilityListener availabilityListener) { synchronized (buffers) { checkState(!isReleased); if (readView != null) { <START> LOG.info("{} ReadView for Subpartition of has not been released!", <END> parent.getOwningTaskName(), getSubPartitionIndex(), parent.getPartitionId()); releaseView(); } LOG.debug("{}: Creating read view for subpartition of partition {}.", parent.getOwningTaskName(), getSubPartitionIndex(), parent.getPartitionId()); readView = new PipelinedApproximateSubpartitionView(this, availabilityListener); } return readView; }</code><technical_language>I this message mention a new view is created</technical_language>

Target:
public PipelinedSubpartitionView createReadView(BufferAvailabilityListener availabilityListener) { synchronized (buffers) { checkState(!isReleased); releaseView(); LOG.debug("{}: Creating read view for subpartition of partition {}.", parent.getOwningTaskName(), getSubPartitionIndex(), parent.getPartitionId()); readView = new PipelinedApproximateSubpartitionView(this, availabilityListener); } return readView; }
Source:
<code>public void repositoryChanged(TaskRepositoryChangeEvent event) { Type type = event.getDelta().getType(); if (type == TaskRepositoryDelta.Type.PROPERTY) { Object key = event.getDelta().getKey(); if (IBugzillaConstants.BUGZILLA_USE_XMLRPC.equals(key) || IBugzillaConstants.BUGZILLA_DESCRIPTOR_FILE.equals(key)) { final TaskRepository repository = event.getRepository(); boolean startJob; <START> synchronized (repository) { <END> startJob = !repository.isUpdating(); if (startJob) { repository.setUpdating(true); } } if (startJob) { TaskJob updateJob = new UpdateRepositoryConfigurationJob( Messages.BugzillaClientManager_Refreshing_repository_configuration, repository, connector); updateJob.setPriority(Job.INTERACTIVE); updateJob.addJobChangeListener(repositoryConfigurationUpdateJobChangeAdapter); updateJob.addJobChangeListener(new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { synchronized (repository) { repository.setUpdating(false); } } }); updateJob.schedule(); } } } }</code><technical_language>This synchronize repository due a risk for dead-locks. BugzillaClientManager a private lock for managing update job</technical_language>

Target:
public void repositoryChanged(TaskRepositoryChangeEvent event) { Type type = event.getDelta().getType(); if (type == TaskRepositoryDelta.Type.PROPERTY) { Object key = event.getDelta().getKey(); if (IBugzillaConstants.BUGZILLA_USE_XMLRPC.equals(key) || IBugzillaConstants.BUGZILLA_DESCRIPTOR_FILE.equals(key)) { final TaskRepository repository = event.getRepository(); boolean startJob; synchronized (updateList) { startJob = !updateList.contains(repository); if (startJob) { updateList.add(repository); } } if (startJob) { TaskJob updateJob = new UpdateRepositoryConfigurationJob( Messages.BugzillaClientManager_Refreshing_repository_configuration, repository, connector); updateJob.setPriority(Job.INTERACTIVE); updateJob.addJobChangeListener(repositoryConfigurationUpdateJobChangeAdapter); updateJob.addJobChangeListener(new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { synchronized (updateList) { updateList.remove(repository); } } }); updateJob.schedule(); } } } }
Source:
<code>public ResponseDto callback(String responseData) { logger.info("[register callback] data is {}", responseData); ResponseDto<RegisterContentDto> responseDto = ApiType.REGISTER.getParser().parse(responseData); if (responseDto == null) { logger.error("[register callback] parse callback data error, data is {}", responseData); return null; } if (responseDto.isSuccess()) { RegisterContentDto registerContentDto = responseDto.getContent(); ExtMarkDto extMarkDto = new GsonBuilder().create().fromJson(registerContentDto.getExtMark(), ExtMarkDto.class); this.messageQueueClient.publishMessage(MessageTopic.CertificationSuccess, Maps.newHashMap(ImmutableMap.<String, String>builder() .put("loginName", extMarkDto.getLoginName()) <START> .put("mobilePhone", registerContentDto.getMobilePhone()) <END> .put("identityCode", registerContentDto.getIdentityCode()) .put("realName", registerContentDto.getRealName()) .put("accountNo", registerContentDto.getAccountNo()) .put("userName", registerContentDto.getUserName()) .put("orderDate", registerContentDto.getRegDate()) .put("orderNo", registerContentDto.getOrderNo()) .build())); } responseDto.setReqData(responseData); updateMapper.updateRegister(responseDto); return responseDto; }</code><technical_language>mobilePhone->mobile</technical_language>

Target:
public ResponseDto callback(String responseData) { logger.info("[register callback] data is {}", responseData); ResponseDto<RegisterContentDto> responseDto = ApiType.REGISTER.getParser().parse(responseData); if (responseDto == null) { logger.error("[register callback] parse callback data error, data is {}", responseData); return null; } if (responseDto.isSuccess()) { RegisterContentDto registerContentDto = responseDto.getContent(); ExtMarkDto extMarkDto = new GsonBuilder().create().fromJson(registerContentDto.getExtMark(), ExtMarkDto.class); this.messageQueueClient.publishMessage(MessageTopic.RegisterBankAccount, Maps.newHashMap(ImmutableMap.<String, String>builder() .put("loginName", extMarkDto.getLoginName()) .put("mobile", registerContentDto.getMobilePhone()) .put("identityCode", registerContentDto.getIdentityCode()) .put("realName", registerContentDto.getRealName()) .put("accountNo", registerContentDto.getAccountNo()) .put("userName", registerContentDto.getUserName()) .put("orderDate", registerContentDto.getRegDate()) .put("orderNo", registerContentDto.getOrderNo()) .build())); } responseDto.setReqData(responseData); updateMapper.updateRegister(responseDto); return responseDto; }
Source:
<code>public void setEndpoints(String notify, String sessions) throws IllegalArgumentException { if (notify == null || "".equals(notify)) { throw new IllegalArgumentException("Notify endpoint cannot be empty or null."); } else { if (delivery instanceof HttpDelivery) { ((HttpDelivery) delivery).setEndpoint(notify); } else { LOGGER.warn("Delivery is not instance of HttpDelivery, cannot set notify endpoint"); } } boolean invalidSessionsEndpoint = sessions == null || "".equals(sessions); String sessionEndpoint = null; if (invalidSessionsEndpoint) { LOGGER.warn("The session tracking endpoint has not been" + " set. Session tracking is disabled"); <START> this.autoCaptureSessions.set(false); <END> } else { sessionEndpoint = sessions; } if (sessionDelivery instanceof HttpDelivery) { ((HttpDelivery) sessionDelivery).setEndpoint(sessionEndpoint); } else { LOGGER.warn("Delivery is not instance of HttpDelivery, cannot set sessions endpoint"); } }</code><technical_language>autoCaptureSessions disabled if setSessionEndpoint is called empty / null</technical_language>

Target:
public void setEndpoints(String notify, String sessions) throws IllegalArgumentException { if (notify == null || notify.isEmpty()) { throw new IllegalArgumentException("Notify endpoint cannot be empty or null."); } else { if (delivery instanceof HttpDelivery) { ((HttpDelivery) delivery).setEndpoint(notify); } else { LOGGER.warn("Delivery is not instance of HttpDelivery, cannot set notify endpoint"); } } boolean invalidSessionsEndpoint = sessions == null || sessions.isEmpty(); String sessionEndpoint = null; if (invalidSessionsEndpoint) { LOGGER.warn("The session tracking endpoint has not been" + " set. Session tracking is disabled"); this.autoCaptureSessions.set(false); } else { sessionEndpoint = sessions; } if (sessionDelivery instanceof HttpDelivery) { ((HttpDelivery) sessionDelivery).setEndpoint(sessionEndpoint); } else { LOGGER.warn("Delivery is not instance of HttpDelivery, cannot set sessions endpoint"); } }
Source:
<code>protected void sendMessage(Message<?> message) { if (message == null) { throw new MessagingException("cannot send a null message"); } if (this.shouldTrack) { message = MessageHistory.write(message, this, this.getMessageBuilderFactory()); } try { this.messagingTemplate.send(getOutputChannel(), message); } catch (RuntimeException e) { MessageChannel errorChannel = getErrorChannel(); if (errorChannel != null) { <START> this.messagingTemplate.send(errorChannel, buildErrorMessage(e)); <END> } else { throw e; } } }</code><technical_language>preferable delegate this injected ErrorMessageStrategy invoking overridable method</technical_language>

Target:
protected void sendMessage(Message<?> message) { if (message == null) { throw new MessagingException("cannot send a null message"); } if (this.shouldTrack) { message = MessageHistory.write(message, this, this.getMessageBuilderFactory()); } try { this.messagingTemplate.send(getOutputChannel(), message); } catch (RuntimeException e) { MessageChannel errorChannel = getErrorChannel(); if (errorChannel != null) { this.messagingTemplate.send(errorChannel, this.errorMessageStrategy.buildErrorMessage(e, ErrorMessageUtils.getAttributeAccessor(message, null))); } else { throw e; } } }
Source:
<code>default List<T> filter(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); List<T> list = this; List<T> result = List.empty(); <START> boolean testFailed = false; <END> while (!list.isEmpty()) { if (predicate.test(list.head())) { result = result.prepend(list.head()); } else { testFailed = true; } list = list.tail(); } return testFailed ? result.reverse() : this; }</code><technical_language>i name isFiltered suggest failed</technical_language>

Target:
default List<T> filter(Predicate<? super T> predicate) { final List<T> filtered = foldLeft(List.<T> empty(), (xs, x) -> predicate.test(x) ? xs.prepend(x) : xs); return this.length() == filtered.length() ? this : filtered.reverse(); }
Source:
<code>public String execute(final LnClientConnection conn, final DlmsDevice device, final DataObject object) throws IOException, TimeoutException, ProtocolAdapterException { final AttributeAddress attributeAddress = new AttributeAddress(CLASS_ID, OBIS_CODE, ATTRIBUTE_ID); LOGGER.info("Retrieving configuration objects for class id: {}, obis code: {}, attribute id: {}", CLASS_ID, OBIS_CODE, ATTRIBUTE_ID); final List<GetResult> getResultList = conn.get(attributeAddress); if (getResultList.isEmpty()) { throw new ProtocolAdapterException("No GetResult received while retrieving configuration objects."); } if (getResultList.size() > 1 || getResultList.get(0) == null) { throw new ProtocolAdapterException("Expected 1 GetResult while retrieving configuration objects, got " + getResultList.size()); } final DataObject resultData = getResultList.get(0).resultData(); if (!resultData.isComplex()) { this.throwUnexpectedTypeProtocolAdapterException(); } @SuppressWarnings("unchecked") final List<DataObject> resultDataValue = (List<DataObject>) getResultList.get(0).resultData().value(); final List<ClassIdObisAttr> allObisCodes = this.getAllObisCodes(resultDataValue); this.logAllObisCodes(allObisCodes); final String output = this.createOutput(conn, allObisCodes); <START> LOGGER.info("Total output is: {}", output); <END> return output; }</code><technical_language>Change log level debug</technical_language>

Target:
public String execute(final LnClientConnection conn, final DlmsDevice device, final DataObject object) throws IOException, TimeoutException, ProtocolAdapterException { final AttributeAddress attributeAddress = new AttributeAddress(CLASS_ID, OBIS_CODE, ATTRIBUTE_ID); LOGGER.debug("Retrieving configuration objects for class id: {}, obis code: {}, attribute id: {}", CLASS_ID, OBIS_CODE, ATTRIBUTE_ID); final List<GetResult> getResultList = conn.get(attributeAddress); if (getResultList.isEmpty()) { throw new ProtocolAdapterException("No GetResult received while retrieving configuration objects."); } if (getResultList.size() > 1 || getResultList.get(0) == null) { throw new ProtocolAdapterException("Expected 1 GetResult while retrieving configuration objects, got " + getResultList.size()); } final DataObject resultData = getResultList.get(0).resultData(); if (!resultData.isComplex()) { this.throwUnexpectedTypeProtocolAdapterException(); } @SuppressWarnings("unchecked") final List<DataObject> resultDataValue = (List<DataObject>) getResultList.get(0).resultData().value(); final List<ClassIdObisAttr> allObisCodes = this.getAllObisCodes(resultDataValue); this.logAllObisCodes(allObisCodes); final String output = this.createOutput(conn, allObisCodes); LOGGER.debug("Total output is: {}", output); return output; }
Source:
<code>protected void ExecuteVdsBrokerCommand() { String storageDomainId = getParameters().getStorageDomainId().toString(); <START> String[] deviceList = getParameters().getDeviceList().toArray(new String[] {}); <END> boolean isForce = getParameters().isForce(); boolean supportForceCreateVG = Config.<Boolean> GetValue( ConfigValues.SupportForceCreateVG, getVds().getvds_group_compatibility_version().toString()); _result = supportForceCreateVG ? getBroker().createVG(storageDomainId, deviceList, isForce) : getBroker().createVG(storageDomainId, deviceList); ProceedProxyReturnValue(); setReturnValue(_result.mUuid); }</code><technical_language>performance: init string size of device list</technical_language>

Target:
protected void ExecuteVdsBrokerCommand() { String storageDomainId = getParameters().getStorageDomainId().toString(); List<String> deviceList = getParameters().getDeviceList(); String[] deviceArray = deviceList.toArray(new String[deviceList.size()]); boolean isForce = getParameters().isForce(); boolean supportForceCreateVG = Config.<Boolean> GetValue( ConfigValues.SupportForceCreateVG, getVds().getvds_group_compatibility_version().toString()); _result = supportForceCreateVG ? getBroker().createVG(storageDomainId, deviceArray, isForce) : getBroker().createVG(storageDomainId, deviceArray); ProceedProxyReturnValue(); setReturnValue(_result.mUuid); }
Source:
<code>public BoundedOffHeapDataContainer(int desiredSize, long maxSize, EvictionType type) { super(desiredSize); this.maxSize = maxSize; if (type == EvictionType.COUNT) { sizeCalculator = i -> 1; } else { <START> sizeCalculator = i -> offHeapEntryFactory.getSize(i) + OffHeapLruNode.getSize(); <END> } this.lruLock = new ReentrantLock(); firstAddress = 0; }</code><technical_language>offHeapEntryFactory.getSize() include size of LRU pointers</technical_language>

Target:
public BoundedOffHeapDataContainer(int desiredSize, long maxSize, EvictionType type) { super(desiredSize); this.maxSize = maxSize; if (type == EvictionType.COUNT) { sizeCalculator = i -> 1; } else { sizeCalculator = i -> offHeapEntryFactory.getSize(i); } this.lruLock = new ReentrantLock(); firstAddress = 0; }
Source:
<code>public UserPortalNewTemplateVmModelBehavior() { <START> super(); <END> }</code><technical_language>call 'super()' is implicit. need state explicitly</technical_language>

Target:
public UserPortalNewTemplateVmModelBehavior() { }
Source:
<code>public static <K, V, K2> Map<K2, V> mapKeys(Map<K, V> map, Function<K, K2> keyMapper) { final Map<K2, V> result = Maps.newHashMapWithExpectedSize(map.size()); map.forEach((k, v) -> { final K2 k2 = keyMapper.apply(k); <START> if (result.containsKey(k2)) { <END> throw new ISE("Conflicting key[%s] calculated via keyMapper for original key[%s]", k2, k); } result.put(k2, v); }); return result; }</code><technical_language>Please lookup operation for key: putIfAbsent()</technical_language>

Target:
public static <K, V, K2> Map<K2, V> mapKeys(Map<K, V> map, Function<K, K2> keyMapper) { final Map<K2, V> result = Maps.newHashMapWithExpectedSize(map.size()); map.forEach((k, v) -> { final K2 k2 = keyMapper.apply(k); if (result.putIfAbsent(k2, v) != null) { throw new ISE("Conflicting key[%s] calculated via keyMapper for original key[%s]", k2, k); } }); return result; }
Source:
<code>public static String getCluster(Configuration jobConf) { String jobtracker = jobConf.get(JOBTRACKER_KEY); <START> if (jobtracker == null) { <END> jobtracker = jobConf.get(RESOURCE_MANAGER_KEY); } int portIdx = jobtracker.indexOf(':'); if (portIdx > -1) { jobtracker = jobtracker.substring(0, portIdx); } String cluster = Cluster.getIdentifier(jobtracker); return cluster != null ? cluster: null; }</code><technical_language>StringUtils.isEmpty(jobtracker) instead of jobtracker == null</technical_language>

Target:
public static String getCluster(Configuration jobConf) { String jobtracker = jobConf.get(JOBTRACKER_KEY); if (jobtracker == null) { jobtracker = jobConf.get(RESOURCE_MANAGER_KEY); } String cluster = null; if (jobtracker != null) { int portIdx = jobtracker.indexOf(':'); if (portIdx > -1) { jobtracker = jobtracker.substring(0, portIdx); } cluster = Cluster.getIdentifier(jobtracker); } return cluster; }
Source:
<code>public static Map<String, Metric> getMetrics() { Map<String, Metric> metrics = new HashMap<>(); metrics.put(CLASSNAME + MetricsAware.KEY_REGEX + TOTAL_EVENTS_COUNT, new Counter()); <START> return metrics; <END> }</code><technical_language>wrap Collections.unmodifiableMap()</technical_language>

Target:
public static Map<String, Metric> getMetrics() { Map<String, Metric> metrics = new HashMap<>(); metrics.put(CLASSNAME + MetricsAware.KEY_REGEX + TOTAL_EVENTS_COUNT, new Counter()); return Collections.unmodifiableMap(metrics); }
Source:
<code>public static ConditionEvaluationResult disabled(String reason, String customReason) { <START> if (customReason.isEmpty()) { <END> return disabled(reason); } return disabled(String.format("%s ==> %s", reason, customReason)); }</code><technical_language>o: StringUtils.isBlank() here</technical_language>

Target:
public static ConditionEvaluationResult disabled(String reason, String customReason) { if (StringUtils.isBlank(customReason)) { return disabled(reason); } return disabled(String.format("%s ==> %s", reason, customReason)); }
Source:
<code>public XAResourceRecord(TransactionImple tx, XAResource res, Xid xid, Object[] params) { if (jtaxLogger.logger.isTraceEnabled()) { jtaxLogger.logger.trace("XAResourceRecord.XAResourceRecord ( " + xid + " )"); } _theXAResource = res; _recoveryObject = null; _tranID = xid; _valid = true; if (params != null) { <START> if (params.length >= XACONNECTION + 1) <END> { if (params[XACONNECTION] instanceof RecoverableXAConnection) _recoveryObject = (RecoverableXAConnection) params[XACONNECTION]; } } _prepared = false; _committed = false; _heuristic = TwoPhaseOutcome.FINISH_OK; _participantStore = null; _theUid = new Uid(); _theReference = null; _recoveryCoordinator = null; _theTransaction = tx; if (_theXAResource instanceof FirstResource) _cachedUidStringForm = START_XARESOURCE.stringForm(); else if (_theXAResource instanceof LastResource) _cachedUidStringForm = END_XARESOURCE.stringForm(); }</code><technical_language>java if (params.length > XACONNECTION)</technical_language>

Target:
public XAResourceRecord(TransactionImple tx, XAResource res, Xid xid, Object[] params) { if (jtaxLogger.logger.isTraceEnabled()) { jtaxLogger.logger.trace("XAResourceRecord.XAResourceRecord ( " + xid + " )"); } _theXAResource = res; _recoveryObject = null; _tranID = xid; _valid = true; if (params != null) { if (params.length > XACONNECTION) { if (params[XACONNECTION] instanceof RecoverableXAConnection) _recoveryObject = (RecoverableXAConnection) params[XACONNECTION]; } } _prepared = false; _committed = false; _heuristic = TwoPhaseOutcome.FINISH_OK; _participantStore = null; _theUid = new Uid(); _theReference = null; _recoveryCoordinator = null; _theTransaction = tx; if (_theXAResource instanceof FirstResource) _cachedUidStringForm = START_XARESOURCE.stringForm(); else if (_theXAResource instanceof LastResource) _cachedUidStringForm = END_XARESOURCE.stringForm(); }
Source:
<code>public void testTumblingWindowsDiscardingMode() throws Exception { StreamGraphBuilder sgb = new KeyedTumblingWindowStreamGraphBuilder(AccumulationMode.DISCARDING); StreamOperatorTask task = new StreamOperatorTask(sgb); task.init(config, taskContext); integers.forEach(n -> task.process(new IntegerMessageEnvelope(n, n), messageCollector, taskCoordinator)); <START> Thread.sleep(1000); <END> task.window(messageCollector, taskCoordinator); Assert.assertEquals(windowPanes.size(), 5); Assert.assertEquals(windowPanes.get(0).getKey().getKey(), new Integer(1)); Assert.assertEquals(((Collection) windowPanes.get(0).getMessage()).size(), 2); Assert.assertEquals(windowPanes.get(1).getKey().getKey(), new Integer(2)); Assert.assertEquals(((Collection) windowPanes.get(1).getMessage()).size(), 2); Assert.assertEquals(windowPanes.get(2).getKey().getKey(), new Integer(1)); Assert.assertEquals(((Collection) windowPanes.get(2).getMessage()).size(), 2); Assert.assertEquals(windowPanes.get(3).getKey().getKey(), new Integer(2)); Assert.assertEquals(((Collection) windowPanes.get(3).getMessage()).size(), 2); Assert.assertEquals(windowPanes.get(4).getKey().getKey(), new Integer(3)); Assert.assertEquals(((Collection) windowPanes.get(4).getMessage()).size(), 1); }</code><technical_language>I address potential perf issue calling System.nanoTime() multiple times invoking onTimer() multiple times</technical_language>

Target:
public void testTumblingWindowsDiscardingMode() throws Exception { StreamApplication sgb = new KeyedTumblingWindowStreamApplication(AccumulationMode.DISCARDING, Duration.ofSeconds(1), Triggers.repeat(Triggers.count(2))); TestClock testClock = new TestClock(); StreamOperatorTask task = new StreamOperatorTask(sgb, testClock, runner); task.init(config, taskContext); integers.forEach(n -> task.process(new IntegerMessageEnvelope(n, n), messageCollector, taskCoordinator)); testClock.advanceTime(Duration.ofSeconds(1)); task.window(messageCollector, taskCoordinator); Assert.assertEquals(windowPanes.size(), 5); Assert.assertEquals(windowPanes.get(0).getKey().getKey(), new Integer(1)); Assert.assertEquals(((Collection<MessageEnvelope<Integer, Integer>>) windowPanes.get(0).getMessage()).size(), 2); Assert.assertEquals(windowPanes.get(1).getKey().getKey(), new Integer(2)); Assert.assertEquals(((Collection<MessageEnvelope<Integer, Integer>>) windowPanes.get(1).getMessage()).size(), 2); Assert.assertEquals(windowPanes.get(2).getKey().getKey(), new Integer(1)); Assert.assertEquals(((Collection<MessageEnvelope<Integer, Integer>>) windowPanes.get(2).getMessage()).size(), 2); Assert.assertEquals(windowPanes.get(3).getKey().getKey(), new Integer(2)); Assert.assertEquals(((Collection<MessageEnvelope<Integer, Integer>>) windowPanes.get(3).getMessage()).size(), 2); Assert.assertEquals(windowPanes.get(4).getKey().getKey(), new Integer(3)); Assert.assertEquals(((Collection<MessageEnvelope<Integer, Integer>>) windowPanes.get(4).getMessage()).size(), 1); }
Source:
<code>private Repository getRepository(boolean warn, IStructuredSelection selection, Shell shell) { RepositoryMapping mapping = null; <START> for (IResource respource : getSelectedResources(selection)) { <END> RepositoryMapping repositoryMapping = RepositoryMapping .getMapping(respource); if (mapping == null) mapping = repositoryMapping; if (repositoryMapping == null) return null; if (mapping.getRepository() != repositoryMapping.getRepository()) { if (warn) MessageDialog.openError(shell, UIText.RepositoryAction_multiRepoSelectionTitle, UIText.RepositoryAction_multiRepoSelection); return null; } } if (mapping == null) { if (warn) MessageDialog.openError(shell, UIText.RepositoryAction_errorFindingRepoTitle, UIText.RepositoryAction_errorFindingRepo); return null; } final Repository repository = mapping.getRepository(); return repository; }</code><technical_language>Variable name 'resource'</technical_language>

Target:
private Repository getRepository(boolean warn, IStructuredSelection selection, Shell shell) { RepositoryMapping mapping = null; for (IResource resource : getSelectedResources(selection)) { RepositoryMapping repositoryMapping = RepositoryMapping .getMapping(resource); if (mapping == null) mapping = repositoryMapping; if (repositoryMapping == null) return null; if (mapping.getRepository() != repositoryMapping.getRepository()) { if (warn) MessageDialog.openError(shell, UIText.RepositoryAction_multiRepoSelectionTitle, UIText.RepositoryAction_multiRepoSelection); return null; } } if (mapping == null) { if (warn) MessageDialog.openError(shell, UIText.RepositoryAction_errorFindingRepoTitle, UIText.RepositoryAction_errorFindingRepo); return null; } final Repository repository = mapping.getRepository(); return repository; }
Source:
<code><START> protected ProgramInformation parseProgramInformation(XmlPullParser xpp) throws IOException, XmlPullParserException { <END> String title = ""; String source = ""; String copyright = ""; List<byte[]> customEvents = new ArrayList<>(); do { xpp.next(); if (XmlPullParserUtil.isStartTag(xpp, "Title")) { title = xpp.getText(); } else if (XmlPullParserUtil.isStartTag(xpp, "Source")) { source = xpp.getText(); } else if (XmlPullParserUtil.isStartTag(xpp, "Copyright")) { copyright = xpp.getText(); } else { byte[] customElement = parseCustomElement(xpp, new ByteArrayOutputStream(512)); if (customElement.length > 0) { customEvents.add(customElement); } } } while (!XmlPullParserUtil.isEndTag(xpp, "ProgramInformation")); return new ProgramInformation(title, source, copyright, customEvents); }</code><technical_language>parse lang moreInformationURL attributes defined in spec, put ProgramInformation well</technical_language>

Target:
protected ProgramInformation parseProgramInformation(XmlPullParser xpp) throws IOException, XmlPullParserException { String title = null; String source = null; String copyright = null; String moreInformationURL = parseString(xpp, "moreInformationURL", null); String lang = parseString(xpp, "lang", null); do { xpp.next(); if (XmlPullParserUtil.isStartTag(xpp, "Title")) { title = xpp.nextText(); } else if (XmlPullParserUtil.isStartTag(xpp, "Source")) { source = xpp.nextText(); } else if (XmlPullParserUtil.isStartTag(xpp, "Copyright")) { copyright = xpp.nextText(); } else { maybeSkipTag(xpp); } } while (!XmlPullParserUtil.isEndTag(xpp, "ProgramInformation")); return new ProgramInformation(title, source, copyright, moreInformationURL, lang); }
Source:
<code>protected Map<ComponentType, String> buildCustomVersionDisplayNames() { <START> Map<ComponentType, String> result = new HashMap<>(); <END> return result; }</code><technical_language>custom Hive version label in component? user work Hive 1.2.0</technical_language>

Target:
protected Map<ComponentType, String> buildCustomVersionDisplayNames() { Map<ComponentType, String> result = new HashMap<>(); result.put(ComponentType.HIVE, "Qubole Hadoop2 (Hive 2.1.1 Beta)"); result.put(ComponentType.PIG, "Qubole Hadoop2"); result.put(ComponentType.PIGOUTPUT, "Qubole Hadoop2"); return result; }
Source:
<code>public void deliverAll(MessageKind kind) { this.delivering = true; for (Tuple update : this.queue.keySet()) { int count = this.queue.get(update); <START> assert count != 0; <END> Direction direction = count < 0 ? Direction.REVOKE : Direction.INSERT; for (int i = 0; i < Math.abs(count); i++) { this.receiver.update(direction, update); } } this.delivering = false; Map<Tuple, Integer> tmp = this.queue; this.queue = this.buffer; this.buffer = tmp; this.buffer.clear(); }</code><technical_language>aware this is a NOP</technical_language>

Target:
public void deliverAll(MessageKind kind) { this.delivering = true; for (Tuple update : this.queue.keySet()) { int count = this.queue.get(update); Direction direction = count < 0 ? Direction.REVOKE : Direction.INSERT; for (int i = 0; i < Math.abs(count); i++) { this.receiver.update(direction, update); } } this.delivering = false; Map<Tuple, Integer> tmp = this.queue; this.queue = this.buffer; this.buffer = tmp; this.buffer.clear(); }
Source:
<code>public void set(String name, Property property) throws PropertyNotFoundException { Field field = getType().getField(name); if (field == null) { Property removedProperty = computeRemovedProperty(name); if (removedProperty != null) { removedProperty.set(name, property); } return; } <START> children.put(field.getName().getPrefixedName(), property); <END> setIsModified(); }</code><technical_language>In get method calls getChild property.getName() instead of field.getName().getPrefixedName() key in children map. this consistent discrepancy prefixed/unprefixed</technical_language>

Target:
public void set(String name, Property property) throws PropertyNotFoundException { Field field = getType().getField(name); if (field == null) { Property removedProperty = computeRemovedProperty(name); if (removedProperty != null) { removedProperty.set(name, property); } return; } children.put(property.getName(), property); setIsModified(); }
Source:
<code>public static MultipartInput buildMultipartInput(Object input, String content) throws IOException { MultipartInput mpinput = new MultipartInput(); mpinput.setRequest(content); if (input instanceof Blob) { Blob blob = (Blob) input; <START> mpinput.setBlob(blob); <END> } else if (input instanceof Blobs) { mpinput.setBlobs((Blobs) input); } else { throw new IllegalArgumentException("Unsupported binary input object: " + input); } return mpinput; }</code><technical_language>need for intermediate blob variable</technical_language>

Target:
public static MultipartInput buildMultipartInput(Object input, String content) throws IOException { MultipartInput mpinput = new MultipartInput(); mpinput.setRequest(content); if (input instanceof Blob) { mpinput.setBlob((Blob) input); } else if (input instanceof Blobs) { mpinput.setBlobs((Blobs) input); } else { throw new IllegalArgumentException("Unsupported binary input object: " + input); } return mpinput; }
Source:
<code>private void invalidateMediaViewIfNeed(View containerView) { int containerViewWidth = containerView.getWidth(); int containerViewHeight = containerView.getHeight(); if (containerViewWidth <= 0 || containerViewHeight <= 0) { return; } boolean isContainerViewLandscape = containerViewWidth > containerViewHeight; ViewGroup.LayoutParams params = mediaView.getLayoutParams(); if (mediaView.getWidth() == 0 && params.width == ViewGroup.LayoutParams.MATCH_PARENT && mediaView.getHeight() == 0 && params.height == ViewGroup.LayoutParams.MATCH_PARENT) { if (containerViewWidth == containerViewHeight) { mediaView.setMinimumWidth(containerViewWidth); mediaView.setMinimumHeight(containerViewHeight); } else { <START> int width = ( isContainerViewLandscape ? containerViewWidth : ( nativeVideo.getVideoOrientation() == VERTICAL ? (int)(containerViewHeight * RATIO_9_TO_16) : (int)(containerViewHeight / RATIO_16_TO_9) ) ); int height = ( !isContainerViewLandscape ? containerViewHeight : ( nativeVideo.getVideoOrientation() == VERTICAL ? (int)(containerViewWidth * RATIO_9_TO_16) : (int)(containerViewWidth / RATIO_16_TO_9) ) ); <END> mediaView.setMinimumWidth(width); mediaView.setMinimumHeight(height); } mediaView.invalidate(); } }</code><technical_language>Please clean ternary operators avoid nesting</technical_language>

Target:
private void invalidateMediaViewIfNeed(View containerView) { int containerViewWidth = containerView.getWidth(); int containerViewHeight = containerView.getHeight(); if (containerViewWidth <= 0 || containerViewHeight <= 0) { return; } boolean isContainerViewLandscape = containerViewWidth > containerViewHeight; ViewGroup.LayoutParams params = mediaView.getLayoutParams(); if (mediaView.getWidth() == 0 && params.width == ViewGroup.LayoutParams.MATCH_PARENT && mediaView.getHeight() == 0 && params.height == ViewGroup.LayoutParams.MATCH_PARENT) { if (containerViewWidth == containerViewHeight) { mediaView.setMinimumWidth(containerViewWidth); mediaView.setMinimumHeight(containerViewHeight); } else { int width = getOffsetSide(containerViewHeight, containerViewWidth, isContainerViewLandscape); int height = getOffsetSide(containerViewWidth, containerViewHeight, !isContainerViewLandscape); mediaView.setMinimumWidth(width); mediaView.setMinimumHeight(height); } mediaView.invalidate(); } }
Source:
<code><START> public boolean onKill(Scheduler.KillTopologyRequest request) { <END> return false; }</code><technical_language>methods need implemented annotated @Override</technical_language>

Target:
public boolean onKill(Scheduler.KillTopologyRequest request) { StringBuilder stdout = new StringBuilder(); StringBuilder stderr = new StringBuilder(); List<String> taskList = getJobLinks(); for (String taskId : taskList) { StringBuilder killJob = new StringBuilder(); killJob.append(EcsContext.composeStopCmd(config)); killJob.append(" "); killJob.append(taskId); int status = ShellUtils.runProcess(killJob.toString(), null); if (status != 0) { LOG.severe(String.format( "Failed to run process. Command=%s, STDOUT=%s, STDERR=%s", EcsContext.composeStopCmd(config), stdout, stderr)); isTopologyKilled = false; } else { LOG.info("Topology Task stop Successful"); isTopologyKilled = true; } } return isTopologyKilled; }
Source:
<code>private void notifyBridgeAboutChildHandlerDisposal(final Thing thing, final ThingHandler thingHandler) { final Bridge bridge = getBridge(thing.getBridgeUID()); if (bridge != null) { ThreadPoolManager.getPool(THING_MANAGER_THREADPOOL_NAME).execute(new Runnable() { @Override public void run() { try { BridgeHandler bridgeHandler = bridge.getHandler(); if (bridgeHandler != null) { bridgeHandler.childHandlerDisposed(thingHandler, thing); } } catch (Exception ex) { logger.error("Exception occured during bridge handler notification ('" + bridge.getUID() + "') about handler disposal of child '{}' '" + thing.getUID() + "': " <START> + ex.getMessage(), ex); <END> } } }); } }</code><technical_language>wrong commit, touched this line instead of string concatenation</technical_language>

Target:
private void notifyBridgeAboutChildHandlerDisposal(final Thing thing, final ThingHandler thingHandler) { final Bridge bridge = getBridge(thing.getBridgeUID()); if (bridge != null) { ThreadPoolManager.getPool(THING_MANAGER_THREADPOOL_NAME).execute(new Runnable() { @Override public void run() { try { BridgeHandler bridgeHandler = bridge.getHandler(); if (bridgeHandler != null) { bridgeHandler.childHandlerDisposed(thingHandler, thing); } } catch (Exception ex) { logger.error( "Exception occured during bridge handler ('{}') notification about handler disposal of child '{}': {}", bridge.getUID(), thing.getUID(), ex.getMessage(), ex); } } }); } }
Source:
<code>private void checkArgument(FunctionCallTree tree, int argNumber) { if (argNumber > tree.arguments().size()) { return; } ExpressionTree arg = tree.arguments().get(argNumber - 1); <START> if(arg.is(Kind.REGULAR_STRING_LITERAL) && ((LiteralTree)arg).value().length() - 2 >= MIN_LENGTH_OF_HARDCODED_PASSWORD) { <END> context().newIssue(this, arg, MESSAGE_ARGUMENTS); } }</code><technical_language>I understand condition length</technical_language>

Target:
private void checkArgument(FunctionCallTree tree, int argNumber) { if (argNumber > tree.arguments().size()) { return; } ExpressionTree arg = tree.arguments().get(argNumber - 1); if (arg.is(Kind.REGULAR_STRING_LITERAL) && !isEmptyStringLiteral((LiteralTree) arg)) { context().newIssue(this, arg, MESSAGE_ARGUMENTS); } }
Source:
<code>protected MongoPersistentProperty returnPropertyIfBetterIdPropertyCandidateOrNull(MongoPersistentProperty property) { Assert.notNull(property); if (!property.isIdProperty()) { return null; } MongoPersistentProperty currentIdProperty = getIdProperty(); boolean currentIdPropertyIsSet = currentIdProperty != null; @SuppressWarnings("null") boolean currentIdPropertyIsExplicit = currentIdPropertyIsSet ? currentIdProperty.isExplicitIdProperty() : false; boolean newIdPropertyIsExplicit = property.isExplicitIdProperty(); if (!currentIdPropertyIsSet) { return property; <START> } else { <END> @SuppressWarnings("null") Field currentIdPropertyField = currentIdProperty.getField(); if (newIdPropertyIsExplicit && currentIdPropertyIsExplicit) { throw new MappingException(String.format( "Attempt to add explicit id property %s but already have an property %s registered " + "as explicit id. Check your mapping configuration!", property.getField(), currentIdPropertyField)); } else if (newIdPropertyIsExplicit && !currentIdPropertyIsExplicit) { return property; } else if (!newIdPropertyIsExplicit && currentIdPropertyIsExplicit) { } else { throw new MappingException(String.format( "Attempt to add id property %s but already have an property %s registered " + "as id. Check your mapping configuration!", property.getField(), currentIdPropertyField)); } } return null; }</code><technical_language>else is obsolete rid of reduces nesting</technical_language>

Target:
protected MongoPersistentProperty returnPropertyIfBetterIdPropertyCandidateOrNull(MongoPersistentProperty property) { Assert.notNull(property); if (!property.isIdProperty()) { return null; } MongoPersistentProperty currentIdProperty = getIdProperty(); boolean currentIdPropertyIsSet = currentIdProperty != null; @SuppressWarnings("null") boolean currentIdPropertyIsExplicit = currentIdPropertyIsSet ? currentIdProperty.isExplicitIdProperty() : false; boolean newIdPropertyIsExplicit = property.isExplicitIdProperty(); if (!currentIdPropertyIsSet) { return property; } @SuppressWarnings("null") Field currentIdPropertyField = currentIdProperty.getField(); if (newIdPropertyIsExplicit && currentIdPropertyIsExplicit) { throw new MappingException(String.format( "Attempt to add explicit id property %s but already have an property %s registered " + "as explicit id. Check your mapping configuration!", property.getField(), currentIdPropertyField)); } else if (newIdPropertyIsExplicit && !currentIdPropertyIsExplicit) { return property; } else if (!newIdPropertyIsExplicit && currentIdPropertyIsExplicit) { } else { throw new MappingException(String.format( "Attempt to add id property %s but already have an property %s registered " + "as id. Check your mapping configuration!", property.getField(), currentIdPropertyField)); } return null; }