auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public String getCacheName(boolean useFullDepName) { if (useFullDepName) { if (!StringUtils.isEmpty(group)) { <START> return group + "--" + name + "--" + String.valueOf(version) + "." + packaging; <END> } else { return name + "." + depFile.getName(); } } else { return depFile.getName(); } }</code><technical_language>lets move -- a constant change easier if needed</technical_language>

Target:
public String getCacheName(boolean useFullDepName) { if (useFullDepName) { if (!StringUtils.isEmpty(group)) { return group + CACHE_DELIMITER + name + CACHE_DELIMITER + String.valueOf(version) + "." + packaging; } else { return name + "." + depFile.getName(); } } else { return depFile.getName(); } }
Source:
<code>public CRAMFileReader(File file, InputStream is, ReferenceSource referenceSource) { this.file = file; this.is = is; this.referenceSource = referenceSource; counter++; if (counter % 1000 == 0) <START> System.err.println("open cram files: " + counter); <END> if (file == null) getIterator(); }</code><technical_language>a library writing stderr for progress counting</technical_language>

Target:
public CRAMFileReader(File file, InputStream is, ReferenceSource referenceSource) { if (file == null && is == null) throw new NullPointerException( "Either file or input stream is required."); this.file = file; this.is = is; this.referenceSource = referenceSource; getIterator(); }
Source:
<code>public void pushExportBuffer( final long startSequenceNumber, final long committedSequenceNumber, final int tupleCount, final long uniqueId, final long genId, final ByteBuffer buffer) { try { m_bufferPushPermits.acquire(); } catch (InterruptedException e) { throw new RuntimeException(e); } if (m_closed) { <START> exportLog.error("Closed: ignoring export buffer with " + tupleCount + " rows"); <END> return; } try { m_es.execute((new Runnable() { @Override public void run() { try { if (!m_closed) { pushExportBufferImpl(startSequenceNumber, committedSequenceNumber, tupleCount, uniqueId, genId, buffer, m_readyForPolling); } else { exportLog.error("Closed: ignoring export buffer with " + tupleCount + " rows"); } } catch (Throwable t) { VoltDB.crashLocalVoltDB("Error pushing export buffer", true, t); } finally { m_bufferPushPermits.release(); } } })); } catch (RejectedExecutionException rej) { m_bufferPushPermits.release(); exportLog.info("Export buffer rejected by data source executor: ", rej); } }</code><technical_language>This rate-limited if unknown condition causing EE push buffer closed EDS, a lot of error message in log</technical_language>

Target:
public void pushExportBuffer( final long startSequenceNumber, final long committedSequenceNumber, final int tupleCount, final long uniqueId, final long genId, final ByteBuffer buffer) { try { m_bufferPushPermits.acquire(); } catch (InterruptedException e) { throw new RuntimeException(e); } if (m_closed) { exportLogLimited.log("Closed: ignoring export buffer with " + tupleCount + " rows", EstTime.currentTimeMillis()); return; } try { m_es.execute((new Runnable() { @Override public void run() { try { if (!m_closed) { pushExportBufferImpl(startSequenceNumber, committedSequenceNumber, tupleCount, uniqueId, genId, buffer, m_readyForPolling); } else { exportLogLimited.log("Closed: ignoring export buffer with " + tupleCount + " rows", EstTime.currentTimeMillis()); } } catch (Throwable t) { VoltDB.crashLocalVoltDB("Error pushing export buffer", true, t); } finally { m_bufferPushPermits.release(); } } })); } catch (RejectedExecutionException rej) { m_bufferPushPermits.release(); exportLog.info("Export buffer rejected by data source executor: ", rej); } }
Source:
<code>public boolean hasActiveEntitlementPools(Owner o, Date date) { if (o == null) { return false; } if (date == null) { date = new Date(); } Criteria crit = createSecureCriteria(); crit.add(Restrictions.eq("activeSubscription", Boolean.TRUE)); crit.add(Restrictions.eq("owner", o)); crit.add(Restrictions.le("startDate", date)); crit.add(Restrictions.ge("endDate", date)); crit.setProjection(Projections.rowCount()); <START> long count = (Long) crit.list().get(0); <END> return count > 0; }</code><technical_language>done this follows, however, if is a difference in uniqueResult list().get(0). investigate -- 100% is TBH. java long count = (Long) crit.uniqueResult();</technical_language>

Target:
public boolean hasActiveEntitlementPools(Owner o, Date date) { if (o == null) { return false; } if (date == null) { date = new Date(); } Criteria crit = createSecureCriteria(); crit.add(Restrictions.eq("activeSubscription", Boolean.TRUE)); crit.add(Restrictions.eq("owner", o)); crit.add(Restrictions.le("startDate", date)); crit.add(Restrictions.ge("endDate", date)); crit.setProjection(Projections.rowCount()); long count = (Long) crit.uniqueResult(); return count > 0; }
Source:
<code>public void partActivated(IWorkbenchPart part) { if (part == AbstractTimeGraphView.this) { synchronized (FIND_ACTION) { if (fFindActionHandler == null) { fFindActionHandler = new ActionHandler(FIND_ACTION); } final Object service = PlatformUI.getWorkbench().getService(IHandlerService.class); ((IHandlerService) <START> service).deactivateHandler(fFindHandlerActivation); <END> fFindHandlerActivation = ((IHandlerService) service).activateHandler(ActionFactory.FIND.getCommandId(), fFindActionHandler); } } FIND_ACTION.partActivated(part); }</code><technical_language>call this null. But..</technical_language>

Target:
public void partActivated(IWorkbenchPart part) { if (part == AbstractTimeGraphView.this) { synchronized (FIND_ACTION) { if (fFindActionHandler == null) { fFindActionHandler = new ActionHandler(FIND_ACTION); } if (fFindHandlerActivation == null) { final Object service = PlatformUI.getWorkbench().getService(IHandlerService.class); fFindHandlerActivation = ((IHandlerService) service).activateHandler(ActionFactory.FIND.getCommandId(), fFindActionHandler); } } } FIND_ACTION.partActivated(part); }
Source:
<code>public void openTaskSelectionScreen(OpenUpgradeScreenEvent event, EntityRef player) { <START> this.upgradeScreenLayer = nuiManager.createScreen("buildingUpgradeScreen"); <END> nuiManager.pushScreen(this.upgradeScreenLayer); }</code><technical_language>Constant</technical_language>

Target:
public void openTaskSelectionScreen(OpenUpgradeScreenEvent event, EntityRef player) { this.upgradeScreenLayer = nuiManager.createScreen(Constants.BUILDING_UPGRADE_SCREEN_URI); nuiManager.pushScreen(this.upgradeScreenLayer); }
Source:
<code>public void testGetCoursesForInstructor() throws Exception { restoreTypicalDataInDatastore(); ______TS("success: instructor with present courses"); String instructorId = getTypicalDataBundle().accounts.get("instructor3").googleId; List<CourseAttributes> courses = coursesLogic.getCoursesForInstructor(instructorId); assertEquals(2, courses.size()); <START> ______TS("fail: instructor without any courses"); <END> instructorId = getTypicalDataBundle().accounts.get("instructorWithoutCourses").googleId; courses = coursesLogic.getCoursesForInstructor(instructorId); assertEquals(0, courses.size()); }</code><technical_language>This is a 'fail' case. is a boundary case</technical_language>

Target:
public void testGetCoursesForInstructor() throws Exception { restoreTypicalDataInDatastore(); ______TS("success: instructor with present courses"); String instructorId = getTypicalDataBundle().accounts.get("instructor3").googleId; List<CourseAttributes> courses = coursesLogic.getCoursesForInstructor(instructorId); assertEquals(2, courses.size()); ______TS("boundary: instructor without any courses"); instructorId = getTypicalDataBundle().accounts.get("instructorWithoutCourses").googleId; courses = coursesLogic.getCoursesForInstructor(instructorId); assertEquals(0, courses.size()); }
Source:
<code>protected void makeInnerQualifyingSet() { if (presentStream == null) { numInnerRows = inputQualifyingSet.getPositionCount(); hasNulls = false; return; } hasNulls = true; if (innerQualifyingSet == null) { innerQualifyingSet = new QualifyingSet(); } int[] inputRows = inputQualifyingSet.getPositions(); int numActive = inputQualifyingSet.getPositionCount(); innerQualifyingSet.reset(numActive); int prevRow = 0; int prevInner = innerPosInRowGroup; <START> numNullsToAdd = 0; <END> boolean keepNulls = filter == null || filter.testNull(); for (int activeIdx = 0; activeIdx < numActive; activeIdx++) { int row = inputRows[activeIdx] - posInRowGroup; if (!present[row]) { if (keepNulls) { addNullToKeep(inputRows[activeIdx], activeIdx); } } else { prevInner += countPresent(prevRow, row); prevRow = row; innerQualifyingSet.append(prevInner, activeIdx); } } numInnerRows = innerQualifyingSet.getPositionCount(); int skip = countPresent(prevRow, inputQualifyingSet.getEnd() - posInRowGroup); innerQualifyingSet.setEnd(skip + prevInner); }</code><technical_language>I understand this change. posInRowGroup points row in row group read. If scan exceeded budget need re-read beginning, posInRowGroup reset zero? confused replaced posInRowGroup 0, in this method usage of posInRowGroup is unchanged. clarify</technical_language>

Target:
protected void makeInnerQualifyingSet() { if (presentStream == null) { numInnerRows = inputQualifyingSet.getPositionCount(); hasNulls = false; return; } hasNulls = true; boolean nonDeterministic = filter != null && !deterministicFilter; if (innerQualifyingSet == null) { innerQualifyingSet = new QualifyingSet(); } int[] inputRows = inputQualifyingSet.getPositions(); int numActive = inputQualifyingSet.getPositionCount(); innerQualifyingSet.reset(numActive); int prevRow = 0; int prevInner = innerPosInRowGroup; numNullsToAdd = 0; boolean keepNulls = filter == null || (!nonDeterministic && filter.testNull()); for (int activeIdx = 0; activeIdx < numActive; activeIdx++) { int row = inputRows[activeIdx] - posInRowGroup; if (!present[row]) { if (keepNulls || (nonDeterministic && testNullAt(row + posInRowGroup))) { addNullToKeep(inputRows[activeIdx], activeIdx); } } else { prevInner += countPresent(prevRow, row); prevRow = row; innerQualifyingSet.append(prevInner, activeIdx); } } numInnerRows = innerQualifyingSet.getPositionCount(); int skip = countPresent(prevRow, inputQualifyingSet.getEnd() - posInRowGroup); innerQualifyingSet.setEnd(skip + prevInner); }
Source:
<code>public void testHttpIngestionInvalidFutureCollectionTime() throws Exception { String prefix = getPrefix(); long time = System.currentTimeMillis() + 600000 + Configuration.getInstance().getLongProperty( CoreConfig.AFTER_CURRENT_COLLECTIONTIME_MS ); HttpResponse response = postGenMetric( TID, prefix, postPath, time ); assertEquals( 400, response.getStatusLine().getStatusCode() ); String[] output = getBodyArray( response ); <START> assertEquals( 4, output.length ); <END> assertTrue( Pattern.matches( JSONMetricsContainerTest.FUTURE_COLLECTION_TIME_REGEX, output[ 1 ] ) ); assertTrue( Pattern.matches( JSONMetricsContainerTest.FUTURE_COLLECTION_TIME_REGEX, output[ 2 ] ) ); assertTrue( Pattern.matches( JSONMetricsContainerTest.FUTURE_COLLECTION_TIME_REGEX, output[ 3 ] ) ); }</code><technical_language>is output[0] contain</technical_language>

Target:
public void testHttpIngestionInvalidFutureCollectionTime() throws Exception { String postfix = getPostfix(); long time = System.currentTimeMillis() + TIME_DIFF_MS + Configuration.getInstance().getLongProperty( CoreConfig.AFTER_CURRENT_COLLECTIONTIME_MS ); HttpResponse response = postGenMetric( TID, postfix, postPath, time ); assertEquals( 400, response.getStatusLine().getStatusCode() ); String[] output = getBodyArray( response ); assertEquals( 4, output.length ); assertTrue( Pattern.matches( FUTURE_COLLECTION_TIME_REGEX, output[ 1 ] ) ); assertTrue( Pattern.matches( FUTURE_COLLECTION_TIME_REGEX, output[ 2 ] ) ); assertTrue( Pattern.matches( FUTURE_COLLECTION_TIME_REGEX, output[ 3 ] ) ); }
Source:
<code>public GoogleCloudStorageItemInfo composeObjects( List<StorageResourceId> sources, final StorageResourceId destination, CreateObjectOptions options) throws IOException { <START> Preconditions.checkArgument(sources.size() <= 32, "Cannot compose more than 32 sources"); <END> ByteArrayOutputStream tempOutput = new ByteArrayOutputStream(); for (StorageResourceId sourceId : sources) { try (SeekableByteChannel sourceChannel = open(sourceId)) { byte[] bufferArray = new byte[4 * 1024 * 1024]; int bytesRead; do { ByteBuffer buffer = ByteBuffer.wrap(bufferArray); bytesRead = sourceChannel.read(buffer); tempOutput.write(bufferArray, 0, buffer.position()); } while (bytesRead >= 0); } } WritableByteChannel destChannel = create(destination, options); destChannel.write(ByteBuffer.wrap(tempOutput.toByteArray())); destChannel.close(); return getItemInfo(destination); }</code><technical_language>constant updated in place. Alternatively, remove this Precondition</technical_language>

Target:
public GoogleCloudStorageItemInfo composeObjects( List<StorageResourceId> sources, final StorageResourceId destination, CreateObjectOptions options) throws IOException { checkArgument( sources.size() <= MAX_COMPOSE_OBJECTS, "Can not compose more than %s sources", MAX_COMPOSE_OBJECTS); ByteArrayOutputStream tempOutput = new ByteArrayOutputStream(); for (StorageResourceId sourceId : sources) { try (SeekableByteChannel sourceChannel = open(sourceId)) { byte[] bufferArray = new byte[4 * 1024 * 1024]; int bytesRead; do { ByteBuffer buffer = ByteBuffer.wrap(bufferArray); bytesRead = sourceChannel.read(buffer); tempOutput.write(bufferArray, 0, buffer.position()); } while (bytesRead >= 0); } } WritableByteChannel destChannel = create(destination, options); destChannel.write(ByteBuffer.wrap(tempOutput.toByteArray())); destChannel.close(); return getItemInfo(destination); }
Source:
<code>private void checkSkipBuild() { synchronized (this) { String skipBuildPhrase = helper.checkSkipBuildPhrase(this.pr); if (!StringUtils.isEmpty(skipBuildPhrase)) { logger.log(Level.INFO, "Pull request commented with {0} skipBuildPhrase. Hence skipping the build.", skipBuildPhrase); shouldRun = false; return; } if (commitAuthor == null){ <START> return; <END> } String blackListCommitAuthor = helper.checkBlackListCommitAuthor(commitAuthor.getName()); if (!StringUtils.isEmpty(blackListCommitAuthor)) { logger.log(Level.INFO, "Pull request triggered by {0} user. Hence skipping the build.", blackListCommitAuthor); shouldRun = false; } } }</code><technical_language>logging a FINE message here? I honestly if this condition nice logging if up</technical_language>

Target:
private void checkSkipBuild() { synchronized (this) { String skipBuildPhrase = helper.checkSkipBuildPhrase(this.pr); if (!StringUtils.isEmpty(skipBuildPhrase)) { logger.log(Level.INFO, "Pull request commented with {0} skipBuildPhrase. Hence skipping the build.", skipBuildPhrase); shouldRun = false; return; } if (commitAuthor == null){ return; } String blackListCommitAuthor = helper.checkBlackListCommitAuthor(commitAuthor.getName()); if (!StringUtils.isEmpty(blackListCommitAuthor)) { logger.log(Level.FINE, "Pull request triggered by user: {0}. Skipping build because that user is blacklisted.", blackListCommitAuthor); shouldRun = false; } } }
Source:
<code>public void setLoggerLevel(LoggerRequest loggerRequest) throws BadRequestException { try { Class.forName(loggerRequest.getName()); } catch (Throwable ignore) { <START> throw new BadRequestException("The name of the logger is incorrect class name"); <END> } org.apache.log4j.Logger logger = LogManager.getLogger(loggerRequest.getName()); if (null == logger) { throw new BadRequestException("The name of the logger is wrong"); } org.apache.log4j.Level level = org.apache.log4j.Level.toLevel(loggerRequest.getLevel(), null); if (null == level) { throw new BadRequestException("The level of the logger is wrong"); } logger.setLevel(level); }</code><technical_language>include bad class name in exception</technical_language>

Target:
public void setLoggerLevel(LoggerRequest loggerRequest) throws BadRequestException { try { Class.forName(loggerRequest.getName()); } catch (Throwable ignore) { throw new BadRequestException( "The class of '" + loggerRequest.getName() + "' doesn't exists"); } org.apache.log4j.Logger logger = LogManager.getLogger(loggerRequest.getName()); if (null == logger) { throw new BadRequestException("The name of the logger is wrong"); } org.apache.log4j.Level level = org.apache.log4j.Level.toLevel(loggerRequest.getLevel(), null); if (null == level) { throw new BadRequestException("The level of the logger is wrong"); } logger.setLevel(level); }
Source:
<code>private IncrementalMetadata getIncrementalMetadata() { <START> if (!"true".equals(processingEnv.getOptions().get(OPTION_INCREMENTAL))) { <END> return null; } Map<String, String> options = processingEnv.getOptions(); String customAnnotationOption = options.get(OPTION_CUSTOM_ANNOTATIONS); if (customAnnotationOption == null) { return new IncrementalMetadata(new String[0]); } return new IncrementalMetadata(customAnnotationOption.split(",")); }</code><technical_language>This is a string, case insensitive? e.g. writing True gradle file match</technical_language>

Target:
private IncrementalMetadata getIncrementalMetadata() { if (!"true".equalsIgnoreCase(processingEnv.getOptions().get(OPTION_INCREMENTAL))) { return null; } Map<String, String> options = processingEnv.getOptions(); String customAnnotationOption = options.get(OPTION_CUSTOM_ANNOTATIONS); if (customAnnotationOption == null) { return new IncrementalMetadata(new String[0]); } return new IncrementalMetadata(customAnnotationOption.split(",")); }
Source:
<code>private static void logMismatch(String fieldName, String tableName, Object clientSideVersion, Object clusterSideVersion) { log.info("Found client/server disagreement on for table {}. (client = ({}), server = ({}))", SafeArg.of("disagreementType", fieldName), <START> UnsafeArg.of("table", tableName), <END> SafeArg.of("clientVersion", clientSideVersion), SafeArg.of("clusterVersion", clusterSideVersion)); }</code><technical_language>LoggingArgs.tableRef() works for refs I think, is for tablenames log TableRef.createUnsafe(name) . This result in greater visibility</technical_language>

Target:
private static void logMismatch(String fieldName, String tableName, Object clientSideVersion, Object clusterSideVersion) { log.info("Found client/server disagreement on for table {}. (client = ({}), server = ({}))", SafeArg.of("disagreementType", fieldName), LoggingArgs.tableRef(TableReference.createUnsafe(tableName)), SafeArg.of("clientVersion", clientSideVersion), SafeArg.of("clusterVersion", clusterSideVersion)); }
Source:
<code>private static JSONArray getListForURLAction(String urlAction, String paramsString, String resultKey, String sessionID, int pageSize, String methodName) throws IOException, JSONException { int page = 0; JSONArray resultList = new JSONArray(); boolean done = false; while (!done) { String params = "?page=" + page + paramsString; String url = makeUrlFor(urlAction,params); Map<String, String> response = request(url, null, sessionID, HTTP_METHOD_GET); int codeResult = checkResponseCode(response.get(RESPONSE_CODE), methodName); if (codeResult != 0) { <START> throw new IOException("Incorrect response of " + methodName + " from CommonSense,\n the content is:" + response.get(RESPONSE_CONTENT)); <END> } JSONObject content = new JSONObject(response.get(RESPONSE_CONTENT)); JSONArray paramList = content.getJSONArray(resultKey); for (int i = 0; i < paramList.length(); i++) { resultList.put(paramList.getJSONObject(i)); } if (paramList.length() < pageSize) { done = true; } else { page++; } } return resultList; }</code><technical_language>@excaliburnan throw response, handled right way. add response code. good response code is session id is expired want this a relogin is required</technical_language>

Target:
private static JSONArray getListForURLAction(String urlAction, String paramsString, String resultKey, String sessionID, int pageSize, String methodName) throws IOException, JSONException { int page = 0; JSONArray resultList = new JSONArray(); boolean done = false; while (!done) { String params = "?page=" + page + paramsString; String url = makeUrlFor(urlAction,params); Map<String, String> response = request(url, null, sessionID, HTTP_METHOD_GET); int codeResult = checkResponseCode(response.get(RESPONSE_CODE), methodName); if (codeResult != 0) { throw new IOException("Incorrect response of " + methodName + " from CommonSense,\n the code is:" + response.get(RESPONSE_CODE)); } JSONObject content = new JSONObject(response.get(RESPONSE_CONTENT)); JSONArray paramList = content.getJSONArray(resultKey); for (int i = 0; i < paramList.length(); i++) { resultList.put(paramList.getJSONObject(i)); } if (paramList.length() < pageSize) { done = true; } else { page++; } } return resultList; }
Source:
<code>public GenericJpaRepository(EntityManagerProvider entityManagerProvider, Class<T> aggregateType, EventBus eventBus, LockFactory lockFactory, Function<String, ?> identifierConverter) { <START> this(entityManagerProvider, aggregateType, eventBus, null, null, lockFactory, identifierConverter); <END> }</code><technical_language>sense getOrDefault() functionality default SimpleEventScheduler (just in Spring config) if DeadlineManager is provided? :thinking:</technical_language>

Target:
public GenericJpaRepository(EntityManagerProvider entityManagerProvider, Class<T> aggregateType, EventBus eventBus, LockFactory lockFactory, Function<String, ?> identifierConverter) { this(entityManagerProvider, aggregateType, eventBus, null, lockFactory, identifierConverter); }
Source:
<code>public void testStatelessExpressionIndex() throws Exception { String ddl = "CREATE TABLE t (k1 INTEGER PRIMARY KEY)"; Connection conn = DriverManager.getConnection(getUrl()); Statement stmt = null; try { stmt = conn.createStatement(); stmt.execute(ddl); stmt.execute("CREATE INDEX i ON t (SUM())"); fail(); } catch (SQLException e) { <START> assertEquals(SQLExceptionCode.STATELESS_EXPRESSION_NOT_ALLOWED_IN_INDEX.getErrorCode(), e.getErrorCode()); <END> } finally { stmt.close(); } }</code><technical_language>This throw AGGREGATION allowed exception. example of stateless if a constant used. I guess this is error condition</technical_language>

Target:
public void testStatelessExpressionIndex() throws Exception { String ddl = "CREATE TABLE t (k1 INTEGER PRIMARY KEY)"; Connection conn = DriverManager.getConnection(getUrl()); Statement stmt = null; try { stmt = conn.createStatement(); stmt.execute(ddl); stmt.execute("CREATE INDEX i ON t (2)"); fail(); } catch (SQLException e) { assertEquals(SQLExceptionCode.STATELESS_EXPRESSION_NOT_ALLOWED_IN_INDEX.getErrorCode(), e.getErrorCode()); } finally { stmt.close(); } }
Source:
<code>private void subscribeToData() { this.data .onBackpressureBuffer(Constants.GB) .subscribe( byteBuffer -> { lock.lock(); try { this.buffer = new ByteArrayInputStream(FluxUtil.byteBufferToArray(byteBuffer)); this.waitingForData = false; dataAvailable.signal(); } finally { lock.unlock(); } }, throwable -> { signalOnCompleteOrError(); if (throwable instanceof HttpResponseException) { this.lastError = new IOException(throwable); } else if (throwable instanceof IllegalArgumentException) { <START> this.lastError = new IOException(throwable); <END> } else if (throwable instanceof IOException) { this.lastError = new IOException(throwable); } }, this::signalOnCompleteOrError, subscription -> { this.subscription = subscription; this.subscribed = true; this.subscription.request(1); } ); }</code><technical_language>I need wrap IllegalArgumentException in IOException. I need wrap ioExceptions in another IOException</technical_language>

Target:
private void subscribeToData() { this.data .onBackpressureBuffer() .subscribe( byteBuffer -> { this.buffer = new ByteArrayInputStream(FluxUtil.byteBufferToArray(byteBuffer)); lock.lock(); try { this.waitingForData = false; dataAvailable.signal(); } finally { lock.unlock(); } }, throwable -> { if (throwable instanceof IOException) { this.lastError = (IOException) throwable; } else { this.lastError = new IOException(throwable); } signalOnCompleteOrError(); }, this::signalOnCompleteOrError, subscription -> { this.subscription = subscription; this.subscribed = true; this.subscription.request(1); } ); }
Source:
<code>private static String getSuggestedType(boolean springInjectionAnnotated, Type leastSpecificType) { if (springInjectionAnnotated && leastSpecificType.is("java.lang.Iterable")) { return "java.util.Collection"; <START> } else { <END> return leastSpecificType.fullyQualifiedName().replace('$', '.'); } }</code><technical_language>minor : need for else returns..</technical_language>

Target:
private static String getSuggestedType(boolean springInjectionAnnotated, Type leastSpecificType) { if (springInjectionAnnotated && leastSpecificType.is("java.lang.Iterable")) { return "java.util.Collection"; } return leastSpecificType.fullyQualifiedName().replace('$', '.'); }
Source:
<code>public Response connectKieServer(@Context HttpHeaders headers, @PathParam("serverInstanceId") String id, String serverInfoPayload) { String contentType = getContentType(headers); logger.debug("Received connect request from server with id {}", id); KieServerInfo serverInfo = unmarshal(serverInfoPayload, contentType, KieServerInfo.class); if (serverInfo == null) { serverInfo = new KieServerInfo(); serverInfo.setServerId(id); } logger.debug("Server info {}", serverInfo); KieServerSetup serverSetup = connect(serverInfo); if (serverSetup.hasNoErrors()) { logger.info("Server with id '{}' connected", id); } else { <START> logger.info("Server with id '{}' failed to connect", id); <END> } String response = marshal(contentType, serverSetup); logger.debug("Returning response for connect of server '{}': {}", id, response); return createCorrectVariant(response, headers, serverSetup.hasNoErrors() ? Response.Status.CREATED : Response.Status.BAD_REQUEST); }</code><technical_language>sense raise log severity warning</technical_language>

Target:
public Response connectKieServer(@Context HttpHeaders headers, @PathParam("serverInstanceId") String id, String serverInfoPayload) { String contentType = getContentType(headers); logger.debug("Received connect request from server with id {}", id); KieServerInfo serverInfo = unmarshal(serverInfoPayload, contentType, KieServerInfo.class); if (serverInfo == null) { serverInfo = new KieServerInfo(); serverInfo.setServerId(id); } logger.debug("Server info {}", serverInfo); KieServerSetup serverSetup = connect(serverInfo); if (serverSetup.hasNoErrors()) { logger.info("Server with id '{}' connected", id); } else { logger.warn("Server with id '{}' failed to connect", id); } String response = marshal(contentType, serverSetup); logger.debug("Returning response for connect of server '{}': {}", id, response); return createCorrectVariant(response, headers, serverSetup.hasNoErrors() ? Response.Status.CREATED : Response.Status.BAD_REQUEST); }
Source:
<code>public CompletionStage<ResultT> start() { LOG.debug("[{}] Executing {}", logPrefix, this); <START> if (preAcquireId && !channel.preAcquireId()) { <END> setFinalError( new BusyConnectionException( String.format( "%s has reached its maximum number of simultaneous requests", channel))); } else { channel.write(message, false, customPayload, this).addListener(this::onWriteComplete); } return result; }</code><technical_language>This is a bit confusing me, I understand, preAcquireId means is pre-acquire, channel.preAcquireId() is actual acquisition of stream id, right? If so, I propose rename local field preAcquireId shouldPreAcquireId, wdyt</technical_language>

Target:
public CompletionStage<ResultT> start() { LOG.debug("[{}] Executing {}", logPrefix, this); if (shouldPreAcquireId && !channel.preAcquireId()) { setFinalError( new BusyConnectionException( String.format( "%s has reached its maximum number of simultaneous requests", channel))); } else { channel.write(message, false, customPayload, this).addListener(this::onWriteComplete); } return result; }
Source:
<code>public void rebindPartialActive(CompoundTransformer transformer, Iterator<BrooklynObject> objectsToRebind) { final ClassLoader classLoader = managementContext.getCatalog().getRootClassLoader(); final RebindExceptionHandler exceptionHandler = RebindExceptionHandlerImpl.builder() <START> .danglingRefFailureMode(danglingRefFailureMode) <END> .danglingRefQuorumRequiredHealthy(danglingRefsQuorumRequiredHealthy) .rebindFailureMode(rebindFailureMode) .addPolicyFailureMode(addPolicyFailureMode) .loadPolicyFailureMode(loadPolicyFailureMode) .build(); final ManagementNodeState mode = getRebindMode(); ActivePartialRebindIteration iteration = new ActivePartialRebindIteration(this, mode, classLoader, exceptionHandler, rebindActive, readOnlyRebindCount, rebindMetrics, persistenceStoreAccess); iteration.setObjectIterator(objectsToRebind); iteration.applyTransformer(transformer); iteration.run(); }</code><technical_language>Do want exception handler start-up? if is unhandled exception? state entities left in? I presume if exception is early (e.g. loading/transforming state etc) a no-op, if entity's manage() changed some entities others? partial-rebind run-time feels more dangerous startup possibly want exception handling (e.g. startup, happy fail-fast, JVM exits)</technical_language>

Target:
public void rebindPartialActive(CompoundTransformer transformer, Iterator<BrooklynObject> objectsToRebind) { final ClassLoader classLoader = managementContext.getCatalog().getRootClassLoader(); final RebindExceptionHandler exceptionHandler = RebindExceptionHandlerImpl.builder() .danglingRefFailureMode(danglingRefFailureMode) .danglingRefQuorumRequiredHealthy(danglingRefsQuorumRequiredHealthy) .rebindFailureMode(rebindFailureMode) .addPolicyFailureMode(addPolicyFailureMode) .loadPolicyFailureMode(loadPolicyFailureMode) .build(); final ManagementNodeState mode = getRebindMode(); ActivePartialRebindIteration iteration = new ActivePartialRebindIteration(this, mode, classLoader, exceptionHandler, rebindActive, readOnlyRebindCount, rebindMetrics, persistenceStoreAccess); iteration.setObjectIterator(Iterators.transform(objectsToRebind, new Function<BrooklynObject,BrooklynObject>() { @Override public BrooklynObject apply(BrooklynObject obj) { if (obj instanceof Entity) obj = Entities.deproxy((Entity)obj); return obj; } })); if (transformer!=null) iteration.applyTransformer(transformer); iteration.run(); }
Source:
<code>public int getItemViewType(int position) { String contentType = sections.get(position).getContentType(); switch (contentType) { case "post": return POST_CAROUSEL; case "chapter_content": return CONTENT_CAROUSEL; case "banner_ad": return OFFERS_CAROUSEL; case "chapter_content_attempt": return CONTENT_CAROUSEL; case "products": return COURSE_CAROUSEL; <START> case "trophy_leaderboard": if (instituteSettings.getLeaderboardEnabled()) return LEADERBOARD_LIST; <END> } return -1; }</code><technical_language>is logic hide leaderboard? check this hides leaderboard</technical_language>

Target:
public int getItemViewType(int position) { String contentType = sections.get(position).getContentType(); switch (contentType) { case "post": return POST_CAROUSEL; case "chapter_content": return CONTENT_CAROUSEL; case "banner_ad": return OFFERS_CAROUSEL; case "chapter_content_attempt": return CONTENT_CAROUSEL; case "products": return COURSE_CAROUSEL; case "trophy_leaderboard": if (isLeaderBoardEnabled()) return LEADERBOARD_LIST; } return -1; }
Source:
<code>public void put(List<Put> puts) throws IOException { <START> batchExecutor.batch(puts); <END> }</code><technical_language>batch -> put ? a test catch it</technical_language>

Target:
public void put(List<Put> puts) throws IOException { batchExecutor.put(puts); }
Source:
<code>public HpccRemoteFileReader(DataPartition dp, FieldDef originalRD, IRecordBuilder recBuilder) throws Exception { <START> this(dp,originalRD,recBuilder,-1); <END> }</code><technical_language>create a Final Static int DEFAULT_CONN_TIMEOUT_OPTION = -1;</technical_language>

Target:
public HpccRemoteFileReader(DataPartition dp, FieldDef originalRD, IRecordBuilder recBuilder) throws Exception { this(dp,originalRD,recBuilder,DEFAULT_CONNECT_TIMEOUT_OPTION); }
Source:
<code>public void dropTableIfExistsCascade(final RelationKey relationKey) throws DbException { switch (jdbcInfo.getDbms()) { case MyriaConstants.STORAGE_SYSTEM_MYSQL: <START> execute("DROP TABLE IF EXISTS " + quote(relationKey)); <END> break; case MyriaConstants.STORAGE_SYSTEM_POSTGRESQL: execute("DROP TABLE IF EXISTS " + quote(relationKey) + " CASCADE"); break; default: throw new UnsupportedOperationException("Don't know whether " + jdbcInfo.getDbms() + " can DROP IF EXISTS a table"); } }</code><technical_language>log a warning MySQL implement CASCADE</technical_language>

Target:
public void dropTableIfExistsCascade(final RelationKey relationKey) throws DbException { switch (jdbcInfo.getDbms()) { case MyriaConstants.STORAGE_SYSTEM_MYSQL: LOGGER.warn("MySQL does not implement DROP TABLE...CASCADE, attempting DROP TABLE instead"); execute("DROP TABLE IF EXISTS " + quote(relationKey)); break; case MyriaConstants.STORAGE_SYSTEM_POSTGRESQL: execute("DROP TABLE IF EXISTS " + quote(relationKey) + " CASCADE"); break; default: throw new UnsupportedOperationException("Don't know whether " + jdbcInfo.getDbms() + " can DROP IF EXISTS...CASCADE a table"); } }
Source:
<code>public static void setCloudNotificationsEnabled(Context context, boolean isEnabled) { SharedPreferences.Editor editor = getSharedPreferences(context).edit(); <START> editor.putBoolean(SETTINGS_CLOUD_NOTIFICATIONS, isEnabled); <END> editor.commit(); CloudMessaging.initialize(context); }</code><technical_language>put .commit() end of this. Editor calls return Editor ;)</technical_language>

Target:
public static void setCloudNotificationsEnabled(Context context, boolean isEnabled) { SharedPreferences.Editor editor = getSharedPreferences(context).edit(); editor.putBoolean(SETTINGS_CLOUD_NOTIFICATIONS, isEnabled).commit(); CloudMessaging.initialize(context); }
Source:
<code>public void showRateLimitError(boolean userTriggered) { if (HiddenPreferences.isRateLimitPopupDisabled() || !userTriggered) { <START> handleFormSendResult(Localization.get("sync.fail.rate.limited.server.error"), false); <END> return; } String title = Localization.get("form.send.rate.limit.error.title"); String message = Localization.get("form.send.rate.limit.error.message"); StandardAlertDialog dialog = StandardAlertDialog.getBasicAlertDialog(this, title, message, null); dialog.setNegativeButton(Localization.get("dialog.button.do.not.show.again"), (dialog1, which) -> { HiddenPreferences.disableRateLimitPopup(true); dismissAlertDialog(); }); dialog.setPositiveButton(Localization.get("dialog.button.close"), (dialog1, which) -> { dismissAlertDialog(); }); showAlertDialog(dialog); }</code><technical_language>show form submission specific message</technical_language>

Target:
public void showRateLimitError(boolean userTriggered) { if (HiddenPreferences.isRateLimitPopupDisabled() || !userTriggered) { handleFormSendResult(Localization.get("form.send.rate.limit.error.toast"), false); return; } String title = Localization.get("form.send.rate.limit.error.title"); String message = Localization.get("form.send.rate.limit.error.message"); StandardAlertDialog dialog = StandardAlertDialog.getBasicAlertDialog(this, title, message, null); dialog.setNegativeButton(Localization.get("rate.limit.error.dialog.do.not.show"), (dialog1, which) -> { HiddenPreferences.disableRateLimitPopup(true); dismissAlertDialog(); }); dialog.setPositiveButton(Localization.get("rate.limit.error.dialog.close"), (dialog1, which) -> { dismissAlertDialog(); }); showAlertDialog(dialog); }
Source:
<code>private void prepareNoteExtendedAttributes() { if (LOG.isDebugEnabled()) { LOG.debug("prepareNoteExtendedAttributes, number of notes to review: " + getNotes().size()); } for (Note note : getNotes()) { <START> if (note.getNoteIdentifier() == null) { <END> LOG.debug("prepareNoteExtendedAttributes, found a note without an ID, it needs to be set."); Long newNoteId = getSequenceAccessorService().getNextAvailableSequenceNumber(CUKFSConstants.NOTE_SEQUENCE_NAME); note.setNoteIdentifier(newNoteId); } NoteExtendedAttribute extendedAttribute; if (ObjectUtils.isNull(note.getExtension())) { if (LOG.isDebugEnabled()) { LOG.debug("prepareNoteExtendedAttributes, found a note without an extentsion, note ID " + note.getNoteIdentifier()); } extendedAttribute = new NoteExtendedAttribute(); note.setExtension(extendedAttribute); } else { extendedAttribute = (NoteExtendedAttribute) note.getExtension(); } if (ObjectUtils.isNull(extendedAttribute.getNoteIdentifier())) { if (LOG.isDebugEnabled()) { LOG.debug("prepareNoteExtendedAttributes, the note " + note.getNoteIdentifier() + " has an extended attribute without a note identifier."); } extendedAttribute.setNoteIdentifier(note.getNoteIdentifier()); } } }</code><technical_language>this method is long, split in smaller pieces</technical_language>

Target:
private void prepareNoteExtendedAttributes() { if (LOG.isDebugEnabled()) { LOG.debug("prepareNoteExtendedAttributes, number of notes to review: " + getNotes().size()); } for (Note note : getNotes()) { setNoteIdentifierIfEmpty(note); NoteExtendedAttribute extendedAttribute = retrieveOrCreateNoteExtendedAttribute(note); setNoteExtendedAttributeNoteIdentifierIfEmpty(note, extendedAttribute); } }
Source:
<code>private Mono<Lease> renew(CancellationToken cancellationToken) { LeaseRenewerImpl self = this; if (cancellationToken.isCancellationRequested()) return Mono.empty(); return self.leaseManager.renew(self.lease) .map(renewedLease -> { if (renewedLease != null) { self.lease = renewedLease; } logger.info(String.format("Partition %s: renewed lease with result %s", self.lease.getLeaseToken(), renewedLease != null)); return renewedLease; }) .onErrorResume(throwable -> { if (throwable instanceof LeaseLostException) { LeaseLostException lle = (LeaseLostException) throwable; self.resultException = lle; <START> logger.error(String.format("Partition %s: lost lease on renew.", self.lease.getLeaseToken()), lle); <END> return Mono.error(lle); } logger.error(String.format("Partition %s: failed to renew lease.", self.lease.getLeaseToken()), throwable); return Mono.empty(); }); }</code><technical_language>slf4j logger support for place holder {}, need String.format here. remove String.format <LINK_0></technical_language>

Target:
private Mono<Lease> renew(CancellationToken cancellationToken) { if (cancellationToken.isCancellationRequested()) { return Mono.empty(); } return this.leaseManager.renew(this.lease) .map(renewedLease -> { if (renewedLease != null) { this.lease = renewedLease; } logger.info("Partition {}: renewed lease with result {}", this.lease.getLeaseToken(), renewedLease != null); return renewedLease; }) .onErrorResume(throwable -> { if (throwable instanceof LeaseLostException) { LeaseLostException lle = (LeaseLostException) throwable; this.resultException = lle; logger.error("Partition {}: lost lease on renew.", this.lease.getLeaseToken(), lle); return Mono.error(lle); } logger.error("Partition {}: failed to renew lease.", this.lease.getLeaseToken(), throwable); return Mono.empty(); }); }
Source:
<code>public void apply(String endpointId, FileChangedEventDto dto) { Tree tree = projectExplorerPresenterProvider.get().getTree(); tree.getNodeStorage() .getAll() .stream() .filter( node -> node instanceof FileNode && ((ResourceNode) node) .getData() .getLocation() .equals(Path.valueOf(dto.getPath()))) .forEach( node -> { ((ResourceNode) node) .getData() .asFile() .setVcsStatus(VcsStatus.from(dto.getStatus().toString())); tree.refresh(node); }); editorAgentProvider .get() .getOpenedEditors() .stream() .filter( editor -> editor.getEditorInput().getFile().getLocation().equals(Path.valueOf(dto.getPath()))) .forEach( editor -> { VcsStatus vcsStatus = VcsStatus.from(dto.getStatus().toString()); EditorTab tab = multiPartStackProvider.get().getTabByPart(editor); if (vcsStatus != null) { tab.setTitleColor(vcsStatus.getColor()); } <START> VcsChangeMarkerRender render = <END> ((HasVcsChangeMarkerRender) editor).getVcsChangeMarkersRender(); if (((File) editor.getEditorInput().getFile()).getVcsStatus() != MODIFIED) { render.clearAllChangeMarkers(); } else { handleEditedRegions(dto.getEditedRegions(), render); } }); appContext.getWorkspaceRoot().synchronize(); }</code><technical_language>Add instance of checks</technical_language>

Target:
public void apply(String endpointId, FileChangedEventDto dto) { Tree tree = projectExplorerPresenterProvider.get().getTree(); tree.getNodeStorage() .getAll() .stream() .filter( node -> node instanceof FileNode && ((ResourceNode) node) .getData() .getLocation() .equals(Path.valueOf(dto.getPath()))) .forEach( node -> { setVcsStatusToEditorsFile( Path.valueOf(dto.getPath()), VcsStatus.from(dto.getStatus().toString())); ((ResourceNode) node) .getData() .asFile() .setVcsStatus(VcsStatus.from(dto.getStatus().toString())); tree.refresh(node); }); editorAgentProvider .get() .getOpenedEditors() .stream() .filter( editor -> editor.getEditorInput().getFile().getLocation().equals(Path.valueOf(dto.getPath())) && editor instanceof HasVcsChangeMarkerRender) .forEach( editor -> { VcsStatus vcsStatus = VcsStatus.from(dto.getStatus().toString()); EditorTab tab = multiPartStackProvider.get().getTabByPart(editor); if (vcsStatus != null) { tab.setTitleColor(vcsStatus.getColor()); } VcsChangeMarkerRender render = ((HasVcsChangeMarkerRender) editor).getVcsChangeMarkersRender(); if (((File) editor.getEditorInput().getFile()).getVcsStatus() != MODIFIED) { render.clearAllChangeMarkers(); } else { handleEditedRegions(dto.getEditedRegions(), render); } }); }
Source:
<code>CronJobsDefinitionsRegistry(final CronJobsRegistry cronJobsRegistry) { cronJobDefinitions = cronJobsRegistry.get() .stream() .map(ThrowingFunction.unchecked(clazz -> clazz.newInstance() .getCronJobDefinition())) <START> .collect(Collectors.toSet()); <END> }</code><technical_language>Is a reason for changing this immutable mutable? this introduce potential concurrency/thread/ordering issues</technical_language>

Target:
CronJobsDefinitionsRegistry(final CronJobsRegistry cronJobsRegistry) { cronJobDefinitions = cronJobsRegistry.get() .stream() .map(ThrowingFunction.unchecked(clazz -> clazz.newInstance() .getCronJobDefinition())) .collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet)); }
Source:
<code>private ApiInfo readApiInfo(ServletContext context) { try { try (InputStream inputStream = context.getResourceAsStream("/META-INF/MANIFEST.MF")) { final Manifest manifest = new Manifest(inputStream); final Attributes mainAttributes = manifest.getMainAttributes(); final DtoFactory dtoFactory = DtoFactory.getInstance(); return dtoFactory .createDto(ApiInfo.class) .withSpecificationVendor(mainAttributes.getValue("Specification-Vendor")) .withImplementationVendor(mainAttributes.getValue("Implementation-Vendor")) <START> .withSpecificationTitle("Codenvy REST API") <END> .withSpecificationVersion(mainAttributes.getValue("Specification-Version")) .withImplementationVersion(mainAttributes.getValue("Implementation-Version")) .withScmRevision(mainAttributes.getValue("SCM-Revision")); } } catch (Exception e) { LOG.error("Unable to read API info. Error: " + e.getMessage(), e); throw new RuntimeException("Unable to read API information", e); } }</code><technical_language>Please consider changing Che REST API in this PR create a separate issue</technical_language>

Target:
private ApiInfo readApiInfo(ServletContext context) { try { try (InputStream inputStream = context.getResourceAsStream("/META-INF/MANIFEST.MF")) { final Manifest manifest = new Manifest(inputStream); final Attributes mainAttributes = manifest.getMainAttributes(); final DtoFactory dtoFactory = DtoFactory.getInstance(); return dtoFactory .createDto(ApiInfo.class) .withSpecificationVendor(mainAttributes.getValue("Specification-Vendor")) .withImplementationVendor(mainAttributes.getValue("Implementation-Vendor")) .withSpecificationTitle("Che REST API") .withSpecificationVersion(mainAttributes.getValue("Specification-Version")) .withImplementationVersion(mainAttributes.getValue("Implementation-Version")) .withScmRevision(mainAttributes.getValue("SCM-Revision")); } } catch (Exception e) { LOG.error("Unable to read API info. Error: " + e.getMessage(), e); throw new RuntimeException("Unable to read API information", e); } }
Source:
<code>public static void writeToBuckFile(Multimap<String, String> loadStatements, List<Rule> rules, File buckFile) { if (!rules.isEmpty()) { File parent = buckFile.getParentFile(); if (!parent.exists() && !parent.mkdirs()) { throw new IllegalStateException("Couldn't create dir: " + parent); } try ( OutputStream fos = new FileOutputStream(buckFile); BufferedOutputStream os = new BufferedOutputStream(fos)){ <START> writeLoadStatements(loadStatements, os); <END> for (int index = 0; index < rules.size(); index++) { if (index != 0) { os.write(NEWLINE); } rules.get(index).render(os); } } catch (IOException e) { throw new IllegalStateException("Couldn't create the buck file", e); } } }</code><technical_language>rocker for passing in a list of loads instead</technical_language>

Target:
public static void writeToBuckFile(Multimap<String, String> loadStatements, List<Rule> rules, File buckFile) { if (!rules.isEmpty()) { File parent = buckFile.getParentFile(); if (!parent.exists() && !parent.mkdirs()) { throw new IllegalStateException("Couldn't create dir: " + parent); } try ( OutputStream fos = new FileOutputStream(buckFile); BufferedOutputStream os = new BufferedOutputStream(fos)){ if (!loadStatements.isEmpty()) { LoadStatements.template(writableLoadStatements(loadStatements)).render(os); } for (int index = 0; index < rules.size(); index++) { if (index != 0) { os.write(NEWLINE); } rules.get(index).render(os); } } catch (IOException e) { throw new IllegalStateException("Couldn't create the buck file", e); } } }
Source:
<code>public String getDisplayValue() { CutoffFacetNode lastNode = this.getHighestTierNode(); if (lastNode == null) return null; <START> return lastNode.getSearchKey(); <END> }</code><technical_language>getSearchKey getDisplayValue</technical_language>

Target:
public String getDisplayValue() { return getSearchKey(); }
Source:
<code>public CompletableFuture<List<Map<String, Object>>> get (DataFetchingEnvironment environment) { Map<String, Object> parentEntityMap = environment.getSource(); String namespace = (String) parentEntityMap.get("namespace"); List<String> inClauseValues = new ArrayList<>(); if (parentJoinField != null) { Map<String, Object> enclosingEntity = environment.getSource(); Object inClauseValue = enclosingEntity.get(parentJoinField); String inClauseString = inClauseValue == null ? null : inClauseValue.toString(); inClauseValues.add(inClauseString); if (inClauseValue == null) { return new CompletableFuture<>(); } } Map<String, Object> arguments = environment.getArguments(); StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder.append("select *"); return getResults( getJdbcQueryDataLoaderFromContext(environment), <START> getDataSourceFromContext(environment), <END> namespace, inClauseValues, arguments, new ArrayList<>(), new ArrayList<>(), new HashSet<>(), sqlBuilder ); }</code><technical_language>data loader data source coming environment variable, pass getResults helper methods method</technical_language>

Target:
public CompletableFuture<List<Map<String, Object>>> get (DataFetchingEnvironment environment) { List<String> inClauseValues = new ArrayList<>(); List<String> whereConditions = new ArrayList<>(); List<String> preparedStatementParameters = new ArrayList<>(); if (parentJoinField != null) { Map<String, Object> enclosingEntity = environment.getSource(); Object inClauseValue = enclosingEntity.get(parentJoinField); String inClauseString = inClauseValue == null ? null : inClauseValue.toString(); inClauseValues.add(inClauseString); if (inClauseValue == null) { return new CompletableFuture<>(); } whereConditions.add(makeInClause(parentJoinField, inClauseValues, preparedStatementParameters)); } return getResults( environment, "select *", new HashSet<>(), whereConditions, preparedStatementParameters ); }