auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private InterpreterResult runSqlList(String sql, InterpreterContext context) { List<SqlInfo> sqlLists = SqlLists.getSQLList(sql); List<SqlCommandParser.SqlCommandCall> sqlCommands = new ArrayList<>(); for (SqlInfo sqlInfo : sqlLists) { Optional<SqlCommandParser.SqlCommandCall> sqlCommand = parse(sqlInfo.getSqlContent()); if (!sqlCommand.isPresent()) { return new InterpreterResult(InterpreterResult.Code.ERROR, "Invalid Sql statement: " + sqlInfo.getSqlContent()); } sqlCommands.add(sqlCommand.get()); } for (SqlCommandParser.SqlCommandCall sqlCommand : sqlCommands) { try { callCommand(sqlCommand, context); context.out.flush(); } catch (Throwable e) { LOGGER.error("Fail to run sql:" + sqlCommand.operands[0] + "\n" <START> + ExceptionUtils.getStackTrace(e)); <END> return new InterpreterResult(InterpreterResult.Code.ERROR, "Fail to run sql command: " + sqlCommand.operands[0] + "\n" + ExceptionUtils.getStackTrace(e)); } } return new InterpreterResult(InterpreterResult.Code.SUCCESS); }</code><technical_language>LOGGER.error("Fail run sql:" + sqlCommand.operands[0], e);</technical_language>

Target:
private InterpreterResult runSqlList(String sql, InterpreterContext context) { List<SqlInfo> sqlLists = SqlLists.getSQLList(sql); List<SqlCommandParser.SqlCommandCall> sqlCommands = new ArrayList<>(); for (SqlInfo sqlInfo : sqlLists) { Optional<SqlCommandParser.SqlCommandCall> sqlCommand = parse(sqlInfo.getSqlContent()); if (!sqlCommand.isPresent()) { return new InterpreterResult(InterpreterResult.Code.ERROR, "Invalid Sql statement: " + sqlInfo.getSqlContent()); } sqlCommands.add(sqlCommand.get()); } for (SqlCommandParser.SqlCommandCall sqlCommand : sqlCommands) { try { callCommand(sqlCommand, context); context.out.flush(); } catch (Throwable e) { LOGGER.error("Fail to run sql:" + sqlCommand.operands[0], e); return new InterpreterResult(InterpreterResult.Code.ERROR, "Fail to run sql command: " + sqlCommand.operands[0] + "\n" + ExceptionUtils.getStackTrace(e)); } } return new InterpreterResult(InterpreterResult.Code.SUCCESS); }
Source:
<code>private void checkNamesAndDependencies(Set<ServiceTermination> terminationSet) { Set<String> uniqueNamesSet = new HashSet<>(); terminationSet.forEach( t -> { if (!uniqueNamesSet.add(t.getServiceName())) { throw new RuntimeException( String.format( "Duplicate termination found with service name %s", t.getServiceName())); } }); terminationSet.forEach( t -> { if (!uniqueNamesSet.containsAll(t.getDependencies())) { throw new RuntimeException( <START> String.format( <END> "Unknown dependency found in termination %s", t.getServiceName())); } }); }</code><technical_language>here... is configure in this case..</technical_language>

Target:
private void checkNamesAndDependencies(Set<ServiceTermination> terminationSet) { Set<String> uniqueNamesSet = new HashSet<>(); terminationSet.forEach( t -> { if (!uniqueNamesSet.add(t.getServiceName())) { throw new ConfigurationException( String.format( "Duplicate termination found with service name %s", t.getServiceName())); } }); terminationSet.forEach( t -> { if (!uniqueNamesSet.containsAll(t.getDependencies())) { throw new RuntimeException( String.format("Unknown dependency found in termination %s", t.getServiceName())); } }); }
Source:
<code>public static RevisionInfo fromEdit(EditInfo edit) { RevisionInfo revisionInfo = <START> (RevisionInfo) createObject(); <END> revisionInfo.takeFromEdit(edit); return revisionInfo; }</code><technical_language>Optional (and I inconsistent elsewhere): createObject().cast()</technical_language>

Target:
public static RevisionInfo fromEdit(EditInfo edit) { RevisionInfo revisionInfo = createObject().cast(); revisionInfo.takeFromEdit(edit); return revisionInfo; }
Source:
<code>public Instant toIndexedValue(Date value, ValueBridgeToIndexedValueContext context) { if ( value == null ) { return null; } <START> return value instanceof java.sql.Date ? Instant.ofEpochMilli( value.getTime() ) : value.toInstant(); <END> }</code><technical_language>Instant.ofEpochMilli( value.getTime() )? spare instanceof</technical_language>

Target:
public Instant toIndexedValue(Date value, ValueBridgeToIndexedValueContext context) { if ( value == null ) { return null; } return Instant.ofEpochMilli( value.getTime() ); }
Source:
<code>public void onTextAvailable(@NotNull ProcessEvent event, Key outputType) { ElixirCompilerError error = ElixirCompilerError.create(myCompileTargetRootPath, event.getText()); if(error != null){ boolean isError = error.getCategory() == CompilerMessageCategory.ERROR; BuildMessage.Kind kind = isError ? BuildMessage.Kind.ERROR : BuildMessage.Kind.WARNING; <START> CompilerMessage msg = new CompilerMessage(myBuilderName, kind, error.getErrorMessage(), VirtualFileManager.extractPath(error.getUrl()), -1, -1, -1, error.getLine(), -1); <END> myContext.processMessage(msg); } }</code><technical_language>[x] do -1's here? intention revealing local variable names explain is doing</technical_language>

Target:
public void onTextAvailable(@NotNull ProcessEvent event, Key outputType) { ElixirCompilerError error = ElixirCompilerError.create(myCompileTargetRootPath, event.getText()); if(error != null){ boolean isError = error.getCategory() == CompilerMessageCategory.ERROR; BuildMessage.Kind kind = isError ? BuildMessage.Kind.ERROR : BuildMessage.Kind.WARNING; CompilerMessage msg = new CompilerMessage(myBuilderName, kind, error.getErrorMessage(), VirtualFileManager.extractPath(error.getUrl()), DEFAULT_PROBLEM_BEGIN_OFFSET, DEFAULT_PROBLEM_END_OFFSET, DEFAULT_PROBLEM_LOCATION_OFFSET, error.getLine(), DEFAULT_LOCATION_COLUMN); myContext.processMessage(msg); } }
Source:
<code><START> public void testRemoveExistingRelationship() throws Exception { <END> final Node diagram = createNode(CaseManagementDiagram.class); final Node stage = createNode(AdHocSubprocess.class); final Node start = createNode(StartNoneEvent.class); final Node end = createNode(EndNoneEvent.class); createChildEdge(diagram, start); createChildEdge(diagram, stage); createChildEdge(diagram, end); createSequenceFlow(start, stage); createSequenceFlow(stage, end); final CaseManagementSetChildNodeGraphCommand command = new CaseManagementSetChildNodeGraphCommand(diagram, stage, index, Optional.of(diagram), originalIndex); command.removeExistingRelationship(context); assertTrue(command.originalIn.isPresent()); assertEquals(start, command.originalIn.get()); assertTrue(command.originalOut.isPresent()); assertEquals(end, command.originalOut.get()); assertEquals(2, diagram.getOutEdges().size()); assertEquals(1, start.getOutEdges().size()); assertEquals(2, end.getInEdges().size()); assertEquals(end, ((Edge) start.getOutEdges().get(0)).getTargetNode()); }</code><technical_language>Exception is thrown</technical_language>

Target:
public void testRemoveExistingRelationship() { final Node diagram = createNode(CaseManagementDiagram.class); final Node stage = createNode(AdHocSubprocess.class); final Node start = createNode(StartNoneEvent.class); final Node end = createNode(EndNoneEvent.class); createChildEdge(diagram, start); createChildEdge(diagram, stage); createChildEdge(diagram, end); createSequenceFlow(start, stage); createSequenceFlow(stage, end); final CaseManagementSetChildNodeGraphCommand command = new CaseManagementSetChildNodeGraphCommand(diagram, stage, index, Optional.of(diagram), originalIndex); command.removeExistingRelationship(context); assertTrue(command.originalIn.isPresent()); assertEquals(start, command.originalIn.get()); assertTrue(command.originalOut.isPresent()); assertEquals(end, command.originalOut.get()); assertEquals(2, diagram.getOutEdges().size()); assertEquals(1, start.getOutEdges().size()); assertEquals(2, end.getInEdges().size()); assertEquals(end, ((Edge) start.getOutEdges().get(0)).getTargetNode()); }
Source:
<code>private void _publishTemplates(ActionRequest req, User user) throws Exception { String[] publishInode = req.getParameterValues("publishInode"); if (publishInode == null) return; ActionRequestImpl reqImpl = (ActionRequestImpl)req; Set relatedPages = new HashSet(); for (int i=0;i<publishInode.length;i++) { Template template = (Template) InodeFactory.getInode(publishInode[i],Template.class); if (InodeUtils.isSet(template.getInode())) { try{ PublishFactory.publishAsset(template,reqImpl.getHttpServletRequest()); ActivityLogger.logInfo(this.getClass(), "Publish Template action", "User " + user.getPrimaryKey() + " publishing template" + template.getTitle(), HostUtil.hostNameUtil(req, _getUser(req))); SessionMessages.add(req, "message", "message.template_list.published"); }catch(WebAssetException wax){ Logger.error(this, wax.getMessage(),wax); SessionMessages.add(req, "error", "message.webasset.published.failed"); } <START> List<HTMLPageAsset> pagesForThisTemplate = APILocator.getTemplateAPI().getPagesUsingTemplate(template, user, false); <END> relatedPages.addAll(pagesForThisTemplate); } } Iterator iterPages = relatedPages.iterator(); while (iterPages.hasNext()) { PageServices.invalidateAll((HTMLPageAsset) iterPages.next()); } }</code><technical_language>delete</technical_language>

Target:
private void _publishTemplates(ActionRequest req, User user) throws Exception { String[] publishInode = req.getParameterValues("publishInode"); if (publishInode == null) return; ActionRequestImpl reqImpl = (ActionRequestImpl)req; for (int i=0;i<publishInode.length;i++) { Template template = (Template) InodeFactory.getInode(publishInode[i],Template.class); if (InodeUtils.isSet(template.getInode())) { try{ PublishFactory.publishAsset(template,reqImpl.getHttpServletRequest()); ActivityLogger.logInfo(this.getClass(), "Publish Template action", "User " + user.getPrimaryKey() + " publishing template" + template.getTitle(), HostUtil.hostNameUtil(req, _getUser(req))); SessionMessages.add(req, "message", "message.template_list.published"); }catch(WebAssetException wax){ Logger.error(this, wax.getMessage(),wax); SessionMessages.add(req, "error", "message.webasset.published.failed"); } } } }
Source:
<code>public Attribute fillAttribute(PerunSession sess, Resource resource, Attribute attribute) throws InternalErrorException { ResourceAttributesModuleImplApi attributeModule = getResourceAttributeModule(sess, attribute); if (attributeModule == null) { <START> log.debug("fillAttribute - There's no attribute module for this attribute. Attribute wasn't filled.", attribute); <END> return attribute; } try { return attributeModule.fillAttribute((PerunSessionImpl) sess, resource, attribute); } catch (WrongAttributeAssignmentException ex) { throw new InternalErrorException(ex); } }</code><technical_language>Original message is ok, placeholder for attribute object end meaning. toString() Attribute if pretty long, "wasn't filled." sight. rephrase message, like: Attribute filled. is module for: place attribute object end. I attribute name is sufficient in this message, pass object</technical_language>

Target:
public Attribute fillAttribute(PerunSession sess, Resource resource, Attribute attribute) throws InternalErrorException { ResourceAttributesModuleImplApi attributeModule = getResourceAttributeModule(sess, attribute); if (attributeModule == null) { log.debug("Attribute wasn't filled. There is no module for: {}.", attribute.getName()); return attribute; } try { return attributeModule.fillAttribute((PerunSessionImpl) sess, resource, attribute); } catch (WrongAttributeAssignmentException ex) { throw new InternalErrorException(ex); } }
Source:
<code>public Map<K, V> getAll(Set<K> keys) { if (trace) log.tracef("GET_ALL cache=%s keys=%s", forceReturn.getName(), keys); Map<K, V> result = new HashMap<>(keys.size()); if (preferAsync) { Map<K, Future<V>> futureMap = new HashMap<>(keys.size()); for (K key : keys) { futureMap.put(key, forceReturn.getAsync(key)); } for (Map.Entry<K, Future<V>> entry : futureMap.entrySet()) { try { V value = entry.getValue().get(); if (value != null) { result.put(entry.getKey(), value); } } catch (Exception e) { throw new RuntimeException(e); } } <START> } else { <END> for (K key : keys) { result.put(key, forceReturn.get(key)); } } return result; }</code><technical_language>preferAsync means async ops _preferred_ native getAll operation. If native getAll operations, do async version, retrieve values sequentially</technical_language>

Target:
public Map<K, V> getAll(Set<K> keys) { if (trace) log.tracef("GET_ALL cache=%s keys=%s", forceReturn.getName(), keys); Map<K, V> result = new HashMap<>(keys.size()); Map<K, Future<V>> futureMap = new HashMap<>(keys.size()); for (K key : keys) { futureMap.put(key, forceReturn.getAsync(key)); } for (Map.Entry<K, Future<V>> entry : futureMap.entrySet()) { try { V value = entry.getValue().get(); if (value != null) { result.put(entry.getKey(), value); } } catch (Exception e) { throw new RuntimeException(e); } } return result; }
Source:
<code>public RegistrationWindows() { <START> registryWriter = new RegistryWriter(); <END> }</code><technical_language>call other constructor</technical_language>

Target:
public RegistrationWindows() { this(new RegistryWriter()); }
Source:
<code>public boolean shutdownVpc(Vpc vpc, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { if (vpc.getState().equals(Vpc.State.Inactive)) { try { Domain vpcDomain = _domainDao.findById(vpc.getDomainId()); HostVO nuageVspHost = getNuageVspHost(getPhysicalNetworkId(vpc.getZoneId())); String preConfiguredDomainTemplateName = _configDao.getValue(NuageVspManager.NuageVspVpcDomainTemplateName.key()); ShutDownVpcVspCommand cmd = new ShutDownVpcVspCommand(vpcDomain.getUuid(), vpc.getUuid(), preConfiguredDomainTemplateName); ShutDownVpcVspAnswer answer = (ShutDownVpcVspAnswer) _agentMgr.easySend(nuageVspHost.getId(), cmd); if (answer == null || !answer.getResult()) { s_logger.error("ShutDownVpcVspCommand for VPC " + vpc.getUuid() + " failed"); if ((null != answer) && (null != answer.getDetails())) { throw new ResourceUnavailableException(answer.getDetails(), Vpc.class, vpc.getId()); } } <START> } catch (Exception e) { <END> s_logger.warn("Failed to destroy VPC in Vsp " + e.getMessage()); } } return true; }</code><technical_language>checked unchecked exceptions caught ignored</technical_language>

Target:
public boolean shutdownVpc(Vpc vpc, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { if (vpc.getState().equals(Vpc.State.Inactive)) { Domain vpcDomain = _domainDao.findById(vpc.getDomainId()); HostVO nuageVspHost = getNuageVspHost(getPhysicalNetworkId(vpc.getZoneId())); String preConfiguredDomainTemplateName = _configDao.getValue(NuageVspManager.NuageVspVpcDomainTemplateName.key()); ShutDownVpcVspCommand.Builder cmdBuilder = new ShutDownVpcVspCommand.Builder() .domainUuid(vpcDomain.getUuid()) .vpcUuid(vpc.getUuid()) .domainTemplateName(preConfiguredDomainTemplateName); Answer answer = _agentMgr.easySend(nuageVspHost.getId(), cmdBuilder.build()); if (answer == null || !answer.getResult()) { s_logger.error("ShutDownVpcVspCommand for VPC " + vpc.getUuid() + " failed on Nuage VSD " + nuageVspHost.getDetail("hostname")); if ((null != answer) && (null != answer.getDetails())) { throw new ResourceUnavailableException(answer.getDetails(), Vpc.class, vpc.getId()); } } } return true; }
Source:
<code>protected void executeQueryCommand() { VM vm = vmDao.get(getParameters().getId()); if (vm == null || <START> vm.getDynamicData().getFqdn() <END> == null) { getQueryReturnValue().setReturnValue(ErrataData.emptyData()); return; } Provider<?> provider = providerDao.get(vm.getProviderId()); if (provider != null) { HostProviderProxy proxy = providerProxyFactory.create(provider); ErrataData errataForVm = proxy.getErrataForHost(vm.getId().toString(), vm.getDynamicData().getFqdn(), vm.getName(), getParameters().getErrataFilter()); getQueryReturnValue().setReturnValue(errataForVm); } else { getQueryReturnValue().setReturnValue(ErrataData.emptyData()); } }</code><technical_language>+1 for Note in terms of implementation directs call socket.getfqdn() <LINK_1> <LINK_0></technical_language>

Target:
protected void executeQueryCommand() { VM vm = vmDao.get(getParameters().getId()); if (vm == null) { getQueryReturnValue().setReturnValue(ErrataData.emptyData()); return; } Provider<?> provider = providerDao.get(vm.getProviderId()); if (provider != null) { HostProviderProxy proxy = providerProxyFactory.create(provider); ErrataData errataForVm = proxy.getErrataForHost(vm.getId().toString(), vm.getDynamicData().getFqdn(), vm.getName(), getParameters().getErrataFilter()); getQueryReturnValue().setReturnValue(errataForVm); } else { getQueryReturnValue().setReturnValue(ErrataData.emptyData()); } }
Source:
<code>public Team update(Long teamId, TeamDTO input) { Team current = getTeamById(teamId); if (!Strings.isNullOrEmpty(input.getTeamName())) { current.setTeamName(input.getTeamName()); } String captainUsername = input.getCaptainUsername(); <START> if (!Strings.isNullOrEmpty(captainUsername)) { <END> User captain = userService.getUserByUsername(captainUsername) .orElseThrow(() -> new UserNotFoundException(captainUsername)); current.setCaptain(captain); } return teamRepository.saveAndFlush(current); }</code><technical_language>I perform a check if captain in input is current captain. I this change in functionality I code. execution</technical_language>

Target:
public Team update(Long teamId, TeamDTO input) { Team current = getTeamById(teamId); if (!Strings.isNullOrEmpty(input.getTeamName())) { current.setTeamName(input.getTeamName()); } String captainUsername = input.getCaptainUsername(); if (!Strings.isNullOrEmpty(captainUsername) && !captainUsername.equals(current.getCaptain().getUsername())) { User captain = userService.getUserByUsername(captainUsername) .orElseThrow(() -> new UserNotFoundException(captainUsername)); current.setCaptain(captain); } return teamRepository.saveAndFlush(current); }
Source:
<code>public void createProjectRequest(final CreateProjectJobRequest jobRequest, final Map<String, Object> headers) { final Map<String, Object> params = getContext(jobRequest); params.put("Space", jobRequest.getSpaceName()); params.put("Project", jobRequest.getProjectName()); params.put("Operation", "createProject"); params.put("acceptLanguage", <START> headers.get("acceptLanguage")); <END> scheduleJob(jobRequest, new CreateProjectCmd(jobRequestHelper, jobResultManager, params)); }</code><technical_language>I avoid magic Strings a constant instead</technical_language>

Target:
public void createProjectRequest(final CreateProjectJobRequest jobRequest, final Map<String, Object> headers) { final Map<String, Object> params = getContext(jobRequest); params.put("Space", jobRequest.getSpaceName()); params.put("Project", jobRequest.getProjectName()); params.put("Operation", "createProject"); params.put(ACCEPT_LANGUAGE, headers.get(ACCEPT_LANGUAGE)); scheduleJob(jobRequest, new CreateProjectCmd(jobRequestHelper, jobResultManager, params)); }
Source:
<code>public ASTValue eval(WordsEnvironment environment) throws WordsRuntimeException { <START> WordsObject obj = children.get(0).eval(environment).objValue; <END> String propertyName = children.get(1).eval(environment).stringValue; ASTValue propertyASTValue = children.get(2).eval(environment); WordsProperty wordsProp = null; switch (propertyASTValue.type) { case NUM: wordsProp = new WordsProperty(propertyASTValue.numValue); break; case STRING: wordsProp = new WordsProperty(propertyASTValue.stringValue); break; case OBJ: wordsProp = new WordsProperty(propertyASTValue.objValue); break; case NOTHING: wordsProp = new WordsProperty(WordsProperty.PropertyType.NOTHING); break; default: throw new AssertionError("Shouldn't get here"); } obj.setProperty(propertyName, wordsProp); return null; }</code><technical_language>right, Assertions a defensive coding practice for ourselves, user see. if trigger AssertionError development, means assumptions code wrong, changed assumptions longer true, of good caught</technical_language>

Target:
public ASTValue eval(WordsEnvironment environment) throws WordsRuntimeException { WordsObject obj = children.get(0).eval(environment).objValue; if (obj == null) { throw new AssertionError("Obj should never be null here"); } String propertyName = children.get(1).eval(environment).stringValue; ASTValue propertyASTValue = children.get(2).eval(environment); WordsProperty wordsProp = null; switch (propertyASTValue.type) { case NUM: wordsProp = new WordsProperty(propertyASTValue.numValue); break; case STRING: wordsProp = new WordsProperty(propertyASTValue.stringValue); break; case OBJ: wordsProp = new WordsProperty(propertyASTValue.objValue); break; case NOTHING: wordsProp = new WordsProperty(WordsProperty.PropertyType.NOTHING); break; default: throw new AssertionError("Shouldn't get here"); } obj.setProperty(propertyName, wordsProp); return null; }
Source:
<code>public void testInstallFeatureCallIsPrivileged() throws Exception { final AtomicReference<StackTraceElement[]> stackTraceElements = new AtomicReference<>(); doAnswer( AdditionalAnswers.answerVoid( o -> stackTraceElements.set(Thread.currentThread().getStackTrace()))) .when(mockFeaturesService) .installFeature(anyString(), any(EnumSet.class)); ApplicationServiceBean serviceBean = new ApplicationServiceBean( testAppService, testConfigAdminExt, mBeanServer, mockFeaturesService); serviceBean.installFeature("profile-name"); assertThat( Arrays.stream(stackTraceElements.get()) <START> .anyMatch(e -> e.toString().startsWith(DO_PRIVILEGED_STACK_ELEMENT)), <END> is(true)); }</code><technical_language>This relies toString() returning a format. of testing classname separately. for testing test method, I is sufficient check if AccessController is stack</technical_language>

Target:
public void testInstallFeatureCallIsPrivileged() throws Exception { StackCaptor stackCaptor = new StackCaptor(); stackCaptor .doCaptureStack() .when(mockFeaturesService) .installFeature(anyString(), any(EnumSet.class)); ApplicationServiceBean serviceBean = new ApplicationServiceBean( testAppService, testConfigAdminExt, mBeanServer, mockFeaturesService); serviceBean.installFeature("profile-name"); assertThat(stackCaptor.getStack(), stackContainsDoPrivilegedCall()); }
Source:
<code><START> public void collect(GenericRow genericRow) { <END> Object[] key = new Object[_keySize]; for (int i = 0; i < _keySize; i++) { key[i] = genericRow.getValue(_keyColumns[i]); } Record keyRecord = new Record(key); GenericRow prev = _collection.get(keyRecord); if (prev == null) { _collection.put(keyRecord, genericRow); } else { for (int i = 0; i < _valueSize; i++) { String valueColumn = _valueColumns[i]; Object aggregate = _valueAggregators[i] .aggregate(prev.getValue(valueColumn), genericRow.getValue(valueColumn), _metricFieldSpecs[i]); prev.putValue(valueColumn, aggregate); } } }</code><technical_language>I guess basically entire data for a segment JVM heap? In future, need add off-heap file-based collector avoid OOM error reading large segments. (e.g. 1-2gb Pinot segment extremely large in row format) Another save memory is sort data dimensions scan for aggregation (but this paying a large cost for cases data need sorted)</technical_language>

Target:
public void collect(GenericRow genericRow) { Object[] key = new Object[_keySize]; for (int i = 0; i < _keySize; i++) { key[i] = genericRow.getValue(_keyColumns[i]); } Record keyRecord = new Record(key); GenericRow prev = _collection.get(keyRecord); if (prev == null) { _collection.put(keyRecord, genericRow); } else { for (int i = 0; i < _valueSize; i++) { String valueColumn = _valueColumns[i]; Object aggregate = _valueAggregators[i].aggregate(prev.getValue(valueColumn), genericRow.getValue(valueColumn)); prev.putValue(valueColumn, aggregate); } } }
Source:
<code>public void addProjectToImport( final ExampleProject exampleProject ) { <START> Button button = (Button) document.createElement( "button" ); <END> button.getClassList().add( "btn" ); button.getClassList().add( "btn-lg" ); button.setTextContent( exampleProject.getName() ); button.setAttribute( "alt", exampleProject.getDescription() ); button.setOnclick( event -> presenter.importProject( exampleProject ) ); importContainer.appendChild( button ); }</code><technical_language>This type of coding harks programmatic view construction older versions of GWT IMO avoided (yes, it''ll a bunch of classes create a re-usable "Button" widget.. @Rikkola @cristianonicolai talked a need for a re-usable set of basic widgets wrapping Element... yet!)</technical_language>

Target:
public void addProjectToImport( final ExampleProject exampleProject ) { final ImportExampleButtonWidget importExampleButton = importExampleButtonWidgets.get(); importExampleButton.init( exampleProject.getName(), exampleProject.getDescription(), () -> presenter.importProject( exampleProject ) ); importContainer.appendChild( importExampleButton.getElement() ); }
Source:
<code>public Options getOpts() { Options opts = new Options(); opts.addOption("appname", true, "Application Name. Default value - Storm-on-Yarn"); opts.addOption("queue", true, "RM Queue in which this application is to be submitted"); opts.addOption("rmAddr", true, "YARN RM's IPC address"); <START> opts.addOption("schedulerAddr", true, "YARN scheduler's IPC address"); <END> opts.addOption("stormHome", true, "Storm Home Directory"); opts.addOption("output", true, "Output file"); opts.addOption("stormZip", true, "file path of storm.zip"); return opts; }</code><technical_language>do need scheduler address? Hadoop configuration</technical_language>

Target:
public Options getOpts() { Options opts = new Options(); opts.addOption("appname", true, "Application Name. Default value - Storm-on-Yarn"); opts.addOption("queue", true, "RM Queue in which this application is to be submitted"); opts.addOption("stormHome", true, "Storm Home Directory"); opts.addOption("output", true, "Output file"); opts.addOption("stormZip", true, "file path of storm.zip"); return opts; }
Source:
<code>public static GenomicVariant fromHgvs(String hgvs) { <START> if (!isHgvs(hgvs)) <END> throw new InvalidHgvsException(); String chr = getPattern("^\\d+(?=:)", hgvs); RefType ref_type = getRefTypeFromHgvs(hgvs); Integer start = Integer.parseInt(getPattern("(?<=\\.)\\d+(?=[_ATGC])", hgvs)); Integer end = getEndFromHgvs(hgvs, start); Type type = getTypeFromHgvs(hgvs); String ref = getRefFromHgvs(hgvs, type); String alt = getAltFromHgvs(hgvs, type); return new GenomicVariant(chr, ref_type, start, end, type, ref, alt); }</code><technical_language>curly brackets if/when/for conditions if is a single line: suggestion if (!isHgvs(hgvs)) { ... }</technical_language>

Target:
public static GenomicVariant fromHgvs(String hgvs) { if (!isHgvs(hgvs)) { throw new InvalidHgvsException(); } String chr = getPattern("^\\d+(?=:)", hgvs); RefType ref_type = getRefTypeFromHgvs(hgvs); Integer start = Integer.parseInt(getPattern("(?<=\\.)\\d+(?=[_ATGC])", hgvs)); Integer end = getEndFromHgvs(hgvs, start); Type type = getTypeFromHgvs(hgvs); String ref = getRefFromHgvs(hgvs, type); String alt = getAltFromHgvs(hgvs, type); return new GenomicVariant(chr, ref_type, start, end, type, ref, alt); }
Source:
<code>protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String contentType = request.getParameter("contenttype"); String fileName = request.getParameter("filename"); Boolean cache = Boolean.parseBoolean(request.getParameter("cache")); String encodingType = request.getParameter("encodingtype"); String content = request.getParameter("content"); if (contentType != null) { response.setContentType(contentType); } if (fileName == null) { fileName = "attachment"; } response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); if (!cache) { response.setHeader("Cache-Control", "no-cache, must-revalidate"); response.setHeader("Expires", "Sat, 26 Jul 1997 05:00:00 GMT"); } <START> if (content == null) { <END> return; } if ("binary".equals(encodingType)) { response.getOutputStream().write(Base64.decodeBase64(content)); } else { response.getWriter().write(content); if (response.getWriter().checkError()) { throw new IOException("Error when writing to response stream"); } } }</code><technical_language>I exception is in this case</technical_language>

Target:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String contentType = request.getParameter("contenttype"); String fileName = request.getParameter("filename"); Boolean cache = Boolean.parseBoolean(request.getParameter("cache")); String encodingType = request.getParameter("encodingtype"); String content = request.getParameter("content"); if (contentType != null) { response.setContentType(contentType); } if (fileName == null) { fileName = "attachment"; } response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); if (!cache) { response.setHeader("Cache-Control", "no-cache, must-revalidate"); response.setHeader("Expires", "Sat, 26 Jul 1997 05:00:00 GMT"); } if (content == null) { return; } if ("binary".equals(encodingType)) { response.getOutputStream().write(Base64.decodeBase64(content)); } else if ("plain".equals(encodingType)) { response.getWriter().write(content); if (response.getWriter().checkError()) { throw new IOException("Error when writing to response stream"); } } else { throw new ServletException(String.format("Unsupported encoding type {0}", encodingType)); } }
Source:
<code>public static Object structAccess(Object structObject, int index, String fieldName) { if (structObject == null) { return null; } if (structObject instanceof Object[]) { return ((Object[]) structObject)[index]; } else if (structObject instanceof List) { return ((List) structObject).get(index); } else if (structObject instanceof Row) { return ((Row) structObject).getObject(index); } else { Class<?> beanClass = structObject.getClass(); try { Field structField; <START> if (index >= 0 && index < beanClass.getDeclaredFields().length) { structField = beanClass.getDeclaredFields()[index]; } else { structField = beanClass.getDeclaredField(fieldName); } <END> return structField.get(structObject); } catch (NoSuchFieldException | IllegalAccessException ex) { throw RESOURCE.failedToAccessField(fieldName, beanClass.getName()).ex(ex); } } }</code><technical_language>Is a reason of access index is preferred access name? getDeclaredFields() efficient getDeclaredField(); involve a copy do a copy of fields</technical_language>

Target:
public static Object structAccess(Object structObject, int index, String fieldName) { if (structObject == null) { return null; } if (structObject instanceof Object[]) { return ((Object[]) structObject)[index]; } else if (structObject instanceof List) { return ((List) structObject).get(index); } else if (structObject instanceof Row) { return ((Row) structObject).getObject(index); } else { Class<?> beanClass = structObject.getClass(); try { Field structField; if (fieldName == null) { structField = beanClass.getDeclaredFields()[index]; } else { structField = beanClass.getDeclaredField(fieldName); } return structField.get(structObject); } catch (NoSuchFieldException | IllegalAccessException ex) { throw RESOURCE.failedToAccessField(fieldName, beanClass.getName()).ex(ex); } } }
Source:
<code>abstract public void validate() throws IndexBuilderException; abstract public void loadIntoTaxonomy(Taxonomy taxonomy) throws IndexBuilderException; abstract public Citation getCitation() throws IndexBuilderException; abstract public Collection<Country> getCountries() throws IndexBuilderException; abstract public Collection<Contact> getContacts() throws IndexBuilderException; public static NameSource create(String f) throws IndexBuilderException { try { <START> File nf = new File(f); <END> NameSource ns; if (!nf.exists()) throw new IndexBuilderException("Name source " + nf + " does not exist"); if (nf.isDirectory()) ns = new DwcaNameSource(nf); else ns = new CSVNameSource(new InputStreamReader(new FileInputStream(nf), "UTF-8")); ns.validate(); return ns; } catch (IOException ex) { throw new UncheckedIOException(ex); } }</code><technical_language>Path Files useful, necessary</technical_language>

Target:
abstract public void validate() throws IndexBuilderException; abstract public void loadIntoTaxonomy(Taxonomy taxonomy) throws IndexBuilderException; abstract public Citation getCitation() throws IndexBuilderException; abstract public Collection<Country> getCountries() throws IndexBuilderException; abstract public Collection<Contact> getContacts() throws IndexBuilderException; public static NameSource create(String f) throws IndexBuilderException { try { File nf = new File(f); NameSource ns; if (!nf.exists()) throw new IndexBuilderException("Name source " + nf + " does not exist"); if (nf.isDirectory()) ns = new DwcaNameSource(nf); else ns = new CSVNameSource(Files.newReader(nf, Charset.forName("UTF-8"))); ns.validate(); return ns; } catch (IOException ex) { throw new UncheckedIOException(ex); } }
Source:
<code>public ScriptedAnalysis createScriptedAnalysis(@Nullable ITmfTrace trace, String analysisName) { if (trace == null) { <START> throw new NullPointerException("Trace should not be null"); END> } return new ScriptedAnalysis(trace, analysisName); }</code><technical_language>for giggles, objects.requiresNotNull(trace, "Trace null");</technical_language>

Target:
public ScriptedAnalysis createScriptedAnalysis(@Nullable ITmfTrace trace, String analysisName) { return new ScriptedAnalysis(Objects.requireNonNull(trace, "Trace should not be null"), analysisName); }
Source:
<code>public AuthorizationFramework getAuthorizationFramework() { try { authFrameworkLock.readLock().lock(); if (authFramework == null) { <START> authFramework = new AuthorizationFramework(getPluginDirectory(), getPluginStack()); <END> } return authFramework; } finally { authFrameworkLock.readLock().unlock(); } }</code><technical_language>Theoretically, this accessed multiple threads. Is okay? If want a singleton, revise this</technical_language>

Target:
public AuthorizationFramework getAuthorizationFramework() { synchronized (authFrameworkLock) { if (authFramework == null) { authFramework = new AuthorizationFramework(getPluginDirectory(), getPluginStack()); } return authFramework; } }
Source:
<code>public void importProject( final ExampleProject exampleProject ) { busyIndicatorView.showBusyIndicator( ts.getTranslation( LibraryConstants.Importing ) ); <START> libraryService.call( new RemoteCallback<Project>() { <END> @Override public void callback( final Project project ) { busyIndicatorView.hideBusyIndicator(); notificationEvent.fire( new NotificationEvent( ts.getTranslation( LibraryConstants.ProjectImportedSuccessfully ), NotificationEvent.NotificationType.SUCCESS ) ); newProjectEvent.fire( new NewProjectEvent( project, sessionInfo.getId(), sessionInfo.getIdentity().getIdentifier() ) ); goToProject( project ); } }, ( o, throwable ) -> { busyIndicatorView.hideBusyIndicator(); notificationEvent.fire( new NotificationEvent( ts.getTranslation( LibraryConstants.ProjectImportError ), NotificationEvent.NotificationType.ERROR ) ); return false; } ).importProject( libraryPlaces.getSelectedOrganizationalUnit(), libraryPlaces.getSelectedRepository(), exampleProject ); }</code><technical_language>Inconsistent of lamdas (your "success" in anonymous class, "error" is a lamda)</technical_language>

Target:
public void importProject( final ExampleProject exampleProject ) { busyIndicatorView.showBusyIndicator( ts.getTranslation( LibraryConstants.Importing ) ); libraryService.call( ( Project project ) -> { busyIndicatorView.hideBusyIndicator(); notificationEvent.fire( new NotificationEvent( ts.getTranslation( LibraryConstants.ProjectImportedSuccessfully ), NotificationEvent.NotificationType.SUCCESS ) ); newProjectEvent.fire( new NewProjectEvent( project, sessionInfo.getId(), sessionInfo.getIdentity().getIdentifier() ) ); goToProject( project ); }, ( o, throwable ) -> { busyIndicatorView.hideBusyIndicator(); notificationEvent.fire( new NotificationEvent( ts.getTranslation( LibraryConstants.ProjectImportError ), NotificationEvent.NotificationType.ERROR ) ); return false; } ).importProject( libraryPlaces.getSelectedOrganizationalUnit(), libraryPlaces.getSelectedRepository(), exampleProject ); }
Source:
<code>public static Pair<String, String[]> createWhere(String[] fieldNames, Object[] values, EncryptedModel em, Persistable p) throws IllegalArgumentException { Set<String> fields = null; if(p instanceof IMetaData) { IMetaData m = (IMetaData)p; String[] thefields = m.getMetaDataFields(); fields = new HashSet<String>(); for(String s : thefields) { fields.add(TableBuilder.scrubName(s)); } } if(em instanceof IMetaData) { IMetaData m = (IMetaData)em; String[] thefields = m.getMetaDataFields(); fields = new HashSet<String>(); for(String s : thefields) { fields.add(TableBuilder.scrubName(s)); } } String ret = ""; ArrayList<String> arguments = new ArrayList<String>(); boolean set = false; for(int i = 0 ; i < fieldNames.length; ++i) { String columnName = TableBuilder.scrubName(fieldNames[i]); if(fields != null) { if(!fields.contains(columnName)) { continue; } } if(set){ ret += " AND "; } <START> ret += columnName + "=?"; <END> arguments.add(values[i].toString()); set = true; } String[] retArray = new String[arguments.size()]; for(int i =0; i< arguments.size(); i++){ retArray[i] = arguments.get(i); } return new Pair<String, String[]>(ret, retArray); }</code><technical_language>a good idea a StringBuilder string construction of a loop</technical_language>

Target:
public static Pair<String, String[]> createWhere(String[] fieldNames, Object[] values, EncryptedModel em, Persistable p) throws IllegalArgumentException { Set<String> fields = null; if(p instanceof IMetaData) { IMetaData m = (IMetaData)p; String[] thefields = m.getMetaDataFields(); fields = new HashSet<String>(); for(String s : thefields) { fields.add(TableBuilder.scrubName(s)); } } if(em instanceof IMetaData) { IMetaData m = (IMetaData)em; String[] thefields = m.getMetaDataFields(); fields = new HashSet<String>(); for(String s : thefields) { fields.add(TableBuilder.scrubName(s)); } } StringBuilder stringBuilder = new StringBuilder(); ArrayList<String> arguments = new ArrayList<String>(); boolean set = false; for(int i = 0 ; i < fieldNames.length; ++i) { String columnName = TableBuilder.scrubName(fieldNames[i]); if(fields != null) { if(!fields.contains(columnName)) { continue; } } if(set){ stringBuilder.append(" AND "); } stringBuilder.append(columnName); stringBuilder.append("=?"); arguments.add(values[i].toString()); set = true; } String[] retArray = new String[arguments.size()]; for(int i =0; i< arguments.size(); i++){ retArray[i] = arguments.get(i); } return new Pair<String, String[]>(stringBuilder.toString(), retArray); }
Source:
<code>public DiscoveryConfiguration getDiscoveryConfigurationByNameOrDso(final String configurationName, final IndexableObject dso) { <START> if (dso instanceof Community && configurationName.contentEquals("showUnDiscoverableItems")) { <END> if (getMap().containsKey(configurationName + "." + ((Community) dso).getHandle())) { return getMap().get(configurationName + "." + ((Community) dso).getHandle()); } else { return getMap().get(configurationName); } } else if (StringUtils.isNotBlank(configurationName) && getMap().containsKey(configurationName)) { return getMap().get(configurationName); } else { return getDiscoveryConfiguration(dso); } }</code><technical_language>normal procedure for defining separate configurations community collection is based discovery.xml map: <LINK_0></technical_language>

Target:
public DiscoveryConfiguration getDiscoveryConfigurationByNameOrDso(final String configurationName, final IndexableObject dso) { if (StringUtils.isNotBlank(configurationName) && getMap().containsKey(configurationName)) { return getMap().get(configurationName); } else { return getDiscoveryConfiguration(dso); } }
Source:
<code>public void testAuthenticityFail() { when(context.getParameter(NinjaConstant.AUTHENTICITY_TOKEN)).thenReturn("foo"); when(context.getSession()).thenReturn(session); when(context.getSession().getAuthenticityToken()).thenReturn("bar"); <START> when(ninjaDefault.getForbiddenResult(context)).thenReturn(forbidden); <END> Result failed = this.authenticityFilter.filter(filterChain, context); assertNotNull(failed); assertEquals(403, failed.getStatusCode()); }</code><technical_language>simplify code a bit... need ok forbidden results... do a check Mockito.verify(ninjaDefault).getForbiddenResult(context) Mockito.verify(filterChain).next(context); assertNotNull assertEquals is needed imho... code a bit shorter..</technical_language>

Target:
public void testAuthenticityFail() { when(context.getParameter(NinjaConstant.AUTHENTICITY_TOKEN)).thenReturn("foo"); when(context.getSession()).thenReturn(session); when(context.getSession().getAuthenticityToken()).thenReturn("bar"); this.authenticityFilter.filter(filterChain, context); Mockito.verify(ninjaDefault).getForbiddenResult(context); }
Source:
<code>public void fill(final Menu menu, int index) { final MenuItem item = new MenuItem(menu, SWT.NONE, index); item.setEnabled(false); if (info == null){ item.setText(Messages.notImplemented); return; } item.setText(Messages.computing); CodeLensParams param = new CodeLensParams(new TextDocumentIdentifier(info.getFileUri().toString()));; info.getInitializedLanguageClient().thenAccept(languageServer -> { final CompletableFuture<List<? extends CodeLens>> codeLens = languageServer .getTextDocumentService().codeLens(param); <START> codeLens.whenComplete(new BiConsumer<List<? extends CodeLens>, Throwable>() { <END> @Override public void accept(List<? extends CodeLens> t, Throwable u) { UIJob job = new UIJob(menu.getDisplay(), Messages.updateCodelensMenu_job) { @Override public IStatus runInUIThread(IProgressMonitor monitor) { if (u != null) { item.setText(u.getMessage()); } else if (t != null) { for (CodeLens lens : t) { if (lens != null && lens.getCommand() != null) { final MenuItem item = new MenuItem(menu, SWT.NONE, index); item.setText(lens.getCommand().getTitle()); item.setEnabled(false); } } } if (menu.getItemCount() == 1) { item.setText(Messages.codeLens_emptyMenu); } else { item.dispose(); } return Status.OK_STATUS; } }; job.schedule(); } }); }); super.fill(menu, index); }</code><technical_language>a lambda expression here</technical_language>

Target:
public void fill(final Menu menu, int index) { final MenuItem item = new MenuItem(menu, SWT.NONE, index); item.setEnabled(false); if (info == null){ item.setText(Messages.notImplemented); return; } item.setText(Messages.computing); CodeLensParams param = new CodeLensParams(new TextDocumentIdentifier(info.getFileUri().toString()));; info.getInitializedLanguageClient().thenAccept(languageServer -> { final CompletableFuture<List<? extends CodeLens>> codeLens = languageServer .getTextDocumentService().codeLens(param); codeLens.whenComplete((t, u) -> { UIJob job = new UIJob(menu.getDisplay(), Messages.updateCodelensMenu_job) { @Override public IStatus runInUIThread(IProgressMonitor monitor) { if (u != null) { item.setText(u.getMessage()); } else if (t != null) { for (CodeLens lens : t) { if (lens != null && lens.getCommand() != null) { final MenuItem item = new MenuItem(menu, SWT.NONE, index); item.setText(lens.getCommand().getTitle()); item.setEnabled(false); } } } if (menu.getItemCount() == 1) { item.setText(Messages.codeLens_emptyMenu); } else { item.dispose(); } return Status.OK_STATUS; } }; job.schedule(); }); }); super.fill(menu, index); }
Source:
<code><START> private String dumpTaskRequest(final RunTaskRequest request) <END> { final StringBuilder sb = new StringBuilder(); sb.append("{"); if (request.getCluster() != null) { sb.append("Cluster: ").append(request.getCluster()).append(","); } if (request.getTaskDefinition() != null) { sb.append("TaskDefinition: ").append(request.getTaskDefinition()).append(","); } if (request.getLaunchType() != null) { sb.append("LaunchType: ").append(request.getLaunchType()).append(","); } if (request.getCapacityProviderStrategy() != null) { sb.append("CapacityProviderStrategy: ").append(request.getCapacityProviderStrategy()).append(","); } if (request.getPlacementConstraints() != null) { sb.append("PlacementConstraints: ").append(request.getPlacementConstraints()).append(","); } if (request.getPlacementStrategy() != null) { sb.append("PlacementStrategy: ").append(request.getPlacementStrategy()).append(","); } if (request.getPlatformVersion() != null) { sb.append("PlatformVersion: ").append(request.getPlatformVersion()).append(","); } TaskOverride overrides = request.getOverrides(); if (overrides != null) { if (overrides.getCpu() != null) { sb.append("CPU: ").append(overrides.getCpu()).append(","); } if (overrides.getCpu() != null) { sb.append("Memory: ").append(overrides.getMemory()); } } sb.append("}"); return sb.toString(); }</code><technical_language>static method</technical_language>

Target:
private static String dumpTaskRequest(final RunTaskRequest request) { final StringBuilder sb = new StringBuilder(); sb.append("{"); if (request.getCluster() != null) { sb.append("Cluster: ").append(request.getCluster()).append(","); } if (request.getTaskDefinition() != null) { sb.append("TaskDefinition: ").append(request.getTaskDefinition()).append(","); } if (request.getLaunchType() != null) { sb.append("LaunchType: ").append(request.getLaunchType()).append(","); } if (request.getCapacityProviderStrategy() != null) { sb.append("CapacityProviderStrategy: ").append(request.getCapacityProviderStrategy()).append(","); } if (request.getPlacementConstraints() != null) { sb.append("PlacementConstraints: ").append(request.getPlacementConstraints()).append(","); } if (request.getPlacementStrategy() != null) { sb.append("PlacementStrategy: ").append(request.getPlacementStrategy()).append(","); } if (request.getPlatformVersion() != null) { sb.append("PlatformVersion: ").append(request.getPlatformVersion()).append(","); } TaskOverride overrides = request.getOverrides(); if (overrides != null) { if (overrides.getCpu() != null) { sb.append("CPU: ").append(overrides.getCpu()).append(","); } if (overrides.getCpu() != null) { sb.append("Memory: ").append(overrides.getMemory()); } } sb.append("}"); return sb.toString(); }
Source:
<code>private static void wrapHttpRequest(HttpUriRequest httpRequest, String username, String password) { <START> if (httpRequest instanceof HttpGet || httpRequest instanceof HttpPut || httpRequest instanceof HttpPost) { <END> try { byte[] authBytes = (username + ":" + password).getBytes("UTF-8"); String authString = Base64.getEncoder().encodeToString(authBytes); httpRequest.addHeader("Authorization", "Basic " + authString); } catch (Exception e) { LOG.error(e.getMessage(), e); } } }</code><technical_language>reducing methods</technical_language>

Target:
private static void wrapHttpRequest(HttpUriRequest httpRequest, String username, String password) { try { byte[] authBytes = (username + ":" + password).getBytes("UTF-8"); String authString = Base64.getEncoder().encodeToString(authBytes); httpRequest.setHeader("Authorization", "Basic " + authString); } catch (UnsupportedEncodingException e) { LOG.error("The charset is not supported.", e); } }
Source:
<code>public void validateHashtags(Change change, Set<String> toAdd, Set<String> toRemove) throws ValidationException { try { if (toRemove != null && !toRemove.isEmpty()) { Set<String> intersection = Sets.intersection( hashtagsUtil.getHashtagsInCurrentPSCommitMessage(change), toRemove); if (!intersection.isEmpty()) { throw new ValidationException(String.format( "Need delete [ %s ] from commit message firstly", intersection.toArray())); } } } catch (OrmException | IOException e) { log.error("Can not valid removed hashtags", e); <START> throw new ValidationException("Can not valid removed hashtags", e); <END> } }</code><technical_language>I do this is clear. "Cannot remove hashtags in commit message" explain issue end user</technical_language>

Target:
public void validateHashtags(Change change, Set<String> toAdd, Set<String> toRemove) throws ValidationException { try { if (toRemove != null && !toRemove.isEmpty()) { Set<String> intersection = Sets.intersection( hashtagsUtil.getHashtagsInCurrentPSCommitMessage(change), toRemove); if (!intersection.isEmpty()) { throw new ValidationException(String.format( "Need delete [ %s ] from commit message firstly", intersection.toArray())); } } } catch (OrmException | IOException e) { log.error("Can not valid removed hashtags", e); throw new ValidationException("Can remove hashtags in commit message", e); } }