auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static Expression newDefaultExpression(AST ast, ITypeBinding type) { if (type.isPrimitive()) { String name= type.getName(); <START> if (null == name) { <END> return ast.newNumberLiteral("0"); } else switch (name) { case "boolean": return ast.newBooleanLiteral(false); case "void": return null; default: return ast.newNumberLiteral("0"); } } return ast.newNullLiteral(); }</code><technical_language>change to: boolean nomatch= false; if (name != null) switch (name) { .... default: nomatch= true; break; .... if (nomatch) { return ast.newNumberLiteral("0")... }</technical_language>

Target:
public static Expression newDefaultExpression(AST ast, ITypeBinding type) { if (type.isPrimitive()) { String name= type.getName(); boolean nomatch= false; if (name != null) switch (name) { case "boolean": return ast.newBooleanLiteral(false); case "void": return null; default: nomatch= true; break; } if (nomatch) { return ast.newNumberLiteral("0"); } } return ast.newNullLiteral(); }
Source:
<code>private boolean isAllowed(MutableHttpServletRequest request, String method) { String typeNameParam = "typeNames"; if (StringUtils.isEmpty(request.getParameterIgnoreCase(typeNameParam))) { <START> typeNameParam = "typeName"; <END> } return isAllowed(request, typeNameParam, method); }</code><technical_language>want check if reuse [enums](<LINK_0> here</technical_language>

Target:
private boolean isAllowed(MutableHttpServletRequest request, String method) { String typeNameParam = OgcEnum.EndPoint.TYPENAMES.toString(); if (StringUtils.isEmpty(request.getParameterIgnoreCase(typeNameParam))) { typeNameParam = OgcEnum.EndPoint.TYPENAME.toString(); } return isAllowed(request, typeNameParam, method); }
Source:
<code>protected NatEventData getNatEventData(final Object evaluationContext) { if (evaluationContext instanceof NatEventData) { return (NatEventData) evaluationContext; } NatEventData eventData = null; if (evaluationContext instanceof IEvaluationContext) { Object value = ((IEvaluationContext) evaluationContext).getVariable(MenuItemProviders.NAT_EVENT_DATA_KEY); if (value instanceof NatEventData) { eventData = (NatEventData) value; } } if (eventData == null) { Point cursorLocation = Display.getDefault().getCursorLocation(); Control control = null; final PapyrusMultiDiagramEditor activeEditor = ((PapyrusMultiDiagramEditor) <START> PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor()); <END> if(null != activeEditor){ final INattableModelManager nattableModelManager = activeEditor.getActiveEditor().getAdapter(INattableModelManager.class); if(null != nattableModelManager){ control = nattableModelManager.getAdapter(NatTable.class); } } if (control instanceof NatTable) { cursorLocation = control.toControl(cursorLocation); Event e = new Event(); e.x = cursorLocation.x; e.y = cursorLocation.y; e.display = Display.getDefault(); e.widget = control; MouseEvent event = new MouseEvent(e); eventData = NatEventData.createInstanceFromEvent(event); } } return eventData; }</code><technical_language>EditorHelper.getActiveEditor + manage ther case is PapyrusMultiDiagramEditor</technical_language>

Target:
protected NatEventData getNatEventData(final Object evaluationContext) { if (evaluationContext instanceof NatEventData) { return (NatEventData) evaluationContext; } NatEventData eventData = null; if (evaluationContext instanceof IEvaluationContext) { Object value = ((IEvaluationContext) evaluationContext).getVariable(MenuItemProviders.NAT_EVENT_DATA_KEY); if (value instanceof NatEventData) { eventData = (NatEventData) value; } } if (eventData == null) { Point cursorLocation = Display.getDefault().getCursorLocation(); Control control = null; final IEditorPart activeEditor = EditorHelper.getCurrentEditor(); if (null != activeEditor) { INattableModelManager nattableModelManager = null; if(activeEditor instanceof IMultiPageEditorPart && null != ((IMultiPageEditorPart)activeEditor).getActiveEditor()){ nattableModelManager = ((IMultiPageEditorPart)activeEditor).getActiveEditor().getAdapter(INattableModelManager.class); }else if(activeEditor instanceof IAdaptable){ nattableModelManager = ((IAdaptable)activeEditor).getAdapter(INattableModelManager.class); } if(null != nattableModelManager){ control = nattableModelManager.getAdapter(NatTable.class); } } if (control instanceof NatTable) { cursorLocation = control.toControl(cursorLocation); Event e = new Event(); e.x = cursorLocation.x; e.y = cursorLocation.y; e.display = Display.getDefault(); e.widget = control; MouseEvent event = new MouseEvent(e); eventData = NatEventData.createInstanceFromEvent(event); } } return eventData; }
Source:
<code>public boolean isNullable(VariableElement variableElement) { if (hasPrimaryKey()) { if (variableElement.equals(getPrimaryKey())) { String elementTypeCanonicalName = variableElement.asType().toString(); String columnType = Constants.JAVA_TO_COLUMN_TYPES.get(elementTypeCanonicalName); <START> if (columnType != null && columnType.equals("RealmFieldType.STRING")) { <END> return true; } else { return false; } } } return nullableFields.contains(variableElement); }</code><technical_language>is Strings keys allowed Null, a bit arbitrary me? nullable integers booleans</technical_language>

Target:
public boolean isNullable(VariableElement variableElement) { return nullableFields.contains(variableElement); }
Source:
<code>public synchronized void heartbeat() { List<alluxio.grpc.ClientMetrics> fsClientMetrics = new ArrayList<>(); String source = mConf.isSet(PropertyKey.USER_APP_ID) <START> ? mConf.get(PropertyKey.USER_APP_ID) : NetworkAddressUtils.getClientHostName(mConf); <END> List<alluxio.grpc.Metric> metrics = MetricsSystem.reportClientMetrics(); if (metrics.size() == 0) { return; } fsClientMetrics.add(ClientMetrics.newBuilder() .setSource(source) .addAllMetrics(metrics) .build()); try { mMasterClient.heartbeat(fsClientMetrics); } catch (IOException e) { SAMPLING_LOG.warn("Failed to send metrics to master: {}", e.toString()); } }</code><technical_language>Consider making this instance variable</technical_language>

Target:
public synchronized void heartbeat() { List<alluxio.grpc.ClientMetrics> fsClientMetrics = new ArrayList<>(); List<alluxio.grpc.Metric> metrics = MetricsSystem.reportClientMetrics(); if (metrics.size() == 0) { return; } fsClientMetrics.add(ClientMetrics.newBuilder() .setSource(mApplicationId) .addAllMetrics(metrics) .build()); try { mMasterClient.heartbeat(fsClientMetrics); } catch (IOException e) { SAMPLING_LOG.warn("Failed to send metrics to master: {}", e.toString()); } }
Source:
<code>public int getTankCapacity(int tank) { <START> return 0; <END> }</code><technical_language>Is this correct</technical_language>

Target:
public int getTankCapacity(int tank) { return BloodBottleIItem.AMOUNT * MULTIPLIER; }
Source:
<code>private Properties readConfig(String filename) { BufferedInputStream stream = null; File configFile = new File(filename); try { stream = new BufferedInputStream(new FileInputStream(configFile)); final Properties formatterOptions = new Properties(); formatterOptions.load(stream); return formatterOptions; } catch (IOException e) { String canonicalPath = null; try { canonicalPath = configFile.getCanonicalPath(); } catch(IOException e2) { canonicalPath = configFile.getAbsolutePath(); } String errorMessage; if (!configFile.exists() && !configFile.isAbsolute()) { errorMessage = Messages.bind(Messages.ConfigFileNotFoundErrorTryFullPath, new Object[] { canonicalPath, System.getProperty("user.dir") }); } else { errorMessage = Messages.bind(Messages.ConfigFileReadingError, canonicalPath); } System.err.println(errorMessage); <START> } finally { <END> if (stream != null) { try { stream.close(); } catch (IOException e) { } } } return null; }</code><technical_language>java 8 io try block try (BufferedInputStream stream = ...) { }</technical_language>

Target:
private Properties readConfig(String filename) { File configFile = new File(filename); try (BufferedInputStream stream = new BufferedInputStream(new FileInputStream(configFile))) { final Properties formatterOptions = new Properties(); formatterOptions.load(stream); return formatterOptions; } catch (IOException e) { String canonicalPath = null; try { canonicalPath = configFile.getCanonicalPath(); } catch(IOException e2) { canonicalPath = configFile.getAbsolutePath(); } String errorMessage; if (!configFile.exists() && !configFile.isAbsolute()) { errorMessage = Messages.bind(Messages.ConfigFileNotFoundErrorTryFullPath, new Object[] { canonicalPath, System.getProperty("user.dir") }); } else { errorMessage = Messages.bind(Messages.ConfigFileReadingError, canonicalPath); } System.err.println(errorMessage); } return null; }
Source:
<code>boolean validate(String optionValue) throws ValidationException { if (optionValue != null) { String[] requestTracingValues = optionValue.split("(?<=\\d)(?=\\D)|(?=\\d)(?<=\\D)"); if (requestTracingValues.length <= 2) { if (requestTracingValues[0].matches("\\d+") && (requestTracingValues.length == 2 && !requestTracingValues[1].matches("\\D+"))) { throw new ValidationException(MessageFormat.format( RuntimeOptions.commandlogstrings.getString("requestTracingIncorrect"), optionValue)); } if (requestTracingValues[0].matches("\\D+") && (requestTracingValues.length == 2)) { throw new ValidationException(MessageFormat.format( RuntimeOptions.commandlogstrings.getString("requestTracingIncorrect"), optionValue)); } } else { throw new ValidationException(MessageFormat.format( RuntimeOptions.commandlogstrings.getString("requestTracingIncorrect"), optionValue)); } <START> return true; <END> } return true; }</code><technical_language>this end in true (or exception) this needed</technical_language>

Target:
boolean validate(String optionValue) throws ValidationException { if (optionValue != null) { String[] requestTracingValues = optionValue.split("(?<=\\d)(?=\\D)|(?=\\d)(?<=\\D)"); if (requestTracingValues.length <= 2) { if (requestTracingValues[0].matches("\\d+") && (requestTracingValues.length == 2 && !requestTracingValues[1].matches("\\D+"))) { throw new ValidationException(MessageFormat.format( RuntimeOptions.commandlogstrings.getString("requestTracingIncorrect"), optionValue)); } if (requestTracingValues[0].matches("\\D+") && (requestTracingValues.length == 2)) { throw new ValidationException(MessageFormat.format( RuntimeOptions.commandlogstrings.getString("requestTracingIncorrect"), optionValue)); } } else { throw new ValidationException(MessageFormat.format( RuntimeOptions.commandlogstrings.getString("requestTracingIncorrect"), optionValue)); } } return true; }
Source:
<code>protected Rectangle getBox() { PrecisionRectangle rBox = null; Object figure = getFigure(); if (figure instanceof IRoundedRectangleFigure) { rBox = new PrecisionRectangle(((IRoundedRectangleFigure) ((IFigure) figure)).getRoundedRectangleBounds()); } else if (figure instanceof IFigure) { rBox = new PrecisionRectangle(getOwner().getBounds()); } <START> if (rBox != null) { <END> ((IFigure) figure).translateToAbsolute(rBox); return rBox.expand(offset.width, offset.height); } return null; }</code><technical_language>'null' operande</technical_language>

Target:
protected Rectangle getBox() { PrecisionRectangle rBox = null; Object figure = getFigure(); if (figure instanceof IRoundedRectangleFigure) { rBox = new PrecisionRectangle(((IRoundedRectangleFigure) ((IFigure) figure)).getRoundedRectangleBounds()); } else if (figure instanceof IFigure) { rBox = new PrecisionRectangle(getOwner().getBounds()); } if (null != rBox) { ((IFigure) figure).translateToAbsolute(rBox); rBox.expand(offset.width, offset.height); } return rBox; }
Source:
<code><START> public static void initializeOprofileModule() { <END> if (!isKernelModuleLoaded()) initializeOprofile(); if (!isKernelModuleLoaded()) { OprofileCorePlugin.showErrorDialog("oprofileInit", null); } else { initializeOprofileCore(); } }</code><technical_language>Is reason this needs public API ? If Oprofile class is loaded oprofile kernel module is loaded</technical_language>

Target:
private static void initializeOprofileModule() { if (!isKernelModuleLoaded()) initializeOprofile(); if (!isKernelModuleLoaded()) { OprofileCorePlugin.showErrorDialog("oprofileInit", null); } else { initializeOprofileCore(); } }
Source:
<code><START> private Mono<Integer> updateAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal) { <END> GenericExecuteSpec executeSpec = databaseClient.sql(UPDATE_AUTHORIZED_CLIENT_SQL); for (Entry<String, Parameter> entry : this.authorizedClientParametersMapper.apply(authorizedClient, principal) .entrySet()) { executeSpec = executeSpec.bind(entry.getKey(), entry.getValue()); } return executeSpec.fetch().rowsUpdated(); }</code><technical_language>move updateAuthorizedClient insertAuthorizedClient right saveAuthorizedClient</technical_language>

Target:
private Mono<Integer> updateAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal) { GenericExecuteSpec executeSpec = this.databaseClient.sql(UPDATE_AUTHORIZED_CLIENT_SQL); for (Entry<String, Parameter> entry : this.authorizedClientParametersMapper .apply(new OAuth2AuthorizedClientHolder(authorizedClient, principal)).entrySet()) { executeSpec = executeSpec.bind(entry.getKey(), entry.getValue()); } return executeSpec.fetch().rowsUpdated(); }
Source:
<code>public Integer getNextEntryNumber(final Integer studyId) { try { <START> final String queryString = "SELECT MAX(Convert(s.uniquename, SIGNED)) FROM stock s where s.project_id = :studyId"; <END> final SQLQuery query = this.getSession().createSQLQuery(queryString); query.setParameter("studyId", studyId); final BigInteger highestEntryNumber = (BigInteger) query.uniqueResult(); if(highestEntryNumber == null) { return 1; } else { return highestEntryNumber.intValue() + 1; } } catch (final HibernateException e) { final String errorMessage = "Error in getNextEntryNumber for studyId=" + studyId + StockDao.IN_STOCK_DAO + e.getMessage(); LOG.error(errorMessage, e); throw new MiddlewareQueryException(errorMessage, e); } }</code><technical_language>@mderamos clear IFNULL in query instead og a IF in java? sum + 1 in query SELECT IFNULL(MAX(Convert(s.uniquename, SIGNED)), 0) + 1 stock s s.project_id = :studyId</technical_language>

Target:
public Integer getNextEntryNumber(final Integer studyId) { try { final String queryString = "SELECT IFNULL(MAX(Convert(s.uniquename, SIGNED)), 0) + 1 FROM stock s where s.project_id = :studyId"; final SQLQuery query = this.getSession().createSQLQuery(queryString); query.setParameter("studyId", studyId); return ((BigInteger) query.uniqueResult()).intValue(); } catch (final HibernateException e) { final String errorMessage = "Error in getNextEntryNumber for studyId=" + studyId + StockDao.IN_STOCK_DAO + e.getMessage(); LOG.error(errorMessage, e); throw new MiddlewareQueryException(errorMessage, e); } }
Source:
<code>public Response addOrUpdateModelInfo( @PathParam("id") final Long modelId, @FormDataParam("modelInfo") final MLModelInfo modelInfo, @FormDataParam("pmmlFile") final InputStream pmmlInputStream, <START> @FormDataParam("pmmlFile") final FormDataContentDisposition fileDisposition) throws IOException { <END> if (pmmlInputStream == null) { throw BadRequestException.missingParameter("pmmlFile"); } try { MLModelInfo createdModelInfo = modelRegistryService.addOrUpdateModelInfo( modelId, modelInfo, pmmlInputStream, fileDisposition); return WSUtils.respondEntity(createdModelInfo, CREATED); } catch (Exception exception) { LOG.debug("Error occured while adding the pmml model", exception); throw exception; } finally { try { if (pmmlInputStream != null) { pmmlInputStream.close(); } } catch (IOException exception) { LOG.debug("Error while closing the pmml file stream", exception); throw exception; } } }</code><technical_language>@shahsank3t is this for</technical_language>

Target:
public Response addOrUpdateModelInfo( @PathParam("id") final Long modelId, @FormDataParam("modelInfo") final MLModelInfo modelInfo, @FormDataParam("pmmlFile") final InputStream pmmlInputStream, @FormDataParam("pmmlFile") final FormDataContentDisposition fileDisposition) throws IOException { if (pmmlInputStream == null) { throw BadRequestException.missingParameter("pmmlFile"); } try { MLModelInfo createdModelInfo = modelRegistryService.addOrUpdateModelInfo( modelId, modelInfo, pmmlInputStream, fileDisposition.getFileName()); return WSUtils.respondEntity(createdModelInfo, CREATED); } catch (Exception exception) { LOG.debug("Error occured while adding the pmml model", exception); throw exception; } finally { try { if (pmmlInputStream != null) { pmmlInputStream.close(); } } catch (IOException exception) { LOG.debug("Error while closing the pmml file stream", exception); throw exception; } } }
Source:
<code>protected void executeQueryCommand() { <START> Integer numOfVms = getDbFacade().getVdsGroupDao().getVmsCountByClusterId(getParameters().getId()); <END> getQueryReturnValue().setReturnValue(numOfVms); }</code><technical_language>integer int? i dont this return null</technical_language>

Target:
protected void executeQueryCommand() { int numOfVms = getDbFacade().getVdsGroupDao().getVmsCountByClusterId(getParameters().getId()); getQueryReturnValue().setReturnValue(numOfVms); }
Source:
<code>protected CheckoutCommand checkoutPaths() throws IOException, RefNotFoundException { RevWalk revWalk = new RevWalk(repo); DirCache dc = repo.lockDirCache(); try { DirCacheEditor editor = dc.editor(); TreeWalk startWalk = new TreeWalk(revWalk.getObjectReader()); startWalk.setRecursive(true); startWalk.setFilter(PathFilterGroup.createFromStrings(paths)); <START> boolean checkoutIndex = (startCommit == null && startPoint == null); <END> if (!checkoutIndex) { startWalk.addTree(revWalk.parseCommit(getStartPoint()) .getTree()); } else { startWalk.addTree(new DirCacheIterator(dc)); } final File workTree = repo.getWorkTree(); final ObjectReader r = repo.getObjectDatabase().newReader(); try { while (startWalk.next()) { final ObjectId blobId = startWalk.getObjectId(0); final FileMode mode = startWalk.getFileMode(0); editor.add(new PathEdit(startWalk.getPathString()) { public void apply(DirCacheEntry ent) { ent.setObjectId(blobId); ent.setFileMode(mode); try { DirCacheCheckout.checkoutEntry(repo, new File( workTree, ent.getPathString()), ent, r); } catch (IOException e) { throw new RuntimeException(e); } } }); } editor.commit(); } finally { startWalk.release(); r.release(); } } finally { dc.unlock(); revWalk.release(); } return this; }</code><technical_language>style nit: parentheses needed right side</technical_language>

Target:
protected CheckoutCommand checkoutPaths() throws IOException, RefNotFoundException { RevWalk revWalk = new RevWalk(repo); DirCache dc = repo.lockDirCache(); try { DirCacheEditor editor = dc.editor(); TreeWalk startWalk = new TreeWalk(revWalk.getObjectReader()); startWalk.setRecursive(true); startWalk.setFilter(PathFilterGroup.createFromStrings(paths)); boolean checkoutIndex = startCommit == null && startPoint == null; if (!checkoutIndex) startWalk.addTree(revWalk.parseCommit(getStartPoint()) .getTree()); else startWalk.addTree(new DirCacheIterator(dc)); final File workTree = repo.getWorkTree(); final ObjectReader r = repo.getObjectDatabase().newReader(); try { while (startWalk.next()) { final ObjectId blobId = startWalk.getObjectId(0); final FileMode mode = startWalk.getFileMode(0); editor.add(new PathEdit(startWalk.getPathString()) { public void apply(DirCacheEntry ent) { ent.setObjectId(blobId); ent.setFileMode(mode); try { DirCacheCheckout.checkoutEntry(repo, new File( workTree, ent.getPathString()), ent, r); } catch (IOException e) { throw new JGitInternalException( MessageFormat.format( JGitText.get().checkoutConflictWithFile, ent.getPathString()), e); } } }); } editor.commit(); } finally { startWalk.release(); r.release(); } } finally { dc.unlock(); revWalk.release(); } return this; }
Source:
<code>public void setEncoding(Encoding encoding) throws IOException { <START> if (encodingWriter != null) { <END> encodingWriter.close(); } this.encoding = encoding; OutputStream interceptor = new FilterOutputStream(pg_output) { @Override public void flush() throws IOException { } @Override public void close() throws IOException { super.flush(); } }; encodingWriter = encoding.getEncodingWriter(interceptor); }</code><technical_language>If want correct style, please send another PR for that? is hard identify changes required for unixsocket support</technical_language>

Target:
public void setEncoding(Encoding encoding) throws IOException { if (encodingWriter != null) encodingWriter.close(); this.encoding = encoding; OutputStream interceptor = new FilterOutputStream(pg_output) { public void flush() throws IOException { } public void close() throws IOException { super.flush(); } }; encodingWriter = encoding.getEncodingWriter(interceptor); }
Source:
<code>protected void index() { List<WorkQueueDescriptor> descriptors = getDescriptors(QUEUES_EP); descriptors.forEach(d -> d.categories.forEach(c -> { categoryToQueueId.computeIfPresent(c, (k, v) -> { if (!v.equals(d.getId())) { log.error("Work category '{}' cannot be assigned to work queue '%s'" <START> + " because it is already assigned to work queue '%s'", c, d.getId(), v); <END> } return v; }); categoryToQueueId.putIfAbsent(c, d.getId()); })); }</code><technical_language>%s</technical_language>

Target:
protected void index() { List<WorkQueueDescriptor> descriptors = getDescriptors(QUEUES_EP); descriptors.forEach(d -> d.categories.forEach(c -> { categoryToQueueId.computeIfPresent(c, (k, v) -> { if (!v.equals(d.getId())) { log.error("Work category '{}' cannot be assigned to work queue '{}'" + " because it is already assigned to work queue '{}'", c, d.getId(), v); } return v; }); categoryToQueueId.putIfAbsent(c, d.getId()); })); }
Source:
<code>public static Iterator iteratorFrom( Object iterable ) { if ( iterable instanceof Iterable ) { return ((Iterable) iterable).iterator(); } else if ( iterable instanceof PrimitiveEntityStream ) { return ((PrimitiveEntityStream) iterable).iterator(); } else if ( iterable instanceof Long) { return (LongStream.of((Long) iterable)).iterator(); } else if ( iterable instanceof LongStream ) { return ((LongStream) iterable).iterator(); } else if ( iterable instanceof Double) { return (DoubleStream.of((Double) iterable)).iterator(); } else if ( iterable instanceof DoubleStream ) { return ((DoubleStream) iterable).iterator(); } else if ( iterable instanceof Integer) { return (IntStream.of((Integer) iterable)).iterator(); } else if ( iterable instanceof IntStream ) { return ((IntStream) iterable).iterator(); } else if ( iterable == null ) { return Collections.emptyIterator(); } else if ( iterable instanceof String ) { <START> String[] singleStringArray = {(String) iterable}; <END> return getIterator( singleStringArray, 1 ); } else if ( iterable.getClass().isArray() ) { int len = Array.getLength( iterable ); return getIterator( iterable, len ); } else { throw new CypherTypeException( "Don't know how to create an iterator out of " + iterable.getClass().getSimpleName(), null ); } }</code><technical_language>Stream.of( iterable ).iterator()</technical_language>

Target:
public static Iterator iteratorFrom( Object iterable ) { if ( iterable instanceof Iterable ) { return ((Iterable) iterable).iterator(); } else if ( iterable instanceof PrimitiveEntityStream ) { return ((PrimitiveEntityStream) iterable).iterator(); } else if ( iterable instanceof LongStream ) { return ((LongStream) iterable).iterator(); } else if ( iterable instanceof DoubleStream ) { return ((DoubleStream) iterable).iterator(); } else if ( iterable instanceof IntStream ) { return ((IntStream) iterable).iterator(); } else if ( iterable == null ) { return Collections.emptyIterator(); } else if ( iterable.getClass().isArray() ) { int len = Array.getLength( iterable ); return new Iterator() { private int position = 0; @Override public boolean hasNext() { return position < len; } @Override public Object next() { if ( position >= len ) { throw new NoSuchElementException(); } return Array.get( iterable, position++ ); } }; } else { return Stream.of(iterable).iterator(); } }
Source:
<code>public void testCorrect() { Set<String> previousNames = new HashSet<String>(); int i = 0; for (String each : wrongNames) { String name = NameUtil.correct(each, i++, previousNames); <START> Assert.assertTrue("too many underline", countUnderLine(name) <= (name.length() / 2)); <END> previousNames.add(name); } Assert.assertEquals("after the correct, we miss some one or create a duplicated one, please check the NameUtil class", wrongNames.length, previousNames.size()); }</code><technical_language>I understand this check special characters replaced</technical_language>

Target:
public void testCorrect() { Set<String> resultNames = new HashSet<String>(); int i = 0; Set<String> expectedSet = new HashSet<>(); expectedSet.addAll(Arrays.asList(expectedNames)); for (String each : wrongNames) { String name = NameUtil.correct(each, i++, resultNames); resultNames.add(name); } Assert.assertEquals(expectedSet, resultNames); }
Source:
<code>public void executeRule() { try { testRulesPath.resetIterator(); File[] ruleFiles = rulesPath.getNextRule(); File[] ruleTestFiles = findMatchingTestFile(ruleFiles[0], ruleFiles[1]); <START> Assert.assertNotNull("No test file found", ruleTestFiles); <END> LOG.info(String.format("Testing execution of rule %s%n", ruleFiles[0].getName())); visit(ruleTestFiles[0], ruleTestFiles[1]); } catch(AssertionError ae) { LOG.error(ae.getMessage()); throw ae; } }</code><technical_language>is this check done in <LINK_0> a test for a rules file</technical_language>

Target:
public void executeRule() { try { testRulesPath.resetIterator(); File[] ruleFiles = rulesPath.getNextRule(); File[] ruleTestFiles = findMatchingTestFile(ruleFiles[0], ruleFiles[1]); Assert.assertNotNull("No test file matching rule", ruleTestFiles); LOG.info(String.format("Testing execution of rule %s%n", ruleFiles[0].getName())); visit(ruleTestFiles[0], ruleTestFiles[1]); } catch(AssertionError ae) { LOG.error(ae.getMessage()); throw ae; } }
Source:
<code>public boolean validate(URL definitionUrl) { boolean isValid = false; try { String definitionContent = IOUtils.toString(definitionUrl.openStream()); isValid = validate(definitionContent); } catch (IOException e) { log.error("Error in reading content in the definition URL: " + definitionUrl, e); <START> } <END> return isValid; }</code><technical_language>capturing logging this, throw a ValidationException</technical_language>

Target:
public boolean validate(URL definitionUrl) throws DefinitionValidationException { boolean isValid; try { String definitionContent = IOUtils.toString(definitionUrl.openStream()); isValid = validate(definitionContent); } catch (IOException e) { throw new DefinitionValidationException("Error in reading content in the definition URL: " + definitionUrl, e); } return isValid; }
Source:
<code>public static void main(String[] args) { final Display display = new Display(); Realm.runWithDefault(DisplayRealm.getRealm(display), () -> { Shell shell = new Shell(display); shell.setText("ISideEffect & AggregateValidationStatus"); shell.setLayout(new <START> GridLayout(2, <END> false)); new Label(shell, SWT.NONE).setText("Enter '5' to be valid:"); Text text = new Text(shell, SWT.BORDER); WritableValue<String> value = new WritableValue<>(); Button okButton = new Button(shell, SWT.BORDER); okButton.setText("Ok"); GridDataFactory.swtDefaults().hint(200, SWT.DEFAULT).applyTo(okButton); DataBindingContext dbc = new DataBindingContext(); dbc.bindValue(WidgetProperties.text(SWT.Modify).observe(text), value, new UpdateValueStrategy().setAfterConvertValidator(textValue -> ("5".equals(textValue)) ? Status.OK_STATUS : ValidationStatus.error("The value was '" + value + "', not '5'")), null); AggregateValidationStatus validationStatus = new AggregateValidationStatus(dbc.getBindings(), AggregateValidationStatus.MAX_SEVERITY); ISideEffect okButtonEnablement = ISideEffect.create(() -> validationStatus.getValue().isOK(), okButton::setEnabled); shell.addDisposeListener(e -> { dbc.dispose(); okButtonEnablement.dispose(); }); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } }); display.dispose(); }</code><technical_language>Delete attachment of a gridlayout here. (see below)</technical_language>

Target:
public static void main(String[] args) { final Display display = new Display(); Realm.runWithDefault(DisplayRealm.getRealm(display), () -> run(display)); display.dispose(); }
Source:
<code>private String getTypeName(Tree tree) { Type type = ((AbstractTypedTree) tree).getSymbolType(); <START> TypeSymbol symbol = type.getSymbol(); <END> String name = symbol.getName(); if (name.isEmpty()) { name = getAnonymousClassTypeName(symbol); } return name; }</code><technical_language>allow reuse I split this a method a name TypeSymbol</technical_language>

Target:
private String getTypeName(Tree tree) { Type type = ((AbstractTypedTree) tree).getSymbolType(); String name = getTypeName(type); if (name.isEmpty()) { name = getAnonymousClassTypeName(type.getSymbol()); } return name; }
Source:
<code>public void invokeShrApplication() { SmartCardController smartCardController = ((MuzimaApplication) getApplicationContext()).getSmartCardController(); SmartCardRecord smartCardRecord = null; try { <START> smartCardRecord = smartCardController.getSmartCardRecordByPersonUuid(patient.getUuid()); <END> } catch (SmartCardController.SmartCardRecordFetchException e) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setCancelable(true) .setMessage("Could not obtain smartcard record for writing to card. " + e.getMessage()) .show(); Log.e("TAG", "Could not obtain smartcard record for writing to card", e); } if (smartCardRecord != null) { SmartCardIntentIntegrator shrIntegrator = new SmartCardIntentIntegrator(this); try { shrIntegrator.initiateCardWrite(smartCardRecord.getPlainPayload()); } catch (IOException e) { Log.e("TAG", "Could not write to card", e); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setCancelable(true) .setMessage("Could not write to card. " + e.getMessage()) .show(); } Toast.makeText(getApplicationContext(), "Opening Card Reader", Toast.LENGTH_LONG).show(); } }</code><technical_language>function getSmartCardRecordByPatientUuid instead of getSmartCardRecordByPersonUuid</technical_language>

Target:
public void invokeShrApplication() { SmartCardController smartCardController = ((MuzimaApplication) getApplicationContext()).getSmartCardController(); SmartCardRecord smartCardRecord = null; try { smartCardRecord = smartCardController.getSmartCardRecordByPersonUuid(patient.getUuid()); } catch (SmartCardController.SmartCardRecordFetchException e) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setCancelable(true) .setMessage(getString(R.string.failure_obtain_smartcard_record) + e.getMessage()) .show(); Log.e("TAG", "Could not obtain smartcard record for writing to card", e); } if (smartCardRecord != null) { SmartCardIntentIntegrator shrIntegrator = new SmartCardIntentIntegrator(this); try { shrIntegrator.initiateCardWrite(smartCardRecord.getPlainPayload()); } catch (IOException e) { Log.e("TAG", "Could not write to card", e); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setCancelable(true) .setMessage("Could not write to card. " + e.getMessage()) .show(); } Toast.makeText(getApplicationContext(), "Opening Card Reader", Toast.LENGTH_LONG).show(); } }
Source:
<code>private void render(final DomainObject domainObject, final Command callback) { <START> if (null != renderer) { <END> getGraphUUID().ifPresent(graphUUID -> renderer.render(graphUUID, domainObject, callback)); } }</code><technical_language>noticed !Objects.isNull(var), null != var var != null. a big deal, I need change in this PR, in future I choose one.. Personally, I Objects.isNull(var) ;-)</technical_language>

Target:
private void render(final DomainObject domainObject, final Command callback) { if (!Objects.isNull(renderer)) { getGraphUUID().ifPresent(graphUUID -> renderer.render(graphUUID, domainObject, callback)); } }
Source:
<code>public void testSendSerialDataAsync802IOError() throws XBeeException, IOException { Mockito.when(xbeeDevice.getXBeeProtocol()).thenReturn(XBeeProtocol.RAW_802_15_4); Mockito.doThrow(new IOException()).when(xbeeDevice).sendXBeePacketAsync(tx16Packet); Mockito.doThrow(new IOException()).when(xbeeDevice).sendXBeePacketAsync(tx64Packet); try { xbeeDevice.sendSerialDataAsync(XBEE_16BIT_ADDRESS, SEND_DATA_BYTES); fail("Tx16 frame shouldn't have been sent successfully."); } catch (Exception e) { <START> assertEquals(XBeeException.class, e.getClass()); <END> } try { xbeeDevice.sendSerialDataAsync(XBEE_64BIT_ADDRESS, SEND_DATA_BYTES); fail("Tx64 frame shouldn't have been sent successfully."); } catch (Exception e) { assertEquals(XBeeException.class, e.getClass()); } try { xbeeDevice.sendSerialDataAsync(mockedDevice, SEND_DATA_BYTES); fail("Tx64 frame shouldn't have been sent successfully."); } catch (Exception e) { assertEquals(XBeeException.class, e.getClass()); } }</code><technical_language>verify other kind of message failed of I/O? java e.getCause()</technical_language>

Target:
public void testSendSerialDataAsync802IOError() throws XBeeException, IOException { Mockito.when(xbeeDevice.getXBeeProtocol()).thenReturn(XBeeProtocol.RAW_802_15_4); Mockito.doThrow(new IOException()).when(xbeeDevice).sendXBeePacketAsync(tx16Packet); Mockito.doThrow(new IOException()).when(xbeeDevice).sendXBeePacketAsync(tx64Packet); try { xbeeDevice.sendSerialDataAsync(XBEE_16BIT_ADDRESS, SEND_DATA_BYTES); fail("Tx16 frame shouldn't have been sent successfully."); } catch (Exception e) { assertEquals(XBeeException.class, e.getClass()); assertEquals(IOException.class, e.getCause().getClass()); } try { xbeeDevice.sendSerialDataAsync(XBEE_64BIT_ADDRESS, SEND_DATA_BYTES); fail("Tx64 frame shouldn't have been sent successfully."); } catch (Exception e) { assertEquals(XBeeException.class, e.getClass()); assertEquals(IOException.class, e.getCause().getClass()); } try { xbeeDevice.sendSerialDataAsync(mockedDevice, SEND_DATA_BYTES); fail("Tx64 frame shouldn't have been sent successfully."); } catch (Exception e) { assertEquals(XBeeException.class, e.getClass()); assertEquals(IOException.class, e.getCause().getClass()); } }
Source:
<code>public DataStoreTransaction beginTransaction() { <START> if (queryEngine == null) { <END> queryEngine = queryEngineFactory.buildQueryEngine(dictionary); } return new AggregationDataStoreTransaction(queryEngine); }</code><technical_language>Instead of this in transaction - do this in populateEntityDictionary</technical_language>

Target:
public DataStoreTransaction beginTransaction() { return new AggregationDataStoreTransaction(queryEngine); }
Source:
<code>public void verifyHttps() throws Exception { <START> log.info("==========================================================="); <END> BrooklynWebServer webServer = buildWebServer(); DefaultHttpClient httpclient = buildHttpsClient(webServer); HttpGet httpget = new HttpGet(webServer.getRootUrl()); System.out.println(httpget); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); InputStream instream = entity.getContent(); log.info("==========================================================="); }</code><technical_language>I log lines useful long-term. If log message "===== Starting verifyHttps test =====" more helpful, console output in jenkins etc</technical_language>

Target:
public void verifyHttps() throws Exception { BrooklynWebServer webServer = buildWebServer(); DefaultHttpClient httpclient = buildHttpsClient(webServer); HttpGet httpget = new HttpGet(webServer.getRootUrl()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); InputStream instream = entity.getContent(); }
Source:
<code>public void or_emptyGroupThrows() { populateTestRealm(); <START> RealmResults<AllTypes> fives = realm.where(AllTypes.class) <END> .equalTo(AllTypes.FIELD_LONG, 5) .or() .beginGroup() .endGroup() .findAll(); }</code><technical_language>this pattern, is difficult guess line throws exception. try capture explicit call in a try/catch. This means @Test( ....) pattern is a bad idea</technical_language>

Target:
public void or_emptyGroupThrows() { populateTestRealm(); RealmQuery<AllTypes> query = realm.where(AllTypes.class) .equalTo(AllTypes.FIELD_LONG, 5) .or() .beginGroup() .endGroup(); try { query.findAll(); } catch (UnsupportedOperationException ignore) { } }
Source:
<code>public static void main(String[] args) throws Exception { String snapshotFile = null; boolean dumpData = false; boolean dumpJson = false; int i; for (i = 0; i < args.length; i++) { if (args[i].equals("-d")) { dumpData = true; } else if (args[i].equals("-json")) { dumpJson = true; <START> } else { <END> snapshotFile = args[i]; i++; break; } } if (args.length != i || snapshotFile == null) { System.err.println("USAGE: SnapshotFormatter [-d] snapshot_file"); System.err.println(" -d dump the data for each znode"); System.err.println(" -json dump znode info in json format"); System.exit(ExitCode.INVALID_INVOCATION.getValue()); } new SnapshotFormatter().run(snapshotFile, dumpData, dumpJson); }</code><technical_language>d -json option, print a mix of dump data json data. Is this intended</technical_language>

Target:
public static void main(String[] args) throws Exception { String snapshotFile = null; boolean dumpData = false; boolean dumpJson = false; int i; for (i = 0; i < args.length; i++) { if (args[i].equals("-d")) { dumpData = true; } else if (args[i].equals("-json")) { dumpJson = true; } else { snapshotFile = args[i]; i++; break; } } if (args.length != i || snapshotFile == null) { System.err.println("USAGE: SnapshotFormatter [-d|-json] snapshot_file"); System.err.println(" -d dump the data for each znode"); System.err.println(" -json dump znode info in json format"); System.exit(ExitCode.INVALID_INVOCATION.getValue()); } if (dumpData && dumpJson) { System.err.println("Cannot specify both data dump (-d) and json mode (-json) in same call"); System.exit(ExitCode.INVALID_INVOCATION.getValue()); } new SnapshotFormatter().run(snapshotFile, dumpData, dumpJson); }
Source:
<code>public void throwsIfNoMoreElement() throws Exception { final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple(HTTP_OK, "[{\"body\":\"hi jeff\"}]") ).start(); final Request request = new ApacheRequest(container.home()); final GhPagination<JsonObject> page = new GhPagination<JsonObject>( request, new GhPagination.Mapping<JsonObject>() { @Override public JsonObject map(final JsonObject object) { return object; } } ); <START> final Iterator<JsonObject> iterator = page.iterator(); <END> MatcherAssert.assertThat( iterator.next().toString(), Matchers.notNullValue() ); MatcherAssert.assertThat( iterator.next(), Matchers.notNullValue() ); container.stop(); }</code><technical_language>replace lines with: Iterables.get(page, 2);</technical_language>

Target:
public void throwsIfNoMoreElement() throws Exception { final MkContainer container = new MkGrizzlyContainer() .next(simple("Hi there")).start(); try { final Request request = new ApacheRequest(container.home()); final GhPagination<JsonObject> page = new GhPagination<JsonObject>( request, new GhPagination.Mapping<JsonObject>() { @Override public JsonObject map(final JsonObject object) { return object; } } ); final Iterator<JsonObject> iterator = page.iterator(); iterator.next(); MatcherAssert.assertThat( iterator.next(), Matchers.notNullValue() ); } finally { container.stop(); } }
Source:
<code>public void setUp() throws Exception { Properties props = new Properties(); <START> java.io.File f = new java.io.File(System.getProperty("user.home"), ".github"); <END> if (f.exists()) { FileInputStream in = new FileInputStream(f); try { props.load(in); gitHub = GitHub.connect(props.getProperty("login"),props.getProperty("oauth")); } finally { IOUtils.closeQuietly(in); } } else { gitHub = GitHub.connect(); } }</code><technical_language>GitHub.connect() for ~/.github, I need original line</technical_language>

Target:
public void setUp() throws Exception { Properties props = new Properties(); java.io.File f = new java.io.File(System.getProperty("user.home"), ".github.kohsuke2"); if (f.exists()) { FileInputStream in = new FileInputStream(f); try { props.load(in); gitHub = GitHub.connect(props.getProperty("login"),props.getProperty("oauth")); } finally { IOUtils.closeQuietly(in); } } else { gitHub = GitHub.connect(); } }
Source:
<code>private StoragePool mockStoragePool() { <START> StoragePool storage_pool = new StoragePool(); <END> storage_pool.setstatus(StoragePoolStatus.Up); return storage_pool; }</code><technical_language>change variable name</technical_language>

Target:
private StoragePool mockStoragePool() { StoragePool storagePool = new StoragePool(); storagePool.setstatus(StoragePoolStatus.Up); return storagePool; }
Source:
<code>private Properties augment(Properties origin) { Properties target = new Properties(); for (Entry<Object, Object> entry : origin.entrySet()) { Object key = entry.getKey(); if (key instanceof String && !key.toString().startsWith(HSEARCH_PREFIX)) { key = HSEARCH_PREFIX + key.toString(); } target.put(key, entry.getValue()); boolean hasAffinity = false; if (key.toString().endsWith(INDEX_MANAGER_IMPL_NAME) && entry.getValue().equals(AffinityIndexManager.class.getName())) { target.put(key.toString().replace(INDEX_MANAGER_IMPL_NAME, SHARDING_STRATEGY), AffinityShardIdentifierProvider.class.getName()); hasAffinity = true; } <START> if (hasAffinity) { <END> Object errorHandler = target.get(Environment.ERROR_HANDLER); if (errorHandler == null) { target.put(Environment.ERROR_HANDLER, new AffinityErrorHandler()); } else { target.put(Environment.ERROR_HANDLER, new AffinityErrorHandler(createErrorHandler(errorHandler))); } } } return target; }</code><technical_language>this else for previous if remove hasAffinity</technical_language>

Target:
private Properties augment(Properties origin) { Properties target = new Properties(); boolean hasAffinity = false; for (Entry<Object, Object> entry : origin.entrySet()) { Object key = entry.getKey(); if (key instanceof String && !key.toString().startsWith(HSEARCH_PREFIX)) { key = HSEARCH_PREFIX + key.toString(); } target.put(key, entry.getValue()); if (key.toString().endsWith(INDEX_MANAGER_IMPL_NAME) && entry.getValue().equals(AffinityIndexManager.class.getName())) { target.put(key.toString().replace(INDEX_MANAGER_IMPL_NAME, SHARDING_STRATEGY), AffinityShardIdentifierProvider.class.getName()); hasAffinity = true; } } configureErrorHandler(target, hasAffinity); return target; }
Source:
<code>public RequestStarter(NodeClientCore node, BaseRequestThrottle throttle, String name, TokenBucket outputBucket, TokenBucket inputBucket, RunningAverage averageOutputBytesPerRequest, RunningAverage averageInputBytesPerRequest, boolean isInsert, boolean isSSK, boolean realTime) { this.core = node; this.stats = core.nodeStats; this.throttle = throttle; this.name = name + (realTime ? " (realtime)" : " (bulk)"); this.outputBucket = outputBucket; this.inputBucket = inputBucket; this.averageOutputBytesPerRequest = averageOutputBytesPerRequest; this.averageInputBytesPerRequest = averageInputBytesPerRequest; this.isInsert = isInsert; this.isSSK = isSSK; this.realTime = realTime; this.lastDelay = 4000; this.ALCHEMY_DELAY_WEIGHT = 24; this.LAST_DEALY_WEIGHT = 75; this.TOADS_DELAY_WEIGHT = 1; this.MIN_ALCHEMY_DELAY = 5; <START> this.MAX_ALCHEMY_DELAY = 500; END> }</code><technical_language>fundamentally risky / break, fixing obvious problem is reasonable</technical_language>

Target:
public RequestStarter(NodeClientCore node, BaseRequestThrottle throttle, String name, TokenBucket outputBucket, TokenBucket inputBucket, RunningAverage averageOutputBytesPerRequest, RunningAverage averageInputBytesPerRequest, boolean isInsert, boolean isSSK, boolean realTime) { this.core = node; this.stats = core.nodeStats; this.throttle = throttle; this.name = name + (realTime ? " (realtime)" : " (bulk)"); this.outputBucket = outputBucket; this.inputBucket = inputBucket; this.averageOutputBytesPerRequest = averageOutputBytesPerRequest; this.averageInputBytesPerRequest = averageInputBytesPerRequest; this.isInsert = isInsert; this.isSSK = isSSK; this.realTime = realTime; this.lastDelay = 4000; }
Source:
<code>private <START> Repository getRepository(ExecutionEvent <END> event) throws ExecutionException { PlatformObject firstElement; IStructuredSelection selection = (IStructuredSelection) HandlerUtil .getCurrentSelection(event); if (selection.getFirstElement() instanceof PlotCommit) { IWorkbenchPart ap = HandlerUtil.getActivePartChecked(event); if (ap instanceof IHistoryView) { firstElement = (PlatformObject) ((IHistoryView) ap) .getHistoryPage().getInput(); } else { return null; } } else { firstElement = (PlatformObject) selection.getFirstElement(); } return Utils.getAdapter(firstElement, Repository.class); }</code><technical_language>mark return @Nullable null analysis detect NPEs compile time</technical_language>

Target:
private @Nullable Repository getRepository(ExecutionEvent event) throws ExecutionException { PlatformObject firstElement; IStructuredSelection selection = (IStructuredSelection) HandlerUtil .getCurrentSelection(event); if (selection.getFirstElement() instanceof PlotCommit) { IWorkbenchPart ap = HandlerUtil.getActivePartChecked(event); if (ap instanceof IHistoryView) { firstElement = (PlatformObject) ((IHistoryView) ap) .getHistoryPage().getInput(); } else { return null; } } else { firstElement = (PlatformObject) selection.getFirstElement(); } return Utils.getAdapter(firstElement, Repository.class); }
Source:
<code>public Iterator<Object> iterator() { Collection beanDefs = IOC.getBeanManager().lookupBeans(type, qualifiers); if(beanDefs==null){ return Collections.emptyList().iterator(); } <START> return beanDefs.iterator(); <END> }</code><technical_language>This line returns Iterator<SyncBeanDef>, want is iterator of instances (i.e. Iterator<T>)</technical_language>

Target:
public Iterator<Object> iterator() { Collection<SyncBeanDef> beanDefs = IOC.getBeanManager().lookupBeans( type, qualifiers ); if(beanDefs==null){ return Collections.emptyList().iterator(); } return new InstanceImplIterator(beanDefs); }