auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean matchingValues(Object object1, Object object2) { final boolean equal; if (object1 == object2) { equal = true; } else if (object1 == null) { equal = "".equals(object2); } else if (object2 == null) { equal = "".equals(object1); } else if (object1 instanceof EObject) { if (object2 instanceof EObject) { equal = matchingEObjects((EObject)object1, (EObject)object2); } else { equal = false; } } else if (object1 instanceof String || object1 instanceof Integer || object1 instanceof Boolean) { equal = object1.equals(object2); } else if (object1.getClass().isArray() && object2.getClass().isArray()) { equal = matchingArrays(object1, object2); } else if (object1 instanceof FeatureMap.Entry && object2 instanceof FeatureMap.Entry) { FeatureMap.Entry featureMapEntry1 = (FeatureMap.Entry)object1; EStructuralFeature key1 = featureMapEntry1.getEStructuralFeature(); FeatureMap.Entry featureMapEntry2 = (FeatureMap.Entry)object2; EStructuralFeature key2 = featureMapEntry2.getEStructuralFeature(); Object value1 = featureMapEntry1.getValue(); Object value2 = featureMapEntry2.getValue(); equal = <START> key1 == key2 && <END> matchingValues(value1, value2); } else { equal = object1.equals(object2); } return equal; }</code><technical_language>I this optimization of repacing .equals '=' is correct. I suspect cases dynamic metamodels instance of feature side of a comparison..</technical_language>

Target:
public boolean matchingValues(Object object1, Object object2) { final boolean equal; if (object1 == object2) { equal = true; } else if (object1 == null) { equal = "".equals(object2); } else if (object2 == null) { equal = "".equals(object1); } else if (object1 instanceof EObject) { if (object2 instanceof EObject) { equal = matchingEObjects((EObject)object1, (EObject)object2); } else { equal = false; } } else if (object1 instanceof String || object1 instanceof Integer || object1 instanceof Boolean) { equal = object1.equals(object2); } else if (object1.getClass().isArray() && object2.getClass().isArray()) { equal = matchingArrays(object1, object2); } else if (object1 instanceof FeatureMap.Entry && object2 instanceof FeatureMap.Entry) { FeatureMap.Entry featureMapEntry1 = (FeatureMap.Entry)object1; EStructuralFeature key1 = featureMapEntry1.getEStructuralFeature(); FeatureMap.Entry featureMapEntry2 = (FeatureMap.Entry)object2; EStructuralFeature key2 = featureMapEntry2.getEStructuralFeature(); Object value1 = featureMapEntry1.getValue(); Object value2 = featureMapEntry2.getValue(); equal = key1.equals(key2) && matchingValues(value1, value2); } else { equal = object1.equals(object2); } return equal; }
Source:
<code>private boolean activeSDsExist(List<LUNs> luns, String vgId, Guid poolId) { <START> List<String> storageIDs = new ArrayList<>(luns.size()); <END> for (LUNs lun : luns) { if (lun.getStorageDomainId() != null && !lun.getvolume_group_id().equals(vgId)) { storageIDs.add(lun.getStorageDomainId().toString()); } } if (!storageIDs.isEmpty()) { String ids = StringUtils.join(storageIDs, ","); List<StoragePoolIsoMap> isomaps = DbFacade.getInstance().getStoragePoolIsoMapDao().getAllForStorages(ids, poolId); return isomaps.size() > 0; } return false; }</code><technical_language>this a set, please a set of Guid</technical_language>

Target:
private boolean activeSDsExist(List<LUNs> luns, String vgId, Guid poolId) { if (poolId == null) { return true; } Set<Guid> storageIDs = new HashSet<>(luns.size()); for (LUNs lun : luns) { if (lun.getStorageDomainId() != null && !lun.getvolume_group_id().equals(vgId)) { storageIDs.add(lun.getStorageDomainId()); } } if (storageIDs.isEmpty()) { return false; } String ids = StringUtils.join(storageIDs, ","); List<StoragePoolIsoMap> isomaps = DbFacade.getInstance().getStoragePoolIsoMapDao().getAllForStorages(ids, poolId); for (StoragePoolIsoMap isomap : isomaps) { if (isomap.getStatus() != StorageDomainStatus.Maintenance) { return true; } } return false; }
Source:
<code>public void sendMessagesToPushNetwork(@Observes @Dequeue MessageHolderWithTokens msg) { final Variant variant = msg.getVariant(); final UnifiedPushMessage unifiedPushMessage = msg.getUnifiedPushMessage(); final Collection<String> deviceTokens = msg.getDeviceTokens(); <START> logger.info(String.format("UnifiedPushMessage was successfully received. Push Notification delivery for the variant ({}) will now be triggered.", variant.getType().getTypeName(), variant.getVariantID())); <END> senders.select(new SenderTypeLiteral(variant.getType())).get() .sendPushMessage(variant, deviceTokens, unifiedPushMessage, msg.getPushMessageInformation().getId(), new SenderServiceCallback( variant, deviceTokens.size(), msg.getPushMessageInformation() ) ); }</code><technical_language>it, please remove String.format() w/ vanilla syntax slf4j. thx</technical_language>

Target:
public void sendMessagesToPushNetwork(@Observes @Dequeue MessageHolderWithTokens msg) { final Variant variant = msg.getVariant(); final UnifiedPushMessage unifiedPushMessage = msg.getUnifiedPushMessage(); final Collection<String> deviceTokens = msg.getDeviceTokens(); logger.info("UnifiedPushMessage was successfully received. Push Notification delivery for the variant ({}) will now be triggered.", variant.getType().getTypeName(), variant.getVariantID()); senders.select(new SenderTypeLiteral(variant.getType())).get() .sendPushMessage(variant, deviceTokens, unifiedPushMessage, msg.getPushMessageInformation().getId(), new SenderServiceCallback( variant, deviceTokens.size(), msg.getPushMessageInformation() ) ); }
Source:
<code>public OVirtNodeUpgrade(VDS vds, File iso) { _vds = vds; _iso = iso; _messages = new InstallerMessages(_vds); _dialog = new <START> EngineSSHDialog(); <END> long softTimeout = 2 * Config.<Integer>getValue(ConfigValues.SSHInactivityTimeoutSeconds) * 1000; long hardTimeout = Config.<Integer>getValue(ConfigValues.SSHInactivityHardTimeoutSeconds) * 1000; _dialog.setSoftTimeout(softTimeout); _dialog.setHardTimeout( softTimeout > hardTimeout ? softTimeout : hardTimeout); _thread = new Thread( this::threadMain, "OVirtNodeUpgrade" ); }</code><technical_language>EngineSSHDialog is in 2 places changed this patch. code is exact in 2 location. suggest adding a new c'tor EngineSSHDialog(hardTimeout, softTimeout) move _dialog.set[Soft|Hard]Timeout there. Alternately, introduce a method HostUpgradeManager.updateSshDialogTimeout(EngineSSHDialog dialog) perform exact code done in places. HostUpgradeManager is a recommendation, other shared reasonable class is good well</technical_language>

Target:
public OVirtNodeUpgrade(VDS vds, File iso) { _vds = vds; _iso = iso; _messages = new InstallerMessages(_vds); _dialog = new EngineSSHDialog( 2 * TimeUnit.SECONDS.toMillis( Config.<Integer>getValue(ConfigValues.SSHInactivityTimeoutSeconds)), TimeUnit.SECONDS.toMillis( Config.<Integer>getValue(ConfigValues.SSHInactivityHardTimeoutSeconds))); _thread = new Thread( this::threadMain, "OVirtNodeUpgrade" ); }
Source:
<code>public void begin() { if ( !session.isOpen() ) { throw new IllegalStateException( "Cannot begin Transaction on closed Session/EntityManager" ); } if ( transactionDriverControl == null ) { transactionDriverControl = transactionCoordinator.getTransactionDriverControl(); } if ( isActive() ) { throw new IllegalStateException( "Transaction already active" ); } <START> if ( LOG.isDebugEnabled() ) { <END> LOG.debug( "begin" ); } this.transactionDriverControl.begin(); }</code><technical_language>changing these? Generally this is done avoid expensive resolution of message log. Here, is case. In fact, this perform worse? IIUC this simply forces 2 "is debug enabled" checks</technical_language>

Target:
public void begin() { if ( !session.isOpen() ) { throw new IllegalStateException( "Cannot begin Transaction on closed Session/EntityManager" ); } if ( transactionDriverControl == null ) { transactionDriverControl = transactionCoordinator.getTransactionDriverControl(); } if ( isActive() ) { throw new IllegalStateException( "Transaction already active" ); } LOG.debug( "begin" ); this.transactionDriverControl.begin(); }
Source:
<code><START> public Boolean isWmtsCiteCompliant() { <END> return wmtsCiteCompliant; }</code><technical_language>Confused change of signature... keeping field Boolean for XStream, "boolean" for methods, do a null check body</technical_language>

Target:
public boolean isWmtsCiteCompliant() { return wmtsCiteCompliant != null ? wmtsCiteCompliant : false; }
Source:
<code>public void leaveToken(DetailAST token) { switch (token.getType()) { <START> case TokenTypes.CLASS_DEF: <END> hasServiceClientBuilderAnnotation = hasServiceClientBuilderAnnotationStack.pop(); break; default: break; } }</code><technical_language>here. case - replace switch if</technical_language>

Target:
public void leaveToken(DetailAST token) { if (token.getType() == TokenTypes.CLASS_DEF) { hasServiceClientBuilderAnnotation = hasServiceClientBuilderAnnotationStack.pop(); hasBuildMethod = hasBuildMethodStack.pop(); if (hasServiceClientBuilderAnnotation && !hasBuildMethod) { log(token, "Class with @ServiceClientBuilder annotation must have a method starting with ''build'' and ending with ''Client''."); } } }
Source:
<code><START> protected void incrementCounter() { for (int i = iv.length - 1; i >= iv.length - Long.BYTES; i--) { iv[i]++; if (iv[i] != 0) { break; } } } <END></code><technical_language>pretty dangerous 2's complement arithmetic - I a decodeLong/encodeLong method..</technical_language>

Target:
protected void incrementCounter() { int off = iv.length - Long.BYTES; long counter = BufferUtils.getLong(iv, off, Long.BYTES); BufferUtils.putLong(Math.addExact(counter, 1L), iv, off, Long.BYTES); }
Source:
<code><START> private void registerPlayStatusMessageHandler() { <END> this.messageDispatch.registerHandler(PlayStatusMessage.class, new IMessageHandler<PlayStatusMessage>() { @Override public void handleMessage(int messageNo, PlayStatusMessage message, String fromAddr) { new BroadcastIntent(ACTION_PLAY_STATUS_MESSAGE) .putExtra( EXTRA_IS_PLAYING, message.getString().equals( PlayStatusMessage.PLAY_MESSAGE)) .send(MessagingService.this); } }); }</code><technical_language>change in this block? Is whitespace</technical_language>

Target:
private void registerPlayStatusMessageHandler() { this.messageDispatch.registerHandler(PlayStatusMessage.class, new IMessageHandler<PlayStatusMessage>() { @Override public void handleMessage(int messageNo, PlayStatusMessage message, String fromAddr) { new BroadcastIntent(ACTION_PLAY_STATUS_MESSAGE) .putExtra(EXTRA_IS_PLAYING, message.isPlaying()) .putExtra(EXTRA_ADDRESS, message.getMacAddress()) .putExtra(EXTRA_SONG_ID, message.getId()) .send(MessagingService.this); } }); }
Source:
<code>public CoordinatorDynamicConfig build() { return new CoordinatorDynamicConfig( <START> millisToWaitBeforeDeleting == null ? 15 * 60 * 1000L : millisToWaitBeforeDeleting, <END> mergeBytesLimit == null ? 524288000L : mergeBytesLimit, mergeSegmentsLimit == null ? 100 : mergeSegmentsLimit, maxSegmentsToMove == null ? 5 : maxSegmentsToMove, replicantLifetime == null ? 15 : replicantLifetime, replicationThrottleLimit == null ? 10 : replicationThrottleLimit, balancerComputeThreads == null ? 1 : balancerComputeThreads, emitBalancingStats == null ? false : emitBalancingStats, killDataSourceWhitelist, killAllDataSources == null ? false : killAllDataSources, maxSegmentsInNodeLoadingQueue == null ? 0 : maxSegmentsInNodeLoadingQueue ); }</code><technical_language>Please TimeUnit.MINUTES.toMillis(15)</technical_language>

Target:
public CoordinatorDynamicConfig build() { return new CoordinatorDynamicConfig( millisToWaitBeforeDeleting == null ? DEFAULT_MILLIS_TO_WAIT_BEFORE_DELETING : millisToWaitBeforeDeleting, mergeBytesLimit == null ? DEFAULT_MERGE_BYTES_LIMIT : mergeBytesLimit, mergeSegmentsLimit == null ? DEFAULT_MERGE_SEGMENTS_LIMIT : mergeSegmentsLimit, maxSegmentsToMove == null ? DEFAULT_MAX_SEGMENTS_TO_MOVE : maxSegmentsToMove, replicantLifetime == null ? DEFAULT_REPLICANT_LIFETIME : replicantLifetime, replicationThrottleLimit == null ? DEFAULT_REPLICATION_THROTTLE_LIMIT : replicationThrottleLimit, balancerComputeThreads == null ? DEFAULT_BALANCER_COMPUTE_THREADS : balancerComputeThreads, emitBalancingStats == null ? DEFAULT_EMIT_BALANCING_STATS : emitBalancingStats, killDataSourceWhitelist, killAllDataSources == null ? DEFAULT_KILL_ALL_DATA_SOURCES : killAllDataSources, maxSegmentsInNodeLoadingQueue == null ? DEFAULT_MAX_SEGMENTS_IN_NODE_LOADING_QUEUE : maxSegmentsInNodeLoadingQueue ); }
Source:
<code><START> static String getEnvironmentalVariable (String envVarName) { <END> String envVarValue = System.getProperty(envVarName); if (envVarValue == null) { long ptr = OS.getenv(ascii(envVarName)); if (ptr != 0) { int length = OS.strlen(ptr); byte[] buffer = new byte[length]; OS.memmove(buffer, ptr, length); char[] convertedChar = new char[buffer.length]; for (int i = 0; i < buffer.length; i++) { convertedChar[i]=(char)buffer[i]; } envVarValue = new String(convertedChar); } } return envVarValue; }</code><technical_language>this method private. a bit more conservative is worth here</technical_language>

Target:
private static String getEnvironmentalVariable (String envVarName) { String envVarValue = System.getProperty(envVarName); if (envVarValue == null) { long ptr = OS.getenv(ascii(envVarName)); if (ptr != 0) { int length = OS.strlen(ptr); byte[] buffer = new byte[length]; OS.memmove(buffer, ptr, length); char[] convertedChar = new char[buffer.length]; for (int i = 0; i < buffer.length; i++) { convertedChar[i]=(char)buffer[i]; } envVarValue = new String(convertedChar); } } return envVarValue; }
Source:
<code>public Mono<T> one(T object) { return Mono.just(object).flatMap(o -> { CouchbaseDocument converted = template.support().encodeEntity(o); return template.getCollection(collection).reactive() <START> .replace(converted.getId(), converted.export(), buildReplaceOptions(object)).map(result -> { <END> template.support().applyUpdatedCas(object, result.cas()); return o; }); }).onErrorMap(throwable -> { if (throwable instanceof RuntimeException) { return template.potentiallyConvertRuntimeException((RuntimeException) throwable); } else { return throwable; } }); }</code><technical_language>nit: this o, object, right</technical_language>

Target:
public Mono<T> one(T object) { return Mono.just(object).flatMap(o -> { CouchbaseDocument converted = template.support().encodeEntity(o); return template.getCollection(collection).reactive() .replace(converted.getId(), converted.export(), buildReplaceOptions(o)).map(result -> { template.support().applyUpdatedCas(o, result.cas()); return o; }); }).onErrorMap(throwable -> { if (throwable instanceof RuntimeException) { return template.potentiallyConvertRuntimeException((RuntimeException) throwable); } else { return throwable; } }); }
Source:
<code>private void deleteVolume(VolumeInfo volumeInfo, long storagePoolId) { try { long volumeId = volumeInfo.getId(); SolidFireUtil.SolidFireConnection sfConnection = SolidFireUtil.getSolidFireConnection(storagePoolId, _storagePoolDetailsDao); deleteSolidFireVolume(sfConnection, volumeInfo); _volumeDetailsDao.removeDetails(volumeId); StoragePoolVO storagePool = _storagePoolDao.findById(storagePoolId); long usedBytes = getUsedBytes(storagePool, volumeId); storagePool.setUsedBytes(usedBytes < 0 ? 0 : usedBytes); _storagePoolDao.update(storagePoolId, storagePool); } <START> catch (Exception ex) { <END> s_logger.debug(SolidFireUtil.LOG_PREFIX + "Failed to delete SolidFire volume. CloudStack volume ID: " + volumeInfo.getId(), ex); throw ex; } }</code><technical_language>needed here? why</technical_language>

Target:
private void deleteVolume(VolumeInfo volumeInfo, long storagePoolId) { try { long volumeId = volumeInfo.getId(); SolidFireUtil.SolidFireConnection sfConnection = SolidFireUtil.getSolidFireConnection(storagePoolId, storagePoolDetailsDao); deleteSolidFireVolume(sfConnection, volumeInfo); volumeDetailsDao.removeDetails(volumeId); StoragePoolVO storagePool = storagePoolDao.findById(storagePoolId); long usedBytes = getUsedBytes(storagePool, volumeId); storagePool.setUsedBytes(usedBytes < 0 ? 0 : usedBytes); storagePoolDao.update(storagePoolId, storagePool); } catch (Exception ex) { LOGGER.debug(SolidFireUtil.LOG_PREFIX + "Failed to delete SolidFire volume. CloudStack volume ID: " + volumeInfo.getId(), ex); throw ex; } }
Source:
<code>private void ensureCredential() throws Exception { if(credential ==null){ try { credential = BuildCredentialForCredentialsFile(ParseCredentialsFile(filepath)); } catch (Exception e){ <START> throw new Exception("Error parsing SDK Auth File", e); <END> } } }</code><technical_language>Good add logger.logExceptionAsError(new Exception....) logger azure core Ideally, a Exception class Exception, InvalidArgumentException. Plus, IOException need handled separately, bubbled is</technical_language>

Target:
void ensureCredential() { if (credential == null) { try { credential = buildCredentialForCredentialsFile(parseCredentialsFile(filepath)); } catch (Exception e) { throw logger.logExceptionAsError(new RuntimeException("Error parsing SDK Auth File", e)); } } }
Source:
<code>public static ResultSet lookupUniversityID(Connection connection, int univid) <START> throws ServiceException{ <END> CodeContract.assertNotNull(univid, "univid"); try{ PreparedStatement lookupStatement = connection.prepareStatement(LOOKUP_UNIVERSITY_ID_QUERY); lookupStatement.setInt(1, univid); return lookupStatement.executeQuery(); }catch (SQLException ex) { throw new ServiceException(ServiceStatus.DATABASE_ERROR, ex); } }</code><technical_language>_nitpick_: space ServiceException curly brace</technical_language>

Target:
public static ResultSet lookupUniversityID(Connection connection, int univid) throws ServiceException { CodeContract.assertNotNull(connection, "connection"); try { PreparedStatement lookupStatement = connection.prepareStatement(LOOKUP_UNIVERSITY_ID_QUERY); lookupStatement.setInt(1, univid); return lookupStatement.executeQuery(); } catch (SQLException ex) { throw new ServiceException(ServiceStatus.DATABASE_ERROR, ex); } }
Source:
<code>public boolean exec() throws CliException { String path = args[1]; CompletableFuture<Integer> cf = new CompletableFuture<>(); try { zk.sync(path, new AsyncCallback.VoidCallback() { public void processResult(int rc, String path, Object ctx) { cf.complete(rc); } }, null); int resultCode = cf.get(SYNC_TIMEOUT, TimeUnit.MILLISECONDS); if (resultCode == 0) { out.println("Sync is OK"); } else { throw new CliWrapperException(new KeeperException.NoNodeException(path)); <START> } <END> } catch (IllegalArgumentException ex) { throw new MalformedPathException(ex.getMessage()); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new CliWrapperException(ie); } catch (TimeoutException | ExecutionException ex) { throw new CliWrapperException(ex); } return false; }</code><technical_language>get a rc code path is exist server send client - alternative is getData exist check existence of path sync - sync api problems user-friendly, depreciate in a new linearity read api</technical_language>

Target:
public boolean exec() throws CliException { String path = args[1]; CompletableFuture<Integer> cf = new CompletableFuture<>(); try { zk.sync(path, (rc, path1, ctx) -> cf.complete(rc), null); int resultCode = cf.get(SYNC_TIMEOUT, TimeUnit.MILLISECONDS); if (resultCode == 0) { out.println("Sync is OK"); } else if (resultCode == KeeperException.Code.NONODE.intValue()) { throw new KeeperException.NoNodeException(path); } else { out.println("Sync has failed. rc=" + resultCode); } } catch (IllegalArgumentException ex) { throw new MalformedPathException(ex.getMessage()); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new CliWrapperException(ie); } catch (TimeoutException | ExecutionException | KeeperException ex) { throw new CliWrapperException(ex); } return false; }
Source:
<code>private static PageSizes computePageSizesAssumingNormalDistribution( int cellBatchHint, double columnsPerRowMean, double columnsPerRowStdDev) { double sigma = Math.min(columnsPerRowStdDev, cellBatchHint * 0.2); double logArg = Math.min(1.0, SQRT_2_PI * sigma / cellBatchHint); double extraColumnsToFetch = logArg < 1e-12 ? 0.0 : sigma * Math.sqrt(-2.0 * Math.log(logArg)); <START> return negotiateExactPageSize(columnsPerRowMean + 1.0 + extraColumnsToFetch, cellBatchHint); <END> }</code><technical_language>negotiate</technical_language>

Target:
private static PageSizes computePageSizesAssumingNormalDistribution( int cellBatchHint, double columnsPerRowMean, double columnsPerRowStdDev) { double sigma = Math.min(columnsPerRowStdDev, cellBatchHint * 0.2); double logArg = Math.min(1.0, SQRT_2_PI * sigma / cellBatchHint); double extraColumnsToFetch = logArg < 1e-12 ? 0.0 : sigma * Math.sqrt(-2.0 * Math.log(logArg)); return getExactPageSize(columnsPerRowMean + 1.0 + extraColumnsToFetch, cellBatchHint); }
Source:
<code>public GMFUMLElementAdapter(View view, ExtendedCSSEngine engine) { super(view, engine); <START> super.helper = new CSSDOMUMLSemanticElementHelper(); <END> }</code><technical_language>other initialise helper field. a setter</technical_language>

Target:
public GMFUMLElementAdapter(View view, ExtendedCSSEngine engine) { super(view, engine); helper = CSSDOMUMLSemanticElementHelper.getInstance(); }
Source:
<code>public Builder adapt(Scan scan, ReadHooks readHooks) { throwIfUnsupportedScan(scan); byte[] startRowBytes = scan.getStartRow(); byte[] stopRowBytes = scan.getStopRow(); ByteString startRow = ByteStringer.wrap(startRowBytes); ByteString stopRow = <START> startRowBytes == stopRowBytes ? startRow : ByteStringer.wrap(stopRowBytes); <END> RowFilter filter = buildFilter(scan, readHooks); return ReadRowsRequest.newBuilder() .setFilter(filter) .setRowRange( RowRange.newBuilder() .setStartKey(startRow) .setEndKey(stopRow)); }</code><technical_language>compare object instead of reference? wrap is cheap now</technical_language>

Target:
public Builder adapt(Scan scan, ReadHooks readHooks) { throwIfUnsupportedScan(scan); RowFilter filter = buildFilter(scan, readHooks); return ReadRowsRequest.newBuilder() .setFilter(filter) .setRowRange( RowRange.newBuilder() .setStartKey(ByteStringer.wrap(scan.getStartRow())) .setEndKey(ByteStringer.wrap(scan.getStopRow()))); }
Source:
<code>public void deleteSurveyPermanently(GuidCreatedOnVersionHolder keys) { Survey existing = new QueryBuilder().setSurvey(keys.getGuid()).setCreatedOn(keys.getCreatedOn()) .setSkipElements(true).getOne(false); <START> if (existing != null) { <END> deleteAllElements(existing.getGuid(), existing.getCreatedOn()); surveyMapper.delete(existing); try { StudyIdentifier studyId = new StudyIdentifierImpl(existing.getStudyIdentifier()); uploadSchemaService.deleteUploadSchemaById(studyId, existing.getIdentifier()); } catch(EntityNotFoundException e) { } } }</code><technical_language>Unit test deleting a non-existent survey fails silently</technical_language>

Target:
public void deleteSurveyPermanently(GuidCreatedOnVersionHolder keys) { Survey existing = new QueryBuilder().setSurvey(keys.getGuid()).setCreatedOn(keys.getCreatedOn()) .setSkipElements(true).getOne(true); deleteAllElements(existing.getGuid(), existing.getCreatedOn()); surveyMapper.delete(existing); try { StudyIdentifier studyId = new StudyIdentifierImpl(existing.getStudyIdentifier()); uploadSchemaService.deleteUploadSchemaById(studyId, existing.getIdentifier()); } catch(EntityNotFoundException e) { } }
Source:
<code>public static void validateGranularity(String granularity) { Preconditions.checkNotNull(granularity, "Granularity string in dateTimeFieldSpec must not be null"); String[] granularityTokens = granularity.split(COLON_SEPARATOR); Preconditions.checkArgument(granularityTokens.length == MAX_GRANULARITY_TOKENS, <START> "Incorrect granularity:%. Must be of format size:timeunit", granularity); <END> Preconditions.checkArgument(granularityTokens[GRANULARITY_SIZE_POSITION].matches(NUMBER_REGEX), "Incorrect granularity size:%. Must be of format [0-9]+:<TimeUnit>", granularityTokens[GRANULARITY_SIZE_POSITION]); Preconditions.checkArgument(EnumUtils.isValidEnum(TimeUnit.class, granularityTokens[GRANULARITY_UNIT_POSITION]), "Incorrect granularity size:%. Must be of format [0-9]+:<TimeUnit>", granularityTokens[GRANULARITY_SIZE_POSITION]); }</code><technical_language>suggestion "Incorrect granularity: %s. of format 'size:timeunit'", granularity);</technical_language>

Target:
public static void validateGranularity(String granularity) { Preconditions.checkNotNull(granularity, "Granularity string in dateTimeFieldSpec must not be null"); String[] granularityTokens = granularity.split(COLON_SEPARATOR); Preconditions.checkState(granularityTokens.length == MAX_GRANULARITY_TOKENS, "Incorrect granularity: %s. Must be of format 'size:timeunit'", granularity); Preconditions.checkState(granularityTokens[GRANULARITY_SIZE_POSITION].matches(NUMBER_REGEX), "Incorrect granularity size: %s. Must be of format '[0-9]+:<TimeUnit>'", granularityTokens[GRANULARITY_SIZE_POSITION]); Preconditions.checkState(EnumUtils.isValidEnum(TimeUnit.class, granularityTokens[GRANULARITY_UNIT_POSITION]), "Incorrect granularity size: %s. Must be of format '[0-9]+:<TimeUnit>'", granularityTokens[GRANULARITY_SIZE_POSITION]); }
Source:
<code>private static boolean jniIsAlreadyLoaded(String libName){ String foundLib = System.mapLibraryName(libName); try { java.lang.reflect.Field LIBRARIES = null; LIBRARIES = ClassLoader.class.getDeclaredField("loadedLibraryNames"); LIBRARIES.setAccessible(true); final Vector<String> libs = (Vector<String>) LIBRARIES.get(ClassLoader.getSystemClassLoader()); for (String l : libs){ <START> System.out.println(l); <END> if (l.contains(foundLib)) return true; } return false; } catch (Throwable e) { return false; } }</code><technical_language>a system.out.println in code, if want list visible for debugging purposes, create a logger Logging.getLogger(class) write log statements debug level</technical_language>

Target:
private static boolean jniIsAlreadyLoaded(String libName){ String foundLib = System.mapLibraryName(libName); try { java.lang.reflect.Field LIBRARIES = null; LIBRARIES = ClassLoader.class.getDeclaredField("loadedLibraryNames"); LIBRARIES.setAccessible(true); final Vector<String> libs = (Vector<String>) LIBRARIES.get(ClassLoader.getSystemClassLoader()); for (String l : libs){ if (l.contains(foundLib)) return true; } return false; } catch (Throwable e) { return false; } }
Source:
<code>public ExtractModuleTask() { try { this.moduleFile = getProject().getObjects().fileProperty(); <START> } catch(NoSuchMethodError e) { <END> this.moduleFile = getProject().getLayout().fileProperty(); } }</code><technical_language>suggestion } catch (NoSuchMethodError e) {</technical_language>

Target:
public ExtractModuleTask() { try { this.moduleFile = getProject().getObjects().fileProperty(); } catch (NoSuchMethodError e) { this.moduleFile = invokeMethod(getProject().getLayout(), "fileProperty"); } }
Source:
<code>public void serialize(final Host host, final JsonGenerator jgen, final SerializerProvider sp) throws IOException, JsonProcessingException { jgen.writeStartObject(); <START> jgen.writeNumberField("hostId", host.getHostId()); <END> jgen.writeStringField("ipAddress", host.getIp().toSimpleString()); jgen.writeStringField("mac", host.getMac().toString()); jgen.writeStringField("vdpid", host.getPort().getParentSwitch() .getSwitchName()); jgen.writeNumberField("vport", host.getPort().getPortNumber()); jgen.writeEndObject(); }</code><technical_language>constants stings defined in API for fields here. SImply, if change I want change in multiple locations</technical_language>

Target:
public void serialize(final Host host, final JsonGenerator jgen, final SerializerProvider sp) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeNumberField(TenantHandler.HOST, host.getHostId()); jgen.writeStringField(TenantHandler.IFADDR, host.getIp().toSimpleString()); jgen.writeStringField(TenantHandler.MAC, host.getMac().toString()); jgen.writeStringField(TenantHandler.VDPID, host.getPort().getParentSwitch() .getSwitchName()); jgen.writeNumberField(TenantHandler.VPORT, host.getPort().getPortNumber()); jgen.writeEndObject(); }
Source:
<code>Data(JSONObject o) { this.sourceId = (String)o.get("id"); JSONObject c = o.optJSONObject("core"); if (c!=null) { core = new Entry(sourceId, c, url); } else { core = null; } JSONArray w = o.optJSONArray("warnings"); if (w != null) { for (int i = 0; i < w.size(); i++) { <START> warnings.add(new Warning(w.getJSONObject(i))); <END> } } for(Map.Entry<String,JSONObject> e : (Set<Map.Entry<String,JSONObject>>)o.getJSONObject("plugins").entrySet()) { Plugin p = new Plugin(sourceId, e.getValue()); List<PluginWrapper.Dependency> implicitDeps = ClassicPluginStrategy.getImpliedDependencies(p.name, p.requiredCore); if(!implicitDeps.isEmpty()) { for(PluginWrapper.Dependency dep : implicitDeps) { if(!p.dependencies.containsKey(dep.shortName)) { p.dependencies.put(dep.shortName, dep.version); } } } plugins.put(e.getKey(), p); } connectionCheckUrl = (String)o.get("connectionCheckUrl"); }</code><technical_language>NIT. This code throw exception if element is a JSONObject (e.g. nested array)</technical_language>

Target:
Data(JSONObject o) { this.sourceId = (String)o.get("id"); JSONObject c = o.optJSONObject("core"); if (c!=null) { core = new Entry(sourceId, c, url); } else { core = null; } JSONArray w = o.optJSONArray("warnings"); if (w != null) { for (int i = 0; i < w.size(); i++) { try { warnings.add(new Warning(w.getJSONObject(i))); } catch (JSONException ex) { LOGGER.log(Level.WARNING, "Failed to parse JSON for warning", ex); } } } for(Map.Entry<String,JSONObject> e : (Set<Map.Entry<String,JSONObject>>)o.getJSONObject("plugins").entrySet()) { Plugin p = new Plugin(sourceId, e.getValue()); List<PluginWrapper.Dependency> implicitDeps = ClassicPluginStrategy.getImpliedDependencies(p.name, p.requiredCore); if(!implicitDeps.isEmpty()) { for(PluginWrapper.Dependency dep : implicitDeps) { if(!p.dependencies.containsKey(dep.shortName)) { p.dependencies.put(dep.shortName, dep.version); } } } plugins.put(e.getKey(), p); } connectionCheckUrl = (String)o.get("connectionCheckUrl"); }
Source:
<code>private static void reboot(@NonNull String endpoint, @NonNull CorfuRuntimeParameters corfuRuntimeParameters, int retries, @NonNull Duration retryDuration, boolean resetData) { IClientRouter router = new NettyClientRouter(NodeLocator.parseString(endpoint), corfuRuntimeParameters); router.addClient(new BaseHandler()); BaseClient baseClient = new BaseClient(router, Layout.INVALID_EPOCH); while (retries-- > 0) { try { if (resetData) { log.info("Attempting to reset server: {}", endpoint); CFUtils.getUninterruptibly(baseClient.reset()); } else { log.info("Attempting to restart server: {}", endpoint); CFUtils.getUninterruptibly(baseClient.restart()); } break; } catch (Exception e) { log.error("Reboot node: failed with exception:", endpoint, e); if (retries == 0) { <START> throw new RuntimeException(e); <END> } log.warn("Retrying times in {}ms.", retries, retryDuration.toMillis()); Sleep.MILLISECONDS.sleepUninterruptibly(retryDuration.toMillis()); } } log.info("Successfully rebooted server:{}", endpoint); router.stop(); }</code><technical_language>please replace RuntimeException a more specific exception</technical_language>

Target:
private static void reboot(@NonNull String endpoint, @NonNull CorfuRuntimeParameters corfuRuntimeParameters, int retries, @NonNull Duration retryDuration, boolean resetData) { IClientRouter router = new NettyClientRouter(NodeLocator.parseString(endpoint), corfuRuntimeParameters); router.addClient(new BaseHandler()); BaseClient baseClient = new BaseClient(router, Layout.INVALID_EPOCH); while (retries-- > 0) { try { if (resetData) { log.info("Attempting to reset server: {}", endpoint); CFUtils.getUninterruptibly(baseClient.reset()); } else { log.info("Attempting to restart server: {}", endpoint); CFUtils.getUninterruptibly(baseClient.restart()); } break; } catch (Exception e) { log.error("Rebooting node: failed with exception:", endpoint, e); if (retries == 0) { throw new RetryExhaustedException("Rebooting node: retry exhausted"); } log.warn("Retrying reboot times in {}ms.", retries, retryDuration.toMillis()); Sleep.MILLISECONDS.sleepUninterruptibly(retryDuration.toMillis()); } } log.info("Successfully rebooted server:{}", endpoint); router.stop(); }
Source:
<code>private void setResponseHeaders(BlobInfo blobInfo, RestResponseChannel restResponseChannel) throws RestServiceException { <START> BlobProperties blobProperties = blobInfo.getBlobProperties(); <END> restResponseChannel.setStatus(ResponseStatus.Ok); restResponseChannel.setHeader(RestUtils.Headers.LAST_MODIFIED, new Date(blobProperties.getCreationTimeInMs())); restResponseChannel.setHeader(RestUtils.Headers.CONTENT_LENGTH, blobProperties.getBlobSize()); if (blobProperties.getContentType() != null) { restResponseChannel.setHeader(RestUtils.Headers.CONTENT_TYPE, blobProperties.getContentType()); } setBlobPropertiesHeaders(blobProperties, restResponseChannel); }</code><technical_language>I continue AmbryBlobStorageService set these</technical_language>

Target:
private void setResponseHeaders(BlobInfo blobInfo, RestResponseChannel restResponseChannel) throws RestServiceException { BlobProperties blobProperties = blobInfo.getBlobProperties(); restResponseChannel.setHeader(RestUtils.Headers.LAST_MODIFIED, new Date(blobProperties.getCreationTimeInMs())); restResponseChannel.setHeader(RestUtils.Headers.CONTENT_LENGTH, blobProperties.getBlobSize()); if (blobProperties.getContentType() != null) { restResponseChannel.setHeader(RestUtils.Headers.CONTENT_TYPE, blobProperties.getContentType()); } setBlobPropertiesHeaders(blobProperties, restResponseChannel); }
Source:
<code>private List<String> getHeaderRow() { List<String> row = new ArrayList<String>(); <START> row.add("ACB"); <END> row.add("Developer"); row.add("Product"); row.add("Version"); row.add("CHPL Product Number"); row.add("Current Certification Status"); row.add("Link"); row.add("Activity Timestamp"); row.add("Responsible User"); row.add("Activity Type"); row.add("Activity"); row.add("Reason for Status Change"); row.add("Reason"); return row; }</code><technical_language>This is "ONC-ACB" displayed public, right</technical_language>

Target:
private List<String> getHeaderRow() { List<String> row = new ArrayList<String>(); row.add("ONC-ACB"); row.add("Developer"); row.add("Product"); row.add("Version"); row.add("CHPL Product Number"); row.add("Current Certification Status"); row.add("Link"); row.add("Activity Timestamp"); row.add("Responsible User"); row.add("Activity Type"); row.add("Activity"); row.add("Reason for Status Change"); row.add("Reason"); return row; }
Source:
<code>static Optional<Pattern> getEndpointsPatterns(ServerProperties serverProperties, WebEndpointProperties webEndpointProperties, EndpointsSupplier<ExposableWebEndpoint> endpointsSupplier) { Collection<ExposableWebEndpoint> endpoints = endpointsSupplier.getEndpoints(); if (endpoints.isEmpty()) { return Optional.empty(); } String contextPath = serverProperties.getServlet().getContextPath(); int size = endpoints.size(); int i = 0; StringBuilder sb = new StringBuilder(); <START> for (ExposableWebEndpoint endpoint : endpoints) { <END> i++; if (StringUtils.hasText(contextPath)) { sb.append(contextPath); } if (!webEndpointProperties.getBasePath().equals("/")) { sb.append(webEndpointProperties.getBasePath()); } sb.append("/") .append(endpoint.getRootPath()) .append(".*"); if (i < size) { sb.append("|"); } } String pattern = sb.toString(); if (StringUtils.hasText(pattern)) { return Optional.of(Pattern.compile(pattern)); } return Optional.empty(); }</code><technical_language>If want a Java Streams variant of this loop, I (resultant pattern is a different): java String pattern = endpoints.stream() .map(PathMappedEndpoint::getRootPath) .map(path -> path + ".*") .collect(Collectors.joining("|", getPathPrefix(contextPath, webBasePath) + "/(", ")")); helper method: java private String getPathPrefix(String contextPath, String actuatorBasePath) { String result = ""; if (StringUtils.hasText(contextPath)) { result += contextPath; } if (!actuatorBasePath.equals("/")) { result += actuatorBasePath; } return result; }</technical_language>

Target:
static Optional<Pattern> getEndpointsPatterns(ServerProperties serverProperties, WebEndpointProperties webEndpointProperties, EndpointsSupplier<ExposableWebEndpoint> endpointsSupplier) { Collection<ExposableWebEndpoint> endpoints = endpointsSupplier.getEndpoints(); if (endpoints.isEmpty()) { return Optional.empty(); } String contextPath = serverProperties.getServlet().getContextPath(); String pattern = endpoints.stream().map(PathMappedEndpoint::getRootPath) .map(path -> path + "|" + path + "/.*").collect( Collectors.joining("|", getPathPrefix(contextPath, webEndpointProperties.getBasePath()) + "/(", ")")); if (StringUtils.hasText(pattern)) { return Optional.of(Pattern.compile(pattern)); } return Optional.empty(); }
Source:
<code>protected void doWork(IProgressMonitor monitor) throws Exception { if (originalBranch != null && !BranchManager.hasMergeBranches( originalBranch) && !originalBranch.getBranchState().isCommitted()) { performUpdate(monitor, originalBranch); <START> <END> activityLog.createEntry(BRANCH_OPERATION_TYPEID, ActivityLog.INITIAL_STATUS, String.format( "Branch Operation Update Branch {branchUUID: %s, branchName: %s parentBranchUUID: %s parentBranchName: %s}", originalBranch.getUuid(), originalBranch.getName(), BranchManager.getParentBranch(originalBranch).getUuid(), BranchManager.getParentBranch(originalBranch).getName())); } }</code><technical_language>Add a try/catch block log errors. want logging affect normal operations</technical_language>

Target:
protected void doWork(IProgressMonitor monitor) throws Exception { if (originalBranch != null && !BranchManager.hasMergeBranches( originalBranch) && !originalBranch.getBranchState().isCommitted()) { performUpdate(monitor, originalBranch); try { activityLog.createEntry(BRANCH_OPERATION_TYPEID, ActivityLog.INITIAL_STATUS, String.format( "Branch Operation Update Branch {branchUUID: %s, branchName: %s parentBranchUUID: %s parentBranchName: %s}", originalBranch.getUuid(), originalBranch.getName(), BranchManager.getParentBranch(originalBranch).getUuid(), BranchManager.getParentBranch(originalBranch).getName())); } catch (OseeCoreException ex) { OseeLog.log(Activator.class, OseeLevel.SEVERE_POPUP, ex); } } }
Source:
<code>public void should_fail_if_actual_has_at_least_one_element() { <START> SoftAssertions softly = new SoftAssertions(); <END> softly.assertThat(newArrayList(1).iterator()).isExhausted(); AssertionError error = catchThrowableOfType(softly::assertAll, AssertionError.class); assertThat(error).hasMessageContaining("\nExpecting iterator to be exhausted."); }</code><technical_language>standard assertions (no need of soft ones)</technical_language>

Target:
public void should_fail_if_actual_has_at_least_one_element() { IteratorAssert iteratorAssert = assertThat(newArrayList(1).iterator()); AssertionError error = catchThrowableOfType(iteratorAssert::isExhausted, AssertionError.class); assertThat(error).hasMessageContaining("\nExpecting iterator to be exhausted."); }
Source:
<code>public void logExtendedCommitInformation() { if (!commitTimeoutReached) { return; } final List<EventTypePartition> toCheck = offsets.entrySet().stream() .filter(e -> !e.getValue().isCommitted()) .map(Map.Entry::getKey) .collect(Collectors.toList()); try { final Map<EventTypePartition, SubscriptionCursorWithoutToken> realCommitted = getZk().getOffsets(toCheck); final List<EventTypePartition> bustedPartitions = offsets.entrySet().stream() .filter(v -> realCommitted.containsKey(v.getKey())) .filter(v -> { final SubscriptionCursorWithoutToken remembered = getContext().getCursorConverter().convertToNoToken(v.getValue().getCommitOffset()); final SubscriptionCursorWithoutToken real = realCommitted.get(v.getKey()); return real.getOffset().compareTo(remembered.getOffset()) > 0; }) .map(Map.Entry::getKey) .collect(Collectors.toList()); if (!bustedPartitions.isEmpty()) { final String bustedData = bustedPartitions.stream().map(etp -> { final PartitionData pd = offsets.get(etp); return "(ETP: " + etp + ", StreamCommitted: " + pd.getCommitOffset() + ", StreamSent: " + pd.getSentOffset() + ", ZkCommitted: " + realCommitted.get(etp) + ")"; }).collect(Collectors.joining(", ")); getLog().warn("Stale offsets during streaming commit timeout: {}", bustedData); TracingService.logWarning(getContext().getCurrentSpan(), "Stale offsets during streaming commit timeout: " + bustedData); } } catch (NakadiRuntimeException ex) { getLog().warn("Failed to get nakadi cursors for logging purposes."); <START> TracingService.logWarning(getContext().getCurrentSpan(), <END> "Failed to get nakadi cursors for logging purposes."); } }</code><technical_language>user need it, is internal exception, track in logs</technical_language>

Target:
public void logExtendedCommitInformation() { if (!commitTimeoutReached) { return; } final List<EventTypePartition> toCheck = offsets.entrySet().stream() .filter(e -> !e.getValue().isCommitted()) .map(Map.Entry::getKey) .collect(Collectors.toList()); try { final Map<EventTypePartition, SubscriptionCursorWithoutToken> realCommitted = getZk().getOffsets(toCheck); final List<EventTypePartition> bustedPartitions = offsets.entrySet().stream() .filter(v -> realCommitted.containsKey(v.getKey())) .filter(v -> { final SubscriptionCursorWithoutToken remembered = getContext().getCursorConverter().convertToNoToken(v.getValue().getCommitOffset()); final SubscriptionCursorWithoutToken real = realCommitted.get(v.getKey()); return real.getOffset().compareTo(remembered.getOffset()) > 0; }) .map(Map.Entry::getKey) .collect(Collectors.toList()); if (!bustedPartitions.isEmpty()) { final String bustedData = bustedPartitions.stream().map(etp -> { final PartitionData pd = offsets.get(etp); return "(ETP: " + etp + ", StreamCommitted: " + pd.getCommitOffset() + ", StreamSent: " + pd.getSentOffset() + ", ZkCommitted: " + realCommitted.get(etp) + ")"; }).collect(Collectors.joining(", ")); getLog().warn("Stale offsets during streaming commit timeout: {}", bustedData); } } catch (NakadiRuntimeException ex) { getLog().warn("Failed to get nakadi cursors for logging purposes."); } }
Source:
<code>private void loadDownloadedProject(String name) { try { ProjectManager.getInstance().loadProject(name, getContext()); Intent intent = new Intent(getContext(), ProjectActivity.class); intent.putExtra(ProjectActivity.EXTRA_FRAGMENT_POSITION, ProjectActivity.FRAGMENT_SCENES); startActivity(intent); <START> } catch (ProjectException e) { <END> Log.e(TAG, Log.getStackTraceString(e)); } }</code><technical_language>Please show error message user (see ToastUtil)</technical_language>

Target:
private void loadDownloadedProject(String name) { try { ProjectManager.getInstance().loadProject(name, getContext()); Intent intent = new Intent(getContext(), ProjectActivity.class); intent.putExtra(ProjectActivity.EXTRA_FRAGMENT_POSITION, ProjectActivity.FRAGMENT_SCENES); startActivity(intent); } catch (ProjectException e) { Log.e(TAG, Log.getStackTraceString(e)); ToastUtil.showError(getActivity(), R.string.error_load_project); } }
Source:
<code>public boolean onTouchEvent(MotionEvent event) { if (getParent() instanceof View) { final View parent = (View)getParent(); View view = ViewUtil.hitTest(parent, event.getX(), event.getY(), mViewSelector); if (event.getAction() != MotionEvent.ACTION_CANCEL) { if (view != null) { <START> mHighlighter.setHighlightedView(view, 0x404040ff); <END> if (event.getAction() == MotionEvent.ACTION_UP) { mListener.onInspectRequested(view); } } } } return true; }</code><technical_language>named constnat</technical_language>

Target:
public boolean onTouchEvent(MotionEvent event) { if (getParent() instanceof View) { final View parent = (View)getParent(); View view = ViewUtil.hitTest(parent, event.getX(), event.getY(), mViewSelector); if (event.getAction() != MotionEvent.ACTION_CANCEL) { if (view != null) { mHighlighter.setHighlightedView(view, INSPECT_HOVER_COLOR); if (event.getAction() == MotionEvent.ACTION_UP) { mListener.onInspectRequested(view); } } } } return true; }
Source:
<code><START> public final String getAuthority() { <END> return mCloudInstanceName; }</code><technical_language>getAuthority [](start = 24, length = 12) I figure out changed here, getAuthority returns mCloudInstanceName is confusing :)</technical_language>

Target:
public final String getAuthority() { return mAuthority; }
Source:
<code>private MkIssueEvents issueEvents() throws Exception { <START> return (MkIssueEvents) (new MkGithub().repos().create( <END> Json.createObjectBuilder().add("name", "test").build() ).issueEvents()); }</code><technical_language>@cvrebert MkIssueEvents.class.cast(</technical_language>

Target:
private MkIssueEvents issueEvents() throws Exception { return MkIssueEvents.class.cast( new MkGithub().repos().create( Json.createObjectBuilder() .add(MkIssueEventsTest.NAME, "test") .build() ).issueEvents() ); }
Source:
<code>private List<AccountInfo> suggestAccountFullSearch( VisibilityControl visibilityControl) throws OrmException { String <START> lCsubstr = <END> query.toLowerCase(); LinkedHashMap<Account.Id, AccountInfo> accountMap = Maps.newLinkedHashMap(); List<Account> accounts = dbProvider.get().accounts().all().toList(); for (Account acc : accounts) { if (acc.getFullName() != null && acc.getFullName().toLowerCase().contains(lCsubstr)) { addSuggestion(accountMap, acc, new AccountInfo(acc.getId()), visibilityControl); } if (accountMap.size() >= limit) { break; } } if (accountMap.size() < limit) { for (Account acc : accounts) { if (acc.getPreferredEmail().toLowerCase().contains(lCsubstr)) { addSuggestion(accountMap, acc, new AccountInfo(acc.getId()), visibilityControl); } if (accountMap.size() >= limit) { break; } } } return Lists.newArrayList(accountMap.values()); }</code><technical_language>str, "lC" prefixes</technical_language>

Target:
private List<AccountInfo> suggestAccountFullSearch( VisibilityControl visibilityControl) throws OrmException { String str = query.toLowerCase(); LinkedHashMap<Account.Id, AccountInfo> accountMap = Maps.newLinkedHashMap(); List<Account> emailMatches = Lists.newArrayList(); for (Account a : dbProvider.get().accounts().all()) { if (a.getFullName() != null && a.getFullName().toLowerCase().contains(str)) { addSuggestion(accountMap, a, new AccountInfo(a.getId()), visibilityControl); } if (a.getPreferredEmail() != null && a.getPreferredEmail().toLowerCase().contains(str)) { emailMatches.add(a); } if (accountMap.size() >= limit) { break; } } if (accountMap.size() < limit) { for (Account a : emailMatches) { addSuggestion(accountMap, a, new AccountInfo(a.getId()), visibilityControl); if (accountMap.size() >= limit) { break; } } } return Lists.newArrayList(accountMap.values()); }
Source:
<code>public void beforeCreateCollection(DBBroker broker, Txn txn, XmldbURI uri) throws TriggerException { <START> if (!triggersSuspended) { <END> for (CollectionTrigger trigger : triggers) { trigger.beforeCreateCollection(broker, txn, uri); } } }</code><technical_language>triggersSuspended checks here. checks present call site in DBBroker. This kinda breaks responsibility pattern</technical_language>

Target:
public void beforeCreateCollection(DBBroker broker, Txn txn, XmldbURI uri) throws TriggerException { for (CollectionTrigger trigger : triggers) { trigger.beforeCreateCollection(broker, txn, uri); } }
Source:
<code>private void ensureKeyspace(String keyspace) { <START> ResultSet resultset = session.execute("SELECT * FROM system_schema.keyspaces WHERE keyspace_name = '" + keyspace + "';"); <END> if (!resultset.iterator().hasNext()) { session.execute("CREATE KEYSPACE " + keyspace + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'} AND durable_writes = true;"); } }</code><technical_language>simply this method. do need query system_schema.keyspaces. IF EXISTS clause, e.g., CREATE KEYSPACE IF EXISTS foo replication = {'class': 'SimpleStrategy', 'replication_factor': 1}</technical_language>

Target:
private void ensureKeyspace(String keyspace) { session.execute("CREATE KEYSPACE IF NOT EXISTS " + keyspace + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'} AND durable_writes = true;"); }