auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static void main(String[] args) throws IOException { String inputFile = null; if (args.length > 0) { inputFile = args[0]; } InputStream is = System.in; if (inputFile != null) { is = new FileInputStream(inputFile); } ANTLRInputStream input = new ANTLRInputStream(is); <START> cqlLexer lexer = new cqlLexer(input); <END> CommonTokenStream tokens = new CommonTokenStream(lexer); tokens.fill(); CommentListener listener = new CommentListener(tokens); listener.rewriteTokens(); cqlParser parser = new cqlParser(listener.tokens); parser.setBuildParseTree(true); ParserRuleContext tree = parser.library(); CqlFormatterVisitor formatter = new CqlFormatterVisitor(); String output = (String)formatter.visit(tree); System.out.print(listener.refineOutput(output)); }</code><technical_language>refactor this, code block test cases, a single static function takes InputStream returns a String is formatted output</technical_language>

Target:
public static void main(String[] args) throws IOException { String inputFile = null; if (args.length > 0) { inputFile = args[0]; } InputStream is = System.in; if (inputFile != null) { is = new FileInputStream(inputFile); } System.out.print(getFormattedOutput(is)); }
Source:
<code>Geometry(GeometryBoundingBox boundingBox, Map<String, Object> properties) { this.boundingBox = boundingBox; if (properties == null) { this.properties = Collections.emptyMap(); } else { <START> this.properties = properties.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); <END> } }</code><technical_language>Collections.unmodifiableMap</technical_language>

Target:
protected Geometry(GeometryBoundingBox boundingBox, Map<String, Object> properties) { this.boundingBox = boundingBox; if (properties == null) { this.properties = null; } else { this.properties = Collections.unmodifiableMap(new HashMap<>(properties)); } }
Source:
<code>public void beginTree(DetailAST rootAST) { currentImportControl = null; processCurrentFile = path.matcher(getFileContents().getFileName()).find(); unitName = null; for (DetailAST sibling = rootAST; sibling != null; sibling = sibling.getNextSibling()) { final int type = sibling.getType(); if (type == TokenTypes.CLASS_DEF || type == TokenTypes.ENUM_DEF || type == TokenTypes.INTERFACE_DEF || type == TokenTypes.ANNOTATION_DEF) { <START> unitName = sibling.findFirstToken(TokenTypes.IDENT).getText(); <END> break; } } }</code><technical_language>unit term, do need parse type name file, lets name of file</technical_language>

Target:
public void beginTree(DetailAST rootAST) { currentImportControl = null; processCurrentFile = path.matcher(getFileContents().getFileName()).find(); fileName = getFileContents().getText().getFile().getName(); final int period = fileName.lastIndexOf('.'); if (period != -1) { fileName = fileName.substring(0, period); } }
Source:
<code>private static void createCustomSkillset(SearchServiceClient searchServiceClient) { HashMap<String, String> headers = new HashMap<>(); headers.put("Ocp-Apim-Subscription-Key", "foobar"); List<InputFieldMappingEntry> inputs = Collections.singletonList( new InputFieldMappingEntry() .setName("text") .setSource("/document/mytext") ); List<OutputFieldMappingEntry> outputs = Collections.singletonList( new OutputFieldMappingEntry() .setName("textItems") .setTargetName("myTextItems") ); Skill webApiSkill = new WebApiSkill() .setUri("<LINK_0>") .setHttpMethod("POST") .setHttpHeaders(headers) .setInputs(inputs) .setOutputs(outputs) .setName("webapi-skill") <START> .setDescription("A WebApi skill that can be used as a custom skillset"); <END> Skillset skillset = new Skillset() .setName("custom-skillset") .setDescription("Skillset for testing custom skillsets") .setSkills(Collections.singletonList(webApiSkill)); System.out.println(String.format("Creating custom skillset '%s'", skillset.getName())); Skillset createdSkillset = searchServiceClient.createSkillset(skillset); System.out.println("Created custom skillset"); System.out.println(String.format("Name: %s", createdSkillset.getName())); System.out.println(String.format("ETag: %s", createdSkillset.getETag())); }</code><technical_language>a description "A WebApiSkill call a custom web api function.". "Custom skillset" a concept sense</technical_language>

Target:
private static void createCustomSkillset(SearchServiceClient searchServiceClient) { HashMap<String, String> headers = new HashMap<>(); headers.put("Ocp-Apim-Subscription-Key", "foobar"); List<InputFieldMappingEntry> inputs = Collections.singletonList( new InputFieldMappingEntry() .setName("text") .setSource("/document/mytext") ); List<OutputFieldMappingEntry> outputs = Collections.singletonList( new OutputFieldMappingEntry() .setName("textItems") .setTargetName("myTextItems") ); Skill webApiSkill = new WebApiSkill() .setUri("<LINK_0>") .setHttpMethod("POST") .setHttpHeaders(headers) .setInputs(inputs) .setOutputs(outputs) .setName("webapi-skill") .setDescription("A WebApiSkill that can be used to call a custom web api function"); Skillset skillset = new Skillset() .setName("custom-skillset") .setDescription("Skillset for testing custom skillsets") .setSkills(Collections.singletonList(webApiSkill)); System.out.println(String.format("Creating custom skillset '%s'", skillset.getName())); Skillset createdSkillset = searchServiceClient.createSkillset(skillset); System.out.println("Created custom skillset"); System.out.println(String.format("Name: %s", createdSkillset.getName())); System.out.println(String.format("ETag: %s", createdSkillset.getETag())); }
Source:
<code>private void recordStateChange(boolean stateChanged, boolean dataChanged, boolean sessionExpired) { if (_monitor != null) { if (stateChanged) { _monitor.increaseStateChangeEventCounter(); <START> if (sessionExpired) { <END> _monitor.increasExpiredSessionCounter(); } } if (dataChanged) { _monitor.increaseDataChangeEventCounter(); } } }</code><technical_language>I simpler caller checking this dependency record method. do if (stateChange) if (dataChange) if (sessionExpired) {}</technical_language>

Target:
private void recordStateChange(boolean stateChanged, boolean dataChanged, boolean sessionExpired) { if (_monitor != null) { if (stateChanged) { _monitor.increaseStateChangeEventCounter(); } if (dataChanged) { _monitor.increaseDataChangeEventCounter(); } if (sessionExpired) { _monitor.increasExpiredSessionCounter(); } } }
Source:
<code>public void showChanges() { <START> diffLink.click(); <END> }</code><technical_language>waitForElementClickable()</technical_language>

Target:
public void showChanges() { wait.forElementClickable(diffLink); diffLink.click(); }
Source:
<code>private static boolean isSerdeSupported(Properties schema) { <START> String serdeName = HiveUtil.getDeserializerClassName(schema); <END> if (!supportedSerdes.contains(serdeName)) { log.debug("Unsupported S3Select serde format found: " + serdeName); return false; } return true; }</code><technical_language>static import getDeserializerClassName</technical_language>

Target:
private static boolean isSerdeSupported(Properties schema) { String serdeName = getDeserializerClassName(schema); if (!SUPPORTED_SERDES.contains(serdeName)) { return false; } return true; }
Source:
<code>public void clickCreateAccountButton() { <START> createAccountButton.click(); <END> }</code><technical_language>click wait for element clickable (ajax thing)</technical_language>

Target:
public void clickCreateAccountButton(){ waitForElementClickableByElement(createAccountButton); createAccountButton.click(); }
Source:
<code>public String toString() { if (string == null) { <START> string = new String(bytes, java.nio.charset.Charset.forName("ISO-8859-1")); <END> } return string; }</code><technical_language>This java.nio.charset.StandardCharsets#US_ASCII</technical_language>

Target:
public String toString() { if (string == null) { string = new String(bytes, java.nio.charset.StandardCharsets.US_ASCII); } return string; }
Source:
<code>protected WebViewClient createWebViewClient(List<String> allowedURL) { if (getIntent().hasExtra(LOCAL_BLOG_ID)) { SiteModel site = mSiteStore.getSiteByLocalId(getIntent().getIntExtra(LOCAL_BLOG_ID, -1)); if (site == null) { AppLog.e(AppLog.T.UTILS, "No valid blog passed to WPWebViewActivity"); finish(); } return new WPWebViewClient(site, mAccountStore.getAccessToken(), allowedURL) { boolean mWebResourceError; @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); mWebResourceError = false; } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); if (!mWebResourceError && mViewModel != null) { mViewModel.onUrlLoaded(); } } @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error); mWebResourceError = true; if (mViewModel != null) { mViewModel.onError(); } } }; } else { return new URLFilteredWebViewClient(allowedURL) { boolean mWebResourceError; @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); mWebResourceError = false; } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); if (!mWebResourceError && mViewModel != null) { mViewModel.onUrlLoaded(); } } @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error); mWebResourceError = true; if (mViewModel != null) { mViewModel.onError(); } } <START> }; <END> } }</code><technical_language>options factorize this code</technical_language>

Target:
protected WebViewClient createWebViewClient(List<String> allowedURL) { URLFilteredWebViewClient webViewClient; if (getIntent().hasExtra(LOCAL_BLOG_ID)) { SiteModel site = mSiteStore.getSiteByLocalId(getIntent().getIntExtra(LOCAL_BLOG_ID, -1)); if (site == null) { AppLog.e(AppLog.T.UTILS, "No valid blog passed to WPWebViewActivity"); finish(); } webViewClient = new WPWebViewClient(site, mAccountStore.getAccessToken(), allowedURL); } else { webViewClient = new URLFilteredWebViewClient(allowedURL); } webViewClient.setMBaseWebViewClientListener(this); return webViewClient; }
Source:
<code>public OutputStreamFlushableCommandline( String[] excludedEnvironmentVariables ) { this.excludedEnvironmentVariables = new ConcurrentLinkedDeque<>(); <START> this.addedEnvironmentVariables = new HashSet<>( ); <END> Collections.addAll( this.excludedEnvironmentVariables, excludedEnvironmentVariables ); }</code><technical_language>try rewrite addedEnvironmentVariables = new HashSet<>(); this space in constructor</technical_language>

Target:
public OutputStreamFlushableCommandline( String[] excludedEnvironmentVariables ) { this.excludedEnvironmentVariables = new ConcurrentLinkedDeque<>(); addedEnvironmentVariables = new HashSet<>(); Collections.addAll( this.excludedEnvironmentVariables, excludedEnvironmentVariables ); }
Source:
<code>public void getClassLoaderModelByArtifact() { ClassLoaderModel pluginClassLoaderModel = new ClassLoaderModel(VERSION_100, mulePluginArtifact.getArtifactCoordinates()); Artifact otherThirdPartyArtifact = new Artifact(new ArtifactCoordinates(ORG_TESTS, "other-third-party", VERSION_100), URI.create("")); pluginClassLoaderModel.setDependencies(ImmutableList.of(otherThirdPartyArtifact)); applicationClassloaderModel.mergeDependencies(ImmutableList.of(pluginClassLoaderModel)); assertThat(applicationClassloaderModel.getArtifacts(), hasSize(3)); assertThat(applicationClassloaderModel.getArtifacts(), contains(thirdPartyArtifact, mulePluginArtifact, otherThirdPartyArtifact)); assertThat(applicationClassloaderModel.getClassLoaderModel(mulePluginArtifact), <START> CoreMatchers.sameInstance(pluginClassLoaderModel)); <END> }</code><technical_language>static import</technical_language>

Target:
public void getClassLoaderModelByArtifact() { ClassLoaderModel pluginClassLoaderModel = new ClassLoaderModel(VERSION_100, mulePluginArtifact.getArtifactCoordinates()); Artifact otherThirdPartyArtifact = new Artifact(new ArtifactCoordinates(ORG_TESTS, "other-third-party", VERSION_100), URI.create("")); pluginClassLoaderModel.setDependencies(ImmutableList.of(otherThirdPartyArtifact)); applicationClassloaderModel.mergeDependencies(ImmutableList.of(pluginClassLoaderModel)); assertThat(applicationClassloaderModel.getArtifacts(), hasSize(3)); assertThat(applicationClassloaderModel.getArtifacts(), contains(thirdPartyArtifact, mulePluginArtifact, otherThirdPartyArtifact)); assertThat(applicationClassloaderModel.getClassLoaderModel(mulePluginArtifact), sameInstance(pluginClassLoaderModel)); }
Source:
<code>public void visit( InputPortInfo p ) { OLSyntaxNode protocol = null, location = null; if( p.protocol() != null ) { <START> p.protocol().accept( this ); <END> protocol = currNode; } if( p.location() != null ) { p.location().accept( this ); location = currNode; } InputPortInfo iport = new InputPortInfo( p.context(), p.id(), location, protocol, p.aggregationList(), p.redirectionMap() ); if( p.getDocumentation() != null && p.getDocumentation().length() > 0 ) { iport.setDocumentation( p.getDocumentation() ); } iport.operationsMap().putAll( p.operationsMap() ); iport.getInterfaceList().addAll( p.getInterfaceList() ); programChildren.add( iport ); }</code><technical_language>call optimize</technical_language>

Target:
public void visit( InputPortInfo p ) { OLSyntaxNode protocol = null, location = null; if( p.protocol() != null ) { protocol = optimizeNode( p.protocol() ); } if( p.location() != null ) { location = optimizeNode( p.location() ); } InputPortInfo iport = new InputPortInfo( p.context(), p.id(), location, protocol, p.aggregationList(), p.redirectionMap() ); if( p.getDocumentation() != null && p.getDocumentation().length() > 0 ) { iport.setDocumentation( p.getDocumentation() ); } iport.operationsMap().putAll( p.operationsMap() ); iport.getInterfaceList().addAll( p.getInterfaceList() ); programChildren.add( iport ); }
Source:
<code>public static String findParameterType(ParameterContext parameterContext) { ResolvedMethodParameter resolvedMethodParameter = parameterContext.resolvedMethodParameter(); ResolvedType parameterType = resolvedMethodParameter.getParameterType(); parameterType = parameterContext.alternateFor(parameterType); if (isFileType(parameterType) || isListOfFiles(parameterType)) { return "form"; } if (resolvedMethodParameter.hasParameterAnnotation(PathVariable.class)) { return "path"; } else if (resolvedMethodParameter.hasParameterAnnotation(RequestBody.class)) { return "body"; } else if (resolvedMethodParameter.hasParameterAnnotation(RequestPart.class)) { return "formData"; } else if (resolvedMethodParameter.hasParameterAnnotation(RequestParam.class)) { return determineScalarParameterType( parameterContext.getOperationContext().consumes(), parameterContext.getOperationContext().httpMethod()); } else if (resolvedMethodParameter.hasParameterAnnotation(RequestHeader.class)) { return "header"; } else if (resolvedMethodParameter.hasParameterAnnotation(ModelAttribute.class)) { LOGGER.warn("@ModelAttribute annotated parameters should have already been expanded via " + "the ExpandedParameterBuilderPlugin"); <START> return "body"; <END> } return determineScalarParameterType( parameterContext.getOperationContext().consumes(), parameterContext.getOperationContext().httpMethod()); }</code><technical_language>I follow this change</technical_language>

Target:
public static String findParameterType(ParameterContext parameterContext) { ResolvedMethodParameter resolvedMethodParameter = parameterContext.resolvedMethodParameter(); ResolvedType parameterType = resolvedMethodParameter.getParameterType(); parameterType = parameterContext.alternateFor(parameterType); if (isFileType(parameterType) || isListOfFiles(parameterType)) { return "form"; } if (resolvedMethodParameter.hasParameterAnnotation(PathVariable.class)) { return "path"; } else if (resolvedMethodParameter.hasParameterAnnotation(RequestBody.class)) { return "body"; } else if (resolvedMethodParameter.hasParameterAnnotation(RequestPart.class)) { return "formData"; } else if (resolvedMethodParameter.hasParameterAnnotation(RequestParam.class)) { return determineScalarParameterType( parameterContext.getOperationContext().consumes(), parameterContext.getOperationContext().httpMethod()); } else if (resolvedMethodParameter.hasParameterAnnotation(RequestHeader.class)) { return "header"; } else if (resolvedMethodParameter.hasParameterAnnotation(ModelAttribute.class)) { LOGGER.warn("@ModelAttribute annotated parameters should have already been expanded via " + "the ExpandedParameterBuilderPlugin"); } if (!resolvedMethodParameter.hasParameterAnnotations()) { return determineScalarParameterType( parameterContext.getOperationContext().consumes(), parameterContext.getOperationContext().httpMethod()); } return "body"; }
Source:
<code>protected void check() { Preconditions.checkState(!(runtimeConfigSupplier().isPresent() && runtimeConfig().isPresent()), <START> "Either Refreshable or Supplier of runtime config must be provided or none, but not both"); <END> }</code><technical_language>nit: enough provide Refreshable Supplier of runtime config</technical_language>

Target:
protected void check() { Preconditions.checkState(!(runtimeConfigSupplier().isPresent() && runtimeConfig().isPresent()), "Cannot provide both Refreshable and Supplier of runtime config"); }
Source:
<code>public boolean addConfiguredRepository(File repositoryDir) throws IllegalArgumentException { synchronized (prefs) { if (!FileKey.isGitRepository(repositoryDir, FS.DETECTED)) throw new IllegalArgumentException( <START> "Repository directory to configure does not look like a Git directory: " + repositoryDir); END> String dirString = getPath(repositoryDir); List<String> dirStrings = getConfiguredRepositories(); if (dirStrings.contains(dirString)) { return false; } else { Set<String> dirs = new HashSet<String>(); dirs.addAll(dirStrings); dirs.add(dirString); saveDirs(dirs); return true; } } }</code><technical_language>externalize error message</technical_language>

Target:
public boolean addConfiguredRepository(File repositoryDir) throws IllegalArgumentException { synchronized (prefs) { if (!FileKey.isGitRepository(repositoryDir, FS.DETECTED)) throw new IllegalArgumentException(MessageFormat.format( CoreText.RepositoryUtil_DirectoryIsNotGitDirectory, repositoryDir)); String dirString = getPath(repositoryDir); List<String> dirStrings = getConfiguredRepositories(); if (dirStrings.contains(dirString)) { return false; } else { Set<String> dirs = new HashSet<String>(); dirs.addAll(dirStrings); dirs.add(dirString); saveDirs(dirs); return true; } } }
Source:
<code>public void visitParenthesisedExpression(ParenthesisedExpressionTree tree) { if (tree.expression().is(Kind.PARENTHESISED_EXPRESSION)) { <START> addIssue(tree, MESSAGE); <END> } super.visitParenthesisedExpression(tree); }</code><technical_language>@vilchik-elena RSPEC (rightfully in opinion) says: primary location extra "(" secondary location extra ")". location is expression. This is much, in: ((function(){ // code var foo = function() {}; window.onload = foo; var a = 1 + ((2 + 3) * 4); var b = 2 - (1 + ((2 + 3) * 4)); var c = (( 1 - 4)); }))(); (the function is highlighted)</technical_language>

Target:
public void visitParenthesisedExpression(ParenthesisedExpressionTree tree) { if (tree.expression().is(Kind.PARENTHESISED_EXPRESSION)) { addIssue(tree.openParenthesis(), MESSAGE) .secondary(tree.closeParenthesis()); } super.visitParenthesisedExpression(tree); }
Source:
<code>public void testHeaderlessSamFormat() throws PathNotFoundException { final SAMFormat result = getSamFormat(new Configuration(), "test_headerless.sam"); <START> assertEquals(result, SAMFormat.SAM); <END> }</code><technical_language>Flip arguments here, for JUnit (unlike TestNG) argument expected value, actual one</technical_language>

Target:
public void testHeaderlessSamFormat() throws PathNotFoundException { final SAMFormat result = getSamFormat(new Configuration(), "test_headerless.sam"); assertEquals(SAMFormat.SAM, result); }
Source:
<code><START> private static String encodeChar(char ch) { <END> return String.format("=%02X", ch & 0xff); }</code><technical_language>try Integer.toHexString padding correction</technical_language>

Target:
private static String encodeChar(char ch) { if (ch < 16) { return "=0" + Integer.toHexString(ch).toUpperCase(); } else { return '=' + Integer.toHexString((ch&0xff)).toUpperCase(); } }
Source:
<code>private ArrayList<ExecutorDetails> getSortedExecs(HashSet<String> spreadComps, Map<String, Map<String, Integer>> constraintMatrix, Map<String, Set<ExecutorDetails>> compToExecs) { <START> ArrayList<ExecutorDetails> retList = new ArrayList<>(); <END> Map<String, Integer> compConstraintCountMap = new HashMap<>(); for (Map.Entry<String, Map<String, Integer>> constraintEntry1 : constraintMatrix.entrySet()) { int count = 0; String comp = constraintEntry1.getKey(); for (Map.Entry<String, Integer> constraintEntry2 : constraintEntry1.getValue().entrySet()) { if (constraintEntry2.getValue() == 1) { count++; } } if (spreadComps.contains(constraintEntry1.getKey())) { count++; } compConstraintCountMap.put(comp, count); } NavigableMap<String, Integer> sortedCompConstraintCountMap = sortByValues(compConstraintCountMap); for (String comp : sortedCompConstraintCountMap.keySet()) { retList.addAll(compToExecs.get(comp)); } return retList; }</code><technical_language>Similar situation TOPOLOGY_RAS_CONSTRAINTS. I give recommendation</technical_language>

Target:
private ArrayList<ExecutorDetails> getSortedExecs(HashSet<String> spreadComps, Map<String, Map<String, Integer>> constraintMatrix, Map<String, Set<ExecutorDetails>> compToExecs) { ArrayList<ExecutorDetails> retList = new ArrayList<>(); Map<String, Integer> compConstraintCountMap = new HashMap<>(); constraintMatrix.forEach((comp, subMatrix) -> { int count = subMatrix.values().stream().mapToInt(Number::intValue).sum(); if (spreadComps.contains(comp)) { count++; } compConstraintCountMap.put(comp, count); }); NavigableMap<String, Integer> sortedCompConstraintCountMap = sortByValues(compConstraintCountMap); for (String comp : sortedCompConstraintCountMap.keySet()) { retList.addAll(compToExecs.get(comp)); } return retList; }
Source:
<code>public int read(long position, final ByteBuffer buf) throws IOException { checkStream(); try { int pos = buf.position(); final int n = ((ByteBufferPositionedReadable) in).read(position, buf); if (n > 0) { decrypt(position, buf, n, pos); } return n; <START> } catch (ClassCastException e) { <END> throw new UnsupportedOperationException("This stream does not support " + "positioned read."); } }</code><technical_language>catch ClassCastException check inpustream implemented ByteBufferPositionedReadable interface ? I a good way, catch{...} block need full stack efficient . : java if(in instanceof ByteBufferPositionedReadable){ //... }else{ throw new UnsupportedOperationException(...) }</technical_language>

Target:
public int read(long position, final ByteBuffer buf) throws IOException { checkStream(); if (!(in instanceof ByteBufferPositionedReadable)) { throw new UnsupportedOperationException("This stream does not support " + "positioned reads with byte buffers."); } int bufPos = buf.position(); final int n = ((ByteBufferPositionedReadable) in).read(position, buf); if (n > 0) { decrypt(position, buf, n, bufPos); } return n; }
Source:
<code>protected void doAperiodicRun() { if (isActive) { try { if (originThread.isAlive()) { originThread.interrupt(); } new TcpSlaveAgentListener(port).start(); LOGGER.log(Level.INFO, "Restarted TcpSlaveAgentListener"); } catch (IOException e1) { <START> LOGGER.log(Level.SEVERE, "Could not reschedule TcpSlaveAgentListener", cause); <END> } isActive = false; } }</code><technical_language>Reschedule another attempt? If Agent port is enabled, is valid use-case for dead thread. is a pending problem if thread is alive rejects stop</technical_language>

Target:
protected void doAperiodicRun() { if (isActive) { try { if (originThread.isAlive()) { originThread.interrupt(); } new TcpSlaveAgentListener(port).start(); LOGGER.log(Level.INFO, "Restarted TcpSlaveAgentListener"); isActive = false; } catch (IOException e) { LOGGER.log(Level.SEVERE, "Could not reschedule TcpSlaveAgentListener - trying again.", cause); } } }
Source:
<code>public Block copyPositions(int[] positions, int offset, int length) { <START> checkValidPositionsArray(positions, offset, length); <END> IntArrayList positionsToCopy = new IntArrayList(); Map<Integer, Integer> oldIndexToNewIndex = new HashMap<>(); int[] newIds = new int[length]; for (int i = 0; i < length; i++) { int position = positions[offset + i]; int oldIndex = getId(position); if (!oldIndexToNewIndex.containsKey(oldIndex)) { oldIndexToNewIndex.put(oldIndex, positionsToCopy.size()); positionsToCopy.add(oldIndex); } newIds[i] = oldIndexToNewIndex.get(oldIndex); } return new DictionaryBlock(dictionary.copyPositions(positionsToCopy.elements(), 0, positionsToCopy.size()), newIds); }</code><technical_language>missing checkValidPosition(positionCount, position); below</technical_language>

Target:
public Block copyPositions(int[] positions, int offset, int length) { checkArrayRange(positions, offset, length); IntArrayList positionsToCopy = new IntArrayList(); Map<Integer, Integer> oldIndexToNewIndex = new HashMap<>(); int[] newIds = new int[length]; for (int i = 0; i < length; i++) { int position = positions[offset + i]; int oldIndex = getId(position); if (!oldIndexToNewIndex.containsKey(oldIndex)) { oldIndexToNewIndex.put(oldIndex, positionsToCopy.size()); positionsToCopy.add(oldIndex); } newIds[i] = oldIndexToNewIndex.get(oldIndex); } return new DictionaryBlock(dictionary.copyPositions(positionsToCopy.elements(), 0, positionsToCopy.size()), newIds); }
Source:
<code>public Builder(String queryText) { if(queryText == null || queryText.isEmpty()) { String msg = "Query Text must not be null or empty"; logger.error(msg); throw new IllegalArgumentException(msg); } this.queryText = BinaryValue.createFromUtf8(queryText); Matcher paramMatcher = paramPattern.matcher(queryText); if(!paramMatcher.matches()) { return; } <START> <END> for (int i = 0; i < paramMatcher.groupCount(); i++) { knownParams.add(paramMatcher.group(i)); } }</code><technical_language>instantiate knownParams here, exact size</technical_language>

Target:
public Builder(String queryText) { if (queryText == null || queryText.isEmpty()) { String msg = "Query Text must not be null or empty"; logger.error(msg); throw new IllegalArgumentException(msg); } this.queryText = queryText; Matcher paramMatcher = paramPattern.matcher(queryText); if (!paramMatcher.matches()) { knownParams = Collections.emptySet(); return; } knownParams = new HashSet<String>(paramMatcher.groupCount()); for (int i = 0; i < paramMatcher.groupCount(); i++) { knownParams.add(paramMatcher.group(i)); } }
Source:
<code>private String getJobOrFlowName(SlaOption slaOption) { String jobName = (String) slaOption.getInfo().get(SlaOption.INFO_JOB_NAME); <START> if (org.apache.commons.lang.StringUtils.isNotBlank(jobName)) { <END> return jobName; } else { return (String) slaOption.getInfo().get(SlaOption.INFO_FLOW_NAME); } }</code><technical_language>isNotEmpty safer</technical_language>

Target:
private String getJobOrFlowName(SlaOption slaOption) { String flowName = (String) slaOption.getInfo().get(SlaOption.INFO_FLOW_NAME); String jobName = (String) slaOption.getInfo().get(SlaOption.INFO_JOB_NAME); if (org.apache.commons.lang.StringUtils.isNotBlank(jobName)) { return flowName + ":" + jobName; } else { return flowName; } }
Source:
<code>private boolean ensureDestinationImageMap() { if (diskInfoDestinationMap.isEmpty()) { if (getParameters().getStorageDomainId() != null && !Guid.Empty.equals(getParameters().getStorageDomainId())) { Guid storageId = getParameters().getStorageDomainId(); ArrayList<Guid> storageIds = new ArrayList<Guid>(); storageIds.add(storageId); for (DiskImage image : getVmTemplate().getDiskTemplateMap().values()) { <START> image.setStorageIds(storageIds); <END> setDestTypeAndFormat(image); diskInfoDestinationMap.put(image.getId(), image); } } else { ImagesHandler.fillImagesMapBasedOnTemplate(getVmTemplate(), diskInfoDestinationMap, destStorages, false); } } if (getVmTemplate().getDiskTemplateMap().values().size() != diskInfoDestinationMap.size()) { log.error("Can not found any default active domain for one of the disks of template with id '{}'", getVmTemplate().getId()); addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_MISSED_STORAGES_FOR_SOME_DISKS); return false; } for (DiskImage diskImage : diskInfoDestinationMap.values()) { setDestTypeAndFormat(diskImage); } return true; }</code><technical_language>Please remove this call for call</technical_language>

Target:
private boolean ensureDestinationImageMap() { if (diskInfoDestinationMap.isEmpty()) { if (getParameters().getStorageDomainId() != null && !Guid.Empty.equals(getParameters().getStorageDomainId())) { Guid storageId = getParameters().getStorageDomainId(); ArrayList<Guid> storageIds = new ArrayList<Guid>(); storageIds.add(storageId); for (DiskImage image : getVmTemplate().getDiskTemplateMap().values()) { image.setStorageIds(storageIds); diskInfoDestinationMap.put(image.getId(), image); } } else { ImagesHandler.fillImagesMapBasedOnTemplate(getVmTemplate(), diskInfoDestinationMap, destStorages, false); } } if (getVmTemplate().getDiskTemplateMap().values().size() != diskInfoDestinationMap.size()) { log.error("Can not found any default active domain for one of the disks of template with id '{}'", getVmTemplate().getId()); addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_MISSED_STORAGES_FOR_SOME_DISKS); return false; } for (DiskImage diskImage : diskInfoDestinationMap.values()) { setDestTypeAndFormat(diskImage); } return true; }
Source:
<code>public String toString() { <START> return innerList.stream().map(Node::toString).collect(Collectors.joining()); <END> }</code><technical_language>this joining(", ")</technical_language>

Target:
public String toString() { return innerList.stream().map(Node::toString).collect(Collectors.joining(", ", "[", "]")); }
Source:
<code>public List<String> getExportedResources() throws IOException { if (exportedResources == null) { exportedResources = new ArrayList<>(); for (Path resourcePath : pom.getResourcesLocation()) { exportedResources.addAll(getResources(resourcePath)); } if (!pom.getResourcesLocation() .stream() <START> .anyMatch(path -> path.endsWith(Paths.get("src", "main", "mule")))) { <END> exportedResources.addAll(getResources(projectStructure.getConfigsPath())); } } return exportedResources; }</code><technical_language>static import</technical_language>

Target:
public List<String> getExportedResources() throws IOException { if (exportedResources == null) { exportedResources = new ArrayList<>(); for (Path resourcePath : pom.getResourcesLocation()) { exportedResources.addAll(getResources(resourcePath)); } if (!pom.getResourcesLocation() .stream() .anyMatch(path -> path.endsWith(get("src", "main", "mule")))) { exportedResources.addAll(getResources(projectStructure.getConfigsPath())); } } return exportedResources; }
Source:
<code>protected boolean validateSourceDomainsSpaceRequirements() { Map<Guid, List<DiskImage>> storageDomainsActiveImagesMap = new HashMap<>(); for (LiveMigrateDiskParameters parameters : getParameters().getParametersList()) { DiskImage diskImage = getDiskImageByImageId(parameters.getImageId()); <START> if (diskImage.getActive()) { <END> MultiValueMapUtils.addToMap(parameters.getSourceStorageDomainId(), diskImage, storageDomainsActiveImagesMap); continue; } } for (Map.Entry<Guid, List<DiskImage>> entry : storageDomainsActiveImagesMap.entrySet()) { Guid sourceDomainId = entry.getKey(); List<DiskImage> disksList = entry.getValue(); Guid storagePoolId = disksList.get(0).getStoragePoolId(); StorageDomain sourceDomain = getStorageDomainById(sourceDomainId, storagePoolId); StorageDomainValidator storageDomainValidator = createStorageDomainValidator(sourceDomain); if (!validate(storageDomainValidator.hasSpaceForNewDisks(disksList))) { return false; } } return true; }</code><technical_language>why</technical_language>

Target:
protected boolean validateSourceDomainsSpaceRequirements() { Map<Guid, List<DiskImage>> storageDomainsActiveImagesMap = new HashMap<>(); for (LiveMigrateDiskParameters parameters : getParameters().getParametersList()) { DiskImage diskImage = getDiskImageByImageId(parameters.getImageId()); MultiValueMapUtils.addToMap(parameters.getSourceStorageDomainId(), diskImage, storageDomainsActiveImagesMap); } for (Map.Entry<Guid, List<DiskImage>> entry : storageDomainsActiveImagesMap.entrySet()) { Guid sourceDomainId = entry.getKey(); List<DiskImage> disksList = entry.getValue(); Guid storagePoolId = disksList.get(0).getStoragePoolId(); StorageDomain sourceDomain = getStorageDomainById(sourceDomainId, storagePoolId); StorageDomainValidator storageDomainValidator = createStorageDomainValidator(sourceDomain); if (!validate(storageDomainValidator.hasSpaceForNewDisks(disksList))) { return false; } } return true; }
Source:
<code>private boolean containsPart(IViewPart[] viewStack, IWorkbenchPart part) { if (viewStack == null) { return false; } for (IViewPart <START> element : <END> viewStack) { if (element == part) { return true; } } return false; }</code><technical_language>rename 'viewPart'</technical_language>

Target:
private boolean containsPart(IViewPart[] viewStack, IWorkbenchPart part) { if (viewStack == null) { return false; } for (IViewPart viewPart : viewStack) { if (viewPart == part) { return true; } } return false; }
Source:
<code><START> public void testDeleteTag() throws Exception{ <END> api.deleteTag(createdTag.getUuid()); }</code><technical_language>[minor] Space Exception</technical_language>

Target:
public void testDeleteTag() throws Exception { String uuid = createdTag.getUuid(); api.deleteTag(uuid); assertNull(api.getTagInfo(uuid)); }
Source:
<code>public static boolean hasLogMessage(String logFileName, String logMessage) throws Exception { BufferedReader fileReader = null; boolean found = false; Path logPath = LoggingUtil.getInServerLogPath(logFileName); <START> fileReader = Files.newBufferedReader(logPath); <END> String line = ""; while ((line = fileReader.readLine()) != null) { if(line.contains(logMessage)) { found = true; break; } } fileReader.close(); return found; }</code><technical_language>a try resources here. a minimum need close in a finally block. public static boolean hasLogMessage(String logFileName, String logMessage) throws Exception { boolean = false; Path logPath = LoggingUtil.getInServerLogPath(logFileName); try (BufferedReader fileReader = Files.newBufferedReader(logPath)) { String line = ""; while ((line = fileReader.readLine()) != null) { if (line.contains(logMessage)) { = true; break; } } } return found; }</technical_language>

Target:
public static boolean hasLogMessage(String logFileName, String logMessage) throws Exception { boolean found = false; Path logPath = LoggingUtil.getInServerLogPath(logFileName); try (BufferedReader fileReader = Files.newBufferedReader(logPath)) { String line = ""; while ((line = fileReader.readLine()) != null) { if (line.contains(logMessage)) { found = true; break; } } } return found; }
Source:
<code>public void should_fail_if_actual_has_message_not_containing_with_expected_description() { AssertionInfo info = someInfo(); String content = "expected description part"; <START> try { <END> throwables.assertHasMessageContaining(info, actual, content); fail("AssertionError expected"); } catch (AssertionError err) { verify(failures).failure(info, shouldContain(actual.getMessage(), content), actual.getMessage(), content); } }</code><technical_language>rewrite tests java 8 love in Throwables_assertHasMessageNotContaining_Test. should_fail_if_actual_has_a_message_containing_some_of_the_given_strings: java import static org.assertj.core.util.AssertionsUtil.expectAssertionError; // AssertionInfo info = someInfo(); String content = "expected description part"; // expectAssertionError(() -> throwables.assertHasMessageContaining(info, actual, content)); // verify(failures).failure(info, shouldContain(actual.getMessage(), content")); I this is more readable elegant try catch (due tests written for Java 7 time)</technical_language>

Target:
public void should_fail_if_actual_has_message_not_containing_with_expected_description() { String content = "expected description part"; expectAssertionError(() -> throwables.assertHasMessageContaining(INFO, actual, content)); verify(failures).failure(INFO, shouldContain(actual.getMessage(), content)); }
Source:
<code>public Object execute(ExecutionEvent event) throws ExecutionException { List<RepositoryGroup> groupsToDelete = new ArrayList<>(); List<RepositoryGroupNode> groupsNodes = new ArrayList<>(); List<RepositoryTreeNode> elements = getSelectedNodes(); for (Object element : elements) { if (element instanceof RepositoryGroupNode) { RepositoryGroupNode groupNode = (RepositoryGroupNode) element; groupsNodes.add(groupNode); groupsToDelete.add(groupNode.getGroup()); } } if (!groupsToDelete.isEmpty()) { DeleteRepositoryGroupConfirmDialog confirmDelete = new DeleteRepositoryGroupConfirmDialog( getShell(event), groupsNodes); if (confirmDelete.open() == Window.OK) { RepositoryGroups groups = new RepositoryGroups(); groups.delete(groupsToDelete); getView(event).refresh(); <START> } <END> } return null; }</code><technical_language>OK. for a follow-up commit: add preference user switch shown dialog</technical_language>

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { List<RepositoryGroup> groupsToDelete = new ArrayList<>(); List<RepositoryGroupNode> groupsNodes = new ArrayList<>(); List<RepositoryTreeNode> elements = getSelectedNodes(); for (Object element : elements) { if (element instanceof RepositoryGroupNode) { RepositoryGroupNode groupNode = (RepositoryGroupNode) element; groupsNodes.add(groupNode); groupsToDelete.add(groupNode.getGroup()); } } if (!groupsToDelete.isEmpty()) { DeleteRepositoryGroupConfirmDialog confirmDelete = new DeleteRepositoryGroupConfirmDialog( getShell(event), groupsNodes); if (confirmDelete.open() == Window.OK) { RepositoryGroups.getInstance().delete(groupsToDelete); getView(event).refresh(); } } return null; }
Source:
<code>public Service create(GatewayServices gatewayServices, ServiceType serviceType, GatewayConfig gatewayConfig, Map<String, String> options, String implementation) throws ServiceLifecycleException { Service service = fetchFromCache(serviceType, implementation); if (service == null) { if (getServiceType() == serviceType) { service = createService(gatewayServices, serviceType, gatewayConfig, options, implementation); if (service == null && StringUtils.isNotBlank(implementation)) { try { service = Service.class.cast(Class.forName(implementation).newInstance()); logServiceUsage(implementation, serviceType); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { <START> throw new ServiceLifecycleException("Errror while instantiating " + serviceType.getShortName() + " service implementation " + implementation, e); <END> } } } if (service != null) { service.init(gatewayConfig, options); cacheService(serviceType, implementation, service); } } return service; }</code><technical_language>Typo in Error :)</technical_language>

Target:
public Service create(GatewayServices gatewayServices, ServiceType serviceType, GatewayConfig gatewayConfig, Map<String, String> options, String implementation) throws ServiceLifecycleException { Service service = null; if (getServiceType() == serviceType) { service = createService(gatewayServices, serviceType, gatewayConfig, options, implementation); if (service == null && StringUtils.isNotBlank(implementation)) { try { service = (Service) Class.forName(implementation).newInstance(); logServiceUsage(implementation, serviceType); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { throw new ServiceLifecycleException("Error while instantiating " + serviceType.getShortName() + " service implementation " + implementation, e); } } } return service; }
Source:
<code>private static boolean hasWrapper(final Ds3Element ds3Element) { if (ds3Element.getName().endsWith("Jobs")) { return false; <START> } else if (ds3Element.getName().equals("CommonPrefixes")) { <END> return false; } return Ds3ElementUtil.hasWrapperAnnotations(ds3Element.getDs3Annotations()); }</code><technical_language>This combined if blocks return false</technical_language>

Target:
private static boolean hasWrapper(final Ds3Element ds3Element) { if (ds3Element.getName().endsWith("Jobs") || ds3Element.getName().equals("CommonPrefixes")) { return false; } return Ds3ElementUtil.hasWrapperAnnotations(ds3Element.getDs3Annotations()); }
Source:
<code>protected void executeCommand() { if (InitializeStorage()) { FencingExecutor executor = new FencingExecutor(getVds(), FenceActionType.Status); if (getVds().getpm_enabled() && executor.FindVdsToFence()) { VDSReturnValue returnValue = executor.Fence(); _fencingSucceeded = returnValue.getSucceeded(); _fenceStatusReturnValue = (FenceStatusReturnValue) returnValue.getReturnValue(); _vdsProxyFound = true; } if (getVds().getspm_status() != VdsSpmStatus.None) { storage_pool pool = DbFacade.getInstance().getStoragePoolDAO().get(getVds().getstorage_pool_id()); if (pool != null && pool.getstatus() == StoragePoolStatus.NotOperational) { pool.setstatus(StoragePoolStatus.Problematic); DbFacade.getInstance().getStoragePoolDAO().updateStatus(pool.getId(), pool.getstatus()); StoragePoolStatusHandler.PoolStatusChanged(pool.getId(), pool.getstatus()); } } } else { SetNonOperationalVdsParameters tempVar = new SetNonOperationalVdsParameters(getVds().getId(), STORAGE_DOMAIN_UNREACHABLE, <START> null); <END> tempVar.setSaveToDb(true); Backend.getInstance().runInternalAction(VdcActionType.SetNonOperationalVds, tempVar); } setSucceeded(true); }</code><technical_language>overload 2 params added null already</technical_language>

Target:
protected void executeCommand() { if (InitializeStorage()) { FencingExecutor executor = new FencingExecutor(getVds(), FenceActionType.Status); if (getVds().getpm_enabled() && executor.FindVdsToFence()) { VDSReturnValue returnValue = executor.Fence(); _fencingSucceeded = returnValue.getSucceeded(); _fenceStatusReturnValue = (FenceStatusReturnValue) returnValue.getReturnValue(); _vdsProxyFound = true; } if (getVds().getspm_status() != VdsSpmStatus.None) { storage_pool pool = DbFacade.getInstance().getStoragePoolDAO().get(getVds().getstorage_pool_id()); if (pool != null && pool.getstatus() == StoragePoolStatus.NotOperational) { pool.setstatus(StoragePoolStatus.Problematic); DbFacade.getInstance().getStoragePoolDAO().updateStatus(pool.getId(), pool.getstatus()); StoragePoolStatusHandler.PoolStatusChanged(pool.getId(), pool.getstatus()); } } } else { SetNonOperationalVdsParameters tempVar = new SetNonOperationalVdsParameters(getVds().getId(), STORAGE_DOMAIN_UNREACHABLE); tempVar.setSaveToDb(true); Backend.getInstance().runInternalAction(VdcActionType.SetNonOperationalVds, tempVar); } setSucceeded(true); }
Source:
<code>public String encode(CharSequence rawPassword) { if (rawPassword == null) { <START> throw new IllegalArgumentException("Raw password cannot be null"); <END> } String salt; if (random != null) { salt = BCrypt.gensalt(version.getVersion(), strength, random); } else { salt = BCrypt.gensalt(version.getVersion(), strength); } return BCrypt.hashpw(rawPassword.toString(), salt); }</code><technical_language>follow Spring Security conventions, please change Raw password match variable name of rawPassword</technical_language>

Target:
public String encode(CharSequence rawPassword) { if (rawPassword == null) { throw new IllegalArgumentException("rawPassword cannot be null"); } String salt; if (random != null) { salt = BCrypt.gensalt(version.getVersion(), strength, random); } else { salt = BCrypt.gensalt(version.getVersion(), strength); } return BCrypt.hashpw(rawPassword.toString(), salt); }
Source:
<code>public Observable<ResultSet> insert(Date timeSlice, JobDetails job) { if (job.getJobId() == null || job.getJobName() == null || job.getJobType() == null || job.getTrigger() == null) { <START> logger.warn("Tried to insert job on scheduled jobs with invalid values"); <END> } return session.execute(insertScheduled.bind(timeSlice, job.getJobId(), job.getJobType(), job.getJobName(), job.getParameters().getMap(), getTriggerValue(session, job.getTrigger()))); }</code><technical_language>I include timeSlice job in log statement provide info possible</technical_language>

Target:
public Observable<ResultSet> insert(Date timeSlice, JobDetails job) { if (job.getJobId() == null || job.getJobName() == null || job.getJobType() == null || job.getTrigger() == null) { logger.warnf("Tried to insert job on scheduled jobs with invalid values, [JobId: %s, TimeSlice: %s]", job .getJobId(), timeSlice); } return session.execute(insertScheduled.bind(timeSlice, job.getJobId(), job.getJobType(), job.getJobName(), job.getParameters().getMap(), getTriggerValue(session, job.getTrigger()))); }
Source:
<code>private List<String> getRcfileNameAsList() { if (rcfileName != null) { return ImmutableList.of(pylintRcfileName + rcfileName); <START> } else { <END> return ImmutableList.of(); } }</code><technical_language>This else is needed</technical_language>

Target:
private List<String> getRcfileNameAsList() { if (rcfileName == null) { return ImmutableList.of(); } return ImmutableList.of(PYLINT_RCFILE_NAME + rcfileName); }
Source:
<code>static void addDefaultCapabilities(MutableCapabilities capabilities) { <START> Set<String> capabilitieNames = capabilities.getCapabilityNames(); <END> if (capabilitieNames.contains(CapabilityType.BROWSER_NAME) && !capabilitieNames.contains(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR)) { capabilities.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE); } }</code><technical_language>suggestion Set<String> capabilityNames = capabilities.getCapabilityNames();</technical_language>

Target:
static void addDefaultCapabilities(MutableCapabilities capabilities) { Set<String> capabilityNames = capabilities.getCapabilityNames(); if (capabilityNames.contains(CapabilityType.BROWSER_NAME) && !capabilityNames.contains(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR)) { capabilities.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE); } }
Source:
<code>public void refresh() { try { refreshVdsRunTimeInfo(); } finally { try { if (firstStatus != vds.getStatus() && vds.getStatus() == VDSStatus.Up) { vdsManager.cancelRecoveryJob(); log.debug("Host '{}' ({}) firing up event.", vds.getName(), vds.getId()); vdsManager.setIsSetNonOperationalExecuted(!getVdsEventListener().vdsUpEvent(vds)); } saveDataToDb(); } catch (IRSErrorException ex) { logFailureMessage("ResourceManager::refreshVdsRunTimeInfo:", ex); log.debug("Exception", ex); } catch (RuntimeException ex) { logFailureMessage("ResourceManager::refreshVdsRunTimeInfo:", ex); <START> log.debug("Exception", ex); <END> } } }</code><technical_language>simplify catch block, IRSErrorException is indirect child of RuntimeException: } catch (RuntimeException ex) { logFailureMessage("ResourceManager::refreshVdsRunTimeInfo:", ex); log.debug("Exception", ex); }</technical_language>

Target:
public void refresh() { try { refreshVdsRunTimeInfo(); } finally { try { if (firstStatus != vds.getStatus() && vds.getStatus() == VDSStatus.Up) { vdsManager.cancelRecoveryJob(); log.debug("Host '{}' ({}) firing up event.", vds.getName(), vds.getId()); vdsManager.setIsSetNonOperationalExecuted(!getVdsEventListener().vdsUpEvent(vds)); } saveDataToDb(); } catch (RuntimeException ex) { logFailureMessage("ResourceManager::refreshVdsRunTimeInfo:", ex); log.debug("Exception", ex); } } }
Source:
<code>public boolean addIncomingChatMarkerMessageListener(ChatMarkersListener listener) { <START> synchronized (incomingListeners) { <END> return incomingListeners.add(listener); } }</code><technical_language>synchronized removed</technical_language>

Target:
public boolean addIncomingChatMarkerMessageListener(ChatMarkersListener listener) { return incomingListeners.add(listener); }