auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected boolean checkArgumentTypeCardinality(final Expression argument, @Nullable final SequenceType argType, final int argPosition) throws XPathException { boolean cardinalityMatches = argument instanceof VariableReference || argType.getCardinality() == Cardinality.ZERO_OR_MORE; <START> if (!cardinalityMatches) { <END> cardinalityMatches = argument.getCardinality().isSubCardinalityOrEqualOf(argType.getCardinality()); if (!cardinalityMatches) { if (argument.getCardinality() == Cardinality.EMPTY_SEQUENCE && argType.getCardinality().atLeastOne()) { throw new XPathException(this, ErrorCodes.XPTY0004, Messages.getMessage(Error.FUNC_EMPTY_SEQ_DISALLOWED, argPosition, ExpressionDumper.dump(argument))); } } } return cardinalityMatches; }</code><technical_language>this rewritten if (!cardinalityMatches) { .... } if (!cardinalityMatches) { .... }</technical_language>

Target:
protected boolean checkArgumentTypeCardinality(final Expression argument, @Nullable final SequenceType argType, final int argPosition) throws XPathException { boolean cardinalityMatches = argument instanceof VariableReference || argType.getCardinality() == Cardinality.ZERO_OR_MORE; if (!cardinalityMatches) { cardinalityMatches = argument.getCardinality().isSubCardinalityOrEqualOf(argType.getCardinality()); } if (!cardinalityMatches) { if (argument.getCardinality() == Cardinality.EMPTY_SEQUENCE && argType.getCardinality().atLeastOne()) { throw new XPathException(this, ErrorCodes.XPTY0004, Messages.getMessage(Error.FUNC_EMPTY_SEQ_DISALLOWED, argPosition, ExpressionDumper.dump(argument))); } } return cardinalityMatches; }
Source:
<code><START> public static void verifyNotContains(LiveSearchResults<String> results, List<Pair<String, String>> values) { <END> values.forEach(value -> assertFalse("Expected value <" + value.getK1() + ", " + value.getK2() + "> is present in results but wasn't expected", results.stream() .filter(entry -> value.getK1().equals(entry.getKey()) && value.getK2().equals(entry.getValue())) .findFirst() .isPresent())); }</code><technical_language>simplified to: java results.stream().anyMatch(entry -> value.getK1().equals(entry.getKey()) && value.getK2().equals(entry.getValue()))</technical_language>

Target:
public static void verifyNotContains(LiveSearchResults<String> results, List<Pair<String, String>> values) { values.forEach(value -> assertFalse("Expected value <" + value.getK1() + ", " + value.getK2() + "> is present in results but wasn't expected", results.stream() .anyMatch(entry -> value.getK1().equals(entry.getKey()) && value.getK2().equals(entry.getValue())))); }
Source:
<code>protected List<SimpleObject> getEncounterListAsJson(User user, ParseEncounterToJson parseEncounterToJson, VisitDomainWrapper visitWrapper, User authenticatedUser, int encounterIndex, int encounterCount) { List<Encounter> sortedEncounters = safeSubList(visitWrapper.getSortedEncounters(), encounterIndex, encounterCount + encounterIndex); List<SimpleObject> encounterJson = new ArrayList<SimpleObject>(); for (Encounter encounter : sortedEncounters) { if (encounter.getEncounterType() != null) { if (encounter.getEncounterType().getViewPrivilege() != null) { if (user.getPrivileges().contains(encounter.getEncounterType().getViewPrivilege()) || user.isSuperUser()) { <START> encounterJson.add(parseEncounterToJson.createEncounterJSON(authenticatedUser, encounter)); <END> } } else { encounterJson.add(parseEncounterToJson.createEncounterJSON(authenticatedUser, encounter)); } } else { encounterJson.add(parseEncounterToJson.createEncounterJSON(authenticatedUser, encounter)); } } return encounterJson; }</code><technical_language>Instead of calling encounterJson.add(..) times, do once</technical_language>

Target:
protected List<SimpleObject> getEncounterListAsJson(User user, ParseEncounterToJson parseEncounterToJson, VisitDomainWrapper visitWrapper, User authenticatedUser, int encounterIndex, int encounterCount) { List<Encounter> sortedEncounters = safeSubList(visitWrapper.getSortedEncounters(), encounterIndex, encounterCount + encounterIndex); List<SimpleObject> encounterJson = new ArrayList<SimpleObject>(); for (Encounter encounter : sortedEncounters) { boolean addEncounter = false; if (encounter.getEncounterType() != null) { if (encounter.getEncounterType().getViewPrivilege() != null) { if (user.getPrivileges().contains(encounter.getEncounterType().getViewPrivilege()) || user.isSuperUser()) { addEncounter = true; } } else { addEncounter = true; } } else { addEncounter = true; } if(addEncounter){ encounterJson.add(parseEncounterToJson.createEncounterJSON(authenticatedUser, encounter)); } } return encounterJson; }
Source:
<code>public OpenBuilder newOpenLedgerOp() { return new OpenBuilder() { long ledgerId; byte[] password; org.apache.bookkeeper.client.api.DigestType digestType; @Override public OpenBuilder withLedgerId(long ledgerId) { this.ledgerId = ledgerId; return this; } @Override public OpenBuilder withRecovery(boolean recovery) { <START> return this; <END> } @Override public OpenBuilder withPassword(byte[] password) { this.password = password; return this; } @Override public OpenBuilder withDigestType(org.apache.bookkeeper.client.api.DigestType digestType) { this.digestType = digestType; return this; } @Override public CompletableFuture<ReadHandle> execute() { CompletableFuture<ReadHandle> promise = new CompletableFuture<ReadHandle>(); if (getProgrammedFailStatus()) { if (failReturnCode != BkTimeoutOperation) { promise.completeExceptionally(BKException.create(failReturnCode)); } return promise; } else if (stopped.get()) { promise.completeExceptionally(BKException.create(BKException.Code.WriteException)); return promise; } MockLedgerHandle lh = ledgers.get(ledgerId); if (lh == null) { promise.completeExceptionally(BKException.create(BKException.Code.NoSuchLedgerExistsException)); } else if (lh.digest != DigestType.fromApiDigestType(digestType)) { promise.completeExceptionally(BKException.create(BKException.Code.DigestMatchException)); } else if (!Arrays.equals(lh.passwd, password)) { promise.completeExceptionally(BKException.create(BKException.Code.UnauthorizedAccessException)); } else { promise.complete(new MockReadHandle(MockBookKeeper.this, ledgerId, lh.getLedgerMetadata(), lh.entries)); } return promise; } }; }</code><technical_language>I guess this enhanced implement a new mock WriteHandle</technical_language>

Target:
public OpenBuilder newOpenLedgerOp() { return new OpenBuilderBase() { @Override public CompletableFuture<ReadHandle> execute() { CompletableFuture<ReadHandle> promise = new CompletableFuture<ReadHandle>(); if (!validate()) { promise.completeExceptionally(new BKException.BKNoSuchLedgerExistsException()); return promise; } else if (getProgrammedFailStatus()) { if (failReturnCode != BkTimeoutOperation) { promise.completeExceptionally(BKException.create(failReturnCode)); } return promise; } else if (stopped.get()) { promise.completeExceptionally(new BKException.BKClientClosedException()); return promise; } MockLedgerHandle lh = ledgers.get(ledgerId); if (lh == null) { promise.completeExceptionally(new BKException.BKNoSuchLedgerExistsException()); } else if (lh.digest != DigestType.fromApiDigestType(digestType)) { promise.completeExceptionally(new BKException.BKDigestMatchException()); } else if (!Arrays.equals(lh.passwd, password)) { promise.completeExceptionally(new BKException.BKUnauthorizedAccessException()); } else { promise.complete(new MockReadHandle(MockBookKeeper.this, ledgerId, lh.getLedgerMetadata(), lh.entries)); } return promise; } }; }
Source:
<code>public void doFilter(ServletRequest baseRequest, ServletResponse baseResponse, FilterChain chain) throws IOException, ServletException { try { super.doFilter(baseRequest, baseResponse, chain); } catch (ServletException e) { SecurityContextRepository repo = new HttpSessionSecurityContextRepository(); HttpServletRequest baseHttpRequest = (HttpServletRequest) baseRequest; HttpRequestResponseHolder holder = new HttpRequestResponseHolder(baseHttpRequest, (HttpServletResponse) baseResponse); SecurityContext securityContext = repo.loadContext(holder); if (securityContext.getAuthentication() == null) { baseHttpRequest.setAttribute("sessionTimeout", true); failureHandler.onAuthenticationFailure((HttpServletRequest) baseRequest, (HttpServletResponse) baseResponse, new AuthenticationException("Session Time Out") { <START> private static final long serialVersionUID = 1L; <END> }); } else { String previousLocation = baseHttpRequest.getHeader("referer"); HttpServletResponse response = (HttpServletResponse) baseResponse; response.sendRedirect(previousLocation); } } }</code><technical_language>This removed; unnecessary anonymous class</technical_language>

Target:
public void doFilter(ServletRequest baseRequest, ServletResponse baseResponse, FilterChain chain) throws IOException, ServletException { try { super.doFilter(baseRequest, baseResponse, chain); } catch (ServletException e) { if (e.getCause() instanceof ServiceException) { HttpServletRequest baseHttpRequest = (HttpServletRequest) baseRequest; if (SecurityContextHolder.getContext().getAuthentication() == null) { baseHttpRequest.setAttribute("sessionTimeout", true); failureHandler.onAuthenticationFailure((HttpServletRequest) baseRequest, (HttpServletResponse) baseResponse, new SessionAuthenticationException("Session Time Out")); } } else { throw e; } } }
Source:
<code>public static <T> void set(T obj, String fieldName, Object value) { try { Field f1 = obj.getClass().getDeclaredField(fieldName); <START> AccessController.doPrivileged(new PrivilegedAction<T>() { <END> @Override public T run() { f1.setAccessible(true); return null; } }); f1.set(obj, value); } catch (NoSuchFieldException | IllegalAccessException e) { throw LOGGER.logExceptionAsError(new RuntimeException(e)); } }</code><technical_language>check Field.isAccessible needing call privileged code</technical_language>

Target:
public static <T> void set(T obj, String fieldName, Object value) { try { Field field = obj.getClass().getDeclaredField(fieldName); if (!field.isAccessible()) { AccessController.doPrivileged(new PrivilegedAction<T>() { @Override public T run() { field.setAccessible(true); return null; } }); } field.set(obj, value); } catch (NoSuchFieldException | IllegalAccessException e) { throw LOGGER.logExceptionAsError(new RuntimeException(e)); } }
Source:
<code>public SfMenuBehavior(String selector, Options options, Boolean verticalSfMenu) { super(selector, METHOD, options); this.add(new CssResourceReference(SfMenuBehavior.class, "css/superfish.css")); if(verticalSfMenu) { this.add(new CssResourceReference(SfMenuBehavior.class, "css/superfish-vertical.css")); } this.add(new JavaScriptResourceReference(SfMenuBehavior.class, "js/hoverIntent.js")); <START> this.add(new JavaScriptResourceReference(SfMenuBehavior.class, "js/superfish.min.js")); <END> }</code><technical_language>non-.min version here, if available. Wicket .min in production mode. I.e. put .js files in js/ folder "js/superfish.js" here. facilitate debugging</technical_language>

Target:
public SfMenuBehavior(String selector, Options options, Boolean verticalSfMenu) { super(selector, METHOD, options); ISuperfishLibrarySettings settings = getLibrarySettings(); if(settings.getSuperfishStyleSheetReference() != null) { this.add(settings.getSuperfishStyleSheetReference()); } if(verticalSfMenu && settings.getSuperfishVerticalStyleSheetReference() != null) { this.add(settings.getSuperfishVerticalStyleSheetReference()); } this.add(HoverIntentJavaScriptResourceReference.get()); this.add(SuperfishJavaScriptResourceReference.get()); }
Source:
<code>private WindowState<WV> applyFoldFunction(WindowState<WV> existingState, M message) { WV wv; long earliesttimestamp; if (existingState == null) { wv = window.getInitializer().get(); earliesttimestamp = clock.currentTimeMillis(); } else { wv = existingState.getWindowValue(); <START> earliesttimestamp = existingState.getEarliestRecvTime(); <END> } WV newVal = window.getFoldFunction().apply(message, wv); WindowState<WV> newState = new WindowState(newVal, earliesttimestamp); return newState; }</code><technical_language>Naming: existingState.getEarliestTimestamp() for consistency. Naming: earliestTimestamp (camelcase)</technical_language>

Target:
private WindowState<WV> applyFoldFunction(WindowState<WV> existingState, M message) { WV wv; long earliestTimestamp; if (existingState == null) { LOG.trace("No existing state found for key"); wv = window.getInitializer().get(); earliestTimestamp = clock.currentTimeMillis(); } else { wv = existingState.getWindowValue(); earliestTimestamp = existingState.getEarliestTimestamp(); } WV newVal = window.getFoldLeftFunction().apply(message, wv); WindowState<WV> newState = new WindowState(newVal, earliestTimestamp); return newState; }
Source:
<code>public void enter() { mUseEap = (IkeSessionOptions.IKE_AUTH_METHOD_EAP == mIkeSessionOptions.getLocalAuthConfig().mAuthMethod); <START> super.enter(); <END> }</code><technical_language>Nit: convention, this is called, a explicit reason needs happen (which is a code smell)</technical_language>

Target:
public void enter() { super.enter(); mUseEap = (IkeSessionOptions.IKE_AUTH_METHOD_EAP == mIkeSessionOptions.getLocalAuthConfig().mAuthMethod); }
Source:
<code>private static boolean shouldCheckWhitespaceAfter(DetailAST ast) { boolean checkWhitespace = true; if (ast.getNextSibling() != null) { <START> final DetailAST sibling = ast.getNextSibling(); <END> if (sibling.getType() == TokenTypes.ANNOTATIONS) { checkWhitespace = false; } else if (sibling.getType() == TokenTypes.ARRAY_DECLARATOR) { checkWhitespace = sibling.getFirstChild().getType() != TokenTypes.ANNOTATIONS; } } return checkWhitespace; }</code><technical_language>please move this line of IF</technical_language>

Target:
private static boolean shouldCheckWhitespaceAfter(DetailAST ast) { boolean checkWhitespace = true; final DetailAST sibling = ast.getNextSibling(); if (sibling != null) { if (sibling.getType() == TokenTypes.ANNOTATIONS) { checkWhitespace = false; } else if (sibling.getType() == TokenTypes.ARRAY_DECLARATOR) { checkWhitespace = sibling.getFirstChild().getType() != TokenTypes.ANNOTATIONS; } } return checkWhitespace; }
Source:
<code>public List<? extends ICompletionProposal> getCompletionProposals(String path, JsonNode data, String prefix,int documentOffset) { final JsonNode definition = schema.getDefinitionForPath(path); final Set<JsonNode> proposals = createProposals(data, definition); final List<ICompletionProposal> result = new ArrayList<>(); prefix = Strings.emptyToNull(prefix); Styler typeStyler = new StyledString.Styler() { @Override public void applyStyles(TextStyle textStyle) { textStyle.foreground = new Color(Display.getCurrent(), new RGB(120, 120, 120)); } }; for (JsonNode proposal: proposals) { String value = proposal.get("value").asText(); String label = proposal.get("label").asText(); String type = proposal.has("type") ? proposal.get("type").asText() : null; StyledString styledString = new StyledString(label); if (type != null) { styledString .append(": ", typeStyler) .append(type, typeStyler); } if (prefix != null) { if (value.startsWith(prefix)) { value = value.substring(prefix.length(), value.length()); result.add(new StyledCompletionProposal(value, styledString, documentOffset, 0, value.length())); } } else { <START> result.add(new StyledCompletionProposal(value, styledString, documentOffset, 0, value.length())); <END> } } return result; }</code><technical_language>Good</technical_language>

Target:
public List<? extends ICompletionProposal> getCompletionProposals(String path, JsonNode data, String prefix,int documentOffset) { final JsonNode definition = schema.getDefinitionForPath(path); final Set<JsonNode> proposals = createProposals(data, definition); final List<ICompletionProposal> result = new ArrayList<>(); prefix = Strings.emptyToNull(prefix); for (JsonNode proposal: proposals) { String value = proposal.get("value").asText(); String label = proposal.get("label").asText(); String type = proposal.has("type") ? proposal.get("type").asText() : null; StyledString styledString = new StyledString(label); if (type != null) { styledString .append(": ", typeStyler) .append(type, typeStyler); } if (prefix != null) { if (value.startsWith(prefix)) { value = value.substring(prefix.length(), value.length()); result.add(new StyledCompletionProposal(value, styledString, documentOffset, 0, value.length())); } } else { result.add(new StyledCompletionProposal(value, styledString, documentOffset, 0, value.length())); } } return result; }
Source:
<code>public void testCorruptedRegionManifest() throws IOException { SnapshotTestingUtils.SnapshotMock snapshotMock = new SnapshotTestingUtils.SnapshotMock(TEST_UTIL.getConfiguration(), fs, rootDir); SnapshotTestingUtils.SnapshotMock.SnapshotBuilder builder = snapshotMock.createSnapshotV2( SNAPSHOT_NAME_STR, TABLE_NAME_STR); builder.addRegionV2(); builder.corruptOneRegionManifest(); long period = Long.MAX_VALUE; SnapshotFileCache cache = new SnapshotFileCache(fs, rootDir, period, 10000000, "test-snapshot-file-cache-refresh", new SnapshotFiles()); try { cache.getSnapshotsInProgress(); <START> } finally { <END> fs.delete(SnapshotDescriptionUtils.getWorkingSnapshotDir(rootDir, TEST_UTIL.getConfiguration()), true); } }</code><technical_language>Is this testing throw exception snapshot is corrupted</technical_language>

Target:
public void testCorruptedRegionManifest() throws IOException { SnapshotTestingUtils.SnapshotMock snapshotMock = new SnapshotTestingUtils.SnapshotMock(conf, fs, rootDir); SnapshotTestingUtils.SnapshotMock.SnapshotBuilder builder = snapshotMock.createSnapshotV2( SNAPSHOT_NAME_STR, TABLE_NAME_STR); builder.addRegionV2(); builder.corruptOneRegionManifest(); long period = Long.MAX_VALUE; SnapshotFileCache cache = new SnapshotFileCache(conf, period, 10000000, "test-snapshot-file-cache-refresh", new SnapshotFiles()); try { cache.getSnapshotsInProgress(); } finally { fs.delete(SnapshotDescriptionUtils.getWorkingSnapshotDir(rootDir, conf), true); } }
Source:
<code>public void testBuilder() throws Exception { final TableLayoutDesc layoutDesc = KijiTableLayouts.getLayout(KijiTableLayouts.SIMPLE); final KijiTableLayout layout = new KijiTableLayout(layoutDesc, null); <START> final EntityIdFactory eidFactory = EntityIdFactory.create(layoutDesc.getKeysFormat()); <END> final EntityId id1 = eidFactory.fromKijiRowKey("row1"); final EntityId id2 = eidFactory.fromKijiRowKey("row2"); final Map<String, Kiji> environment = new EnvironmentBuilder() .withInstance("inst1") .withTable("table", layout) .withRow(id1) .withFamily("family") .withQualifier("column").withValue(2, "foo1") .withQualifier("column").withValue(1, "foo2") .withRow(id2) .withFamily("family") .withQualifier("column").withValue(100, "foo3") .build(); final KijiTable table = environment.get("inst1").openTable("table"); final KijiTableReader reader = table.openTableReader(); final KijiRowData row1 = reader.get(id1, new KijiDataRequest() .addColumn(new KijiDataRequest.Column("family", "column"))); assertEquals("foo2", row1.getValue("family", "column", 1).toString()); final KijiRowData row2 = reader.get(id2, new KijiDataRequest() .addColumn(new KijiDataRequest.Column("family", "column"))); assertEquals("foo3", row2.getValue("family", "column", 100).toString()); }</code><technical_language>This block of code in user's test, entityIDs out of strings. prefer eliminate this set do entity-iding scenes</technical_language>

Target:
public void testBuilder() throws Exception { final KijiTableLayout layout = new KijiTableLayout(KijiTableLayouts.getLayout(KijiTableLayouts.SIMPLE), null); final Map<String, Kiji> environment = new EnvironmentBuilder() .withInstance("inst1") .withTable("table", layout) .withRow("row1") .withFamily("family") .withQualifier("column").withValue(1, "foo1") .withValue(2, "foo2") .withRow("row2") .withFamily("family") .withQualifier("column").withValue(100, "foo3") .build(); final KijiTable table = environment.get("inst1").openTable("table"); final KijiTableReader reader = table.openTableReader(); final KijiRowData row1 = reader.get(table.getEntityId("row1"), new KijiDataRequest() .addColumn(new KijiDataRequest.Column("family", "column"))); assertEquals("foo2", row1.getValue("family", "column", 2).toString()); final KijiRowData row2 = reader.get(table.getEntityId("row2"), new KijiDataRequest() .addColumn(new KijiDataRequest.Column("family", "column"))); assertEquals("foo3", row2.getValue("family", "column", 100).toString()); IOUtils.closeQuietly(reader); IOUtils.closeQuietly(table); IOUtils.closeQuietly(environment.get("inst1")); }
Source:
<code>public NewLineSeparator getNewLineSeparator() { <START> String newline = get(JabRefPreferences.NEWLINE); <END> if ("\r".equals(newline)) { return NewLineSeparator.CR; } else if ("\n".equals(newline)) { return NewLineSeparator.LF; } else { return NewLineSeparator.CRLF; } }</code><technical_language>a method in OS class returns system line separator</technical_language>

Target:
public NewLineSeparator getNewLineSeparator() { return NewLineSeparator.parse(get(JabRefPreferences.NEWLINE)); }
Source:
<code>private void fillDefaults(Map<String, Object> argMap) { for(ParserArgument arg : arguments.values()) { if (!argMap.containsKey(arg.getName())) { if (arg.getDefaultValue() != null) { argMap.put( arg.getName(), Util.getObjectValueByString(arg.getConvert(), arg.getDefaultValue()) <START> ); <END> } } } }</code><technical_language>sorry... forgot... if multi need create a collection</technical_language>

Target:
private void fillDefaults(Map<String, Object> argMap) { for(ParserArgument arg : arguments.values()) { if (!argMap.containsKey(arg.getName()) && arg.getDefaultValue() != null) { putValue( argMap, arg, Util.getObjectValueByString(arg.getConvert(), arg.getDefaultValue()) ); } } }
Source:
<code>protected AbstractTestIntegrationSmokeTest(QueryRunnerSupplier supplier) { <START> super(supplier, FeatureSelection.all()); <END> }</code><technical_language>nit: AbstractTestIntegrationSmokeTest of feature selection (if did, a constructor accepting feature selection needed). superclass (AbstractTestQueryFramework) provide a constructor require passing feature selection</technical_language>

Target:
protected AbstractTestIntegrationSmokeTest(QueryRunnerSupplier supplier) { super(supplier); }
Source:
<code>public AbstractDiskVmCommand(T parameters) { super(parameters); if (parameters.getDiskInfo() != null && DiskStorageType.IMAGE == parameters.getDiskInfo().getDiskStorageType()) { setQuotaId(((DiskImage) parameters.getDiskInfo()).getQuotaId()); <START> } <END> if (parameters.getStoragePoolId() != null && !parameters.getStoragePoolId().equals(Guid.Empty)) { setStoragePoolId(parameters.getStoragePoolId()); } else if (getVm() != null) { setStoragePoolId(getVm().getstorage_pool_id()); } }</code><technical_language>wrong logic a poolId retrieved domain of disk passed params, a provided vm wrong pool</technical_language>

Target:
public AbstractDiskVmCommand(T parameters) { super(parameters); if (parameters.getDiskInfo() != null && DiskStorageType.IMAGE == parameters.getDiskInfo().getDiskStorageType()) { setQuotaId(((DiskImage) parameters.getDiskInfo()).getQuotaId()); } else if (getVm() != null) { setStoragePoolId(getVm().getstorage_pool_id()); } }
Source:
<code>public void cipherCanEncodeWithGivenKey() { <START> String expectedOutput = "abcdefghij"; <END> assertEquals(expectedOutput, cipherWithSetKey.encode("aaaaaaaaaa")); }</code><technical_language>a more intention revealing name expectedOutput? is string returned encode() represent</technical_language>

Target:
public void cipherCanEncodeWithGivenKey() { String cipherText = "abcdefghij"; assertEquals(cipherText, cipherWithSetKey.encode("aaaaaaaaaa")); }
Source:
<code>public void run() throws Exception { HadoopConfigurationInjector.prepareResourcesToInject(getJobProps(), getWorkingDirectory()); File tokenFile = null; if (shouldProxy && obtainTokens) { userToProxy = getJobProps().getString(USER_TO_PROXY); getLog().info("Need to proxy. Getting tokens."); Props props = new Props(); props.putAll(getJobProps()); props.putAll(getSysProps()); tokenFile = getHadoopTokens(props); getJobProps().put("env." + HADOOP_TOKEN_FILE_LOCATION, tokenFile.getAbsolutePath()); } try { super.run(); <START> } catch (Exception e) { <END> e.printStackTrace(); getLog().error("caught exception running the job"); throw new Exception(e); } catch (Throwable t) { t.printStackTrace(); getLog().error("caught error running the job"); throw new Exception(t); } finally { if (tokenFile != null) { cancelHadoopTokens(tokenFile); if (tokenFile.exists()) { tokenFile.delete(); } } } }</code><technical_language>combine catch clauses one</technical_language>

Target:
public void run() throws Exception { HadoopConfigurationInjector.prepareResourcesToInject(getJobProps(), getWorkingDirectory()); File tokenFile = null; if (shouldProxy && obtainTokens) { userToProxy = getJobProps().getString(USER_TO_PROXY); getLog().info("Need to proxy. Getting tokens."); Props props = new Props(); props.putAll(getJobProps()); props.putAll(getSysProps()); tokenFile = HadoopJobUtils.getHadoopTokens(hadoopSecurityManager, props, getLog()); getJobProps().put("env." + HADOOP_TOKEN_FILE_LOCATION, tokenFile.getAbsolutePath()); } try { super.run(); } catch (Throwable t) { t.printStackTrace(); getLog().error("caught error running the job"); throw new Exception(t); } finally { if (tokenFile != null) { HadoopJobUtils.cancelHadoopTokens(hadoopSecurityManager, userToProxy, tokenFile, getLog()); if (tokenFile.exists()) { tokenFile.delete(); } } } }
Source:
<code>protected boolean makeFileFromResourceFile(String fileName, String postFix) { String resourceFileName = fileName + postFix; File dbDir = new File(absolutePathOfStorageDir); if (!dbDir.exists() && !dbDir.mkdir()) log.warn("make dir failed.\ndbDir=" + dbDir.getAbsolutePath()); File destinationFile = new File(Paths.get(absolutePathOfStorageDir, fileName).toString()); if (!destinationFile.exists()) { try { log.info("We copy resource to file: resourceFileName={}, destinationFile={}", resourceFileName, destinationFile); FileUtil.resourceToFile(resourceFileName, destinationFile); return true; } catch (ResourceNotFoundException e) { log.info("Could not find resourceFile " + resourceFileName + ". That is expected if none is provided yet."); } catch (Throwable e) { log.error("Could not copy resourceFile " + resourceFileName + " to " + destinationFile.getAbsolutePath() + ".\n" + e.getMessage()); e.printStackTrace(); } } else { <START> log.info("No resource file have been copied. exists already.", fileName); <END> } return false; }</code><technical_language>log.info("No resource file copied. exists already.", fileName); log.info("No resource file copied. exists already.", fileName); (grammar)</technical_language>

Target:
protected boolean makeFileFromResourceFile(String fileName, String postFix) { String resourceFileName = fileName + postFix; File dbDir = new File(absolutePathOfStorageDir); if (!dbDir.exists() && !dbDir.mkdir()) log.warn("make dir failed.\ndbDir=" + dbDir.getAbsolutePath()); File destinationFile = new File(Paths.get(absolutePathOfStorageDir, fileName).toString()); if (!destinationFile.exists()) { try { log.info("We copy resource to file: resourceFileName={}, destinationFile={}", resourceFileName, destinationFile); FileUtil.resourceToFile(resourceFileName, destinationFile); return true; } catch (ResourceNotFoundException e) { log.info("Could not find resourceFile " + resourceFileName + ". That is expected if none is provided yet."); } catch (Throwable e) { log.error("Could not copy resourceFile " + resourceFileName + " to " + destinationFile.getAbsolutePath() + ".\n" + e.getMessage()); e.printStackTrace(); } } else { log.info("No resource file was copied. exists already.", fileName); } return false; }
Source:
<code>public Invocation toInvocation() { if (method == null) { if (argTypes == null) { argTypes = new LinkedList<Class<?>>(); for (Object arg : args) { if (arg == null) { argTypes.add(Object.class); } else { argTypes.add(arg.getClass()); } } } try { method = IMethods.class.getMethod(methodName, argTypes.toArray(new Class[argTypes.size()])); } catch (Exception e) { throw new RuntimeException("builder only creates invocations of IMethods interface", e); } } Invocation i = new InvocationImpl(mock, new SerializableMethod(method), args, sequenceNumber, <START> new RealMethod() { <END> @Override public Object invoke(Object target, Object[] arguments) throws Throwable { AccessibilityChanger accessibilityChanger = new AccessibilityChanger(); try { accessibilityChanger.enableAccess(method); return method.invoke(target, arguments); } finally { accessibilityChanger.safelyDisableAccess(method); } } }, location == null ? new LocationImpl() : location); if (verified) { i.markVerified(); } return i; }</code><technical_language>Break this out a local variable for readibility</technical_language>

Target:
public Invocation toInvocation() { if (method == null) { if (argTypes == null) { argTypes = new LinkedList<Class<?>>(); for (Object arg : args) { if (arg == null) { argTypes.add(Object.class); } else { argTypes.add(arg.getClass()); } } } try { method = IMethods.class.getMethod(methodName, argTypes.toArray(new Class[argTypes.size()])); } catch (Exception e) { throw new RuntimeException("builder only creates invocations of IMethods interface", e); } } Invocation i = new InvocationImpl(mock, new SerializableMethod(method), args, sequenceNumber, toDumbRealMethod(), location == null ? new LocationImpl() : location); if (verified) { i.markVerified(); } return i; }
Source:
<code><START> public ResourceRequest process(ResourceRequest input) <END> throws PluginExecutionException, StopProcessingException { Object subjectObj = input.getPropertyValue(SecurityConstants.SECURITY_SUBJECT); if (subjectObj instanceof Subject) { String username = SubjectUtils.getName((Subject) subjectObj); String msg = "User [" + username + "] is attempting to retrieve resource [" + input .getAttributeValue() + "] by [" + input.getAttributeName() + "]."; SecurityLogger.logInfo(msg); } return input; }</code><technical_language>kinda silly I recommend checking inputs for null in case request</technical_language>

Target:
public ResourceRequest process(ResourceRequest input) throws PluginExecutionException, StopProcessingException { if (input != null) { Object subjectObj = input.getPropertyValue(SecurityConstants.SECURITY_SUBJECT); if (subjectObj instanceof Subject) { String username = SubjectUtils.getName((Subject) subjectObj); String msg = "User [" + username + "] is attempting to retrieve resource [" + input .getAttributeValue() + "] by [" + input.getAttributeName() + "]."; SecurityLogger.logInfo(msg); } } return input; }
Source:
<code><START> public Optional<Object> select(GenericRecord record) { <END> Object current = record; Iterator<String> iter = path.iterator(); while (iter.hasNext()) { String selector = iter.next(); current = ((GenericRecord) current).get(selector); if (!(current instanceof GenericRecord)) { break; } } return iter.hasNext() ? empty() : Optional.ofNullable(current); }</code><technical_language>this public</technical_language>

Target:
private Optional<Object> select(GenericRecord record) { Object current = record; Iterator<String> iter = path.iterator(); while (iter.hasNext()) { String selector = iter.next(); current = ((GenericRecord) current).get(selector); if (!(current instanceof GenericRecord)) { break; } } return iter.hasNext() ? empty() : Optional.ofNullable(current); }
Source:
<code>public void testDefaultAesCipherParams() throws InvalidParametersException { String msg1 = "AAAAAA"; String msg2 = "AAAAAAAAAABBBBBBBBBBCCCCCCCCCCCC"; String msg3 = "AAAAAAAAAABBBBBBBBBBCCCCCCCCCCCCAAAAAAAAAABBBBBBBBBBCCCCCCCCCCCC"; String expectedCiphertext; String actualCiphertext; <START> String[] inputMsg = {msg1, msg2, msg3}; <END> for (String msg : inputMsg) { actualCiphertext = encryptWithoutSpecifyingAlgorithmParams(msg); expectedCiphertext = StringHelper.encrypt(msg); assertEquals(actualCiphertext, expectedCiphertext); } }</code><technical_language>inputMsg -> inputMsgs</technical_language>

Target:
public void testDefaultAesCipherParams() throws Exception { String plaintextLength124 = StringHelper.generateStringOfLength(31, 'A'); assertEncryptionUsesExpectedDefaultParams(plaintextLength124); String plaintextLength128 = StringHelper.generateStringOfLength(32, 'A'); assertEncryptionUsesExpectedDefaultParams(plaintextLength128); String plaintextLength132 = StringHelper.generateStringOfLength(33, 'A'); assertEncryptionUsesExpectedDefaultParams(plaintextLength132); }
Source:
<code>public void MessageWall_016_CloseThread() { MessageWallPageObject wall = new MessageWallPageObject(driver); <START> String timeStamp = wall.getTimeStamp(); <END> String title = PageContent.messageWallTitlePrefix + timeStamp; String message = PageContent.messageWallMessagePrefix + timeStamp; wall.openWikiPage(); CommonFunctions.logInCookie(Properties.userNameStaff, Properties.passwordStaff); wall.openMessageWall(Properties.userNameStaff); wall.writeMessage(title, message); wall.clickPostButton(); wall.verifyPostedMessageWithTitle(title, message); wall.closeThread("reason"); CommonFunctions.logOut(driver); }</code><technical_language>move variables beginning of class</technical_language>

Target:
public void MessageWall_016_CloseThread() { MessageWallPageObject wall = new MessageWallPageObject(driver); timeStamp = wall.getTimeStamp(); title = PageContent.messageWallTitlePrefix + timeStamp; message = PageContent.messageWallMessagePrefix + timeStamp; wall.openWikiPage(); CommonFunctions.logInCookie(Properties.userNameStaff, Properties.passwordStaff); wall.openMessageWall(Properties.userNameStaff); wall.writeMessage(title, message); wall.clickPostButton(); wall.verifyPostedMessageWithTitle(title, message); wall.closeThread(PageContent.messageWallCloseReopenReason); CommonFunctions.logOut(driver); }
Source:
<code>public Shell getShells () { checkDevice (); int index = 0; Shell result = new Shell [16]; for (int i = 0; i < widgetTable.length; i++) { Widget widget = widgetTable [i]; if (!(widget instanceof Shell)) { continue; } if (!widget.isDisposed()) { int j = 0; while (j < index) { if (result [j] == widget) break; j++; } if (j == index) { if (index == result.length) { Shell newResult = new Shell [index + 16]; System.arraycopy (result, 0, newResult, 0, index); result = newResult; } result [index++] = (Shell) widget; } } else { System.err.println ("SWT ERROR: disposed shell detected in the table" + debugInfoForIndex(index)); <START> for (int j = i; i < widgetTable.length; i++) { <END> if(widgetTable[j] == widget) { widgetTable[j] = null; } } } } if (index == result.length) return result; Shell newResult = new Shell [index]; System.arraycopy (result, 0, newResult, 0, index); return newResult; }</code><technical_language>I meant for (int j = i; j < widgetTable.length; j++) {</technical_language>

Target:
public Shell getShells () { checkDevice (); int index = 0; Shell result = new Shell [16]; for (int i = 0; i < widgetTable.length; i++) { Widget widget = widgetTable [i]; if (!(widget instanceof Shell)) { continue; } if (!widget.isDisposed()) { int j = 0; while (j < index) { if (result [j] == widget) break; j++; } if (j == index) { if (index == result.length) { Shell newResult = new Shell [index + 16]; System.arraycopy (result, 0, newResult, 0, index); result = newResult; } result [index++] = (Shell) widget; } } else { System.err.println ("SWT ERROR: disposed shell detected in the table" + debugInfoForIndex(index)); for (int j = i; j < widgetTable.length; j++) { if(widgetTable[j] == widget) { widgetTable[j] = null; } } } } if (index == result.length) return result; Shell newResult = new Shell [index]; System.arraycopy (result, 0, newResult, 0, index); return newResult; }
Source:
<code>private static int getSupport( final Unit unit, final Set<List<UnitSupportAttachment>> supportsAvailable, final IntegerMap<UnitSupportAttachment> supportLeft, final Map<UnitSupportAttachment, IntegerMap<Unit>> supportUnitsLeft, final Map<Unit, IntegerMap<Unit>> unitSupportMap, final Predicate<UnitSupportAttachment> ruleFilter) { int givenSupport = 0; for (final List<UnitSupportAttachment> bonusType : supportsAvailable) { final int bonusTypeCount = bonusType.get(0).getBonusType().getFirst(); int maxPerBonusType = bonusTypeCount >= 1 ? bonusTypeCount : Integer.MAX_VALUE; for (final UnitSupportAttachment rule : bonusType) { if (!ruleFilter.test(rule)) { continue; } final Set<UnitType> types = rule.getUnitType(); if (types != null && types.contains(unit.getType()) && supportLeft.getInt(rule) > 0) { <START> final int numSupportToApply = <END> Math.min( maxPerBonusType, Math.min(supportLeft.getInt(rule), supportUnitsLeft.get(rule).size())); for (int i = 0; i < numSupportToApply; i++) { givenSupport += rule.getBonus(); supportLeft.add(rule, -1); final Set<Unit> supporters = supportUnitsLeft.get(rule).keySet(); final Unit u = supporters.iterator().next(); supportUnitsLeft.get(rule).add(u, -1); if (supportUnitsLeft.get(rule).getInt(u) <= 0) { supportUnitsLeft.get(rule).removeKey(u); } unitSupportMap.computeIfAbsent(u, j -> new IntegerMap<>()).add(unit, rule.getBonus()); } maxPerBonusType -= numSupportToApply; if (maxPerBonusType <= 0) { break; } } } } return givenSupport; }</code><technical_language>Is this code covered existing tests? safe is update</technical_language>

Target:
private static int getSupport( final Unit unit, final Set<List<UnitSupportAttachment>> supportsAvailable, final IntegerMap<UnitSupportAttachment> supportLeft, final Map<UnitSupportAttachment, IntegerMap<Unit>> supportUnitsLeft, final Map<Unit, IntegerMap<Unit>> unitSupportMap, final Predicate<UnitSupportAttachment> ruleFilter) { int givenSupport = 0; for (final List<UnitSupportAttachment> bonusType : supportsAvailable) { int maxPerBonusType = bonusType.get(0).getBonusType().getCount(); for (final UnitSupportAttachment rule : bonusType) { if (!ruleFilter.test(rule)) { continue; } final Set<UnitType> types = rule.getUnitType(); if (types != null && types.contains(unit.getType()) && supportLeft.getInt(rule) > 0) { final int numSupportToApply = Math.min( maxPerBonusType, Math.min(supportLeft.getInt(rule), supportUnitsLeft.get(rule).size())); for (int i = 0; i < numSupportToApply; i++) { givenSupport += rule.getBonus(); supportLeft.add(rule, -1); final Set<Unit> supporters = supportUnitsLeft.get(rule).keySet(); final Unit u = supporters.iterator().next(); supportUnitsLeft.get(rule).add(u, -1); if (supportUnitsLeft.get(rule).getInt(u) <= 0) { supportUnitsLeft.get(rule).removeKey(u); } unitSupportMap.computeIfAbsent(u, j -> new IntegerMap<>()).add(unit, rule.getBonus()); } maxPerBonusType -= numSupportToApply; if (maxPerBonusType <= 0) { break; } } } } return givenSupport; }
Source:
<code>public <S extends T> Iterable<S> saveAll(Iterable<S> entities) { Assert.notNull(entities, "Cannot insert 'null' as a List."); Iterator<S> iterator = entities.iterator(); if (iterator.hasNext()) { S entity = iterator.next(); <START> operations.save(entities, getIndexCoordinates()); <END> operations.getIndexOperations(entity.getClass()).refresh(); } return entities; }</code><technical_language>returning List<T> save( ) investigate index coordinates? In some cases, folks repo.saveAll(() -> Stream.of( ).map( )) a proper iterable way</technical_language>

Target:
public <S extends T> Iterable<S> saveAll(Iterable<S> entities) { Assert.notNull(entities, "Cannot insert 'null' as a List."); IndexCoordinates indexCoordinates = getIndexCoordinates(); operations.save(entities, indexCoordinates); operations.indexOps(indexCoordinates).refresh(); return entities; }
Source:
<code>private Trigger postNewTriggerWithForm( @NonNull TriggeredCommandForm form, @NonNull Predicate predicate, @Nullable TriggerOptions options) throws ThingIFException { if (this.target == null) { throw new IllegalStateException("Can not perform this action before onboarding"); } if (form == null) { throw new IllegalArgumentException("form is null."); } <START> if (predicate == null) { <END> throw new IllegalArgumentException("predicate is null."); } Schema schema = this.getSchema(form.getSchemaName(), form.getSchemaVersion()); JSONObject requestBody = options != null ? JsonUtils.newJson(GsonRepository.gson().toJson(options)) : new JSONObject(); try { requestBody.put("triggersWhat", TriggersWhat.COMMAND.name()); requestBody.put("predicate", JsonUtils.newJson( GsonRepository.gson(schema).toJson(predicate))); JSONObject command = JsonUtils.newJson( GsonRepository.gson(schema).toJson(form)); command.put("issuer", this.owner.getTypedID()); if (form.getTargetID() == null) { command.put("target", this.target.getTypedID().toString()); } requestBody.put("command", command); } catch (JSONException e) { throw new RuntimeException(e); } return postNewTrigger(requestBody); }</code><technical_language>do need check nullable null parameter ? i is redundancy</technical_language>

Target:
private Trigger postNewTriggerWithForm( @NonNull TriggeredCommandForm form, @NonNull Predicate predicate, @Nullable TriggerOptions options) throws ThingIFException { if (this.target == null) { throw new IllegalStateException("Can not perform this action before onboarding"); } if (form == null) { throw new IllegalArgumentException("form is null."); } if (predicate == null) { throw new IllegalArgumentException("predicate is null."); } JSONObject requestBody = options != null ? JsonUtils.newJson(GsonRepository.gson().toJson(options)) : new JSONObject(); try { requestBody.put("triggersWhat", TriggersWhat.COMMAND.name()); requestBody.put("predicate", JsonUtils.newJson( GsonRepository.gson().toJson(predicate))); JSONObject command = JsonUtils.newJson( GsonRepository.gson( this.getSchema( form.getSchemaName(), form.getSchemaVersion())).toJson(form)); command.put("issuer", this.owner.getTypedID()); if (form.getTargetID() == null) { command.put("target", this.target.getTypedID().toString()); } requestBody.put("command", command); } catch (JSONException e) { throw new RuntimeException(e); } return postNewTrigger(requestBody); }
Source:
<code>public void completed(AbstractBuild r) { if (skipOnMatrixChildren(r)) { return; } String key = BuildKey.format(r); AbstractProject<?, ?> project = r.getProject(); AbstractBuild<?, ?> previousBuild = project.getLastBuild(); if (null != previousBuild) { do { previousBuild = previousBuild.getPreviousCompletedBuild(); <START> } while (null != previousBuild && previousBuild.getResult() == Result.ABORTED); <END> if (null != previousBuild) { log.info(key, "found #%d as previous completed, non-aborted build", previousBuild.getNumber()); } else { log.debug(key, "did not find previous completed, non-aborted build"); } NotificationConditions conditions = NotificationConditions.create(notifier, log); if (conditions.test(new Context(r, previousBuild))) { String message = getBuildStatusMessage(r, notifier.getIncludeTestSummary(), notifier.getIncludeFailedTests(), notifier.getIncludeCustomMessage()); if (notifier.getCommitInfoChoice().showAnything()) { message = message + "\n" + getCommitList(r); } slackFactory.apply(r).publish(message, getBuildColor(r)); } } }</code><technical_language>change this</technical_language>

Target:
public void completed(AbstractBuild r) { if (skipOnMatrixChildren(r)) { return; } String key = BuildKey.format(r); AbstractProject<?, ?> project = r.getProject(); AbstractBuild<?, ?> previousBuild = project.getLastBuild(); if (null != previousBuild) { do { previousBuild = previousBuild.getPreviousCompletedBuild(); } while ((null != previousBuild && previousBuild.getResult() == Result.ABORTED) || (null != previousBuild && previousBuild.getNumber() == r.getNumber())); if (null != previousBuild) { log.info(key, "found #%d as previous completed, non-aborted build", previousBuild.getNumber()); } else { log.debug(key, "did not find previous completed, non-aborted build"); } NotificationConditions conditions = NotificationConditions.create(notifier, log); if (conditions.test(new Context(r, previousBuild))) { String message = getBuildStatusMessage(r, notifier.getIncludeTestSummary(), notifier.getIncludeFailedTests(), notifier.getIncludeCustomMessage()); if (notifier.getCommitInfoChoice().showAnything()) { message = message + "\n" + getCommitList(r); } slackFactory.apply(r).publish(message, getBuildColor(r)); } } }
Source:
<code>protected void internalReceiveCommand(final String itemName, final Command command) { <START> if (this.logger.isDebugEnabled()) { <END> this.logger.debug("internalReceiveCommand({},{}) is called!", itemName, command); } ISYBindingConfig config = getBindingConfigByName(itemName); if (config != null) { processCommand(config, command); } else { this.logger.warn( "No configured Insteon address found for item [{}]", itemName); } }</code><technical_language>unneeded if clause</technical_language>

Target:
protected void internalReceiveCommand(final String itemName, final Command command) { this.logger.debug("internalReceiveCommand({},{}) is called!", itemName, command); ISYBindingConfig config = getBindingConfigByName(itemName); if (config != null) { processCommand(config, command); } else { this.logger.warn( "No configured Insteon address found for item [{}]", itemName); } }
Source:
<code>private static void watch(String path) { FileWatcher watcher; FileWatcherCallback callback = new FileWatcherCallback() { public void pathChanged(Type type, String changedPath) { System.out.printf("Change detected: %s / '%s'%n", type, changedPath); } }; if (Platform.current().isMacOs()) { watcher = createMacOsFileWatcher(path, callback); } else if (Platform.current().isWindows()) { watcher = createWindowsFileWatcher(path, callback); } else { throw new RuntimeException("Only Windows and macOS are supported for file watching"); } try { System.out.println("Waiting - type ctrl-d to exit ..."); while (true) { int ch = System.in.read(); if (ch < 0) { break; } } <START> watcher.close(); <END> } catch (Exception e) { throw new RuntimeException(e); } finally { try { watcher.close(); } catch (IOException e) { e.printStackTrace(); } } System.out.println("Done"); }</code><technical_language>close twice</technical_language>

Target:
private static void watch(String path) { FileWatcher watcher; FileWatcherCallback callback = new FileWatcherCallback() { public void pathChanged(Type type, String changedPath) { System.out.printf("Change detected: %s / '%s'%n", type, changedPath); } }; if (Platform.current().isMacOs()) { watcher = createMacOsFileWatcher(path, callback); } else if (Platform.current().isWindows()) { watcher = createWindowsFileWatcher(path, callback); } else { throw new RuntimeException("Only Windows and macOS are supported for file watching"); } try { System.out.println("Waiting - type ctrl-d to exit ..."); while (true) { int ch = System.in.read(); if (ch < 0) { break; } } } catch (Exception e) { throw new RuntimeException(e); } finally { try { watcher.close(); } catch (IOException e) { e.printStackTrace(); } } System.out.println("Done"); }
Source:
<code>public boolean canExecute() { <START> return true; <END> }</code><technical_language>Iterables.all(toolGroup.getTools(), Predicates.instanceof( AbstractToolDescription.class)); allow return false if items of type AbstractToolDescription</technical_language>

Target:
public boolean canExecute() { if (selection != null && selection.size() > 1) { for (EObject tool : selection) { if (!(tool instanceof AbstractToolDescription)) { return false; } } } return true; }