auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected GlusterGeoRepSession getSession(String masterVolumeName, Map<String, Object> innerMap) { GlusterGeoRepSession geoRepSession = new GlusterGeoRepSession(); String sessionKey = (String) innerMap.get(SESSION_KEY); String[] sessSplit = sessionKey.split("([://]+)"); <START> String slaveNode = sessSplit.length == 5 ? sessSplit[sessSplit.length - 3] : sessSplit[sessSplit.length - 2]; <END> if(slaveNode.contains("@")) { String[] hostComponents = slaveNode.split("@"); slaveNode = hostComponents[hostComponents.length - 1]; geoRepSession.setUserName(hostComponents[0]); } String slaveVolume = (String) innerMap.get(REMOTE_VOL_NAME); geoRepSession.setSlaveHostName(slaveNode); geoRepSession.setSlaveVolumeName(slaveVolume); geoRepSession.setSessionKey(sessionKey); geoRepSession.setMasterVolumeName(masterVolumeName); return geoRepSession; }</code><technical_language>String slaveNode = sessSplit[2]</technical_language>

Target:
protected GlusterGeoRepSession getSession(String masterVolumeName, Map<String, Object> innerMap) { GlusterGeoRepSession geoRepSession = new GlusterGeoRepSession(); String sessionKey = (String) innerMap.get(SESSION_KEY); String[] sessSplit = sessionKey.split("([://]+)"); String slaveNode = sessSplit[2]; if(slaveNode.contains("@")) { String[] hostComponents = slaveNode.split("@"); slaveNode = hostComponents[hostComponents.length - 1]; geoRepSession.setUserName(hostComponents[0]); } String slaveVolume = (String) innerMap.get(REMOTE_VOL_NAME); geoRepSession.setSlaveHostName(slaveNode); geoRepSession.setSlaveVolumeName(slaveVolume); geoRepSession.setSessionKey(sessionKey); geoRepSession.setMasterVolumeName(masterVolumeName); return geoRepSession; }
Source:
<code>public TransitionPropertyDialog(Shell shell, ActorClass ac, Transition trans) { super(shell, "Edit Transition", ac); this.trans = trans; m2s = new DetailCodeToString(); m2s_null_empty = new DetailCodeToString(true); s2m = new StringToDetailCode(); s2m_not_null = new StringToDetailCode(false); interfaceItems = new ArrayList<InterfaceItem>(); CommunicationType protocolCommType = null; switch(ac.getCommType()){ case EVENT_DRIVEN: case ASYNCHRONOUS: protocolCommType = CommunicationType.EVENT_DRIVEN; break; case DATA_DRIVEN: protocolCommType = CommunicationType.DATA_DRIVEN; break; case SYNCHRONOUS: protocolCommType = CommunicationType.SYNCHRONOUS; break; } <START> if(protocolCommType == CommunicationType.EVENT_DRIVEN){ <END> for(InterfaceItem item : RoomHelpers.getAllInterfaceItems(ac)){ ProtocolClass pc = RoomHelpers.getProtocol(item); if(pc != null && pc.getCommType() == protocolCommType) interfaceItems.add(item); } } inherited = RoomHelpers.getActorClass(trans)!=ac; refined = null; if (inherited) { if (getActorClass().getStateMachine()!=null) for (RefinedTransition rt : getActorClass().getStateMachine().getRefinedTransitions()) { if (rt.getTarget()==trans) { refined = rt; break; } } } if (inherited && refined==null) setTitle("View Transition"); }</code><technical_language>sufficient filter for interface items event driven protocols (regardless of actor class communication type)? list is compute triggers in case of TriggeredTransitions</technical_language>

Target:
public TransitionPropertyDialog(Shell shell, ActorClass ac, Transition trans) { super(shell, "Edit Transition", ac); this.trans = trans; m2s = new DetailCodeToString(); m2s_null_empty = new DetailCodeToString(true); s2m = new StringToDetailCode(); s2m_not_null = new StringToDetailCode(false); interfaceItems = new ArrayList<InterfaceItem>(); for(InterfaceItem item : RoomHelpers.getAllInterfaceItems(ac)){ ProtocolClass pc = RoomHelpers.getProtocol(item); if(pc != null && pc.getCommType() == CommunicationType.EVENT_DRIVEN) interfaceItems.add(item); } inherited = RoomHelpers.getActorClass(trans)!=ac; refined = null; if (inherited) { if (getActorClass().getStateMachine()!=null) for (RefinedTransition rt : getActorClass().getStateMachine().getRefinedTransitions()) { if (rt.getTarget()==trans) { refined = rt; break; } } } if (inherited && refined==null) setTitle("View Transition"); }
Source:
<code><START> public String getFontConfKey(FontUtils.FontType fontType, String postfix) { <END> StringBuilder result = new StringBuilder(); result.append("view."); result.append(fontTypePrefixes.get(fontType)); result.append(postfix); return result.toString(); }</code><technical_language>This private</technical_language>

Target:
private String getFontConfKey(FontUtils.FontType fontType, String postfix) { StringBuilder result = new StringBuilder(); result.append("view."); result.append(fontTypePrefixes.get(fontType)); result.append(postfix); return result.toString(); }
Source:
<code>private String getLocalDependencyDir(){ <START> String dependencyDir = System.getenv("ROBOLECTRIC_DEPENDENCY_DIR"); <END> if (dependencyDir == null) { dependencyDir = System.getProperty("robolectric.dependency.dir"); } return dependencyDir; }</code><technical_language>currently expose configuration environment variables, prefer do this in a separate commit (and potentially do for of robolectric's configuration)</technical_language>

Target:
private String getLocalDependencyDir(){ return System.getProperty("robolectric.dependency.dir"); }
Source:
<code><E extends Entity> BinaryLatch removePropertyData( Iterable<PropertyEntry<E>> propertyEntries, Map<Long,Map<String,Object>> state, WritableFulltext index ) throws IOException { BinaryLatch completedLatch = new BinaryLatch(); FulltextIndexUpdate update = () -> { for ( PropertyEntry<E> propertyEntry : propertyEntries ) { if ( index.properties().contains( propertyEntry.key() ) ) { long entityId = propertyEntry.entity().getId(); Map<String,Object> allProperties = state.get( entityId ); if ( allProperties == null || allProperties.isEmpty() ) { index.getIndexWriter().deleteDocuments( newTermForChangeOrRemove( entityId ) ); } } } return Pair.of( index, completedLatch ); <START> }; <END> enqueueUpdate( update ); return completedLatch; }</code><technical_language>this creates index writer time</technical_language>

Target:
<E extends Entity> AsyncFulltextIndexOperation removePropertyData( Iterable<PropertyEntry<E>> propertyEntries, Map<Long,Map<String,Object>> state, WritableFulltext index ) throws IOException { Latch completedLatch = new Latch(); FulltextIndexUpdate update = () -> { for ( PropertyEntry<E> propertyEntry : propertyEntries ) { if ( index.properties().contains( propertyEntry.key() ) ) { long entityId = propertyEntry.entity().getId(); Map<String,Object> allProperties = state.get( entityId ); if ( allProperties == null || allProperties.isEmpty() ) { index.getIndexWriter().deleteDocuments( newTermForChangeOrRemove( entityId ) ); } } } return Pair.of( index, completedLatch ); }; enqueueUpdate( update ); return completedLatch; }
Source:
<code>public Environment(String name, ObjectMapper objectMapper, Validator validator, MetricRegistry metricRegistry, ClassLoader classLoader) { this.name = name; this.objectMapper = objectMapper; this.metricRegistry = metricRegistry; this.healthCheckRegistry = new HealthCheckRegistry(); this.validator = validator; this.servletContext = new MutableServletContextHandler(); servletContext.setClassLoader(classLoader); this.servletEnvironment = new ServletEnvironment(servletContext); this.adminContext = new MutableServletContextHandler(); adminContext.setClassLoader(classLoader); this.adminEnvironment = new AdminEnvironment(adminContext, healthCheckRegistry, metricRegistry); this.lifecycleEnvironment = new LifecycleEnvironment(); final DropwizardResourceConfig jerseyConfig = new DropwizardResourceConfig(metricRegistry); this.jerseyServletContainer = new JerseyContainerHolder(new ServletContainer(jerseyConfig)); this.jerseyEnvironment = new JerseyEnvironment(jerseyServletContainer, jerseyConfig); this.healthCheckExecutorService = this.lifecycle().executorService("TimeBoundHealthCheck-pool-%d") <START> .workQueue(new ArrayBlockingQueue<Runnable>(4)) <END> .minThreads(1) .maxThreads(4) .threadFactory(new ThreadFactoryBuilder().setDaemon(true).build()) .rejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()) .build(); }</code><technical_language>I need a queue a size more 1. reason in preserving pool size. In case if DB is 2 concurrent request happen, situation is worse, request wiil forced wait 5 seconds processed</technical_language>

Target:
public Environment(String name, ObjectMapper objectMapper, Validator validator, MetricRegistry metricRegistry, ClassLoader classLoader) { this.name = name; this.objectMapper = objectMapper; this.metricRegistry = metricRegistry; this.healthCheckRegistry = new HealthCheckRegistry(); this.validator = validator; this.servletContext = new MutableServletContextHandler(); servletContext.setClassLoader(classLoader); this.servletEnvironment = new ServletEnvironment(servletContext); this.adminContext = new MutableServletContextHandler(); adminContext.setClassLoader(classLoader); this.adminEnvironment = new AdminEnvironment(adminContext, healthCheckRegistry, metricRegistry); this.lifecycleEnvironment = new LifecycleEnvironment(); final DropwizardResourceConfig jerseyConfig = new DropwizardResourceConfig(metricRegistry); this.jerseyServletContainer = new JerseyContainerHolder(new ServletContainer(jerseyConfig)); this.jerseyEnvironment = new JerseyEnvironment(jerseyServletContainer, jerseyConfig); this.healthCheckExecutorService = this.lifecycle().executorService("TimeBoundHealthCheck-pool-%d") .workQueue(new ArrayBlockingQueue<Runnable>(1)) .minThreads(1) .maxThreads(4) .threadFactory(new ThreadFactoryBuilder().setDaemon(true).build()) .rejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()) .build(); }
Source:
<code>public boolean isBranchesAllCommittedExcept(Artifact art, Branch branch) { boolean toReturn = false; try { <START> toReturn = AtsBranchManagerCore.isBranchesAllCommittedExcept((TeamWorkFlowArtifact) art, branch); <END> } catch (OseeCoreException ex) { OseeLog.log(Activator.class, Level.SEVERE, ex.toString(), ex); toReturn = false; } return toReturn; }</code><technical_language>a catch for ClassCastException? is art checked verify is a teamWorkFlowArtifact</technical_language>

Target:
public boolean isBranchesAllCommittedExcept(Artifact art, Branch branch) { boolean toReturn = false; if (art instanceof TeamWorkFlowArtifact) { try { toReturn = AtsBranchManagerCore.isBranchesAllCommittedExcept((TeamWorkFlowArtifact) art, branch); } catch (OseeCoreException ex) { OseeLog.log(Activator.class, Level.SEVERE, ex.toString(), ex); toReturn = false; } } return toReturn; }
Source:
<code>private boolean parseMessage(String message) { boolean error = false; XmlDocument doc = new XmlDocument(); doc.LoadXml(message); XmlNode node = doc.ChildNodes[0]; if (node != null) { StringBuilder sb = new StringBuilder(); AuditLogType logType; if (node.Attributes.get("status") == null) { logType = AuditLogType.VDS_INSTALL_IN_PROGRESS_WARNING; } else if (node.Attributes.get("status").getValue().equals("OK")) { logType = AuditLogType.VDS_INSTALL_IN_PROGRESS; } else if (node.Attributes.get("status").getValue().equals("WARN")) { logType = AuditLogType.VDS_INSTALL_IN_PROGRESS_WARNING; } else { error = true; logType = AuditLogType.VDS_INSTALL_IN_PROGRESS_ERROR; } if ((node.Attributes.get("component") != null) && (StringUtils.isNotEmpty(node.Attributes.get("component").getValue()))) { sb.append("Step: " + node.Attributes.get("component").getValue()); } if ((node.Attributes.get("message") != null) && (StringUtils.isNotEmpty(node.Attributes.get("message").getValue()))) { sb.append("; "); sb.append("Details: " + node.Attributes.get("message").getValue()); sb.append(" "); } if ((node.Attributes.get("result") != null) && (StringUtils.isNotEmpty(node.Attributes.get("result").getValue()))) { sb.append(" (" + node.Attributes.get("result").getValue() + ")"); } AuditLogableBase logable = new AuditLogableBase(_vdsId); logable.AddCustomValue("Message", StringUtils.stripEnd(sb.toString(), " ")); AuditLogDirector.log(logable, logType); <START> return error; <END> } return error; }</code><technical_language>Do need return error? I return error is enough for cases. isn't</technical_language>

Target:
private boolean parseMessage(String message) { boolean error = false; XmlDocument doc = new XmlDocument(); doc.LoadXml(message); XmlNode node = doc.ChildNodes[0]; if (node != null) { StringBuilder sb = new StringBuilder(); AuditLogType logType; if (node.Attributes.get("status") == null) { logType = AuditLogType.VDS_INSTALL_IN_PROGRESS_WARNING; } else if (node.Attributes.get("status").getValue().equals("OK")) { logType = AuditLogType.VDS_INSTALL_IN_PROGRESS; } else if (node.Attributes.get("status").getValue().equals("WARN")) { logType = AuditLogType.VDS_INSTALL_IN_PROGRESS_WARNING; } else { error = true; logType = AuditLogType.VDS_INSTALL_IN_PROGRESS_ERROR; } if ((node.Attributes.get("component") != null) && (StringUtils.isNotEmpty(node.Attributes.get("component").getValue()))) { sb.append("Step: " + node.Attributes.get("component").getValue()); } if ((node.Attributes.get("message") != null) && (StringUtils.isNotEmpty(node.Attributes.get("message").getValue()))) { sb.append("; "); sb.append("Details: " + node.Attributes.get("message").getValue()); sb.append(" "); } if ((node.Attributes.get("result") != null) && (StringUtils.isNotEmpty(node.Attributes.get("result").getValue()))) { sb.append(" (" + node.Attributes.get("result").getValue() + ")"); } AuditLogableBase logable = new AuditLogableBase(_vdsId); logable.AddCustomValue("Message", StringUtils.stripEnd(sb.toString(), " ")); AuditLogDirector.log(logable, logType); } return error; }
Source:
<code>public void execute(WorkflowExecutor workflowExecutor) throws IOException { <START> if (!isComplete()) throw new IllegalArgumentException("Workflow is not complete"); <END> Pool pool = step1.getInput(); pool.setConcentration((double) step0.getInput()); workflowExecutor.save(pool); }</code><technical_language>issue argument (workflowExecutor), IllegalStateException more sense</technical_language>

Target:
public void execute(WorkflowExecutor workflowExecutor) throws IOException { if (!isComplete()) throw new IllegalStateException("Workflow is not complete"); Pool pool = step1.getInput(); pool.setConcentration((double) step0.getInput()); workflowExecutor.save(pool); }
Source:
<code>public NotesMergeConflictException(Note base, Note ours, Note theirs) { super(MessageFormat.format(JGitText.get().mergeConflictOnNotes, <START> base.getName(), ours.getName(), theirs.getName())); <END> }</code><technical_language>names same... notes value. I need 4 strings: getName() non-null base/ours/theirs this is name of object note is on, getData().getName() non-null base, ours, is name of blob content for note. like: private static String noteOn(Note base, Note ours, Note theirs) { if (base != null) return base.name(); if (ours != null) return ours.name(); return theirs.name(); } private static String noteData(Note n) { if (n != null) return n.getData().name(); return ""; } public NotesMergeConflictException(Note base, Note ours, Note theirs) { super(MessageFormat.format(JGitText.get().mergeConflictOnNotes(), noteOn(base, ours, theirs), noteData(base), noteData(ours), noteData(theirs)));</technical_language>

Target:
public NotesMergeConflictException(Note base, Note ours, Note theirs) { super(MessageFormat.format(JGitText.get().mergeConflictOnNotes, noteOn(base, ours, theirs), noteData(base), noteData(ours), noteData(theirs))); }
Source:
<code>public void onBreakBlock(BlockBreakEvent event) { final Player player = event.getPlayer(); <START> for (ItemStack block : event.getBlock().getDrops()) <END> { event.getBlock().setType(Material.AIR); player.getInventory().addItem(block); event.setCancelled(true); } }</code><technical_language>This stack block</technical_language>

Target:
public void onBreakBlock(BlockBreakEvent event) { final Player player = event.getPlayer(); if (player.getGameMode().equals(SURVIVAL)) { for (ItemStack stack : event.getBlock().getDrops()) { event.getBlock().setType(Material.AIR); player.getInventory().addItem(stack); event.setCancelled(true); } } }
Source:
<code>private Git setUpRepoWithRemote() throws Exception { Repository remoteRepository = createWorkRepository(); Git remoteGit = new Git(remoteRepository); File sourceFile = new File(remoteRepository.getWorkTree(), "Test.txt"); FileOutputStream fos = new FileOutputStream(sourceFile); fos.write("Hello world".getBytes("UTF-8")); fos.close(); remoteGit.add().addFilepattern("Test.txt").call(); initialCommit = remoteGit.commit().setMessage("Initial commit").call(); fos = new FileOutputStream(sourceFile); fos.write("Some change".getBytes("UTF-8")); fos.close(); remoteGit.add().addFilepattern("Test.txt").call(); secondCommit = remoteGit.commit().setMessage("Second commit").call(); RefUpdate rup = remoteRepository.updateRef("refs/heads/master"); rup.setNewObjectId(initialCommit.getId()); rup.forceUpdate(); <START> Repository localRepository = createWorkRepository(); <END> Git localGit = new Git(localRepository); StoredConfig config = localRepository.getConfig(); RemoteConfig rc = new RemoteConfig(config, "origin"); rc.addURI(new URIish(remoteRepository.getDirectory().getPath())); rc.addFetchRefSpec(new RefSpec("+refs/heads/*:refs/remotes/origin/*")); rc.update(config); config.save(); FetchResult res = localGit.fetch().setRemote("origin").call(); assertFalse(res.getTrackingRefUpdates().isEmpty()); rup = localRepository.updateRef("refs/heads/master"); rup.setNewObjectId(initialCommit.getId()); rup.forceUpdate(); rup = localRepository.updateRef(Constants.HEAD); rup.link("refs/heads/master"); rup.setNewObjectId(initialCommit.getId()); rup.update(); return localGit; }</code><technical_language>needed create localRepository. this test is subclass of RepositoryTestCase tests automatically access a test repo. call getRepository() get access it</technical_language>

Target:
private Git setUpRepoWithRemote() throws Exception { Repository remoteRepository = createWorkRepository(); Git remoteGit = new Git(remoteRepository); writeTrashFile("Test.txt", "Hello world"); remoteGit.add().addFilepattern("Test.txt").call(); initialCommit = remoteGit.commit().setMessage("Initial commit").call(); writeTrashFile("Test.txt", "Some change"); remoteGit.add().addFilepattern("Test.txt").call(); secondCommit = remoteGit.commit().setMessage("Second commit").call(); RefUpdate rup = remoteRepository.updateRef("refs/heads/master"); rup.setNewObjectId(initialCommit.getId()); rup.forceUpdate(); Repository localRepository = createWorkRepository(); Git localGit = new Git(localRepository); StoredConfig config = localRepository.getConfig(); RemoteConfig rc = new RemoteConfig(config, "origin"); rc.addURI(new URIish(remoteRepository.getDirectory().getPath())); rc.addFetchRefSpec(new RefSpec("+refs/heads/*:refs/remotes/origin/*")); rc.update(config); config.save(); FetchResult res = localGit.fetch().setRemote("origin").call(); assertFalse(res.getTrackingRefUpdates().isEmpty()); rup = localRepository.updateRef("refs/heads/master"); rup.setNewObjectId(initialCommit.getId()); rup.forceUpdate(); rup = localRepository.updateRef(Constants.HEAD); rup.link("refs/heads/master"); rup.setNewObjectId(initialCommit.getId()); rup.update(); return localGit; }
Source:
<code>private SystemEventType getSystemEventType(Contentlet contentlet, boolean isNew) { <START> String methodName = isNew ? "SAVE" : "UPDATE"; <END> String contentType = getType(contentlet); String eventName = String.format("%s_%s", methodName, contentType); try { return SystemEventType.valueOf(eventName); }catch(IllegalArgumentException e){ return null; } }</code><technical_language>constants</technical_language>

Target:
private SystemEventType getSystemEventType(Contentlet contentlet, boolean isNew) { String methodName = isNew ? SAVE_EVENT_PREFIX : UPDATE_EVENT_PREFIX; String contentType = getType(contentlet); String eventName = String.format("%s_%s", methodName, contentType); try { return SystemEventType.valueOf(eventName.toUpperCase()); }catch(IllegalArgumentException e){ return null; } }
Source:
<code>private Job getJob() throws IOException { <START> if ((null == this.queues) || (this.queues.isEmpty())) { <END> return null; } final int queueSize = this.queues.size(); int count = 0; while (!this.shutDown) { if (!this.queueItor.hasNext()) { this.queueItor = this.queues.iterator(); } final Queue queue = this.queueItor.next(); final Job job = queue.pop(); if (null != job) { return job; } if (++count == queueSize) { break; } } return null; }</code><technical_language>this.queues is final initialized a non-null ArrayList. this null check is false</technical_language>

Target:
private Job getJob() throws IOException { if ((null == this.queues) || (this.queues.isEmpty())) { return null; } final int queueSize = this.queues.size(); int count = 0; while (!this.shutDown && (count < queueSize)) { if (!this.queueIter.hasNext()) { this.queueIter = this.queues.iterator(); } final Queue queue = this.queueIter.next(); final Job job = queue.pop(); if (null != job) { return job; } ++count; } return null; }
Source:
<code>public void close() throws IOException { <START> CloseQuietly.close(jsonParser); <END> it = Iterators.emptyIterator(); }</code><technical_language>If close() throws IOException, consume IOException in jsonParser</technical_language>

Target:
public void close() throws IOException { if (jsonParser != null) { jsonParser.close(); } it = Iterators.emptyIterator(); }
Source:
<code>public Exec createExec(final CreateExecParams params) throws IOException { final ExecConfig execConfig = new ExecConfig().withCmd(params.getCmd()) .withAttachStderr(params.isDetach() == Boolean.FALSE) .withAttachStdout(params.isDetach() == Boolean.FALSE); <START> byte[] entityBytesArray = toJson(execConfig).getBytes(); <END> try (DockerConnection connection = connectionFactory.openConnection(dockerDaemonUri) .method("POST") .path("/containers/" + params.getContainer() + "/exec") .header("Content-Type", MediaType.APPLICATION_JSON) .header("Content-Length", entityBytesArray.length) .entity(entityBytesArray)) { final DockerResponse response = connection.request(); if (response.getStatus() / 100 != 2) { throw getDockerException(response); } return new Exec(params.getCmd(), parseResponseStreamAndClose(response.getInputStream(), ExecCreated.class).getId()); } }</code><technical_language>I encoding explicitly calling .getBytes()</technical_language>

Target:
public Exec createExec(final CreateExecParams params) throws IOException { final ExecConfig execConfig = new ExecConfig().withCmd(params.getCmd()) .withAttachStderr(params.isDetach() == Boolean.FALSE) .withAttachStdout(params.isDetach() == Boolean.FALSE); byte[] entityBytesArray = toJson(execConfig).getBytes(StandardCharsets.UTF_8); try (DockerConnection connection = connectionFactory.openConnection(dockerDaemonUri) .method("POST") .path("/containers/" + params.getContainer() + "/exec") .header("Content-Type", MediaType.APPLICATION_JSON) .header("Content-Length", entityBytesArray.length) .entity(entityBytesArray)) { final DockerResponse response = connection.request(); if (response.getStatus() / 100 != 2) { throw getDockerException(response); } return new Exec(params.getCmd(), parseResponseStreamAndClose(response.getInputStream(), ExecCreated.class).getId()); } }
Source:
<code>public void messageLogged(final BuildEvent event) { Object categoryObject = event.getTask(); if (categoryObject == null) { categoryObject = event.getTarget(); if (categoryObject == null) { categoryObject = event.getProject(); } } final Logger log = Logger.getLogger(categoryObject.getClass().getName()); switch (event.getPriority()) { case Project.MSG_WARN: log.warn(event.getMessage()); break; case Project.MSG_INFO: log.info(event.getMessage()); break; case Project.MSG_VERBOSE: case Project.MSG_DEBUG: log.debug(event.getMessage()); break; <START> case Project.MSG_ERR: <END> default: log.error(event.getMessage()); break; } }</code><technical_language>Personally I prefer explicit case a fallthrough default case</technical_language>

Target:
public void messageLogged(final BuildEvent event) { Object categoryObject = event.getTask(); if (categoryObject == null) { categoryObject = event.getTarget(); if (categoryObject == null) { categoryObject = event.getProject(); } } final Logger log = Logger.getLogger(categoryObject.getClass().getName()); switch (event.getPriority()) { case Project.MSG_ERR: log.error(event.getMessage()); break; case Project.MSG_WARN: log.warn(event.getMessage()); break; case Project.MSG_INFO: log.info(event.getMessage()); break; case Project.MSG_VERBOSE: case Project.MSG_DEBUG: log.debug(event.getMessage()); break; default: log.error(event.getMessage()); break; } }
Source:
<code>public FeedbackResponseCommentAttributes createFeedbackResponseComment( FeedbackResponseCommentAttributes frComment) throws InvalidParametersException, EntityDoesNotExistException { verifyIsCoursePresent(frComment.courseId); verifyIsInstructorOfCourse(frComment.courseId, frComment.giverEmail); verifyIsFeedbackSessionOfCourse(frComment.courseId, frComment.feedbackSessionName); try{ return frcDb.createEntity(frComment); } catch (EntityAlreadyExistsException e) { try{ FeedbackResponseCommentAttributes existingComment = new FeedbackResponseCommentAttributes(); existingComment = frcDb.getFeedbackResponseComment(frComment.feedbackResponseId, frComment.giverEmail, frComment.createdAt); if(existingComment == null){ existingComment = frcDb.getFeedbackResponseComment(frComment.courseId, frComment.createdAt, frComment.giverEmail); } frComment.setId(existingComment.getId()); <START> return frcDb.updateFeedbackResponseComment(frComment, true); <END> } catch(Exception EntityDoesNotExistException){ Assumption.fail(); return null; } } }</code><technical_language>boolean provide information. need extract method a meaningful name</technical_language>

Target:
public FeedbackResponseCommentAttributes createFeedbackResponseComment( FeedbackResponseCommentAttributes frComment) throws InvalidParametersException, EntityDoesNotExistException { verifyIsCoursePresent(frComment.courseId); verifyIsInstructorOfCourse(frComment.courseId, frComment.giverEmail); verifyIsFeedbackSessionOfCourse(frComment.courseId, frComment.feedbackSessionName); try{ return frcDb.createEntity(frComment); } catch (EntityAlreadyExistsException e) { try{ FeedbackResponseCommentAttributes existingComment = new FeedbackResponseCommentAttributes(); existingComment = frcDb.getFeedbackResponseComment(frComment.feedbackResponseId, frComment.giverEmail, frComment.createdAt); if(existingComment == null){ existingComment = frcDb.getFeedbackResponseComment(frComment.courseId, frComment.createdAt, frComment.giverEmail); } frComment.setId(existingComment.getId()); return frcDb.updateFeedbackResponseComment(frComment); } catch(Exception EntityDoesNotExistException){ Assumption.fail(); return null; } } }
Source:
<code>public void onConfigurationChange(Configuration newConf) { initReconfigurable(newConf); if (scheduler instanceof ConfigurationObserver) { ((ConfigurationObserver) scheduler).onConfigurationChange(newConf); } <START> HBasePolicyProvider.init(newConf, authManager); <END> }</code><technical_language>thread-safety, do need synchronize authManager while this happens? authorize() requests this init race result in some weird authz results.</technical_language>

Target:
public void onConfigurationChange(Configuration newConf) { initReconfigurable(newConf); if (scheduler instanceof ConfigurationObserver) { ((ConfigurationObserver) scheduler).onConfigurationChange(newConf); } System.setProperty("hadoop.policy.file", "hbase-policy.xml"); synchronized (authManager) { authManager.refresh(newConf, new HBasePolicyProvider()); } LOG.info("Refreshed hbase-policy.xml successfully"); ProxyUsers.refreshSuperUserGroupsConfiguration(newConf); LOG.info("Refreshed super and proxy users successfully"); }
Source:
<code>public void handleSetActivityCalendarResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType responseMessageResultType, final OsgpException exception, final String resultString) { LOGGER.info("handleSetActivityCalendarResponse for MessageType: {}", deviceMessageMetadata.getMessageType()); ResponseMessageResultType result = responseMessageResultType; if (exception != null) { LOGGER.error("Set Activity Calendar Response not ok. Unexpected Exception", exception); result = ResponseMessageResultType.NOT_OK; } <START> this.webServiceResponseMessageSender.send( <END> ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception).withDataObject(resultString) .withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(), deviceMessageMetadata.getMessageType()); }</code><technical_language>Extract building of ResponseMessage variable (in eclipse, select text, right-click > refactor > extract local variable / select code + shift+alt+L). This code a bit more readable, especially passing in other besides ResponseMessage</technical_language>

Target:
public void handleSetActivityCalendarResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType responseMessageResultType, final OsgpException exception, final String resultString) { LOGGER.info("handleSetActivityCalendarResponse for MessageType: {}", deviceMessageMetadata.getMessageType()); ResponseMessageResultType result = responseMessageResultType; if (exception != null) { LOGGER.error("Set Activity Calendar Response not ok. Unexpected Exception", exception); result = ResponseMessageResultType.NOT_OK; } ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception).withDataObject(resultString) .withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(); this.webServiceResponseMessageSender.send( responseMessage, deviceMessageMetadata.getMessageType()); }
Source:
<code>private SubmitLink saveLink() { return new SubmitLink("save"){ @Override public void onSubmit() { if(lgEntryPanel.getEntries().size() == 0) { error((String) new ParamResourceModel("oneLayerMinimum", getPage()).getObject()); return; } LayerGroupInfo lg = (LayerGroupInfo) lgModel.getObject(); if (!LayerGroupInfo.Mode.EO.equals(lg.getMode())) { lg.setRootLayer(null); lg.setRootLayerStyle(null); } else { if (lg.getRootLayerStyle() == null && lg.getRootLayer() != null) { lg.setRootLayerStyle(lg.getRootLayer().getDefaultStyle()); } } lg.getLayers().clear(); lg.getStyles().clear(); for ( LayerGroupEntry entry : lgEntryPanel.getEntries() ) { lg.getLayers().add(entry.getLayer()); lg.getStyles().add(entry.getStyle()); } Boolean queryable = queryableCheckBox.getModelObject(); <START> if (!queryable) lg.setNotQueryableEnabled(true); else lg.setNotQueryableEnabled(null); <END> try { AbstractLayerGroupPage.this.save(); } catch(Exception e) { error(e); LOGGER.log(Level.WARNING, "Error adding/modifying layer group.", e); } } }; }</code><technical_language>able bind property layer group is property is called "queryable"</technical_language>

Target:
private SubmitLink saveLink() { return new SubmitLink("save"){ @Override public void onSubmit() { if(lgEntryPanel.getEntries().size() == 0) { error((String) new ParamResourceModel("oneLayerMinimum", getPage()).getObject()); return; } LayerGroupInfo lg = (LayerGroupInfo) lgModel.getObject(); if (!LayerGroupInfo.Mode.EO.equals(lg.getMode())) { lg.setRootLayer(null); lg.setRootLayerStyle(null); } else { if (lg.getRootLayerStyle() == null && lg.getRootLayer() != null) { lg.setRootLayerStyle(lg.getRootLayer().getDefaultStyle()); } } lg.getLayers().clear(); lg.getStyles().clear(); for ( LayerGroupEntry entry : lgEntryPanel.getEntries() ) { lg.getLayers().add(entry.getLayer()); lg.getStyles().add(entry.getStyle()); } Boolean queryable = queryableCheckBox.getModelObject(); lg.setQueryDisabled(!queryable); try { AbstractLayerGroupPage.this.save(); } catch(Exception e) { error(e); LOGGER.log(Level.WARNING, "Error adding/modifying layer group.", e); } } }; }
Source:
<code>public XBeeDevice(IConnectionInterface connectionInterface) { if (connectionInterface == null) throw new IllegalArgumentException("ConnectionInterface cannot be null."); this.connectionInterface = connectionInterface; <START> this.logger = LoggerFactory.getLogger(XBeeDevice.class); <END> }</code><technical_language>I log a debug message indicating IConnectionInterface class (at moment SerialPortRxTx configuration of interface (toString() method of IConnectionInterface)</technical_language>

Target:
public XBeeDevice(IConnectionInterface connectionInterface) { if (connectionInterface == null) throw new NullPointerException("ConnectionInterface cannot be null."); this.connectionInterface = connectionInterface; this.logger = LoggerFactory.getLogger(XBeeDevice.class); logger.debug(toString() + "Using the connection interface {}.", connectionInterface.getClass().getSimpleName(), connectionInterface.toString()); }
Source:
<code>public void fit(EntryPointFitParameters entryPointFitParameters) throws IOException, InterruptedException, InvalidKerasConfigurationException, UnsupportedKerasConfigurationException { try { MultiLayerNetwork multiLayerNetwork; if ("sequential".equals(entryPointFitParameters.getType())) { multiLayerNetwork = KerasModelImport.importKerasSequentialModelAndWeights(entryPointFitParameters.getModelFilePath()); multiLayerNetwork.init(); } else { throw new RuntimeException("Model type unsupported! (" + entryPointFitParameters.getType() + ")"); } INDArray features = h5FileToNDArray(entryPointFitParameters.getTrainFeaturesFile()); INDArray labels = h5FileToNDArray(entryPointFitParameters.getTrainLabelsFile()); INDArrayIndex[] ndIndexes = new INDArrayIndex[features.shape().length]; for (int i = 0; i < ndIndexes.length; i++) { ndIndexes[i] = NDArrayIndex.all(); } for (int i = 0; i < entryPointFitParameters.getNbEpoch(); i++) { <START> log.info("Fitting: " + i); <END> int begin = 0; while (begin < features.size(0)) { int end = begin + entryPointFitParameters.getBatchSize(); if (log.isTraceEnabled()) { log.trace("Processing batch: " + begin + " " + end); } ndIndexes[0] = NDArrayIndex.interval(begin, end); INDArray featuresBatch = features.get(ndIndexes); INDArray labelsBatch = labels.get(NDArrayIndex.interval(begin, end)); multiLayerNetwork.fit(featuresBatch, labelsBatch); begin += entryPointFitParameters.getBatchSize(); } } log.info("Learning model finished"); } catch (Throwable e) { log.error("Error while handling request!", e); throw e; } }</code><technical_language>This is a lot of code. a unit test for *just* this section? I encapsulate this in a method. views main concern</technical_language>

Target:
public void fit(EntryPointFitParameters entryPointFitParameters) throws Exception { try { MultiLayerNetwork multiLayerNetwork = neuralNetworkReader.readNeuralNetwork(entryPointFitParameters); DataSetIterator dataSetIterator = new HDF5MiniBatchDataSetIterator( entryPointFitParameters.getTrainFeaturesDirectory(), entryPointFitParameters.getTrainLabelsDirectory() ); for (int i = 0; i < entryPointFitParameters.getNbEpoch(); i++) { log.info("Fitting: " + i); multiLayerNetwork.fit(dataSetIterator); } log.info("Learning model finished"); } catch (Throwable e) { log.error("Error while handling request!", e); throw e; } }
Source:
<code>private void writeGoAwayFrame(ChannelHandlerContext ctx, Http2GoAwayFrame frame, ChannelPromise promise) { if (frame.lastStreamId() > -1) { frame.release(); throw new IllegalArgumentException("Last stream id must not be set on GOAWAY frame"); } <START> int lastStreamCreated = connection().remote().lastStreamCreated(); <END> long lastStreamId = lastStreamCreated + ((long) frame.extraStreamIds()) * 2; if (lastStreamId > MAX_VALUE) { lastStreamId = MAX_VALUE; } goAway(ctx, (int) lastStreamId, frame.errorCode(), frame.content(), promise); }</code><technical_language>sort of important _Integer_.MAX_VALUE, Long.MAX_VALUE work. prefer this stay explicit</technical_language>

Target:
private void writeGoAwayFrame(ChannelHandlerContext ctx, Http2GoAwayFrame frame, ChannelPromise promise) { if (frame.lastStreamId() > -1) { frame.release(); throw new IllegalArgumentException("Last stream id must not be set on GOAWAY frame"); } int lastStreamCreated = connection().remote().lastStreamCreated(); long lastStreamId = lastStreamCreated + ((long) frame.extraStreamIds()) * 2; if (lastStreamId > Integer.MAX_VALUE) { lastStreamId = Integer.MAX_VALUE; } goAway(ctx, (int) lastStreamId, frame.errorCode(), frame.content(), promise); }
Source:
<code>public TmfAnalysisRequirement instanciateRequirements(IKernelAnalysisEventLayout layout) { <START> List<@Nullable String> eventNames = fEventNames.stream().map(l -> l.getEventName(layout)) .filter(name -> name != null) .collect(Collectors.toList()); List<String> nonNullEvents = new ArrayList<>(); for (String name : eventNames) { nonNullEvents.add(NonNullUtils.checkNotNull(name)); } <END> return new TmfAnalysisEventRequirement(nonNullEvents, fLevel); }</code><technical_language>I sincerely asking, is clearer. (this streams fixed, is faster, matter IMO). {ImmutableList.builder b = new Builder(); for(ILayoutToEventName eventNameLayout : fEventNames){ String eventName= eventNameLayout.getEventName(layout); if(eventName.getEventName(layout)!= null){ b.add(eventName); } } return b.build(); }</technical_language>

Target:
public TmfAnalysisRequirement instanciateRequirements(IKernelAnalysisEventLayout layout) { Builder<String> events = new Builder<>(); for (ILayoutToEventName eventNameLayout : fEventNames) { String eventName = eventNameLayout.getEventName(layout); if (eventName != null) { events.add(eventName); } } return new TmfAnalysisEventRequirement(events.build(), fLevel); }
Source:
<code>public boolean isEmpty() { <START> return fQueueSize.get() == 0; <END> }</code><technical_language>Add parentheses, helps readability: return (fQueueSize.get() == 0);</technical_language>

Target:
public boolean isEmpty() { return (fQueueSize.get() == 0); }
Source:
<code>public LenientComparisonStringNormalizer() { <START> this(Lists.newArrayList()); <END> }</code><technical_language>immutable list</technical_language>

Target:
public LenientComparisonStringNormalizer() { this(ImmutableList.of()); }
Source:
<code>private static Set<RyaURI> getPropURIFromStrings(final String... props) { final Set<RyaURI> properties = new HashSet<>(); if (props != null) { for(final String prop : props) { <START> if (prop != null) { <END> properties.add(new RyaURI(prop)); } } } return properties; }</code><technical_language>Do want/need empty string check here? Do need/have a unit test exercise this</technical_language>

Target:
private static Set<RyaURI> getPropURIFromStrings(final String... props) { final Set<RyaURI> properties = new HashSet<>(); if (props != null) { for(final String prop : props) { if (StringUtils.isNotBlank(prop)) { properties.add(new RyaURI(prop)); } } } return properties; }
Source:
<code>private void onRemove() { if (getProgress() != null) { return; } <START> ArrayList<VdcActionParametersBase> list = new ArrayList<VdcActionParametersBase>(); <END> for (DiskProfile profile : getProfiles()) { VdcActionParametersBase parameters = getRemoveDiskProfileParams(profile); list.add(parameters); } startProgress(null); Frontend.getInstance().runMultipleAction(VdcActionType.RemoveDiskProfile, list, new IFrontendMultipleActionAsyncCallback() { @Override public void executed(FrontendMultipleActionAsyncResult result) { stopProgress(); cancel(); } }, null); }</code><technical_language>rename - a bit more specific :)</technical_language>

Target:
private void onRemove() { if (getProgress() != null) { return; } ArrayList<VdcActionParametersBase> vdcActionParametersBaseList = new ArrayList<VdcActionParametersBase>(); for (DiskProfile profile : getProfiles()) { VdcActionParametersBase parameters = getRemoveDiskProfileParams(profile); vdcActionParametersBaseList.add(parameters); } startProgress(null); Frontend.getInstance().runMultipleAction(VdcActionType.RemoveDiskProfile, vdcActionParametersBaseList, new IFrontendMultipleActionAsyncCallback() { @Override public void executed(FrontendMultipleActionAsyncResult result) { stopProgress(); cancel(); } }, null); }
Source:
<code>public void ignoreCache(String cacheName) { Set<String> currentValue = stateCache.get(IGNORED_CACHES_KEY); Set<String> newValue = currentValue == null ? new HashSet<>() : currentValue; <START> if (newValue.add(cacheName)) stateCache.put(IGNORED_CACHES_KEY, newValue); <END> }</code><technical_language>safe me. If multiple concurrent ignore requests, lose some of them</technical_language>

Target:
public CompletionStage<Void> ignoreCache(String cacheName) { return stateCache.put(IGNORED_CACHES_KEY, cacheName); }
Source:
<code>private int getNumberOfExtractMethods() { List<Method> extractMethods = Arrays.asList(ReflectionUtils.getAllDeclaredMethods(JudgmentDataExtractor.class)).stream().filter(m->m.getName().startsWith("extract")).collect(Collectors.toList()); return extractMethods.size(); <START> } <END></code><technical_language>Consider of count() instead of collect() stream</technical_language>

Target:
private long getNumberOfExtractMethods() { return Arrays.asList(ReflectionUtils.getAllDeclaredMethods(JudgmentDataExtractor.class)).stream().filter(m->m.getName().startsWith("extract")).count(); }
Source:
<code>private void doAddNewStrategy() { final MergeStrategySection.SubmitType submitType; if (submitTypeBox.getSelectedIndex() >= 0) { submitType = MergeStrategySection.SubmitType.valueOf(submitTypeBox .getValue(submitTypeBox.getSelectedIndex())); } else { return; } final String refPattern = refPatternTxt.getText().trim(); if (!refPattern.isEmpty()) { final MergeStrategySection mergeStrategySection = new MergeStrategySection(refPattern); mergeStrategySection.setSubmitType(submitType); if (!mergeStrategies.addNew(mergeStrategySection)) { <START> Window.alert(Util.C.errorPatternHasStrategy()); <END> } refPatternTxt.setText(""); submitTypeBox.setSelectedIndex(0); } }</code><technical_language>I error displayed in other errors in Gerrit displayed: new ErrorDialog(Util.C.errorPatternHasStrategy()).center();</technical_language>

Target:
private void doAddNewStrategy() { final MergeStrategySection.SubmitType submitType; if (submitTypeBox.getSelectedIndex() >= 0) { submitType = MergeStrategySection.SubmitType.valueOf(submitTypeBox .getValue(submitTypeBox.getSelectedIndex())); } else { return; } final String refPattern = refPatternTxt.getText().trim(); if (!refPattern.isEmpty()) { final MergeStrategySection mergeStrategySection = new MergeStrategySection(refPattern); mergeStrategySection.setSubmitType(submitType); mergeStrategySection.setUseContentMerge(useContentMerge.getValue()); if (!mergeStrategies.addNew(mergeStrategySection)) { new ErrorDialog(Util.C.errorPatternHasStrategy()); } else { refPatternTxt.setText(""); submitTypeBox.setSelectedIndex(0); useContentMerge.setValue(false); useContentMerge.setEnabled(false); } } }
Source:
<code>public void addMember(PDOMNode member, int visibility) throws CoreException { if (nextMemberPosition == MAX_MEMBER_COUNT) { PDOMCPPMemberBlock nextBlock = getNextBlock(); if (nextBlock == null) { nextBlock = new PDOMCPPMemberBlock(linkage); setNextBlock(nextBlock); } nextBlock.addMember(member, visibility); } else { long memberLocationOffset = getMemberRecord(nextMemberPosition); <START> long rec = member != null ? member.getRecord() : 0; <END> getDB().putRecPtr(memberLocationOffset, rec); setAccessibility(nextMemberPosition, visibility); nextMemberPosition++; } }</code><technical_language>Null member NPE</technical_language>

Target:
public void addMember(PDOMNode member, int visibility) throws CoreException { if (getNextPosition() == MAX_MEMBER_COUNT) { PDOMCPPMemberBlock nextBlock = getNextBlock(); if (nextBlock == null) { nextBlock = new PDOMCPPMemberBlock(linkage); setNextBlock(nextBlock); } nextBlock.addMember(member, visibility); } else { long memberLocationOffset = getMemberOffset(getNextPosition()); long rec = member.getRecord(); getDB().putRecPtr(memberLocationOffset, rec); setVisibility(getNextPosition(), visibility); nextMemberPosition++; } }
Source:
<code>public HadoopPigJob(String jobid, Props sysProps, Props jobProps, Logger log) throws IOException { super(jobid, sysProps, jobProps, log); HADOOP_SECURE_PIG_WRAPPER = HadoopSecurePigWrapper.class.getName(); getJobProps().put("azkaban.job.id", jobid); shouldProxy = getSysProps().getBoolean("azkaban.should.proxy", false); getJobProps().put("azkaban.should.proxy", Boolean.toString(shouldProxy)); obtainTokens = getSysProps().getBoolean("obtain.binary.token", false); userPigJar = getJobProps().getBoolean("use.user.pig.jar", false); boolean obtainHcatToken = getJobProps().getBoolean(HadoopSecurityManager.OBTAIN_HCAT_TOKEN, false); <START> getSysProps().put(HadoopSecurityManager.OBTAIN_HCAT_TOKEN, Boolean.toString(obtainHcatToken)); <END> if (shouldProxy) { getLog().info("Initiating hadoop security manager."); try { hadoopSecurityManager = loadHadoopSecurityManager(getSysProps(), log); } catch (RuntimeException e) { throw new RuntimeException("Failed to get hadoop security manager!" + e); } } }</code><technical_language>overwriting property in private.properties. want option of this config in private.config writable user ? boolean obtainHcatToken = getSysProps().getBoolean(HadoopSecurityManager.OBTAIN_HCAT_TOKEN, false); obtainHcatToken = getJobProps().getBoolean(HadoopSecurityManager.OBTAIN_HCAT_TOKEN, obtainHcatToken); getSysProps().put(HadoopSecurityManager.OBTAIN_HCAT_TOKEN, Boolean.toString(obtainHcatToken));</technical_language>

Target:
public HadoopPigJob(String jobid, Props sysProps, Props jobProps, Logger log) throws IOException { super(jobid, sysProps, jobProps, log); HADOOP_SECURE_PIG_WRAPPER = HadoopSecurePigWrapper.class.getName(); getJobProps().put("azkaban.job.id", jobid); shouldProxy = getSysProps().getBoolean("azkaban.should.proxy", false); getJobProps().put("azkaban.should.proxy", Boolean.toString(shouldProxy)); obtainTokens = getSysProps().getBoolean("obtain.binary.token", false); userPigJar = getJobProps().getBoolean("use.user.pig.jar", false); boolean obtainHcatToken = getSysProps().getBoolean(HadoopSecurityManager.OBTAIN_HCAT_TOKEN, false); obtainHcatToken = getJobProps().getBoolean(HadoopSecurityManager.OBTAIN_HCAT_TOKEN, obtainHcatToken); getSysProps().put(HadoopSecurityManager.OBTAIN_HCAT_TOKEN, Boolean.toString(obtainHcatToken)); if (shouldProxy) { getLog().info("Initiating hadoop security manager."); try { hadoopSecurityManager = loadHadoopSecurityManager(getSysProps(), log); } catch (RuntimeException e) { throw new RuntimeException("Failed to get hadoop security manager!" + e); } } }