auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean isValueInReferenceSet(String value, int referenceSetID, int correlationTypeID) throws EamDbException{ Connection conn = connect(); Long matchingInstances = 0L; PreparedStatement preparedStatement = null; ResultSet resultSet = null; String sql = "SELECT count(*) FROM %s WHERE value=? AND reference_set_id=?"; String fileTableName = EamDbUtil.correlationTypeToReferenceTableName(getCorrelationTypeById(correlationTypeID)); try { preparedStatement = conn.prepareStatement(String.format(sql, fileTableName)); preparedStatement.setString(1, value); preparedStatement.setInt(2, referenceSetID); resultSet = preparedStatement.executeQuery(); resultSet.next(); matchingInstances = resultSet.getLong(1); } catch (SQLException ex) { <START> throw new EamDbException("Error determining if file is in reference set.", ex); END> } finally { EamDbUtil.closePreparedStatement(preparedStatement); EamDbUtil.closeResultSet(resultSet); EamDbUtil.closeConnection(conn); } return 0 < matchingInstances; }</code><technical_language>I debugging if include some identification of reference set experienced error condition in error message. Also, file => value</technical_language>

Target:
public boolean isValueInReferenceSet(String value, int referenceSetID, int correlationTypeID) throws EamDbException{ Connection conn = connect(); Long matchingInstances = 0L; PreparedStatement preparedStatement = null; ResultSet resultSet = null; String sql = "SELECT count(*) FROM %s WHERE value=? AND reference_set_id=?"; String fileTableName = EamDbUtil.correlationTypeToReferenceTableName(getCorrelationTypeById(correlationTypeID)); try { preparedStatement = conn.prepareStatement(String.format(sql, fileTableName)); preparedStatement.setString(1, value); preparedStatement.setInt(2, referenceSetID); resultSet = preparedStatement.executeQuery(); resultSet.next(); matchingInstances = resultSet.getLong(1); } catch (SQLException ex) { throw new EamDbException("Error determining if value (" + value + ") is in reference set " + referenceSetID, ex); } finally { EamDbUtil.closePreparedStatement(preparedStatement); EamDbUtil.closeResultSet(resultSet); EamDbUtil.closeConnection(conn); } return 0 < matchingInstances; }
Source:
<code>public void testGetJobTasksIdsPaginated() throws Throwable { int nbTasks = 50; String jobIdStr = "1"; JobState job = newMockedJob(jobIdStr, nbTasks); when(mockOfScheduler.getJobState(jobIdStr)).thenReturn(job); List<String> res = restInterface.getJobTasksIdsPaginated(sessionId, jobIdStr, 0, nbTasks); assertEquals("Number of tasks is incorrect", nbTasks, res.size()); <START> for (int i = 0; i < nbTasks; i++) { <END> assertEquals("Task readable name is incorrect", generateReadableName(jobIdStr, i, nbTasks), res.get(i)); } }</code><technical_language>Assertion factorized avoid code duplication</technical_language>

Target:
public void testGetJobTasksIdsPaginated() throws Throwable { int nbTasks = 50; String jobIdStr = "1"; JobState job = newMockedJob(jobIdStr, nbTasks); when(mockOfScheduler.getJobState(jobIdStr)).thenReturn(job); TaskIdsPage page = restInterface.getTasksNamesPaginated(sessionId, jobIdStr, 0, nbTasks); assertTasks(nbTasks, jobIdStr, page); }
Source:
<code>public ClientStats getClientStats() { <START> Map<String, Long> totalConnectionsPerHost = openChannels.stream().map(Channel::remoteAddress).filter(Objects::nonNull).filter(a -> a.getClass() == InetSocketAddress.class) <END> .map(a -> (InetSocketAddress) a).map(InetSocketAddress::getHostString).collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); Map<String, Long> idleConnectionsPerHost = channelPool.getIdleChannelCountPerHost(); Map<String, HostStats> statsPerHost = totalConnectionsPerHost.entrySet().stream().collect(Collectors.toMap(Entry::getKey, entry -> { final long totalConnectionCount = entry.getValue(); final long idleConnectionCount = idleConnectionsPerHost.getOrDefault(entry.getKey(), 0L); final long activeConnectionCount = totalConnectionCount - idleConnectionCount; return new HostStats(activeConnectionCount, idleConnectionCount); })); return new ClientStats(statsPerHost); }</code><technical_language>Actually, 2 issues: single filter, (existing issue), equality comparison ==. filter(a -> a instanceof InetSocketAddress)</technical_language>

Target:
public ClientStats getClientStats() { Map<String, Long> totalConnectionsPerHost = openChannels.stream().map(Channel::remoteAddress).filter(a -> a instanceof InetSocketAddress) .map(a -> (InetSocketAddress) a).map(InetSocketAddress::getHostString).collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); Map<String, Long> idleConnectionsPerHost = channelPool.getIdleChannelCountPerHost(); Map<String, HostStats> statsPerHost = totalConnectionsPerHost.entrySet().stream().collect(Collectors.toMap(Entry::getKey, entry -> { final long totalConnectionCount = entry.getValue(); final long idleConnectionCount = idleConnectionsPerHost.getOrDefault(entry.getKey(), 0L); final long activeConnectionCount = totalConnectionCount - idleConnectionCount; return new HostStats(activeConnectionCount, idleConnectionCount); })); return new ClientStats(statsPerHost); }
Source:
<code>private boolean pmwDtosCouldConvertCustomAttributesToPmwJavaClassAttributes(PaymentWorksVendor stgNewVendorRequestDetailToProcess) { <START> if (stgNewVendorRequestDetailToProcess.isCustomFieldConversionErrors()) { <END> return false; } else{ return true; } }</code><technical_language>return !stgNewVendorRequestDetailToProcess.isCustomFieldConversionErrors()</technical_language>

Target:
private boolean pmwDtosCouldConvertCustomAttributesToPmwJavaClassAttributes(PaymentWorksVendor stgNewVendorRequestDetailToProcess) { return !stgNewVendorRequestDetailToProcess.isCustomFieldConversionErrors(); }
Source:
<code><START> static void rotateProc(long gesture, double angle, double angle_delta, long user_data) { <END> if (OS.gtk_gesture_is_recognized(gesture)) { double delta = OS.gtk_gesture_rotate_get_angle_delta(gesture)*100; Control control = getControl(user_data); control.sendGestureEvent(0,SWT.GESTURE_ROTATE,0,0,delta); } }</code><technical_language>space long/*int*/ is critical for replace task</technical_language>

Target:
static void rotateProc(long gesture, double angle, double angle_delta, long user_data) { if (OS.gtk_gesture_is_recognized(gesture)) { double delta = -(OS.gtk_gesture_rotate_get_angle_delta(gesture)*100); Control control = getControl(user_data); control.sendGestureEvent(0,SWT.GESTURE_ROTATE,0,0,delta); } }
Source:
<code><START> public String getConsumerName() { <END> return consumerName; }</code><technical_language>@xiaolong-sn This is a [good usecase](<LINK_0> for Optional if</technical_language>

Target:
public Optional<String> getConsumerName() { return Optional.ofNullable(consumerName); }
Source:
<code>public Builder addFieldsFromPOJO(final Object pojo) { Class<? extends Object> clazz = pojo.getClass(); for (Field field : clazz.getDeclaredFields()) { Column column = field.getAnnotation(Column.class); if (column == null) { continue; } String fieldName = column.name(); <START> if (isPublic(field)) { <END> addFieldByAttribute(pojo, field, column, fieldName); } else { addFieldByMethod(pojo, clazz, field, column, fieldName); } } if (this.fields.isEmpty()) { throw new BuilderException("Class " + pojo.getClass().getName() + " has no @" + Column.class.getSimpleName() + " annotation"); } return this; }</code><technical_language>I matters if field is public not: get field annotated (at)Column annotation</technical_language>

Target:
public Builder addFieldsFromPOJO(final Object pojo) { Class<? extends Object> clazz = pojo.getClass(); for (Field field : clazz.getDeclaredFields()) { Column column = field.getAnnotation(Column.class); if (column == null) { continue; } field.setAccessible(true); String fieldName = column.name(); addFieldByAttribute(pojo, field, column, fieldName); } if (this.fields.isEmpty()) { throw new BuilderException("Class " + pojo.getClass().getName() + " has no @" + Column.class.getSimpleName() + " annotation"); } return this; }
Source:
<code>public TransactionParser getParser(KXmlParser parser) { String namespace = parser.getNamespace(); String name = parser.getName(); if (LedgerXmlParsers.STOCK_XML_NAMESPACE.equals(namespace)) { if (stockParser == null) { throw new RuntimeException("Couldn't process Stock transaction without initialization!"); } req(); return stockParser.getParser(parser); } else if ("case".equalsIgnoreCase(name)) { if (caseParser == null) { throw new RuntimeException("Couldn't receive Case transaction without initialization!"); } req(); return caseParser.getParser(parser); } else if ("registration".equalsIgnoreCase(name)) { if (userParser == null) { throw new RuntimeException("Couldn't receive User transaction without initialization!"); } req(); return userParser.getParser(parser); } else if ("fixture".equalsIgnoreCase(name)) { req(); return fixtureParser.getParser(parser); } else if ("sync".equalsIgnoreCase(name) && <START> "<LINK_0>".equals(namespace)) { <END> return new TransactionParser<String>(parser) { public void commit(String parsed) throws IOException public String parse() throws InvalidStructureException, IOException, XmlPullParserException, UnfullfilledRequirementsException { this.checkNode("sync"); this.nextTag("restore_id"); String syncToken = parser.nextText(); if (syncToken == null) { throw new InvalidStructureException("Sync block must contain restore_id with valid ID inside!", parser); } sandbox.setSyncToken(syncToken); return syncToken; } }; } return null; }</code><technical_language>This annotation stay, for parse</technical_language>

Target:
public TransactionParser getParser(KXmlParser parser) { String namespace = parser.getNamespace(); String name = parser.getName(); if (LedgerXmlParsers.STOCK_XML_NAMESPACE.equals(namespace)) { if (stockParser == null) { throw new RuntimeException("Couldn't process Stock transaction without initialization!"); } req(); return stockParser.getParser(parser); } else if ("case".equalsIgnoreCase(name)) { if (caseParser == null) { throw new RuntimeException("Couldn't receive Case transaction without initialization!"); } req(); return caseParser.getParser(parser); } else if ("registration".equalsIgnoreCase(name)) { if (userParser == null) { throw new RuntimeException("Couldn't receive User transaction without initialization!"); } req(); return userParser.getParser(parser); } else if ("fixture".equalsIgnoreCase(name)) { req(); return fixtureParser.getParser(parser); } else if ("sync".equalsIgnoreCase(name) && "<LINK_0>".equals(namespace)) { return new TransactionParser<String>(parser) { @Override public void commit(String parsed) throws IOException @Override public String parse() throws InvalidStructureException, IOException, XmlPullParserException, UnfullfilledRequirementsException { this.checkNode("sync"); this.nextTag("restore_id"); String syncToken = parser.nextText(); if (syncToken == null) { throw new InvalidStructureException("Sync block must contain restore_id with valid ID inside!", parser); } sandbox.setSyncToken(syncToken); return syncToken; } }; } return null; }
Source:
<code>public RenderPipelineTask generateTask() { if (task == null) { <START> if (isTheDefaultInstance()) { <END> frameBuffersManager = dynamicFBOsManager; } task = new SetViewportSizeOfTask(fboName); frameBuffersManager.subscribe(this); update(); } return task; }</code><technical_language>if (this.isTheDefaultInstance..</technical_language>

Target:
public RenderPipelineTask generateTask() { if (task == null) { if (isTheDefaultInstance()) { frameBuffersManager = displayResolutionDependentFBOs; } task = new SetViewportSizeOfTask(fboName); frameBuffersManager.subscribe(this); update(); } return task; }
Source:
<code>public DeclType typeCheck(TypeContext ctx, TypeContext thisCtx) { TypeContext methodCtx = thisCtx; for (FormalArg arg : formalArgs) { methodCtx = methodCtx.extend(arg.getName(), arg.getType()); } for (String freeVar : this.getFreeVariables()) { ValueType t = (new Variable(freeVar)).typeCheck(methodCtx); <START> if (t instanceof StructuralType) { <END> this.resourceFlag = ((StructuralType) t).isResource(); } else if (t instanceof NominalType) { this.resourceFlag = t.getStructuralType(ctx).isResource(); } } ValueType bodyType = body.typeCheck(methodCtx); if (!bodyType.isSubtypeOf(getType(), methodCtx)) { ToolError.reportError(ErrorMessage.NOT_SUBTYPE, this, "method body's type", "declared type");; } return new DefDeclType(getName(), type, formalArgs); }</code><technical_language>Avoid instanceof making isResource() a member of ValueType (and providing implementations for other kinds of ValueTypes)</technical_language>

Target:
public DeclType typeCheck(TypeContext ctx, TypeContext thisCtx) { TypeContext methodCtx = thisCtx; for (FormalArg arg : formalArgs) { methodCtx = methodCtx.extend(arg.getName(), arg.getType()); } if (!this.containsResource()) { for (String freeVar : this.getFreeVariables()) { ValueType t = (new Variable(freeVar)).typeCheck(methodCtx); if (t != null && t.isResource(methodCtx)) { this.setHasResource(true); break; } } } ValueType bodyType = body.typeCheck(methodCtx); if (!bodyType.isSubtypeOf(getType(), methodCtx)) { ToolError.reportError(ErrorMessage.NOT_SUBTYPE, this, "method body's type", "declared type");; } return new DefDeclType(getName(), type, formalArgs); }
Source:
<code>public Iterable<Result> execute(Query query) throws Exception { JMXConnection jmxConnection = null; try { jmxConnection = pool.borrowObject(this); ImmutableList.Builder<Result> results = ImmutableList.builder(); <START> if(query.getQueryType() == Query.QueryType.POLL) { <END> MBeanServerConnection connection = jmxConnection.getMBeanServerConnection(); for (ObjectName queryName : query.queryNames(connection)) { results.addAll(query.fetchResults(connection, queryName)); } } else { if(!query.isNotificationListenerRegistered(jmxConnection)) { query.subscribeToNotifications(jmxConnection); } results.addAll(query.processNotifications(jmxConnection)); } return results.build(); } catch (Exception e) { if (jmxConnection != null) { pool.invalidateObject(this, jmxConnection); jmxConnection = null; } throw e; } finally { if (jmxConnection != null) { pool.returnObject(this, jmxConnection); } } }</code><technical_language>Enum a good candidate for a switch statement instead of ifs</technical_language>

Target:
public Iterable<Result> execute(Query query) throws Exception { JMXConnection jmxConnection = null; try { jmxConnection = pool.borrowObject(this); ImmutableList.Builder<Result> results = ImmutableList.builder(); MBeanServerConnection connection = jmxConnection.getMBeanServerConnection(); for (ObjectName queryName : query.queryNames(connection)) { results.addAll(query.fetchResults(connection, queryName)); } return results.build(); } catch (Exception e) { if (jmxConnection != null) { pool.invalidateObject(this, jmxConnection); jmxConnection = null; } throw e; } finally { if (jmxConnection != null) { pool.returnObject(this, jmxConnection); } } }
Source:
<code>private static void copy(JarFile jar, JarEntry from, File to) throws IOException { <START> InputStream is = jar.getInputStream(from); <END> FileOutputStream os = new FileOutputStream(to); IOUtils.copy(is, os); os.close(); is.close(); }</code><technical_language>try-with-resources</technical_language>

Target:
private static void copy(JarFile jar, JarEntry from, File to) throws IOException { try (InputStream is = jar.getInputStream(from); FileOutputStream os = new FileOutputStream(to)) { IOUtils.copy(is, os); } }
Source:
<code>public void getWhenMultipleIssuersThenUsesIssuerClaimToDifferentiate() throws Exception { this.spring.register(WebServerConfig.class, MultipleIssuersConfig.class, BasicController.class).autowire(); MockWebServer server = this.spring.getContext().getBean(MockWebServer.class); String metadata = "{\n" + " \"issuer\": \"%s\", \n" + " \"jwks_uri\": \"%s/.well-known/jwks.json\" \n" + "}"; String jwkSet = jwkSet(); String issuerOne = server.url("/issuerOne").toString(); String issuerTwo = server.url("/issuerTwo").toString(); String issuerThree = server.url("/issuerThree").toString(); String jwtOne = jwtFromIssuer(issuerOne); String jwtTwo = jwtFromIssuer(issuerTwo); String jwtThree = jwtFromIssuer(issuerThree); mockWebServer(String.format(metadata, issuerOne, issuerOne)); mockWebServer(jwkSet); this.mvc.perform(get("/authenticated") .with(bearerToken(jwtOne))) .andExpect(status().isOk()) .andExpect(content().string("test-subject")); mockWebServer(String.format(metadata, issuerTwo, issuerTwo)); mockWebServer(jwkSet); this.mvc.perform(get("/authenticated") .with(bearerToken(jwtTwo))) .andExpect(status().isOk()) .andExpect(content().string("test-subject")); mockWebServer(String.format(metadata, issuerThree, issuerThree)); mockWebServer(jwkSet); this.mvc.perform(get("/authenticated") .with(bearerToken(jwtThree))) <START> .andExpect(status().isUnauthorized()); <END> }</code><technical_language>narrow validation criteria, verify failure invalid issuer? (401 arise a misconfiguration, a broad error)</technical_language>

Target:
public void getWhenMultipleIssuersThenUsesIssuerClaimToDifferentiate() throws Exception { this.spring.register(WebServerConfig.class, MultipleIssuersConfig.class, BasicController.class).autowire(); MockWebServer server = this.spring.getContext().getBean(MockWebServer.class); String metadata = "{\n" + " \"issuer\": \"%s\", \n" + " \"jwks_uri\": \"%s/.well-known/jwks.json\" \n" + "}"; String jwkSet = jwkSet(); String issuerOne = server.url("/issuerOne").toString(); String issuerTwo = server.url("/issuerTwo").toString(); String issuerThree = server.url("/issuerThree").toString(); String jwtOne = jwtFromIssuer(issuerOne); String jwtTwo = jwtFromIssuer(issuerTwo); String jwtThree = jwtFromIssuer(issuerThree); mockWebServer(String.format(metadata, issuerOne, issuerOne)); mockWebServer(jwkSet); this.mvc.perform(get("/authenticated") .with(bearerToken(jwtOne))) .andExpect(status().isOk()) .andExpect(content().string("test-subject")); mockWebServer(String.format(metadata, issuerTwo, issuerTwo)); mockWebServer(jwkSet); this.mvc.perform(get("/authenticated") .with(bearerToken(jwtTwo))) .andExpect(status().isOk()) .andExpect(content().string("test-subject")); mockWebServer(String.format(metadata, issuerThree, issuerThree)); mockWebServer(jwkSet); this.mvc.perform(get("/authenticated") .with(bearerToken(jwtThree))) .andExpect(status().isUnauthorized()) .andExpect(invalidTokenHeader("Invalid issuer")); }
Source:
<code>public T read(Object id, Class<T> objectType) { List<T> queryList = null; T foundRecord = null; try { session = getSessionFactory().openSession(); tx = session.beginTransaction(); LOG.info("Reading Record..."); Criteria aCriteria = session.createCriteria(objectType); aCriteria.add(Expression.eq("id", id)); queryList = aCriteria.list(); <START> if (queryList != null && !queryList.isEmpty()) { <END> foundRecord = queryList.get(0); } } catch (HibernateException | NullPointerException e) { LOG.error("Exception during read occured due to : {}", e.getMessage(), e); } finally { if (session != null) { try { session.flush(); session.close(); } catch (HibernateException e) { LOG.error("Exception while closing the session after a read: {}", e.getMessage(), e); } } } LOG.debug("GenericDaoJpaImpl.read() - End"); return foundRecord; }</code><technical_language>CollectionUtil.isnotempty instead of conditions</technical_language>

Target:
public T read(Object id, Class<T> objectType) { List<T> queryList = null; T foundRecord = null; try { session = getSessionFactory().openSession(); tx = session.beginTransaction(); LOG.info("Reading Record..."); Criteria aCriteria = session.createCriteria(objectType); aCriteria.add(Expression.eq("id", id)); queryList = aCriteria.list(); if (CollectionUtils.isNotEmpty(queryList)) { foundRecord = queryList.get(0); } } catch (HibernateException | NullPointerException e) { LOG.error("Exception during read occured due to : {}", e.getMessage(), e); } finally { if (session != null) { try { session.flush(); session.close(); } catch (HibernateException e) { LOG.error("Exception while closing the session after a read: {}", e.getMessage(), e); } } } LOG.debug("GenericDaoJpaImpl.read() - End"); return foundRecord; }
Source:
<code>protected R updateReservedRecordInternal(K key, V value, R reservedRecord, long reservationId) { if (reservedRecord.getReservationId() != reservationId) { return reservedRecord; } updateRecordValue(reservedRecord, value); if (value == null) { reservedRecord.setCachedAsNull(true); } reservedRecord.setReservationId(READ_PERMITTED); nearCacheStats.incrementOwnedEntryMemoryCost(getTotalStorageMemoryCost(key, reservedRecord)); nearCacheStats.incrementOwnedEntryCount(); <START> <END> return reservedRecord; }</code><technical_language>null covered if set reservation ID READ_PERMITTED is null</technical_language>

Target:
protected R updateReservedRecordInternal(K key, V value, R reservedRecord, long reservationId) { if (reservedRecord.getReservationId() != reservationId) { return reservedRecord; } boolean update = reservedRecord.getValue() != null || reservedRecord.isCachedAsNull(); if (update) { nearCacheStats.incrementOwnedEntryMemoryCost(-getTotalStorageMemoryCost(key, reservedRecord)); } updateRecordValue(reservedRecord, value); if (value == null) { reservedRecord.setCachedAsNull(true); } reservedRecord.setReservationId(READ_PERMITTED); nearCacheStats.incrementOwnedEntryMemoryCost(getTotalStorageMemoryCost(key, reservedRecord)); if (!update) { nearCacheStats.incrementOwnedEntryCount(); } return reservedRecord; }
Source:
<code>public TmfXmlReadOnlyStateValue(TmfXmlReadOnlyModelFactory modelFactory, Element node, IXmlStateSystemContainer container, String eventField) { <START> super(modelFactory, node, container, NonNullUtils.checkNotNull(Collections.EMPTY_LIST), eventField); <END> }</code><technical_language>bloops</technical_language>

Target:
public TmfXmlReadOnlyStateValue(TmfXmlReadOnlyModelFactory modelFactory, Element node, IXmlStateSystemContainer container, String eventField) { super(modelFactory, node, container, checkNotNull(Collections.EMPTY_LIST), eventField); }
Source:
<code>private void doCreateProject() { final String projectName = project.getText().trim(); final String parentName = sugestParent.getText().trim(); if ("".equals(projectName)) { project.setFocus(true); return; } enableForm(false); Util.PROJECT_SVC.createNewProject(projectName, parentName, emptyCommit.getValue(), permissionsOnly.getValue(), new GerritCallback<VoidResult>() { @Override public void onSuccess(VoidResult result) { History.newItem(Dispatcher.toProjectAdmin(new Project.NameKey( projectName), ProjectScreen.INFO)); } @Override public void onFailure(Throwable caught) { new ErrorDialog(caught.getMessage()) { @Override public void setText(final String t) { } <START> }.center(); <END> enableForm(true); } }); }</code><technical_language>this center() do anything</technical_language>

Target:
private void doCreateProject() { final String projectName = project.getText().trim(); final String parentName = sugestParent.getText().trim(); if ("".equals(projectName)) { project.setFocus(true); return; } enableForm(false); Util.PROJECT_SVC.createNewProject(projectName, parentName, emptyCommit.getValue(), permissionsOnly.getValue(), new GerritCallback<VoidResult>() { @Override public void onSuccess(VoidResult result) { History.newItem(Dispatcher.toProjectAdmin(new Project.NameKey( projectName), ProjectScreen.INFO)); } @Override public void onFailure(Throwable caught) { new ErrorDialog(caught.getMessage()).center(); enableForm(true); } }); }
Source:
<code>public void setRemoteDirectory(String remoteDirectory) { this.remoteDirectoryExpression = new LiteralExpression(remoteDirectory); <START> evalueRemoteDirectory(); <END> }</code><technical_language>close topic I meant this yesterday: java EvaluationContext context = this.evaluationContext; if (!(this.localFilenameGeneratorExpression instanceof LiteralExpression) && this.localFilenameGeneratorExpression.getExpressionString().contains("#remoteDirectory")) { context = IntegrationContextUtils.getEvaluationContext(this.beanFactory); context.setVariable("remoteDirectory", remoteDirectoryPath); } return this.localFilenameGeneratorExpression.getValue(context , remoteFileName, String.class); done fully solution need special review. For example synchronize in RotatingServerAdvice reconfigure a MessageSource, apply state? reconfiguring source anyway, matter wins</technical_language>

Target:
public void setRemoteDirectory(String remoteDirectory) { this.remoteDirectoryExpression = new LiteralExpression(remoteDirectory); evaluateRemoteDirectory(); }
Source:
<code>public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { try { Timber.i("Downgrading database from version %d to %d", oldVersion, newVersion); <START> upgradeToVersion5(db); <END> Timber.i("Downgrading database from version %d to %d completed with success.", oldVersion, newVersion); isDatabaseBeingMigrated = false; } catch (SQLException e) { isDatabaseBeingMigrated = false; throw e; } }</code><technical_language>I this upgradeToVersion6</technical_language>

Target:
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { try { Timber.i("Downgrading database from version %d to %d", oldVersion, newVersion); String temporaryTableName = INSTANCES_TABLE_NAME + "_tmp"; createInstancesTableV5(db, temporaryTableName); upgradeToVersion6(db, temporaryTableName); dropObsoleteColumns(db, CURRENT_VERSION_COLUMN_NAMES, temporaryTableName); Timber.i("Downgrading database from version %d to %d completed with success.", oldVersion, newVersion); isDatabaseBeingMigrated = false; } catch (SQLException e) { isDatabaseBeingMigrated = false; throw e; } }
Source:
<code><START> public SetPath(Optional<NodeLocation> location, PathSpecification pathSpecification) <END> { super(location); this.pathSpecification = requireNonNull(pathSpecification, "path is null"); }</code><technical_language>this is internally, private</technical_language>

Target:
private SetPath(Optional<NodeLocation> location, PathSpecification pathSpecification) { super(location); this.pathSpecification = requireNonNull(pathSpecification, "path is null"); }
Source:
<code>public List<String> getHighlights() { <START> return highlights; <END> }</code><technical_language>pencil2: protect accidental mutation if return unmodifiable view of list. <LINK_0></technical_language>

Target:
public List<Highlight> getHighlights() { return Collections.unmodifiableList(highlights); }
Source:
<code>public boolean handleResponse(EventDispatcher eventDispatcher, SatelMessage response) { if (super.handleResponse(eventDispatcher, response)) { eventDispatcher.dispatchEvent(new NewStatesEvent(response.getPayload())); return true; } else { return true; <START> } <END> }</code><technical_language>Move return true; out of if/else block clearer a typo return true in case (if a typo)</technical_language>

Target:
public boolean handleResponse(EventDispatcher eventDispatcher, SatelMessage response) { if (super.handleResponse(eventDispatcher, response)) { eventDispatcher.dispatchEvent(new NewStatesEvent(response.getPayload())); return true; } else { return false; } }
Source:
<code>public void init() throws Exception { FilterConfig cfg = mock(FilterConfig.class); when(cfg.getInitParameter(MetricsFilter.PATH_COMPONENT_PARAM)).thenReturn("4"); f.init(cfg); assertEquals(f.getPathComponents(), 4); <START> HttpServletRequest req = mock(HttpServletRequest.class); <END> when(req.getRequestURI()).thenReturn("/foo/bar/baz/bang/zilch/zip/nada"); when(req.getMethod()).thenReturn(HttpMethods.GET); HttpServletResponse res = mock(HttpServletResponse.class); FilterChain c = mock(FilterChain.class); f.doFilter(req, res, c); verify(c).doFilter(req, res); final Double sampleValue = CollectorRegistry.defaultRegistry.getSampleValue(MetricsFilter.FILTER_NAME + "_count", new String[]{"path", "verb"}, new String[]{"/foo/bar/baz/bang", HttpMethods.GET}); assertNotNull(sampleValue); assertEquals(sampleValue, 1, 0.0001); }</code><technical_language>Formatting is</technical_language>

Target:
public void init() throws Exception { FilterConfig cfg = mock(FilterConfig.class); when(cfg.getInitParameter(anyString())).thenReturn(null); String metricName = "foo"; when(cfg.getInitParameter(MetricsFilter.METRIC_NAME_PARAM)).thenReturn(metricName); when(cfg.getInitParameter(MetricsFilter.PATH_COMPONENT_PARAM)).thenReturn("4"); f.init(cfg); assertEquals(f.pathComponents, 4); HttpServletRequest req = mock(HttpServletRequest.class); when(req.getRequestURI()).thenReturn("/foo/bar/baz/bang/zilch/zip/nada"); when(req.getMethod()).thenReturn(HttpMethods.GET); HttpServletResponse res = mock(HttpServletResponse.class); FilterChain c = mock(FilterChain.class); f.doFilter(req, res, c); verify(c).doFilter(req, res); final Double sampleValue = CollectorRegistry.defaultRegistry.getSampleValue(metricName + "_count", new String[]{"path", "method"}, new String[]{"/foo/bar/baz/bang", HttpMethods.GET}); assertNotNull(sampleValue); assertEquals(1, sampleValue, 0.0001); }
Source:
<code>protected ToStringHelper string() { ToStringHelper toString = Objects.toStringHelper("").omitNullValues(); toString.add("keyName", keyName); if (securityGroupNames.size() > 0) toString.add("securityGroupNames", securityGroupNames); if (metadata.size() > 0) toString.add("metadata", metadata); if (personality.size() > 0) toString.add("personality", personality); if (adminPass != null) toString.add("adminPassPresent", true); if (diskConfig != null) toString.add("diskConfig", diskConfig); toString.add("userData", userData == null ? null : new String(userData)); if (!networks.isEmpty()) toString.add("networks", networks); if (availabilityZone != null) <START> toString.add("availability_zone", availabilityZone); <END> return toString; }</code><technical_language>reason logic is for userData above</technical_language>

Target:
protected ToStringHelper string() { ToStringHelper toString = Objects.toStringHelper("").omitNullValues(); toString.add("keyName", keyName); if (securityGroupNames.size() > 0) toString.add("securityGroupNames", securityGroupNames); if (metadata.size() > 0) toString.add("metadata", metadata); if (personality.size() > 0) toString.add("personality", personality); if (adminPass != null) toString.add("adminPassPresent", true); if (diskConfig != null) toString.add("diskConfig", diskConfig); toString.add("userData", userData == null ? null : new String(userData)); if (!networks.isEmpty()) toString.add("networks", networks); toString.add("availability_zone", availabilityZone == null ? null : availabilityZone); return toString; }
Source:
<code>public void run() throws Exception { response = true; MultiMapContainer container = getOrCreateContainerWithoutAccess(); for (Map.Entry<Data, Collection<MultiMapRecord>> entry : backupEntries.entrySet()) { Data key = entry.getKey(); Collection<MultiMapRecord> value = entry.getValue(); if (value.isEmpty()) { container.remove(key, false); } else { MultiMapValue containerValue = container.getOrCreateMultiMapValue(key); Collection<MultiMapRecord> collection = containerValue.getCollection(false); <START> container.decrementSize(collection.size()); <END> collection.clear(); if (!collection.addAll(value)) { response = false; } else { container.incrementSize(value.size()); } } } }</code><technical_language>want messing size of container outside. This care of internals of map container. end procedural spaghetti</technical_language>

Target:
public void run() throws Exception { response = true; MultiMapContainer container = getOrCreateContainerWithoutAccess(); for (Map.Entry<Data, Collection<MultiMapRecord>> entry : backupEntries.entrySet()) { Data key = entry.getKey(); Collection<MultiMapRecord> value = entry.getValue(); if (value.isEmpty()) { container.remove(key, false); } else { response = container.setValue(key, value); } } }
Source:
<code>public boolean createOrUpdateAndStartSupervisor(SupervisorSpec spec) { Preconditions.checkState(started, "SupervisorManager not started"); Preconditions.checkNotNull(spec, "spec"); <START> Preconditions.checkNotNull(spec.getId(), "spec.getStream()"); <END> Preconditions.checkNotNull(spec.getDataSources(), "spec.getDatasources()"); synchronized (lock) { Preconditions.checkState(started, "SupervisorManager not started"); possiblyStopAndRemoveSupervisorInternal(spec.getId(), false); return createAndStartSupervisorInternal(spec, true); } }</code><technical_language>This spec.getId() (since a generic Supervisor necessarily need stream related)</technical_language>

Target:
public boolean createOrUpdateAndStartSupervisor(SupervisorSpec spec) { Preconditions.checkState(started, "SupervisorManager not started"); Preconditions.checkNotNull(spec, "spec"); Preconditions.checkNotNull(spec.getId(), "spec.getId()"); Preconditions.checkNotNull(spec.getDataSources(), "spec.getDatasources()"); synchronized (lock) { Preconditions.checkState(started, "SupervisorManager not started"); possiblyStopAndRemoveSupervisorInternal(spec.getId(), false); return createAndStartSupervisorInternal(spec, true); } }
Source:
<code><START> private void expand(ClickEvent event, final int numRows) { <END> Cell cell = table.getCellForEvent(event); int row = cell.getRowIndex(); if(!(getRowItem(row) instanceof SkippedLine)) { return; } SkippedLine line = (SkippedLine) getRowItem(row); int loopTo = numRows; if(numRows == 0) { loopTo = line.getSize(); } else if(numRows < 0) { loopTo = -numRows; } int offset = 0; if(numRows < 0) { offset = 1; } for(int i = 0 + offset; i < loopTo + offset; i++) { insertRow(row + i); int lineA = line.getStartA() + i; int lineB = line.getStartB() + i; if(numRows < 0) { lineA = line.getStartA() + line.getSize() + numRows + i - offset; lineB = line.getStartB() + line.getSize() + numRows + i - offset; } setHtml(row + i, 1, "<a href=\"javascript:void(0)\">" + (lineA + 1) + "</a>"); setHtml(row + i, 2, a.getSafeHtmlLine(lineA).asString()); setHtml(row + i, 3, "<a href=\"javascript:void(0)\">" + (lineB + 1) + "</a>"); setHtml(row + i, 4, b.getSafeHtmlLine(lineB).asString()); setRowItem(row + i, new PatchLine(CONTEXT, lineA, lineB)); } if (numRows > 0) { line.incrementStart(numRows); createSkipLine(row + loopTo, line); } else if (numRows < 0) { line.reduceSize(-numRows); createSkipLine(row, line); } else { removeRow(row + loopTo); } }</code><technical_language>fine. This code is complex</technical_language>

Target:
private void expand(ClickEvent event, final int numRows) { Cell cell = table.getCellForEvent(event); int row = cell.getRowIndex(); if (!(getRowItem(row) instanceof SkippedLine)) { return; } SkippedLine line = (SkippedLine) getRowItem(row); int loopTo = numRows; if (numRows == 0) { loopTo = line.getSize(); } else if (numRows < 0) { loopTo = -numRows; } int offset = 0; if (numRows < 0) { offset = 1; } for (int i = 0 + offset; i < loopTo + offset; i++) { insertRow(row + i); int lineA = line.getStartA() + i; int lineB = line.getStartB() + i; if (numRows < 0) { lineA = line.getStartA() + line.getSize() + numRows + i - offset; lineB = line.getStartB() + line.getSize() + numRows + i - offset; } setHtml(row + i, 1, "<a href=\"javascript:void(0)\">" + (lineA + 1) + "</a>"); addStyle(row + i, 1, Gerrit.RESOURCES.css().lineNumber()); setHtml(row + i, 2, a.getSafeHtmlLine(lineA).asString()); addStyle(row + i, 2, Gerrit.RESOURCES.css().fileLine()); addStyle(row + i, 2, Gerrit.RESOURCES.css().fileLineCONTEXT()); setHtml(row + i, 3, "<a href=\"javascript:void(0)\">" + (lineB + 1) + "</a>"); addStyle(row + i, 3, Gerrit.RESOURCES.css().lineNumber()); setHtml(row + i, 4, b.getSafeHtmlLine(lineB).asString()); addStyle(row + i, 4, Gerrit.RESOURCES.css().fileLine()); addStyle(row + i, 4, Gerrit.RESOURCES.css().fileLineCONTEXT()); setRowItem(row + i, new PatchLine(CONTEXT, lineA, lineB)); } if (numRows > 0) { line.incrementStart(numRows); createSkipLine(row + loopTo, line); } else if (numRows < 0) { line.reduceSize(-numRows); createSkipLine(row, line); } else { removeRow(row + loopTo); } }
Source:
<code><START> private static IVMInstall[] sortVMs(IVMInstall[] installs) { <END> List<IVMInstall2> all = new ArrayList<IVMInstall2>(); for (int i = 0; i < installs.length; i++) { if( installs[i] instanceof IVMInstall2 ) { all.add((IVMInstall2) installs[i]); } } Collections.sort(all, new Comparator<IVMInstall2>() { public int compare(IVMInstall2 o1, IVMInstall2 o2) { String arg0vers = o1.getJavaVersion(); String arg1vers = o2.getJavaVersion(); return compareJavaVersions(arg0vers, arg1vers); } }); return (IVMInstall[]) all.toArray(new IVMInstall[all.size()]); }</code><technical_language>bother keeping arrays? List internally</technical_language>

Target:
private static List<IVMInstall2> sortVMs(IVMInstall[] installs) { List<IVMInstall2> all = new ArrayList<IVMInstall2>(); for (int i = 0; i < installs.length; i++) { if( installs[i] instanceof IVMInstall2 ) { String version = ((IVMInstall2)installs[i]).getJavaVersion(); if( version != null ) { try { getMajorMinor(version); all.add((IVMInstall2) installs[i]); } catch( IllegalArgumentException iae) { } } } } Collections.sort(all, new Comparator<IVMInstall2>() { public int compare(IVMInstall2 o1, IVMInstall2 o2) { String arg0vers = o1.getJavaVersion(); String arg1vers = o2.getJavaVersion(); return compareJavaVersions(arg0vers, arg1vers); } }); return all; }
Source:
<code>public String toJson() throws IOException { ObjectMapper mapper = new ObjectMapper(); <START> mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); <END> mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); return mapper.writeValueAsString(this); }</code><technical_language>add?: java mapper.configure(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS, false);</technical_language>

Target:
public String toJson() throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); mapper.configure(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS, false); return mapper.writeValueAsString(this); }
Source:
<code>public void informsHasNextValue() { <START> final List<String> VALID_LIST = Arrays.asList( <END> "Accept: text/plain", "Accept-Charset: utf-8", "Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", "Cache-Control: no-cache", "From: user@example.com"); MatcherAssert.assertThat(new VerboseIterable<String>( VALID_LIST, "Empty Error Message") .iterator().hasNext(), equalTo(true)); }</code><technical_language>@m4solutions valid</technical_language>

Target:
public final void informsHasNextValue() { MatcherAssert.assertThat( new VerboseIterable<String>( Arrays.asList( "User-Agent: LII-Cello/1.0 libwww/2.5", "accept-extension = \";\"", "Accept: text/*;", "Accept-Encoding: gzip;q=1.0" ), "This error should not be thrown" ).iterator().hasNext(), Matchers.equalTo(true) ); }
Source:
<code>public SlackUtil slackUtil() { SlackUtil slackUtil = Mockito.mock(SlackUtil.class); <START> return slackUtil; <END> }</code><technical_language>return Mockito.mock(SlackUtil.class) if customization</technical_language>

Target:
public SlackUtil slackUtil() { return Mockito.mock(SlackUtil.class); }
Source:
<code>public Iterable<Issue> search( @NotNull(message = "Sort field can't be NULL") final Sort sort, @NotNull(message = "Sort direction can't be NULL") final Search.Order direction, @NotNull(message = "Search qualifiers can't be NULL") <START> final EnumMap<Qualifier, String> qualifiers) <END> throws IOException { final Map<String, String> params = new HashMap<String, String>(); for (final EnumMap.Entry<Qualifier, String> pair : qualifiers .entrySet()) { params.put(pair.getKey().getQualifier(), pair.getValue()); } params.put("sort", sort.getSort()); params.put("direction", direction.getOrder()); return this.iterate(params); }</code><technical_language>do need EnumMap instead of Map in this method</technical_language>

Target:
public Iterable<Issue> search( @NotNull(message = "Sort field can't be NULL") final Sort sort, @NotNull(message = "Sort direction can't be NULL") final Search.Order direction, @NotNull(message = "Search qualifiers can't be NULL") final EnumMap<Qualifier, String> qualifiers) throws IOException { final Map<String, String> params = new HashMap<String, String>(); for (final EnumMap.Entry<Qualifier, String> pair : qualifiers .entrySet()) { params.put(pair.getKey().identifier(), pair.getValue()); } params.put("sort", sort.identifier()); params.put("direction", direction.identifier()); return this.iterate(params); }
Source:
<code>public String toString() { StringJoiner joiner = new StringJoiner(", ", "Worldpay authorisation response (", ")"); if (StringUtils.isNotBlank(getTransactionId())) { joiner.add("orderCode: " + getTransactionId()); } if (StringUtils.isNotBlank(getLastEvent())) { joiner.add("lastEvent: "+ getLastEvent()); } if (StringUtils.isNotBlank(getRefusedReturnCode())) { joiner.add("ISO8583ReturnCode code: " + getRefusedReturnCode()); } if (StringUtils.isNotBlank(getRefusedReturnCodeDescription())) { joiner.add("ISO8583ReturnCode description: " + getRefusedReturnCodeDescription()); } if (StringUtils.isNotBlank(issuerUrl)) { joiner.add("issuerURL: " + issuerUrl); } if (StringUtils.isNotBlank(paRequest)) { <START> joiner.add("issuerURL: " + paRequest); <END> } if (StringUtils.isNotBlank(getErrorCode())) { joiner.add("error code: " + getErrorCode()); } if (StringUtils.isNotBlank(getErrorMessage())) { joiner.add("error: " + getErrorMessage()); } return joiner.toString(); }</code><technical_language>label's wrong here! Also, opaque string - is outputting this</technical_language>

Target:
public String toString() { StringJoiner joiner = new StringJoiner(", ", "Worldpay authorisation response (", ")"); if (StringUtils.isNotBlank(getTransactionId())) { joiner.add("orderCode: " + getTransactionId()); } if (StringUtils.isNotBlank(getLastEvent())) { joiner.add("lastEvent: "+ getLastEvent()); } if (StringUtils.isNotBlank(getRefusedReturnCode())) { joiner.add("ISO8583ReturnCode code: " + getRefusedReturnCode()); } if (StringUtils.isNotBlank(getRefusedReturnCodeDescription())) { joiner.add("ISO8583ReturnCode description: " + getRefusedReturnCodeDescription()); } if (StringUtils.isNotBlank(issuerUrl)) { joiner.add("issuerURL: " + issuerUrl); } if (StringUtils.isNotBlank(paRequest)) { joiner.add("paRequest: " + paRequest); } if (StringUtils.isNotBlank(getErrorCode())) { joiner.add("error code: " + getErrorCode()); } if (StringUtils.isNotBlank(getErrorMessage())) { joiner.add("error: " + getErrorMessage()); } return joiner.toString(); }
Source:
<code>public void clickShareButton() { waitForElementByElement(shareButton); JavascriptExecutor executor = (JavascriptExecutor)driver; <START> executor.executeScript("$('a.share-button.secondary').click()"); <END> waitForElementByElement(moreInfoThumbnail); PageObjectLogging.log("clickShareButton", "share button is clicked", true); }</code><technical_language>Try $('.LightboxHeader a.share-button.secondary') selector for this WebElement current selector is choosing share button article page lightbox</technical_language>

Target:
public void clickShareButton() { waitForElementByElement(shareButton); shareButton.click(); waitForElementByElement(moreInfoThumbnail); PageObjectLogging.log("clickShareButton", "share button is clicked", true); }
Source:
<code>private List<RemoteReplicaInfo> createRemoteReplicaInfos(List<? extends ReplicaId> peerReplicas, ReplicaId replicaId) { List<RemoteReplicaInfo> remoteReplicaInfos = new ArrayList<>(); PartitionId partition = replicaId.getPartitionId(); Store store = storeManager.getStore(partition); try { for (ReplicaId remoteReplica : peerReplicas) { FindToken findToken = this.tokenHelper.getFindTokenFactoryFromReplicaType(remoteReplica.getReplicaType()).getNewFindToken(); RemoteReplicaInfo remoteReplicaInfo = null; remoteReplicaInfo = new RemoteReplicaInfo(remoteReplica, replicaId, store, findToken, TimeUnit.SECONDS.toMillis(storeConfig.storeDataFlushIntervalSeconds) * Replication_Delay_Multiplier, SystemTime.getInstance(), remoteReplica.getDataNodeId().getPortToConnectTo(), storeKeyConverterFactory.getStoreKeyConverter()); replicationMetrics.addMetricsForRemoteReplicaInfo(remoteReplicaInfo, trackPerPartitionLagInMetric); remoteReplicaInfos.add(remoteReplicaInfo); } if (replicationConfig.replicationTrackPerPartitionLagFromRemote) { replicationMetrics.addLagMetricForPartition(partition); } } catch (Exception e) { <START> logger.error("Encountered exception instantiating RemoteReplicaInfos", e); <END> } return remoteReplicaInfos; }</code><technical_language>swallowing this exception means end a partial list of remoteReplicaInfos. Is ok for callers of this method</technical_language>

Target:
private List<RemoteReplicaInfo> createRemoteReplicaInfos(List<? extends ReplicaId> peerReplicas, ReplicaId replicaId) { List<RemoteReplicaInfo> remoteReplicaInfos = new ArrayList<>(); PartitionId partition = replicaId.getPartitionId(); Store store = storeManager.getStore(partition); for (ReplicaId remoteReplica : peerReplicas) { FindToken findToken = this.tokenHelper.getFindTokenFactoryFromReplicaType(remoteReplica.getReplicaType()).getNewFindToken(); RemoteReplicaInfo remoteReplicaInfo = new RemoteReplicaInfo(remoteReplica, replicaId, store, findToken, TimeUnit.SECONDS.toMillis(storeConfig.storeDataFlushIntervalSeconds) * Replication_Delay_Multiplier, SystemTime.getInstance(), remoteReplica.getDataNodeId().getPortToConnectTo()); replicationMetrics.addMetricsForRemoteReplicaInfo(remoteReplicaInfo, trackPerPartitionLagInMetric); remoteReplicaInfos.add(remoteReplicaInfo); } if (replicationConfig.replicationTrackPerPartitionLagFromRemote) { replicationMetrics.addLagMetricForPartition(partition); } return remoteReplicaInfos; }
Source:
<code>private RedisQueueOutboundChannelAdapter createProducerEndpoint(String name, ProducerProperties properties) { String partitionKeyExtractorClass = properties.getPartitionKeyExtractorClass(); <START> String partitionKeyExpression = properties.getPartitionKeyExpression(); <END> RedisQueueOutboundChannelAdapter queue; if (partitionKeyExpression == null && !StringUtils.hasText(partitionKeyExtractorClass)) { queue = new RedisQueueOutboundChannelAdapter(name, this.connectionFactory); } else { queue = new RedisQueueOutboundChannelAdapter( parser.parseExpression(buildPartitionRoutingExpression(name)), this.connectionFactory); } queue.setIntegrationEvaluationContext(this.evaluationContext); queue.setBeanFactory(this.getBeanFactory()); queue.afterPropertiesSet(); return queue; }</code><technical_language>partitionKeyExpression Expression type properties object? (there is a Converter for conversion properties bound... rely for some of out-of-the-box spring-cloud-stream apps)</technical_language>

Target:
private RedisQueueOutboundChannelAdapter createProducerEndpoint(String name, ProducerProperties properties) { RedisQueueOutboundChannelAdapter queue; if (!properties.isPartitioned()) { queue = new RedisQueueOutboundChannelAdapter(name, this.connectionFactory); } else { queue = new RedisQueueOutboundChannelAdapter( parser.parseExpression(buildPartitionRoutingExpression(name)), this.connectionFactory); } queue.setIntegrationEvaluationContext(this.evaluationContext); queue.setBeanFactory(this.getBeanFactory()); queue.afterPropertiesSet(); return queue; }