auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public final void createIndex(final IndexDesc index) throws DuplicateIndexException { <END> try { final BlockingInterface stub = getStub(); final ReturnState state = stub.createIndex(null, index.getProto()); throwsIfThisError(state, DuplicateIndexException.class); ensureOk(state); } catch (ServiceException e) { throw new RuntimeException(e); } }</code><technical_language>If index creation is based table, need Undefined(Table|Database)Exception</technical_language>

Target:
public final void createIndex(final IndexDesc index) throws DuplicateIndexException, UndefinedDatabaseException, UndefinedTableException { try { final BlockingInterface stub = getStub(); final ReturnState state = stub.createIndex(null, index.getProto()); throwsIfThisError(state, DuplicateIndexException.class); throwsIfThisError(state, UndefinedTableException.class); throwsIfThisError(state, UndefinedDatabaseException.class); ensureOk(state); } catch (ServiceException e) { throw new RuntimeException(e); } }
Source:
<code>private static Predicate<Element> isNotTrusted(TrustedDomains trustedDomains) { return element -> { <START> Optional<URI> maybeRessourceUri = SupportedElements.getHost(element); <END> return element.getAttributeValue("integrity") == null && !maybeRessourceUri .map(ressourceUri -> trustedDomains.isIncluded(ressourceUri.toString())) .orElse(false); }; }</code><technical_language>Typo: Double S in resource</technical_language>

Target:
private static Predicate<Element> isNotTrusted(TrustedDomains trustedDomains) { return element -> { Optional<URI> maybeResourceUri = SupportedElements.getHost(element); return element.getAttributeValue("integrity") == null && !maybeResourceUri .map(resourceUri -> trustedDomains.isIncluded(resourceUri.toString())) .orElse(false); }; }
Source:
<code>public static UserDefinedFunction createFunction( FunctionDescriptor descriptor, ClassLoader classLoader, boolean performValidation, ReadableConfig config) { DescriptorProperties properties = new DescriptorProperties(true); properties.putProperties(descriptor.toProperties()); if (performValidation) { new FunctionDescriptorValidator().validate(properties); } Object instance; switch (properties.getString(FunctionDescriptorValidator.FROM)) { case FunctionDescriptorValidator.FROM_VALUE_CLASS: instance = generateInstance( HierarchyDescriptorValidator.EMPTY_PREFIX, properties, classLoader); break; case FunctionDescriptorValidator.FROM_VALUE_PYTHON: String fullyQualifiedName = properties.getString(PythonFunctionValidator.FULLY_QUALIFIED_NAME); try { <START> Class pythonFunctionFactory = Class.forName( <END> "org.apache.flink.client.python.PythonFunctionFactory", true, Thread.currentThread().getContextClassLoader()); instance = pythonFunctionFactory.getMethod( "getPythonFunction", String.class, ReadableConfig.class) .invoke(null, fullyQualifiedName, config); } catch (IllegalAccessException | ClassNotFoundException | NoSuchMethodException | InvocationTargetException e) { throw new IllegalStateException( String.format( "Instantiating python function '%s' failed.", fullyQualifiedName), e); } break; default: throw new ValidationException("Unsupported function descriptor: " + properties); } if (!UserDefinedFunction.class.isAssignableFrom(instance.getClass())) { throw new ValidationException(String.format( "Instantiated class '%s' is not a user-defined function.", instance.getClass().getName())); } return (UserDefinedFunction) instance; }</code><technical_language>code is duplicate FunctionDefinitionUtil.createPythonFunctionDefinition. abstract a remove duplication</technical_language>

Target:
public static UserDefinedFunction createFunction( FunctionDescriptor descriptor, ClassLoader classLoader, boolean performValidation, ReadableConfig config) { DescriptorProperties properties = new DescriptorProperties(true); properties.putProperties(descriptor.toProperties()); if (performValidation) { new FunctionDescriptorValidator().validate(properties); } Object instance; switch (properties.getString(FunctionDescriptorValidator.FROM)) { case FunctionDescriptorValidator.FROM_VALUE_CLASS: instance = generateInstance( HierarchyDescriptorValidator.EMPTY_PREFIX, properties, classLoader); break; case FunctionDescriptorValidator.FROM_VALUE_PYTHON: String fullyQualifiedName = properties.getString(PythonFunctionValidator.FULLY_QUALIFIED_NAME); instance = PythonFunctionUtils.getPythonFunction(fullyQualifiedName, config); break; default: throw new ValidationException(String.format( "Unsupported function descriptor: %s", properties.getString(FunctionDescriptorValidator.FROM))); } if (!UserDefinedFunction.class.isAssignableFrom(instance.getClass())) { throw new ValidationException(String.format( "Instantiated class '%s' is not a user-defined function.", instance.getClass().getName())); } return (UserDefinedFunction) instance; }
Source:
<code>private List<Plugin> getDefaultPluginConfig() { List<Plugin> plugins = new ArrayList<>(); plugins.add(new Plugin("org.eclipse.core.runtime", true, 4)); plugins.add(new Plugin("org.eclipse.equinox.common", true, 2)); plugins.add(new Plugin("org.eclipse.equinox.ds", true, 2)); plugins.add(new Plugin("org.eclipse.equinox.p2.reconciler.dropins", true, 4)); plugins.add(new Plugin("org.eclipse.equinox.simpleconfigurator", true, 1)); <START> plugins.add(new Plugin("org.eclipse.update.configurator", true, 1)); <END> return plugins; }</code><technical_language>sort lines start order. WDYT</technical_language>

Target:
private List<Plugin> getDefaultPluginConfig() { List<Plugin> plugins = new ArrayList<>(); plugins.add(new Plugin("org.eclipse.update.configurator", true, 1)); plugins.add(new Plugin("org.eclipse.equinox.simpleconfigurator", true, 1)); plugins.add(new Plugin("org.eclipse.equinox.ds", true, 2)); plugins.add(new Plugin("org.eclipse.equinox.common", true, 2)); plugins.add(new Plugin("org.eclipse.core.runtime", true, 4)); plugins.add(new Plugin("org.eclipse.equinox.p2.reconciler.dropins", true, 4)); return plugins; }
Source:
<code>private synchronized void loadPatterns() throws DotDataException { <START> patternsCache = new TreeSet<>(); <END> final List<SimpleStructureURLMap> urlMaps = StructureFactory.findStructureURLMapPatterns(); final StringBuilder masterRegEx = new StringBuilder(); for (final SimpleStructureURLMap urlMap : urlMaps) { final PatternCache patternCache = new PatternCache(); final String regEx = StructureUtil.generateRegExForURLMap(urlMap.getURLMapPattern()); if (!UtilMethods.isSet(regEx) || regEx.trim().length() < 3) { continue; } patternCache.setRegEx(regEx); patternCache.setStructureInode(urlMap.getInode()); patternCache.setURLpattern(urlMap.getURLMapPattern()); patternCache.setFieldMatches(getFieldMathed(urlMap)); patternsCache.add(patternCache); if (masterRegEx.length() > 0) { masterRegEx.append('|'); } masterRegEx.append(regEx); } CacheLocator.getContentTypeCache().addURLMasterPattern(masterRegEx.toString()); }</code><technical_language>patternsCache is a thread-safe collection, mark a volatile instead</technical_language>

Target:
private synchronized void loadPatterns() throws DotDataException { patternsCache = new TreeSet<>(); final List<SimpleStructureURLMap> urlMaps = StructureFactory.findStructureURLMapPatterns(); final StringBuilder masterRegEx = new StringBuilder(); for (final SimpleStructureURLMap urlMap : urlMaps) { final String regEx = StructureUtil.generateRegExForURLMap(urlMap.getURLMapPattern()); if (!UtilMethods.isSet(regEx) || regEx.trim().length() < 3) { continue; } patternsCache.add(new ContentTypeURLPattern( regEx, urlMap.getInode(), urlMap.getURLMapPattern(), getFieldMathed(urlMap) )); if (masterRegEx.length() > 0) { masterRegEx.append('|'); } masterRegEx.append(regEx); } CacheLocator.getContentTypeCache().addURLMasterPattern(masterRegEx.toString()); }
Source:
<code>private <T extends StorableBlock> FreenetStore<T> makeStore(String type, String store, long maxKeys, StoreCallback<T> cb, boolean lateStart, byte[] clientCacheMasterKey) throws IOException { Logger.normal(this, "Initializing "+type+" Data"+store); System.out.println("Initializing "+type+" Data"+store+" (" + maxStoreKeys + " keys)"); SaltedHashFreenetStore<T> fs = SaltedHashFreenetStore.<T>construct(getStoreDir(), type+"-"+store, cb, random, maxKeys, storeUseSlotFilters, shutdownHook, storePreallocate, storeSaltHashResizeOnStart && !lateStart, lateStart ? ticker : null, clientCacheMasterKey); cb.setStore(fs); CachingFreenetStore<T> cachingStore = new CachingFreenetStore<T>(cb, cachingFreenetStoreMaxSize, cachingFreenetStorePeriod, fs, ticker); <START> return cachingStore; <END> }</code><technical_language>instead? Do need local variable? return new CachingFreenetStore<T>(cb, cachingFreenetStoreMaxSize, cachingFreenetStorePeriod, fs, ticker);</technical_language>

Target:
private <T extends StorableBlock> FreenetStore<T> makeStore(String type, String store, long maxKeys, StoreCallback<T> cb, boolean lateStart, byte[] clientCacheMasterKey) throws IOException { Logger.normal(this, "Initializing "+type+" Data"+store); System.out.println("Initializing "+type+" Data"+store+" (" + maxStoreKeys + " keys)"); SaltedHashFreenetStore<T> fs = SaltedHashFreenetStore.<T>construct(getStoreDir(), type+"-"+store, cb, random, maxKeys, storeUseSlotFilters, shutdownHook, storePreallocate, storeSaltHashResizeOnStart && !lateStart, lateStart ? ticker : null, clientCacheMasterKey); cb.setStore(fs); return new CachingFreenetStore<T>(cb, cachingFreenetStoreMaxSize, cachingFreenetStorePeriod, fs, ticker); }
Source:
<code><START> public void addQuotaPermissionSubject(List<PermissionSubject> quotaPermissionList) { <END> if (!isInternalExecution() && getStoragePool() != null && getStoragePool().getQuotaEnforcementType() != QuotaEnforcementTypeEnum.DISABLED && getStoragePool().getQuotaEnforcementType() != QuotaEnforcementTypeEnum.SOFT_ENFORCEMENT) { List<QuotaConsumptionParameter> consumptionParameters = getQuotaConsumptionParameters(); if (consumptionParameters != null) { for (QuotaConsumptionParameter parameter : getQuotaConsumptionParameters()) { if (parameter.getQuotaGuid() != null && parameter.getQuotaGuid() != Guid.Empty && parameter.getParameterType() != QuotaConsumptionParameter.ParameterType.SANITY) { quotaPermissionList.add(new PermissionSubject(parameter.getQuotaGuid(), VdcObjectType.Quota, ActionGroup.CONSUME_QUOTA)); } } } } }</code><technical_language>please override this method in updateVmCommand</technical_language>

Target:
public void addQuotaPermissionSubject(List<PermissionSubject> quotaPermissionList) { if (!isInternalExecution() && getStoragePool() != null && getStoragePool().getQuotaEnforcementType() != QuotaEnforcementTypeEnum.DISABLED && getStoragePool().getQuotaEnforcementType() != QuotaEnforcementTypeEnum.SOFT_ENFORCEMENT) { List<QuotaConsumptionParameter> consumptionParameters = getQuotaConsumptionParameters(); if (consumptionParameters != null) { for (QuotaConsumptionParameter parameter : getQuotaConsumptionParameters()) { if (parameter.getQuotaGuid() != null && !Guid.Empty.equals(parameter.getQuotaGuid())) { quotaPermissionList.add(new PermissionSubject(parameter.getQuotaGuid(), VdcObjectType.Quota, ActionGroup.CONSUME_QUOTA)); } } } } }
Source:
<code>public void comments() throws Exception { PushOneCommit.Result r = createChange(); CommentInput in = new CommentInput(); in.line = 1; in.message = "nit: trailing <START> hitespace"; <END> in.path = FILE_NAME; ReviewInput reviewInput = new ReviewInput(); Map<String, List<CommentInput>> comments = new HashMap<>(); comments.put(FILE_NAME, Collections.singletonList(in)); reviewInput.comments = comments; reviewInput.message = "comment test"; gApi.changes() .id(r.getChangeId()) .current() .review(reviewInput); Map<String, List<CommentInfo>> out = gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .comments(); assertThat(out).hasSize(1); CommentInfo comment = Iterables.getOnlyElement(out.get(FILE_NAME)); assertThat(comment.message).isEqualTo(in.message); assertThat(comment.author.email).isEqualTo(admin.email); assertThat(gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .comment(comment.id) .get() .message) .isEqualTo(in.message); }</code><technical_language>whitespace</technical_language>

Target:
public void comments() throws Exception { PushOneCommit.Result r = createChange(); CommentInput in = new CommentInput(); in.line = 1; in.message = "nit: trailing whitespace"; in.path = FILE_NAME; ReviewInput reviewInput = new ReviewInput(); Map<String, List<CommentInput>> comments = new HashMap<>(); comments.put(FILE_NAME, Collections.singletonList(in)); reviewInput.comments = comments; reviewInput.message = "comment test"; gApi.changes() .id(r.getChangeId()) .current() .review(reviewInput); Map<String, List<CommentInfo>> out = gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .comments(); assertThat(out).hasSize(1); CommentInfo comment = Iterables.getOnlyElement(out.get(FILE_NAME)); assertThat(comment.message).isEqualTo(in.message); assertThat(comment.author.email).isEqualTo(admin.email); assertThat(gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .comment(comment.id) .get() .message) .isEqualTo(in.message); }
Source:
<code>private ExpressionPostAggregator( final String name, final String expression, @Nullable final String ordering, final ExprMacroTable macroTable, <START> final Map<String, Function<Object, Object>> finalizers <END> ) { Preconditions.checkArgument(expression != null, "expression cannot be null"); this.name = name; this.expression = expression; this.ordering = ordering; this.comparator = ordering == null ? DEFAULT_COMPARATOR : Ordering.valueOf(ordering); this.macroTable = macroTable; this.finalizers = ImmutableMap.copyOf(finalizers); this.parsed = Parser.parse(expression, macroTable); this.dependentFields = ImmutableSet.copyOf(Parser.findRequiredBindings(parsed)); }</code><technical_language>Suggested change type ImmutableMap do extra copy</technical_language>

Target:
private ExpressionPostAggregator( final String name, final String expression, @Nullable final String ordering, final ExprMacroTable macroTable, final Map<String, Function<Object, Object>> finalizers ) { Preconditions.checkArgument(expression != null, "expression cannot be null"); this.name = name; this.expression = expression; this.ordering = ordering; this.comparator = ordering == null ? DEFAULT_COMPARATOR : Ordering.valueOf(ordering); this.macroTable = macroTable; this.finalizers = finalizers; this.parsed = Parser.parse(expression, macroTable); this.dependentFields = ImmutableSet.copyOf(Parser.findRequiredBindings(parsed)); }
Source:
<code>public boolean valueEquals(K key, V value) { V oldValue = stateMap.get(key); <START> if ((value == null && oldValue == null) || (value != null && value.equals(oldValue))) { <END> return true; } return false; }</code><technical_language>simplify this return Objects.equals(value, oldValue). requesting change this, however. pointing out</technical_language>

Target:
public boolean valueEquals(K key, V value) { V oldValue = stateMap.get(key); return Objects.equals(value, oldValue); }
Source:
<code>private static List<String> getListOfPollingFilters(String filterForPollSCM, String subPath) { final String DELIMITER = ","; List<String> result = new ArrayList<>(); <START> if (filterForPollSCM != null && !(filterForPollSCM.isEmpty())) { <END> for (String filter : filterForPollSCM.split(DELIMITER)) { result.add(filter.trim()); } } else { if (subPath != null && !(subPath.isEmpty())) { for (String filter : subPath.split(DELIMITER)) { result.add(filter.trim()); } } } return result; }</code><technical_language>Consider StringUtils.isNotEmpty(filterForPollSCM)</technical_language>

Target:
private static Set<String> getListOfPollingFilters(String filterForPollSCM, String subPath) { if (StringUtils.isNotBlank(filterForPollSCM)) { return splitAndSanitizeFilters(filterForPollSCM); } return splitAndSanitizeFilters(subPath); }
Source:
<code>private void maybeScheduleCheckpoint() { switch (state()) { case RESTORING: this.checkpoint = checkpointableOffsets(); break; case RUNNING: if (!eosEnabled) { this.checkpoint = checkpointableOffsets(); } break; case SUSPENDED: this.checkpoint = Collections.emptyMap(); break; case CREATED: case CLOSED: <START> throw new IllegalStateException("Illegal state " + state() + " while closing active task " + id); <END> default: throw new IllegalStateException("Unknown state " + state() + " while closing active task " + id); } }</code><technical_language>update exception text while scheduling checkpoint</technical_language>

Target:
private void maybeScheduleCheckpoint() { switch (state()) { case RESTORING: case SUSPENDED: this.checkpoint = checkpointableOffsets(); break; case RUNNING: if (!eosEnabled) { this.checkpoint = checkpointableOffsets(); } break; case CREATED: case CLOSED: throw new IllegalStateException("Illegal state " + state() + " while scheduling checkpoint for active task " + id); default: throw new IllegalStateException("Unknown state " + state() + " while scheduling checkpoint for active task " + id); } }
Source:
<code><START> public Result(final Issue issue, String altSummaryFields) { <END> this.key = issue.getKey(); if(altSummaryFields == null || altSummaryFields.isEmpty() ) { this.summary = issue.getSummary(); } else { String[] fields = altSummaryFields.split(","); StringBuilder sb = new StringBuilder(); for(String f : fields) { sb.append(issue.getFieldByName(f).getValue()); sb.append(' '); } this.summary = sb.toString(); } }</code><technical_language>breaking compat.</technical_language>

Target:
public Result(final Issue issue, String altSummaryFields) { this.key = issue.getKey(); if(StringUtils.isEmpty(altSummaryFields)) { this.summary = issue.getSummary(); } else { String[] fields = altSummaryFields.split(","); StringBuilder sb = new StringBuilder(); for(String f : fields) { String fn = f.trim(); if(StringUtils.isNotEmpty(fn)) { IssueField field = issue.getFieldByName(fn); if(field != null && field.getValue() != null) { String fv = field.getValue().toString(); if(StringUtils.isNotEmpty(fv)) { sb.append(fv); sb.append(' '); } } } } this.summary = sb.toString().trim(); } }
Source:
<code>public void doLocalClearThrowsForceReattemptExceptionWhenAnExceptionIsThrownDuringClearOperation() <START> throws ForceReattemptException { <END> DistributedLockService mockLockService = mock(DistributedLockService.class); doReturn(mockLockService).when(message).getPartitionRegionLockService(); NullPointerException exception = new NullPointerException("Error encountered"); doThrow(exception).when(bucketRegion).cmnClearRegion(any(), anyBoolean(), anyBoolean()); when(bucketRegion.isPrimary()).thenReturn(true); when(mockLockService.lock(any(), anyLong(), anyLong())).thenReturn(true); assertThatThrownBy(() -> message.doLocalClear(region)) .isInstanceOf(ForceReattemptException.class) .hasMessageContaining(ClearPRMessage.EXCEPTION_THROWN_DURING_CLEAR_OPERATION); verify(bucketRegion, times(1)).cmnClearRegion(any(), anyBoolean(), anyBoolean()); verify(mockLockService, times(1)).lock(any(), anyLong(), anyLong()); verify(mockLockService, times(1)).unlock(any()); }</code><technical_language>This exception is thrown this method, safely removed</technical_language>

Target:
public void doLocalClearThrowsForceReattemptExceptionWhenAnExceptionIsThrownDuringClearOperation() { DistributedLockService mockLockService = mock(DistributedLockService.class); doReturn(mockLockService).when(message).getPartitionRegionLockService(); NullPointerException exception = new NullPointerException("Error encountered"); doThrow(exception).when(bucketRegion).cmnClearRegion(any(), anyBoolean(), anyBoolean()); when(bucketRegion.isPrimary()).thenReturn(true); when(mockLockService.lock(any(), anyLong(), anyLong())).thenReturn(true); assertThatThrownBy(() -> message.doLocalClear(region)) .isInstanceOf(ForceReattemptException.class) .hasMessageContaining(ClearPRMessage.EXCEPTION_THROWN_DURING_CLEAR_OPERATION); verify(bucketRegion, times(1)).cmnClearRegion(any(), anyBoolean(), anyBoolean()); }
Source:
<code>protected List<Issue> getIssues(String jql, int start, int maxPerQuery, int maxResults) { <START> LOG.info("Start indexing current JIRA issues..."); <END> List<Issue> issues = new ArrayList<>(); while (true) { SearchRestClient searchRestClient = endpoint.getClient().getSearchClient(); SearchResult searchResult = searchRestClient.searchJql(jql, maxResults, start, null).claim(); for (Issue issue : searchResult.getIssues()) { issues.add(issue); } if (start >= searchResult.getTotal() || (maxResults > 0 && issues.size() >= maxResults)) { break; } start += maxPerQuery; } LOG.info("End indexing current JIRA issues. issues indexed.", issues.size()); return issues; }</code><technical_language>Do need this INFO logging noise? If this method is invoked frequently get spammed logs. this DEBUG</technical_language>

Target:
protected List<Issue> getIssues(String jql, int start, int maxPerQuery, int maxResults) { LOG.debug("Start indexing current JIRA issues..."); List<Issue> issues = new ArrayList<>(); while (true) { SearchRestClient searchRestClient = endpoint.getClient().getSearchClient(); SearchResult searchResult = searchRestClient.searchJql(jql, maxResults, start, null).claim(); for (Issue issue : searchResult.getIssues()) { issues.add(issue); } if (start >= searchResult.getTotal() || (maxResults > 0 && issues.size() >= maxResults)) { break; } start += maxPerQuery; } LOG.debug("End indexing current JIRA issues. issues indexed.", issues.size()); return issues; }
Source:
<code>public void before() throws Exception { <START> configDirectory = Files.createTempDirectory(null); <END> config = new NioFileConfigDirectory(configDirectory); c5Server = context.mock(C5Server.class, "mockC5Server"); discoveryModule = context.mock(DiscoveryModule.class); replicationModule = context.mock(ReplicationModule.class); replicator = context.mock(ReplicationModule.Replicator.class); C5FiberFactory fiberFactory = () -> new ThreadFiber(); context.checking(new Expectations() {{ oneOf(c5Server).getFiberFactory(with(any(Consumer.class))); will(returnValue(fiberFactory)); oneOf(c5Server).getModule(with(ModuleType.Discovery)); will(returnValue(discoveryServiceFuture)); discoveryServiceFuture.set(discoveryModule); oneOf(c5Server).getModule(with(ModuleType.Replication)); will(returnValue(replicationServiceFuture)); replicationServiceFuture.set(replicationModule); oneOf(c5Server).isSingleNodeMode(); will(returnValue(true)); oneOf(discoveryModule).getNewNodeNotifications(); will(returnValue(newNodeNotificationChannel)); oneOf(discoveryModule).getState(); will(returnValue(stateFuture)); }}); tabletService = new TabletService(c5Server); }</code><technical_language>arent mocking ConfigDirectory</technical_language>

Target:
public void before() throws Exception { config = context.mock(ConfigDirectory.class); configDirectory = Files.createTempDirectory(null); c5Server = context.mock(C5Server.class, "mockC5Server"); discoveryModule = context.mock(DiscoveryModule.class); replicationModule = context.mock(ReplicationModule.class); replicator = context.mock(ReplicationModule.Replicator.class); context.checking(new Expectations() {{ allowing(config).getBaseConfigPath(); will(returnValue(configDirectory)); allowing(config).writeBinaryData(with(any(String.class)), with(any(String.class)), with(any(byte[].class))); allowing(config).writePeersToFile(with(any(String.class)), with(any(List.class))); allowing(config).configuredQuorums(); will(returnValue(Arrays.asList("testTable,\\x00,1.064e3eb1da827b1dc753e03a797dba37."))); oneOf(c5Server).getFiberFactory(with(any(Consumer.class))); will(returnValue(fiberFactory)); oneOf(c5Server).getModule(with(ModuleType.Discovery)); will(returnValue(discoveryServiceFuture)); discoveryServiceFuture.set(discoveryModule); oneOf(c5Server).getModule(with(ModuleType.Replication)); will(returnValue(replicationServiceFuture)); replicationServiceFuture.set(replicationModule); oneOf(c5Server).isSingleNodeMode(); will(returnValue(true)); oneOf(discoveryModule).getNewNodeNotifications(); will(returnValue(newNodeNotificationChannel)); oneOf(discoveryModule).getState(); will(returnValue(stateFuture)); }}); tabletService = new TabletService(c5Server); }
Source:
<code>public UserDevfileImpl createDevfile(Devfile devfile) throws ServerException, NotFoundException, ConflictException { requireNonNull(devfile, "Required non-null devfile"); UserDevfileImpl result = userDevfileDao.create( <START> new UserDevfileImpl(NameGenerator.generate("usrdevfile", 16), devfile)); <END> LOG.info( "UserDevfile '{}' with id '{}' created by user '{}'", result.getName(), result.getId(), EnvironmentContext.getCurrent().getSubject().getUserName()); eventService.publish(new DevfileCreatedEvent(result)); return result; }</code><technical_language>sense save 1 byte usr instead user ? :)</technical_language>

Target:
public UserDevfile createDevfile(Devfile devfile) throws ServerException, NotFoundException, ConflictException { requireNonNull(devfile, "Required non-null devfile"); UserDevfile result = userDevfileDao.create(new UserDevfileImpl(NameGenerator.generate("devfile", 16), devfile)); LOG.debug( "UserDevfile '{}' with id '{}' created by user '{}'", result.getName(), result.getId(), EnvironmentContext.getCurrent().getSubject().getUserName()); eventService.publish(new DevfileCreatedEvent(result)); return result; }
Source:
<code><START> public Object compute(final Map<String, Object> combinedAggregators) <END> { final ArrayOfDoublesSketch sketch = (ArrayOfDoublesSketch) getField().compute(combinedAggregators); return sketch.getEstimate(); }</code><technical_language>Please change return type Double for type safety</technical_language>

Target:
public Double compute(final Map<String, Object> combinedAggregators) { final ArrayOfDoublesSketch sketch = (ArrayOfDoublesSketch) getField().compute(combinedAggregators); return sketch.getEstimate(); }
Source:
<code>public static PreparedStatement prepareIdSelectStatement(Connection c, String storageKey, int id) { try { PreparedStatement preparedStatement = c.prepareStatement("SELECT * FROM " + storageKey + " WHERE " + DatabaseHelper.ID_COL + " = ?;"); preparedStatement.setInt(1, id); return preparedStatement; } catch (SQLException e) { <START> e.printStackTrace(); <END> return null; } }</code><technical_language>This right me. rethrowing a runtime if process, shoudln't we</technical_language>

Target:
public static PreparedStatement prepareIdSelectStatement(Connection c, String storageKey, int id) { try { PreparedStatement preparedStatement = c.prepareStatement("SELECT * FROM " + storageKey + " WHERE " + DatabaseHelper.ID_COL + " = ?;"); preparedStatement.setInt(1, id); return preparedStatement; } catch (SQLException e) { throw new RuntimeException(e); } }
Source:
<code>public static Response decrypt(Response response) throws OSException { discardEOptions(response); OSCoreCtxDB db = HashMapCtxDB.getInstance(); byte[] protectedData = collectData(response); Encrypt0Message enc = null; Token token = response.getToken(); OSCoreCtx ctx = null; if (token != null) { ctx = db.getContextByToken(token); if (ctx == null) { LOGGER.severe(OSExceptionHandler.TOKEN_INVALID); throw new OSException(OSExceptionHandler.TOKEN_INVALID); } enc = decompression(protectedData, response); } else { LOGGER.severe(OSExceptionHandler.TOKEN_NULL); throw new OSException(OSExceptionHandler.TOKEN_NULL); } <START> byte[] content = decryptAndDecode(enc, response, ctx, db.getSeqByToken(token)); <END> response = OptionJuggle.setRealCodeResponse(response, CoAP.ResponseCode.valueOf(content[0])); content = Arrays.copyOfRange(content, 1, content.length); byte[] payload = OSSerializer.readPayload(content); response.setPayload(payload); db.removeToken(token); return response; }</code><technical_language>PR #660 similar to: byte[] plaintext = decryptAndDecode(enc, response, ctx, db.getSeqByToken(token)); DatagramReader reader = new DatagramReader(new ByteArrayInputStream(plaintext)); response = OptionJuggle.setRealCodeResponse(response, CoAP.ResponseCode.valueOf(reader.read(CoAP.MessageFormat.CODE_BITS))); DataParser.parseOptionsAndPayload(reader, response); implementation ignore E options for responses. This new implementation mix E U options original options. I guess, is missing</technical_language>

Target:
public static Response decrypt(Response response) throws OSException { discardEOptions(response); OSCoreCtxDB db = HashMapCtxDB.getInstance(); byte[] protectedData = response.getPayload(); Encrypt0Message enc = null; Token token = response.getToken(); OSCoreCtx ctx = null; OptionSet uOptions = response.getOptions(); if (token != null) { ctx = db.getContextByToken(token); if (ctx == null) { LOGGER.error(Error.TOKEN_INVALID); throw new OSException(Error.TOKEN_INVALID); } enc = decompression(protectedData, response); } else { LOGGER.error(Error.TOKEN_NULL); throw new OSException(Error.TOKEN_NULL); } byte[] plaintext = decryptAndDecode(enc, response, ctx, db.getSeqByToken(token)); DatagramReader reader = new DatagramReader(new ByteArrayInputStream(plaintext)); response = OptionJuggle.setRealCodeResponse(response, CoAP.ResponseCode.valueOf(reader.read(CoAP.MessageFormat.CODE_BITS))); response.setOptions(EMPTY); DataParser.parseOptionsAndPayload(reader, response); OptionSet eOptions = response.getOptions(); eOptions = OptionJuggle.merge(eOptions, uOptions); response.setOptions(eOptions); db.removeToken(token); return response; }
Source:
<code>public List<PermissionSubject> getPermissionCheckSubjects() { if (permsList == null && getDisk() != null) { permsList = new ArrayList<PermissionSubject>(); permsList.add(new PermissionSubject(getDisk().getId(), VdcObjectType.Disk, <START> ActionGroup.ATTACH_DISK)); <END> } return permsList; }</code><technical_language>a manipulate disk permission</technical_language>

Target:
public List<PermissionSubject> getPermissionCheckSubjects() { if (permsList == null && getDisk() != null) { permsList = new ArrayList<PermissionSubject>(); permsList.add(new PermissionSubject(getDisk().getId(), VdcObjectType.Disk, ActionGroup.ATTACH_DISK)); permsList.add(new PermissionSubject(getDisk().getId(), VdcObjectType.Disk, ActionGroup.EDIT_DISK_PROPERTIES)); } return permsList; }
Source:
<code>private void log(IStatus status, String prefix) { if (status.getSeverity() >= minSeverity) { log(prefix + status.getMessage()); String exceptionMessage = status.getException() != null ? status.getException().getMessage() : null; if (exceptionMessage != null) log(prefix + exceptionMessage); IStatus[] nestedStatus = status.getChildren(); if (nestedStatus != null) for (IStatus <START> nestedStatu : <END> nestedStatus) { log(nestedStatu, prefix + INDENT); } } }</code><technical_language>Find name</technical_language>

Target:
private void log(IStatus status, String prefix) { if (status.getSeverity() >= minSeverity) { log(prefix + status.getMessage()); String exceptionMessage = status.getException() != null ? status.getException().getMessage() : null; if (exceptionMessage != null) log(prefix + exceptionMessage); IStatus[] nestedStatus = status.getChildren(); if (nestedStatus != null) for (IStatus s : nestedStatus) { log(s, prefix + INDENT); } } }
Source:
<code>protected void updateOSValue(final Integer selectedOsId) { <START> List<Integer> vmOsValues; <END> Cluster cluster = getModel().getSelectedCluster(); if (cluster != null) { vmOsValues = AsyncDataProvider.getInstance().getOsIds(cluster.getArchitecture()); if (selectedOsId != null && vmOsValues.contains(selectedOsId)) { getModel().getOSType().setSelectedItem(selectedOsId); } else { updateOSValues(); } } else { updateOSValues(); } }</code><technical_language>Please move declaration line vmOsValues is initialized</technical_language>

Target:
protected void updateOSValue(final Integer selectedOsId) { Cluster cluster = getModel().getSelectedCluster(); if (cluster != null) { List<Integer> vmOsValues = AsyncDataProvider.getInstance().getOsIds(cluster.getArchitecture()); if (selectedOsId == null || !vmOsValues.contains(selectedOsId)) { updateOSValues(); return; } getModel().getOSType().setSelectedItem(selectedOsId); } }
Source:
<code>public ImmutableValue<String> lockToken() { <START> return new ImmutableSpongeValue<String>(this.usedKey, this.value); <END> }</code><technical_language>Include default argument please. Also, send this a field return field reference</technical_language>

Target:
public ImmutableValue<String> lockToken() { return this.lockToken; }
Source:
<code>public static void main(String[] args) { System.setProperty("smart-socket.server.pageSize", (32 * 1024 * 1024) + ""); System.setProperty("smart-socket.session.writeChunkSize", (1024 * 8) + ""); HttpMessageProcessor processor = new HttpMessageProcessor(System.getProperty("webapps.dir", "./")); processor.route("/plaintext", new HttpHandle() { @Override public void doHandle(HttpRequest request, HttpResponse response) throws IOException { response.setContentLength(body.length); response.setContentType("text/plain; charset=UTF-8"); response.getOutputStream().write(body); } }); processor.route("/json", new HttpHandle() { <START> byte[] b = JSON.toJson(new Message("Hello, World!")); <END> @Override public void doHandle(HttpRequest request, HttpResponse response) throws IOException { response.setContentLength(b.length); response.setContentType("application/json"); response.getOutputStream().write(b); } }); http(processor); }</code><technical_language>Is this created request? If processor.route sets route public void doHandle() is called request route, this moved comply test rules</technical_language>

Target:
public static void main(String[] args) { System.setProperty("smart-socket.server.pageSize", (32 * 1024 * 1024) + ""); System.setProperty("smart-socket.session.writeChunkSize", (1024 * 8) + ""); HttpMessageProcessor processor = new HttpMessageProcessor(System.getProperty("webapps.dir", "./")); processor.route("/plaintext", new HttpHandle() { @Override public void doHandle(HttpRequest request, HttpResponse response) throws IOException { response.setContentLength(body.length); response.setContentType("text/plain; charset=UTF-8"); response.getOutputStream().write(body); } }); processor.route("/json", new HttpHandle() { @Override public void doHandle(HttpRequest request, HttpResponse response) throws IOException { byte[] b = JSON.toJson(new Message("Hello, World!")); response.setContentLength(b.length); response.setContentType("application/json"); response.getOutputStream().write(b); } }); http(processor); }
Source:
<code>R apply(T input) throws IOException; } private <T,R> R wrapWithSnappyOrThrow(T stream, IOFunction<T, R> wrapper){ if (isSnappyAvailable()) { try { return wrapper.apply(stream); } catch (Exception e) { <START> throw new SAMException("Error instantiating SnappyInputStream", e); <END> } } else { final String errorMessage = Defaults.DISABLE_SNAPPY_COMPRESSOR ? "Cannot wrap stream with snappy compressor because snappy was disabled via the " + Defaults.DISABLE_SNAPPY_PROPERTY_NAME + " system property." : "Cannot wrap stream with snappy compressor because we could not load the snappy library."; throw new SAMException(errorMessage); } }</code><technical_language>This read Error wrapping stream snappy similarly generic</technical_language>

Target:
R apply(T input) throws IOException; } private <T,R> R wrapWithSnappyOrThrow(T stream, IOFunction<T, R> wrapper){ if (isSnappyAvailable()) { try { return wrapper.apply(stream); } catch (Exception e) { throw new SAMException("Error wrapping stream with snappy", e); } } else { final String errorMessage = Defaults.DISABLE_SNAPPY_COMPRESSOR ? "Cannot wrap stream with snappy compressor because snappy was disabled via the " + Defaults.DISABLE_SNAPPY_PROPERTY_NAME + " system property." : "Cannot wrap stream with snappy compressor because we could not load the snappy library."; throw new SAMException(errorMessage); } }
Source:
<code>private static RowType createJsonRowType(DataType databaseSchema) { return (RowType) DataTypes.ROW( <START> DataTypes.FIELD("after", databaseSchema), <END> DataTypes.FIELD("op", DataTypes.STRING())).getLogicalType(); }</code><technical_language>This is wrong. Debezium serialize insert data in "after", delete data in "before"</technical_language>

Target:
private static RowType createJsonRowType(DataType databaseSchema) { return (RowType) DataTypes.ROW( DataTypes.FIELD("before", databaseSchema), DataTypes.FIELD("after", databaseSchema), DataTypes.FIELD("op", DataTypes.STRING())).getLogicalType(); }
Source:
<code>public static void main(String[] args) throws Exception { System.setProperty("hazelcast.jmx", "true"); Hazelcast.newHazelcastInstance(); Hazelcast.newHazelcastInstance(); Hazelcast.newHazelcastInstance(); HazelcastInstance hz = Hazelcast.newHazelcastInstance(); System.out.println("Hazelcast cluster was started. Number of members: " + hz.getCluster().getMembers().size()); IMap<String, String> map = hz.getMap("cities"); map.put("where to live", "Brno"); map.put("where to have a joy", "Paris"); map.put("where to go next", "London"); System.out.println("Entries were added to 'cities' IMap, current size is: " + map.size()); for (int i = 0; i < 15; i++) { <START> Thread.sleep(2000L); <END> printMapStatistics(); } Hazelcast.shutdownAll(); }</code><technical_language>com.hazelcast.examples.helper.CommonUtils.sleepSeconds here, a bit easier read (and need throws Exception then)</technical_language>

Target:
public static void main(String[] args) { System.setProperty("hazelcast.jmx", "true"); Hazelcast.newHazelcastInstance(); Hazelcast.newHazelcastInstance(); Hazelcast.newHazelcastInstance(); HazelcastInstance hz = Hazelcast.newHazelcastInstance(); System.out.println("Hazelcast cluster was started. Number of members: " + hz.getCluster().getMembers().size()); IMap<String, String> map = hz.getMap("cities"); map.put("where to live", "Brno"); map.put("where to have a joy", "Paris"); map.put("where to go next", "London"); System.out.println("Entries were added to 'cities' IMap, current size is: " + map.size()); for (int i = 0; i < 15; i++) { sleepSeconds(2); printMapStatistics(); } Hazelcast.shutdownAll(); }
Source:
<code>public VfsEventService() { <START> this.executor = newSingleThreadExecutor(); <END> this.running = new AtomicBoolean(false); }</code><technical_language>Please thread builder factory set name of thread. in case need analyze thread dump. is example of <LINK_0></technical_language>

Target:
VfsEventService() { final String threadName = getClass().getSimpleName().concat("Thread-%d"); final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(threadName) .setDaemon(TRUE) .build(); this.executor = newSingleThreadExecutor(threadFactory); this.running = new AtomicBoolean(FALSE); }
Source:
<code>public Builder fetch( Rule rule, Path outputDirectory, BlazeDirectories directories, Environment env, Map<String, String> markerData) throws RepositoryFunctionException { CPU hostCpu = CPU.getCurrent(); OS hostOs = OS.getCurrent(); <START> List<String> constraints = generateConstraints(hostCpu, hostOs); <END> try { outputDirectory.createDirectoryAndParents(); RepositoryFunction.writeFile( outputDirectory, "WORKSPACE", workspaceFileContent(rule.getName())); RepositoryFunction.writeFile( outputDirectory, "BUILD.bazel", buildFileContent(rule.getName())); RepositoryFunction.writeFile( outputDirectory, "constraints.bzl", constraintFileContent(constraints)); } catch (IOException e) { throw new RepositoryFunctionException( new IOException("Could not create content for " + rule.getName() + ": " + e.getMessage()), Transience.TRANSIENT); } return RepositoryDirectoryValue.builder().setPath(outputDirectory); }</code><technical_language>This is a list open possibility of more constraint types forward</technical_language>

Target:
public Builder fetch( Rule rule, Path outputDirectory, BlazeDirectories directories, Environment env, Map<String, String> markerData) throws RepositoryFunctionException { CPU hostCpu = CPU.getCurrent(); OS hostOs = OS.getCurrent(); try { outputDirectory.createDirectoryAndParents(); RepositoryFunction.writeFile( outputDirectory, "WORKSPACE", workspaceFileContent(rule.getName())); RepositoryFunction.writeFile( outputDirectory, "BUILD.bazel", buildFileContent(rule.getName())); RepositoryFunction.writeFile( outputDirectory, "constraints.bzl", constraintFileContent(hostCpu, hostOs)); } catch (IOException e) { throw new RepositoryFunctionException( new IOException("Could not create content for " + rule.getName() + ": " + e.getMessage()), Transience.TRANSIENT); } return RepositoryDirectoryValue.builder().setPath(outputDirectory); }
Source:
<code>public void missingFields_hiddenSilently() { SyncConfiguration config = configFactory.createSyncConfigurationBuilder(SyncTestUtils.createTestUser(), "<LINK_0>") .schema(StringOnly.class) .build(); String className = StringOnly.class.getSimpleName(); DynamicRealm dynamicRealm = DynamicRealm.getInstance(config); RealmSchema schema = dynamicRealm.getSchema(); dynamicRealm.beginTransaction(); schema.create(className) .addField(StringOnly.FIELD_CHARS, String.class) .addField("newField", String.class); <START> OsObjectStore.setSchemaVersion(dynamicRealm.getSharedRealm(), 0); <END> dynamicRealm.commitTransaction(); dynamicRealm.close(); Realm realm = Realm.getInstance(config); RealmObjectSchema stringOnlySchema = realm.getSchema().get(className); try { assertTrue(stringOnlySchema.hasField(StringOnly.FIELD_CHARS)); assertTrue(stringOnlySchema.hasField("newField")); assertEquals(2, stringOnlySchema.getFieldNames().size()); } finally { realm.close(); } }</code><technical_language>this implementation dynamicRealm.setVersion(0), more readable dynamicRealm. this change new developers need change version number</technical_language>

Target:
public void missingFields_hiddenSilently() { SyncConfiguration config = configFactory.createSyncConfigurationBuilder(SyncTestUtils.createTestUser(), "<LINK_0>") .schema(StringOnly.class) .build(); String className = StringOnly.class.getSimpleName(); DynamicRealm dynamicRealm = DynamicRealm.getInstance(config); RealmSchema schema = dynamicRealm.getSchema(); dynamicRealm.beginTransaction(); schema.create(className) .addField(StringOnly.FIELD_CHARS, String.class) .addField("newField", String.class); dynamicRealm.setVersion(0); dynamicRealm.commitTransaction(); dynamicRealm.close(); Realm realm = Realm.getInstance(config); RealmObjectSchema stringOnlySchema = realm.getSchema().get(className); try { assertTrue(stringOnlySchema.hasField(StringOnly.FIELD_CHARS)); assertTrue(stringOnlySchema.hasField("newField")); assertEquals(2, stringOnlySchema.getFieldNames().size()); } finally { realm.close(); } }
Source:
<code>private void validateJson() throws ValidationException { <START> PolicyMuleArtifactJsonVerifier.validate(projectInformation, getMuleArtifactFile()); <END> }</code><technical_language>a rule of thumb, avoid static method, tightly couple implementations, difficult testing, leak memory. If JsonVerifier a clear intention, a defined protocol, lets instance ;)</technical_language>

Target:
private void validateJson() throws ValidationException { new PolicyMuleArtifactJsonVerifier(projectInformation, getMuleArtifactFile()).validate(); }
Source:
<code>public Mono<Void> deleteAllById(Iterable<? extends ID> ids) { Assert.notNull(ids, "The given Iterable of ids must not be null!"); <START> return Flux.fromIterable(ids).flatMap(this::deleteById).then(); <END> }</code><technical_language>collect ID's a query run a single delete query avoid issuing a query Id</technical_language>

Target:
public Mono<Void> deleteAllById(Iterable<? extends ID> ids) { Assert.notNull(ids, "The given Iterable of ids must not be null!"); Collection<?> idCollection = StreamUtils.createStreamFromIterator(ids.iterator()).collect(Collectors.toList()); Criteria idsInCriteria = where(entityInformation.getIdAttribute()).in(idCollection); return mongoOperations .remove(new Query(idsInCriteria), entityInformation.getJavaType(), entityInformation.getCollectionName()) .then(); }
Source:
<code>public void testButtonVisibilityForMusicFile() throws Throwable { Uri uri = Uri.parse("android.resource://" + mContext.getPackageName() + "/" + R.raw.test_music); final MediaItem uriMediaItem = createTestMediaItem2(uri); final CountDownLatch latch = new CountDownLatch(1); final MediaController controller = createController(new MediaController.ControllerCallback() { @NonNull @Override public SessionResult onCustomCommand(@NonNull MediaController controller, @NonNull SessionCommand command, @Nullable Bundle args) { if (command.getCustomAction() == MediaControlView.EVENT_UPDATE_TRACK_STATUS) { latch.countDown(); } return new SessionResult(SessionResult.RESULT_SUCCESS, null); } }); mActivityRule.runOnUiThread(new Runnable() { @Override public void run() { mVideoView.setMediaItem(uriMediaItem); } }); assertTrue(latch.await(WAIT_TIME_MS, TimeUnit.MILLISECONDS)); <START> onView(withId(R.id.subtitle)).check(matches(not(isCompletelyDisplayed()))); <END> }</code><technical_language>Q) isDisplayed? is checking displayed. (ditto for others)</technical_language>

Target:
public void testButtonVisibilityForMusicFile() throws Throwable { Uri uri = Uri.parse("android.resource://" + mContext.getPackageName() + "/" + R.raw.test_music); final MediaItem uriMediaItem = createTestMediaItem2(uri); final CountDownLatch latch = new CountDownLatch(1); final MediaController controller = createController(new MediaController.ControllerCallback() { @NonNull @Override public SessionResult onCustomCommand(@NonNull MediaController controller, @NonNull SessionCommand command, @Nullable Bundle args) { if (command.getCustomAction() == MediaControlView.EVENT_UPDATE_TRACK_STATUS) { latch.countDown(); } return new SessionResult(SessionResult.RESULT_SUCCESS, null); } }); mActivityRule.runOnUiThread(new Runnable() { @Override public void run() { mVideoView.setMediaItem(uriMediaItem); } }); assertTrue(latch.await(WAIT_TIME_MS, TimeUnit.MILLISECONDS)); onView(withId(R.id.subtitle)).check(matches(not(isDisplayed()))); }