auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static <R extends BaseResource> UriBuilder getUriBuilder(UriInfo uriInfo, R model, Class<? extends BaseResource> suggestedParentType) { Collection collection = getCollection(model, suggestedParentType); if (collection == null) { return null; } <START> UriBuilder uriBuilder = builderMap.get(collection); <END> if (uriBuilder == null) { if (collection.getParentType() != NO_PARENT) { BaseResource parent = getParentModel(model, collection.getParentType()); Collection parentCollection = getCollection(parent, suggestedParentType); String path = getPath(collection.getCollectionType(), parentCollection.getResourceType(), model.getClass()); uriBuilder = getUriBuilder(uriInfo, parent).path(path); } else { String path = getPath(collection.getCollectionType()); uriBuilder = uriInfo != null ? UriBuilder.fromPath(uriInfo.getBaseUri().getPath()).path(path) : UriBuilder.fromPath(path); } builderMap.put(collection, uriBuilder.clone()); } else { uriBuilder = uriBuilder.clone(); } return uriBuilder.path(model.getId()); }</code><technical_language>collection key of map improves situation. I concerns: 1. "Collection" class implement "equals" "hashCode" methods, this work correctly if trust instances of "Collection" create different. is a safe assumption moment, of create them. Anyhow, suggest implement "equals" "hashCode" methods correctly, in case. 2. state of class UriBuilderImpl (the default implementation of UriBulider) includes identifiers of entities. For example, calling this method build link for a VM store path in "path" field: /ovirt-engine/api/vms/84f3a784-d78f-468b-88d0-cbe8133e6a77 happen building next VM? bad, builder cache data remove identifier replace new one. still, this is kind of leaking information request a one, potentially dangerous me. try modify this methods potentially populate cache receive model instance? I mean, if method receives "Class modelClass" instead of "R model" is chance get information specific a entity put in cache</technical_language>

Target:
public static <R extends BaseResource> UriBuilder getUriBuilder(UriInfo uriInfo, R model, Class<? extends BaseResource> suggestedParentType) { Collection collection = getCollection(model, suggestedParentType); if (collection == null) { return null; } UriBuilder uriBuilder; if (collection.getParentType() != NO_PARENT) { BaseResource parent = getParentModel(model, collection.getParentType()); Collection parentCollection = getCollection(parent, suggestedParentType); String path = getPath(collection.getCollectionType(), parentCollection.getResourceType(), model.getClass()); uriBuilder = getUriBuilder(uriInfo, parent).path(path); } else { uriBuilder = builderMap.get(collection); if (uriBuilder == null) { String path = getPath(collection.getCollectionType()); uriBuilder = uriInfo != null ? UriBuilder.fromPath(uriInfo.getBaseUri().getPath()).path(path) : UriBuilder.fromPath(path); builderMap.put(collection, uriBuilder.clone()); } else { uriBuilder = uriBuilder.clone(); } } return uriBuilder.path(model.getId()); }
Source:
<code>public Optional<Metacard> apply(String featureMember, WfsMetadata metadata) { for (FeatureTransformer featureTransformer : transformerServiceList) { try (InputStream featureMemberInputStream = new BufferedInputStream(new ByteArrayInputStream(featureMember.getBytes()))) { Optional<Metacard> metacardOptional = featureTransformer.apply(featureMemberInputStream, metadata); if (metacardOptional.isPresent()) { return metacardOptional; } } catch (IOException e) { <START> LOGGER.debug( <END> "Error transforming feature member:{}, with feature transformer: {}", featureMember, featureTransformer); } } return Optional.empty(); }</code><technical_language>is for featureMember null? Also, more sense this try block of for loop</technical_language>

Target:
public Optional<Metacard> apply(String featureMember, WfsMetadata metadata) { if (StringUtils.isEmpty(featureMember)) { return Optional.empty(); } for (FeatureTransformer featureTransformer : transformerServiceList) { try (InputStream featureMemberInputStream = new BufferedInputStream(new ByteArrayInputStream(featureMember.getBytes()))) { Optional<Metacard> metacardOptional = featureTransformer.apply(featureMemberInputStream, metadata); if (metacardOptional.isPresent()) { return metacardOptional; } } catch (IOException e) { LOGGER.error( "Error transforming feature member:{}, with feature transformer: {}", featureMember, featureTransformer); } } return Optional.empty(); }
Source:
<code>public void shouldThrowExceptionOnValidationNonValidDevfile( String resourceFilePath, String expectedMessageRegexp) throws Exception { try { schemaValidator.validateBySchema(getResource(resourceFilePath), false); } catch (DevfileFormatException e) { if (!Pattern.matches(expectedMessageRegexp, e.getMessage())) { assertEquals( e.getMessage(), expectedMessageRegexp, "DevfileFormatException with unexpected message is thrown: "); <START> } <END> return; } fail("DevfileFormatException expected to be thrown but is was not"); }</code><technical_language>a check if (!Pattern.matches(expectedMessageRegexp, e.getMessage())) { assertEquals here? print expected, actual</technical_language>

Target:
public void shouldThrowExceptionOnValidationNonValidDevfile( String resourceFilePath, String expectedMessageRegexp) throws Exception { try { schemaValidator.validateBySchema(getResource(resourceFilePath), false); } catch (DevfileFormatException e) { if (!Pattern.matches(expectedMessageRegexp, e.getMessage())) { assertEquals( e.getMessage(), expectedMessageRegexp, "DevfileFormatException thrown with message that doesn't match expected pattern:"); } return; } fail("DevfileFormatException expected to be thrown but is was not"); }
Source:
<code>public static boolean useLegacyParser(final Class<?> clazz) { <START> String legacyPropertyValue = null; <END> if (useLegacyParser == null) { legacyPropertyValue = System.getProperty(PROPERTY_USE_LEGACY_PARSER); if (null == legacyPropertyValue){ Properties props = PropertyUtils.loadPropertiesFile(PICARD_CMDLINE_PROPERTIES_FILE, clazz); if (props != null) { legacyPropertyValue = props.getProperty(PROPERTY_USE_LEGACY_PARSER); } } useLegacyParser = legacyPropertyValue == null || Boolean.parseBoolean(legacyPropertyValue); } return useLegacyParser; }</code><technical_language>scoped if need initialization</technical_language>

Target:
public static boolean useLegacyParser(final Class<?> clazz) { if (useLegacyParser == null) { String legacyPropertyValue = legacyPropertyValue = System.getProperty(PROPERTY_USE_LEGACY_PARSER); if (null == legacyPropertyValue){ final Properties props = PropertyUtils.loadPropertiesFile(PICARD_CMDLINE_PROPERTIES_FILE, clazz); if (props != null) { legacyPropertyValue = props.getProperty(PROPERTY_USE_LEGACY_PARSER); } } useLegacyParser = legacyPropertyValue == null ? true : Boolean.parseBoolean(legacyPropertyValue); } return useLegacyParser; }
Source:
<code>private void setOrReplace(String name, Map<String, String> namesMap, String field) { String existingName = namesMap.get("name"); if (!name.equals(existingName)) { if (log.isDebugEnabled()) { log.debug("Replacing "+ field +" name '"+existingName+"' with '"+ name+ "' for osmId #" + osmId); } <START> namesMap.put("formerName", existingName); <END> namesMap.put("name", name); } }</code><technical_language>I more thinking of adding context hashset. If a completePlace() function in NominatimConnector.java, this is multiple city-like address parts show up</technical_language>

Target:
private void setOrReplace(String name, Map<String, String> namesMap, String field) { String existingName = namesMap.get("name"); if (!name.equals(existingName)) { if (log.isDebugEnabled()) { log.debug("Replacing "+ field +" name '"+existingName+"' with '"+ name+ "' for osmId #" + osmId); } if(!Objects.isNull(existingName)) { context.add(ImmutableMap.of("formerName", existingName)); } namesMap.put("name", name); } }
Source:
<code>private static void ensureResultTypesMatch(Collection<? extends Symbol> results) { <START> HashSet<DataType<?>> resultTypes = new LinkedHashSet<>(results.size()); <END> for (Symbol result : results) { resultTypes.add(result.valueType()); } if (resultTypes.size() == 2 && !resultTypes.contains(DataTypes.UNDEFINED) || resultTypes.size() > 2) { throw new UnsupportedOperationException(String.format(Locale.ENGLISH, "Data types of all result expressions of a CASE statement must be equal, found: %s", resultTypes)); } }</code><technical_language>instead of switching a LinkedHashSet sort types throws block. pay price in error case instead of time</technical_language>

Target:
private static void ensureResultTypesMatch(Collection<? extends Symbol> results) { HashSet<DataType<?>> resultTypes = new HashSet<>(results.size()); for (Symbol result : results) { resultTypes.add(result.valueType()); } if (resultTypes.size() == 2 && !resultTypes.contains(DataTypes.UNDEFINED) || resultTypes.size() > 2) { throw new UnsupportedOperationException(String.format(Locale.ENGLISH, "Data types of all result expressions of a CASE statement must be equal, found: %s", results.stream().map(Symbol::valueType).collect(toList()))); } }
Source:
<code>private boolean canDoSnapshot(VM vm) { if (!isLiveSnapshotEnabled() && !vm.isDown()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DATA_CENTER_VERSION_DOESNT_SUPPORT_LIVE_SNAPSHOT); } <START> if (!getVdsFromRunningVm(vm).getLiveSnapshotSupport()) { <END> return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_QEMU_UNSUPPORTED_OPERATION); } return true; }</code><technical_language>i user getVds() logic get host vm, in case need check for null, vm</technical_language>

Target:
private boolean canDoSnapshot(VM vm) { if (!isLiveSnapshotEnabled() && !vm.isDown()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DATA_CENTER_VERSION_DOESNT_SUPPORT_LIVE_SNAPSHOT); } VDS vds = getVds(); if (vds != null && !vds.getLiveSnapshotSupport()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_QEMU_UNSUPPORTED_OPERATION); } return true; }
Source:
<code>public void processBindingConfiguration(String context, Item item, String bindingConfig) throws BindingConfigParseException { logger.debug("PowerDogLocalApi:processBindingConfiguration called"); super.processBindingConfiguration(context, item, bindingConfig); if (bindingConfig != null) { PowerDogLocalApiBindingConfig config = parseBindingConfig(item, bindingConfig); <START> logger.debug("bindingConfig adeed (config=" + config.toString() <END> + ")"); addBindingConfig(item, config); } else { logger.warn("bindingConfig is NULL (item=" + item + ") -> process bindingConfig aborted!"); } }</code><technical_language>parameterized logging instead of string concatenation</technical_language>

Target:
public void processBindingConfiguration(String context, Item item, String bindingConfig) throws BindingConfigParseException { logger.debug("PowerDogLocalApi:processBindingConfiguration called"); super.processBindingConfiguration(context, item, bindingConfig); if (bindingConfig != null) { PowerDogLocalApiBindingConfig config = parseBindingConfig(item, bindingConfig); logger.debug("bindingConfig added (config={})", config.toString()); addBindingConfig(item, config); } else { logger.warn("bindingConfig is NULL (item={}) -> process bindingConfig aborted!", item); } }
Source:
<code>public void horizontalConflictWithTwoQueens() { Queen queen1 = new Queen(0, row1, column1); Queen queen2 = new Queen(1, row1, column2); constraintVerifier.forConstraint(constraintProvider::horizontalConflict) .given(queen1, queen2) <START> .expectReward(1); <END> }</code><technical_language>a penalty, it</technical_language>

Target:
public void horizontalConflictWithTwoQueens() { Queen queen1 = new Queen(0, row1, column1); Queen queen2 = new Queen(1, row1, column2); constraintVerifier.verifyThat(constraintProvider::horizontalConflict) .given(queen1, queen2) .penalizesBy(1); }
Source:
<code>public void handleDelete(ActionParameters params) throws ActionException { final int id = params.getRequiredParamInt(PARAM_ID); final boolean deleteLayers = params.getRequiredParamBoolean(PARAM_DELETE_LAYERS); if (!dataProviderService.hasPermissionToUpdate(params.getUser(), id)) { throw new ActionDeniedException("Unauthorized user tried to remove data provider id=" + id); } <START> if (deleteLayers) { deleteDataProviderAndLayers(id, params); } else { deleteDataProvider(id, params); } <END> }</code><technical_language>easier instantly whats if a method deleteLayersForProvider() removeProviderFromLayers() called based boolean. conditional statements call deleteDataProvider() return removed provider. write response based in handleDelete</technical_language>

Target:
public void handleDelete(ActionParameters params) throws ActionException { final int id = params.getRequiredParamInt(PARAM_ID); final boolean deleteLayers = params.getRequiredParamBoolean(PARAM_DELETE_LAYERS); if (!dataProviderService.hasPermissionToUpdate(params.getUser(), id)) { throw new ActionDeniedException("Unauthorized user tried to remove data provider id=" + id); } List<OskariLayer> layers = mapLayerService.findByDataProviderId(id); if (!deleteLayers) { removeProviderFromLayers(layers, id); } deleteDataProvider(layers, deleteLayers, id, params); }
Source:
<code>public PetriNet() { super(); <START> includes = new IncludeHierarchy(this, null); <END> }</code><technical_language>a fan of passing in null methods/constructors. feels a hacky. I factory/builder design pattern IncludeHierarchy a ways construct it</technical_language>

Target:
public PetriNet() { this(new NormalPetriNetName("")); }
Source:
<code>private void expire(final String key, final int expireInSeconds) { ops.expire(key, expireInSeconds); <START> } <END></code><technical_language>In original logic in RedisLockDao, this checked return of expire(). Do longer need do that</technical_language>

Target:
private void expire(final String key, final int expireInSeconds) { final Long result = ops.expire(key, expireInSeconds); if (result != 1L) { throw new RedisException("Failed to expire key " + key + "."); } }
Source:
<code>private List<Step> buildStepsTree(List<Step> steps) { List<Step> jobDirectSteps = new ArrayList<>(); Map<Guid, List<Step>> parentStepMap = new HashMap<>(); for (Step step : steps) { if (step.getParentStepId() == null) { jobDirectSteps.add(step); } else { MultiValueMapUtils.addToMap(step.getParentStepId(), step, parentStepMap); } } for (Step step : steps) { if <START> (parentStepMap.get(step.getId()) != null) { <END> step.setSteps(parentStepMap.get(step.getId())); } } return jobDirectSteps; }</code><technical_language>parentStepMap.containsKey(step.getId()) a fit here</technical_language>

Target:
private List<Step> buildStepsTree(List<Step> steps) { List<Step> jobDirectSteps = new ArrayList<>(); Map<Guid, List<Step>> parentStepMap = new HashMap<>(); for (Step step : steps) { if (step.getParentStepId() == null) { jobDirectSteps.add(step); } else { MultiValueMapUtils.addToMap(step.getParentStepId(), step, parentStepMap); } } for (Step step : steps) { if (parentStepMap.containsKey(step.getId())) { step.setSteps(parentStepMap.get(step.getId())); } } return jobDirectSteps; }
Source:
<code>BeanPojoProperties(Type type) { super(type); try { this.info = Introspector.getBeanInfo(GenericTypes.getErasedType(type)); } catch (IntrospectionException e) { throw new IllegalArgumentException("Failed to inspect bean " + type, e); } final Map<String, BeanPojoProperty<T>> props = new LinkedHashMap<>(); for (PropertyDescriptor property : info.getPropertyDescriptors()) { <START> final BeanPojoProperty<T> bp = new BeanPojoProperty<>(property); <END> props.put(bp.getName(), bp); } properties = Collections.unmodifiableMap(props); }</code><technical_language>sift out class property</technical_language>

Target:
BeanPojoProperties(Type type) { super(type); try { this.info = Introspector.getBeanInfo(GenericTypes.getErasedType(type)); } catch (IntrospectionException e) { throw new IllegalArgumentException("Failed to inspect bean " + type, e); } final Map<String, BeanPojoProperty<T>> props = new LinkedHashMap<>(); for (PropertyDescriptor property : info.getPropertyDescriptors()) { if (shouldSeeProperty(property)) { final BeanPojoProperty<T> bp = new BeanPojoProperty<>(property); props.put(bp.getName(), bp); } } properties = Collections.unmodifiableMap(props); }
Source:
<code>public Object execute(ExecutionEvent event) throws ExecutionException { RepositoryTreeNode<String> node = getSelectedNodes(event).get(0); URIish uri; try { uri = new URIish(node.getObject()); } catch (URISyntaxException e) { Activator.error(e.getMessage(), e); return null; } UserPasswordCredentials credentials = LoginDialog.changeCredentials(getShell(event), uri); if (credentials == null) return null; try { Activator.getDefault().getSecureStore().putCredentials(uri, credentials); } catch (StorageException e) { <START> Activator.error(UIText.ChangeCredentialsPushCommand_writingToSecureStoreFailed, e); <END> } return null; }</code><technical_language>key for externalized text Push in name, this command is related push this key renamed "ChangeCredentialsCommand_writingToSecureStoreFailed"</technical_language>

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { RepositoryTreeNode<String> node = getSelectedNodes(event).get(0); URIish uri; try { uri = new URIish(node.getObject()); } catch (URISyntaxException e) { Activator.error(e.getMessage(), e); return null; } UserPasswordCredentials credentials = LoginDialog.changeCredentials(getShell(event), uri); if (credentials == null) return null; try { Activator.getDefault().getSecureStore().putCredentials(uri, credentials); } catch (StorageException e) { Activator.error(UIText.ChangeCredentialsCommand_writingToSecureStoreFailed, e); } return null; }
Source:
<code>public long serialize(final SnapshotBuffer sb) { ReceivedRootNode rm = (ReceivedRootNode) this.onReceive.getRootNode(); if (VmSettings.TEST_SNAPSHOTS || VmSettings.TEST_SERIALIZE_ALL <START> || sb.getSnapshotVersion() > this.getMessageId()) { <END> return rm.getSerializer().execute(this, sb); } else { return -1; } }</code><technical_language>suggestion || sb.needsToBeSnapshot(getMessageId())) { This encapsulate logic. I surprised || in expression. && in parentheses a ||? I guess, but, || odd</technical_language>

Target:
public long serialize(final SnapshotBuffer sb) { ReceivedRootNode rm = (ReceivedRootNode) this.onReceive.getRootNode(); if (sb.needsToBeSnapshot(getMessageId())) { return rm.getSerializer().execute(this, sb); } else { return -1; } }
Source:
<code>private Boolean getBooleanCapability(String key) { Object o = getRawCapabilities().get(key); if (o == null) { return null; } else if (o instanceof Boolean) { return (Boolean) o; } else { <START> throw new ClassCastException("DesiredCapability " + key <END> + "'s value is expected to of type Boolean but has been set as type " + o.getClass().getName()); } }</code><technical_language>this consistent exception previously thrown a more useful error message. I if add o.toString() in message, event more helpful: throw new ClassCastException(String.format("DesiredCapability %s's boolean: %s of type %s", key, o.toString(), o.getClass().getName()))</technical_language>

Target:
private Boolean getBooleanCapability(String key) { Object o = getRawCapabilities().get(key); if (o == null) { return null; } else if (o instanceof Boolean) { return (Boolean) o; } else { throw new ClassCastException(String.format( "DesiredCapability %s's value should be boolean: found value %s of type %s", key, o.toString(), o.getClass() .getName())); } }
Source:
<code>private String alertFingerprint(Alert alert) { <START> return alert.getPluginId() + "/" + alert.getName() + "/" + alert.getRisk() + "/" + alert.getConfidence(); <END> }</code><technical_language>Consider adding this in another commit, easier note (important) change/fix</technical_language>

Target:
private String alertFingerprint(Alert alert) { return alert.getPluginId() + "/" + alert.getRisk() + "/" + alert.getConfidence(); }
Source:
<code>public Iterator<JsonObject> execJsonItems() { JsonArray array = execJson().getAsArray(); List<JsonObject> x = new ArrayList<>(array.size()); array.forEach(elt->{ <START> if ( ! elt.isObject()) <END> x.add(elt.getAsObject()); }); return x.iterator(); }</code><technical_language>if necessary</technical_language>

Target:
public Iterator<JsonObject> execJsonItems() { JsonArray array = execJson().getAsArray(); List<JsonObject> x = new ArrayList<>(array.size()); array.forEach(elt->{ if ( ! elt.isObject()) throw new QueryExecException("Item in an array from a JSON query isn't an object"); x.add(elt.getAsObject()); }); return x.iterator(); }
Source:
<code>public void block() { if (block) { throw new IllegalStateException("Realm is already blocking."); } if (Thread.currentThread() != thread) { throw new IllegalStateException("The current thread is not the correct thread."); } try { block = true; synchronized (queue) { queue.notifyAll(); } while (block) { Runnable runnable = null; synchronized (queue) { if <START> (doProcess) <END> { if (queue.isEmpty()) { queue.wait(); } else { runnable = queue.getFirst(); } } } if (runnable != null) { safeRun(runnable); synchronized (queue) { queue.removeFirst(); queue.notifyAll(); } } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { block = false; } }</code><technical_language>Is necessary additional loop for spurious wake-ups? outer loop care of those</technical_language>

Target:
public void block() { if (block) { throw new IllegalStateException("Realm is already blocking."); } if (Thread.currentThread() != thread) { throw new IllegalStateException("The current thread is not the correct thread."); } try { block = true; synchronized (queue) { queue.notifyAll(); } while (block) { Runnable runnable = null; synchronized (queue) { if (queue.isEmpty()) { queue.wait(); } else { runnable = queue.getFirst(); } } if (runnable != null) { safeRun(runnable); synchronized (queue) { queue.removeFirst(); queue.notifyAll(); } } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { block = false; } }
Source:
<code>private boolean addMember(Address joiner, CacheJoinInfo joinInfo) { synchronized (this) { if (expectedMembers.contains(joiner)) { return false; } <START> if (persistentState.isPresent()) { <END> if (!joinInfo.getPersistentStateChecksum().isPresent()) { if (status == ComponentStatus.INSTANTIATED) { throw log.nodeWithoutPersistentStateJoiningCacheWithState(joiner, cacheName); } } else if (persistentState.get().getChecksum() != joinInfo.getPersistentStateChecksum().get()){ throw log.nodeWithIncompatibleStateJoiningCache(joiner, cacheName); } } else { if (joinInfo.getPersistentStateChecksum().isPresent()) { throw log.nodeWithPersistentStateJoiningClusterWithoutState(joiner, cacheName); } } if (this.joinInfo == null) { this.joinInfo = joinInfo; } HashMap<Address, Float> newCapacityFactors = new HashMap<Address, Float>(capacityFactors); newCapacityFactors.put(joiner, joinInfo.getCapacityFactor()); capacityFactors = Immutables.immutableMapWrap(newCapacityFactors); expectedMembers = immutableAdd(expectedMembers, joiner); joiners = immutableAdd(joiners, joiner); if (trace) log.tracef("Added joiner %s to cache %s: members = %s, joiners = %s", joiner, cacheName, expectedMembers, joiners); return true; } }</code><technical_language>cache's persistent state exist coordinator? if of nodes' disk is lost, node start</technical_language>

Target:
private boolean addMember(Address joiner, CacheJoinInfo joinInfo) { synchronized (this) { if (expectedMembers.contains(joiner)) { return false; } if (persistentState.isPresent()) { if (!joinInfo.getPersistentStateChecksum().isPresent()) { if (status == ComponentStatus.INSTANTIATED) { throw log.nodeWithoutPersistentStateJoiningCacheWithState(joiner, cacheName); } } else if (persistentState.get().getChecksum() != joinInfo.getPersistentStateChecksum().get()){ throw log.nodeWithIncompatibleStateJoiningCache(joiner, cacheName); } } else { if (joinInfo.getPersistentStateChecksum().isPresent()) { throw log.nodeWithPersistentStateJoiningClusterWithoutState(joiner, cacheName); } } if (this.joinInfo == null) { this.joinInfo = joinInfo; } HashMap<Address, Float> newCapacityFactors = new HashMap<Address, Float>(capacityFactors); newCapacityFactors.put(joiner, joinInfo.getCapacityFactor()); capacityFactors = Immutables.immutableMapWrap(newCapacityFactors); expectedMembers = immutableAdd(expectedMembers, joiner); persistentUUIDManager.addPersistentAddressMapping(joiner, joinInfo.getPersistentUUID()); joiners = immutableAdd(joiners, joiner); if (trace) log.tracef("Added joiner %s to cache %s with persistent uuid %s: members = %s, joiners = %s", joiner, cacheName, joinInfo.getPersistentUUID(), expectedMembers, joiners); return true; } }
Source:
<code>public void and_overloaded() { when(mock.oneArg(and(eq(false), eq(false)))).thenReturn("0"); when(mock.oneArg(and(eq((byte) 1), eq((byte) 1)))).thenReturn("1"); when(mock.oneArg(and(eq('a'), eq('a')))).thenReturn("2"); when(mock.oneArg(and(eq((double) 1), eq((double) 1)))).thenReturn("3"); <START> when(mock.oneArg(and(eq((float) 1), eq((float) 1)))).thenReturn("4"); <END> when(mock.oneArg(and(eq((int) 1), eq((int) 1)))).thenReturn("5"); when(mock.oneArg(and(eq(1L), eq(1L)))).thenReturn("6"); when(mock.oneArg(and(eq((short) 1), eq((short) 1)))).thenReturn("7"); when(mock.oneArg(and(contains("a"), contains("d")))).thenReturn("8"); when(mock.oneArg(and(isA(Class.class), eq(Object.class)))).thenReturn("9"); assertEquals("0", mock.oneArg(false)); assertEquals(null, mock.oneArg(true)); assertEquals("1", mock.oneArg((byte) 1)); assertEquals("2", mock.oneArg('a')); assertEquals("3", mock.oneArg((double) 1)); assertEquals("4", mock.oneArg((float) 1)); assertEquals("5", mock.oneArg((int) 1)); assertEquals("6", mock.oneArg(1L)); assertEquals("7", mock.oneArg((short) 1)); assertEquals("8", mock.oneArg("abcde")); assertEquals(null, mock.oneArg("aaaaa")); assertEquals("9", mock.oneArg(Object.class)); }</code><technical_language>Do want update while it</technical_language>

Target:
public void and_overloaded() { when(mock.oneArg(and(eq(false), eq(false)))).thenReturn("0"); when(mock.oneArg(and(eq((byte) 1), eq((byte) 1)))).thenReturn("1"); when(mock.oneArg(and(eq('a'), eq('a')))).thenReturn("2"); when(mock.oneArg(and(eq(1D), eq(1D)))).thenReturn("3"); when(mock.oneArg(and(eq(1F), eq(1F)))).thenReturn("4"); when(mock.oneArg(and(eq(1), eq(1)))).thenReturn("5"); when(mock.oneArg(and(eq(1L), eq(1L)))).thenReturn("6"); when(mock.oneArg(and(eq((short) 1), eq((short) 1)))).thenReturn("7"); when(mock.oneArg(and(contains("a"), contains("d")))).thenReturn("8"); when(mock.oneArg(and(isA(Class.class), eq(Object.class)))).thenReturn("9"); assertEquals("0", mock.oneArg(false)); assertEquals(null, mock.oneArg(true)); assertEquals("1", mock.oneArg((byte) 1)); assertEquals("2", mock.oneArg('a')); assertEquals("3", mock.oneArg(1D)); assertEquals("4", mock.oneArg(1F)); assertEquals("5", mock.oneArg(1)); assertEquals("6", mock.oneArg(1L)); assertEquals("7", mock.oneArg((short) 1)); assertEquals("8", mock.oneArg("abcde")); assertEquals(null, mock.oneArg("aaaaa")); assertEquals("9", mock.oneArg(Object.class)); }
Source:
<code>public void run() { int qSize = hwf.getWorkerQueue().size(); while(!stopped.get()){ try{ <START> while(hwf.getWorkerQueue().size() > qSize/2 && !stopped.get()){ <END> UtilWaitThread.sleep(50, stopped); } List<TabletInfo<TabletData>> tablets = new ArrayList<>(tabletInfoCache.getTablets()); Collections.shuffle(tablets, rand); long minRetryTime = MAX_SLEEP_TIME + System.currentTimeMillis(); int notifications = 0; int tabletsScanned = 0; try{ for (TabletInfo<TabletData> tabletInfo : tablets) { if(System.currentTimeMillis() >= tabletInfo.getData().retryTime){ int count = 0; ModulusParams modParams = hwf.getModulusParams(); if(modParams != null){ count = scan(modParams, tabletInfo.getRange()); tabletsScanned++; } tabletInfo.getData().updateScanCount(count); notifications += count; if(stopped.get()) break; } minRetryTime = Math.min(tabletInfo.getData().retryTime, minRetryTime); } }catch(ModParamsChangedException mpce){ hwf.getWorkerQueue().clear(); waitForFindersToStabalize(); } long sleepTime = Math.max(MIN_SLEEP_TIME, minRetryTime - System.currentTimeMillis()); qSize = hwf.getWorkerQueue().size(); log.debug("Scanned of tablets, added new notifications (total queued {})", tabletsScanned, tablets.size(), notifications, qSize); UtilWaitThread.sleep(sleepTime, stopped); }catch(Exception e){ if(isInterruptedException(e)) log.debug("Error while looking for notifications", e); else log.error("Error while looking for notifications", e); } } }</code><technical_language>If queue size is 4, wait 2. I this stop if queue size 10 (or sense)... java while(hwf.getWorkerQueue().size() > 10) && (hwf.getWorkerQueue().size() > qSize/2) && !stopped.get())</technical_language>

Target:
public void run() { int qSize = hwf.getWorkerQueue().size(); while(!stopped.get()){ try{ while(hwf.getWorkerQueue().size() > qSize/2 && !stopped.get()){ UtilWaitThread.sleep(50, stopped); } List<TabletInfo<TabletData>> tablets = new ArrayList<>(tabletInfoCache.getTablets()); Collections.shuffle(tablets, rand); long minRetryTime = max_sleep_time + System.currentTimeMillis(); int notifications = 0; int tabletsScanned = 0; try{ for (TabletInfo<TabletData> tabletInfo : tablets) { if(System.currentTimeMillis() >= tabletInfo.getData().retryTime){ int count = 0; ModulusParams modParams = hwf.getModulusParams(); if(modParams != null){ count = scan(modParams, tabletInfo.getRange()); tabletsScanned++; } tabletInfo.getData().updateScanCount(count, max_sleep_time); notifications += count; if(stopped.get()) break; } minRetryTime = Math.min(tabletInfo.getData().retryTime, minRetryTime); } }catch(ModParamsChangedException mpce){ hwf.getWorkerQueue().clear(); waitForFindersToStabalize(); } long sleepTime = Math.max(min_sleep_time, minRetryTime - System.currentTimeMillis()); qSize = hwf.getWorkerQueue().size(); log.debug("Scanned of tablets, added new notifications (total queued {})", tabletsScanned, tablets.size(), notifications, qSize); if (!stopped.get()) UtilWaitThread.sleep(sleepTime, stopped); }catch(Exception e){ if(isInterruptedException(e)) log.debug("Error while looking for notifications", e); else log.error("Error while looking for notifications", e); } } }
Source:
<code>public static void startES() throws Exception { FileUtil.delete("target/data"); Settings localSettings = Settings.settingsBuilder() .put("http.enabled", true) .put("number_of_shards", 1) .put("number_of_replicas", 1) .put("path.home", "target/data") .build(); esNode = NodeBuilder.nodeBuilder().settings(localSettings).local(false).build().start(); <START> Thread.currentThread().sleep(3000); <END> }</code><technical_language>I 1000 (1sec) is enough this is standalone tests (from es-index-provoider module)</technical_language>

Target:
public static void startES() throws Exception { FileUtil.delete("target/data"); Settings localSettings = Settings.settingsBuilder() .put("http.enabled", true) .put("number_of_shards", 1) .put("number_of_replicas", 1) .put("path.home", "target/data") .build(); esNode = NodeBuilder.nodeBuilder().settings(localSettings).local(false).build().start(); Thread.currentThread().sleep(1000); }
Source:
<code>private void maybeRecordE2ELatency(final long recordTimestamp, final long now, final String nodeName) { final Sensor e2eLatencySensor = e2eLatencySensors.get(nodeName); if (e2eLatencySensor == null) { throw new IllegalStateException("Requested to record e2e latency but could not find sensor for node " + nodeName); } else if (e2eLatencySensor.shouldRecord() && e2eLatencySensor.hasMetrics()) { final long e2eLatency = now - recordTimestamp; <START> if (e2eLatency > MAXIMUM_E2E_LATENCY) { <END> log.warn("Skipped recording e2e latency for node because is higher than maximum allowed latency {}", nodeName, e2eLatency, MAXIMUM_E2E_LATENCY); } else if (e2eLatency < MINIMUM_E2E_LATENCY) { log.warn("Skipped recording e2e latency for node because is smaller than minimum allowed latency {}", nodeName, e2eLatency, MINIMUM_E2E_LATENCY); } else { e2eLatencySensor.record(e2eLatency, now); } } }</code><technical_language>this... do need/want a limit? Nit: double space</technical_language>

Target:
private void maybeRecordE2ELatency(final long recordTimestamp, final long now, final String nodeName) { final Sensor e2eLatencySensor = e2eLatencySensors.get(nodeName); if (e2eLatencySensor == null) { throw new IllegalStateException("Requested to record e2e latency but could not find sensor for node " + nodeName); } else if (e2eLatencySensor.shouldRecord() && e2eLatencySensor.hasMetrics()) { e2eLatencySensor.record(now - recordTimestamp, now); } }
Source:
<code>public void testFormatTimeCalendar() { String calendarTime = Utils.formatTime(37935447675l, TimeFormat.CALENDAR, Resolution.NANOSEC); <START> assertEquals("19:00:37.935447675", calendarTime); <END> }</code><technical_language>Try string.endswith this</technical_language>

Target:
public void testFormatTimeCalendar() { String calendarTime = Utils.formatTime(37935447675l, TimeFormat.CALENDAR, Resolution.NANOSEC); assertTrue(calendarTime.endsWith("37.935447675")); }
Source:
<code>private void initNetworkList(Guid dataCenterId) { startProgress(); IdQueryParameters queryParams = new IdQueryParameters(dataCenterId); Frontend.getInstance().runQuery(QueryType.GetAllNetworks, queryParams, new AsyncQuery<QueryReturnValue>(returnValue -> { Collection<Network> <START> networks = <END> returnValue.getReturnValue(); getNetwork().setItems(networks.stream().filter(Network::isVmNetwork).collect(Collectors.toList())); updateNetworks(networks); stopProgress(); })); }</code><technical_language>please remove non-vm networks networks? removeIf nice</technical_language>

Target:
private void initNetworkList(Guid dataCenterId) { startProgress(); AsyncDataProvider.getInstance().getNetworkList(new AsyncQuery<>(returnValue -> { Collection<Network> networks = returnValue.stream().filter(Network::isVmNetwork).collect(Collectors.toList()); getNetwork().setItems(networks); updateNetworks(networks); stopProgress(); }), dataCenterId); }
Source:
<code>public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } VDS other = (VDS) obj; return (ObjectUtils.objectsEqual(mVdsStatic, other.mVdsStatic) && ObjectUtils.objectsEqual(cpuName, other.cpuName) && _spm_status == other._spm_status && cpuOverCommitDurationMinutes == other.cpuOverCommitDurationMinutes && highUtilization == other.highUtilization && lowUtilization == other.lowUtilization && ObjectUtils.objectsEqual(mImagesLastCheck, other.mImagesLastCheck) && ObjectUtils.objectsEqual(mImagesLastDelay, other.mImagesLastDelay) && ObjectUtils.objectsEqual(mInterfaceList, other.mInterfaceList) && ObjectUtils.objectsEqual(mNetworkList, other.mNetworkList) && maxVdsMemoryOverCommit == other.maxVdsMemoryOverCommit && ObjectUtils.objectsEqual(privateDomains, other.privateDomains) && ObjectUtils.objectsEqual(vdsSpmId, other.vdsSpmId) && selectionAlgorithm == other.selectionAlgorithm && ObjectUtils.objectsEqual(storagePoolId, other.storagePoolId) && ObjectUtils.objectsEqual(storagePoolName, other.storagePoolName) && ObjectUtils.objectsEqual(vdsGroupCompatibilityVersion, other.vdsGroupCompatibilityVersion) && ObjectUtils.objectsEqual(vdsGroupCpuName, other.vdsGroupCpuName) && ObjectUtils.objectsEqual(vdsGroupDescription, other.vdsGroupDescription) && ObjectUtils.objectsEqual(vdsGroupName, other.vdsGroupName) <START> $$ trustedService == other.trustedService); <END> }</code><technical_language>is $$ ? please ObjectUtils.objectsEqual(trustedService, other.trustedService)</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } VDS other = (VDS) obj; return (ObjectUtils.objectsEqual(mVdsStatic, other.mVdsStatic) && ObjectUtils.objectsEqual(cpuName, other.cpuName) && _spm_status == other._spm_status && cpuOverCommitDurationMinutes == other.cpuOverCommitDurationMinutes && highUtilization == other.highUtilization && lowUtilization == other.lowUtilization && ObjectUtils.objectsEqual(mImagesLastCheck, other.mImagesLastCheck) && ObjectUtils.objectsEqual(mImagesLastDelay, other.mImagesLastDelay) && ObjectUtils.objectsEqual(mInterfaceList, other.mInterfaceList) && ObjectUtils.objectsEqual(mNetworkList, other.mNetworkList) && maxVdsMemoryOverCommit == other.maxVdsMemoryOverCommit && ObjectUtils.objectsEqual(privateDomains, other.privateDomains) && ObjectUtils.objectsEqual(vdsSpmId, other.vdsSpmId) && selectionAlgorithm == other.selectionAlgorithm && ObjectUtils.objectsEqual(storagePoolId, other.storagePoolId) && ObjectUtils.objectsEqual(storagePoolName, other.storagePoolName) && ObjectUtils.objectsEqual(vdsGroupCompatibilityVersion, other.vdsGroupCompatibilityVersion) && ObjectUtils.objectsEqual(vdsGroupCpuName, other.vdsGroupCpuName) && ObjectUtils.objectsEqual(vdsGroupDescription, other.vdsGroupDescription) && ObjectUtils.objectsEqual(vdsGroupName, other.vdsGroupName) && trustedService == other.trustedService); }
Source:
<code>private SolrClient getSolrClient(String storeName) throws PersistenceException { try { <START> final SolrClient solrClient = solrCients.computeIfAbsent(storeName, clientFactory::newClient); <END> if (solrClient.isAvailable(5, TimeUnit.SECONDS)) { return solrClient; } } catch (InterruptedException e) { LOGGER.warn("Error getting available solr server for core: {}", storeName, e); Thread.currentThread().interrupt(); } throw new PersistenceException("Solr client is not available"); }</code><technical_language>Nitpick: solrCients typo</technical_language>

Target:
private SolrClient getSolrClient(String storeName) throws PersistenceException { try { final SolrClient solrClient = solrClients.computeIfAbsent(storeName, clientFactory::newClient); if (solrClient.isAvailable(5, TimeUnit.SECONDS)) { return solrClient; } } catch (InterruptedException e) { LOGGER.warn("Error getting available solr server for core: {}", storeName, e); Thread.currentThread().interrupt(); } throw new PersistenceException("Solr client is not available"); }
Source:
<code>public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeyException, XmlPullParserException { try { MinioClient minioClient = new MinioClient("<LINK_1>", "Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG"); NotificationConfiguration notificationConfiguration = minioClient.getBucketNotification("my-bucketname"); List<TopicConfiguration> topicConfigurationList = notificationConfiguration.topicConfigurationList(); TopicConfiguration topicConfiguration = new TopicConfiguration(); topicConfiguration.setTopic("arn:aws:sns:us-west-2:444455556666:sns-topic-xyz"); List<String> eventList = new LinkedList<>(); <START> eventList.add("s3:ObjectCreated:Put"); <END> eventList.add("s3:ObjectCreated:Copy"); topicConfiguration.setEvents(eventList); notificationConfiguration.setTopicConfigurationList(topicConfigurationList); minioClient.setBucketNotification("my-bucketname", notificationConfiguration); System.out.println("Bucket notification is set successfully"); } catch (MinioException e) { System.out.println("Error occurred: " + e); } }</code><technical_language>I if some constants represent events (like s3:ObjectCreated:Put) put in java doc. way, easier for developer add events</technical_language>

Target:
public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeyException, XmlPullParserException { try { MinioClient minioClient = new MinioClient("<LINK_1>", "Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG"); NotificationConfiguration notificationConfiguration = minioClient.getBucketNotification("my-bucketname"); List<TopicConfiguration> topicConfigurationList = notificationConfiguration.topicConfigurationList(); TopicConfiguration topicConfiguration = new TopicConfiguration(); topicConfiguration.setTopic("arn:aws:sns:us-west-2:444455556666:sns-topic-xyz"); List<EventType> eventList = new LinkedList<>(); eventList.add(EventType.OBJECT_CREATED_PUT); eventList.add(EventType.OBJECT_CREATED_COPY); topicConfiguration.setEvents(eventList); Filter filter = new Filter(); filter.setPrefixRule("images"); filter.setSuffixRule("pg"); topicConfiguration.setFilter(filter); topicConfigurationList.add(topicConfiguration); notificationConfiguration.setTopicConfigurationList(topicConfigurationList); minioClient.setBucketNotification("my-bucketname", notificationConfiguration); System.out.println("Bucket notification is set successfully"); } catch (MinioException e) { System.out.println("Error occurred: " + e); } }
Source:
<code>public void testValidation() { try { new JsonItemReaderBuilder<String>() .build(); fail("A json object reader is required."); } catch (IllegalArgumentException iae) { assertEquals("A json object reader is required.", iae.getMessage()); } try { new JsonItemReaderBuilder<String>() .jsonObjectReader(this.jsonObjectReader) .build(); fail("A resource is required."); } catch (IllegalArgumentException iae) { assertEquals("A resource is required.", iae.getMessage()); } try { new JsonItemReaderBuilder<String>() .jsonObjectReader(this.jsonObjectReader) .resource(this.resource) <START> .saveState(true) <END> .build(); fail("A name is required when saveState is set to true."); } catch (IllegalStateException iae) { assertEquals("A name is required when saveState is set to true.", iae.getMessage()); } }</code><technical_language>This line is redundant (save state defaults true)</technical_language>

Target:
public void testValidation() { try { new JsonItemReaderBuilder<String>() .build(); fail("A json object reader is required."); } catch (IllegalArgumentException iae) { assertEquals("A json object reader is required.", iae.getMessage()); } try { new JsonItemReaderBuilder<String>() .jsonObjectReader(this.jsonObjectReader) .build(); fail("A resource is required."); } catch (IllegalArgumentException iae) { assertEquals("A resource is required.", iae.getMessage()); } try { new JsonItemReaderBuilder<String>() .jsonObjectReader(this.jsonObjectReader) .resource(this.resource) .build(); fail("A name is required when saveState is set to true."); } catch (IllegalStateException iae) { assertEquals("A name is required when saveState is set to true.", iae.getMessage()); } }
Source:
<code>public ParamertizedString(final String pattern) { final StringBuilder raw = new StringBuilder(); final List<Parameter> prs = new ArrayList<Parameter>(4); final List<Format> ops = new ArrayList<Format>(4); final List<Function> functions = new ArrayList<Function>(); int i = 0; while (i < pattern.length()) { final int b = pattern.indexOf("${", i); if (b < 0) { break; } final int e = pattern.indexOf("}", b + 2); if (e < 0) { break; } raw.append(pattern.substring(i, b)); ops.add(new Constant(pattern.substring(i, b))); String expr = pattern.substring(b + 2, e); String parameterName = ""; if (!expr.contains(".")) { parameterName = expr; } else { int firstDot = expr.indexOf('.'); parameterName = expr.substring(0, firstDot); String actionsStr = expr.substring(firstDot + 1); String[] actions = actionsStr.split("\\."); for (String action : actions) { Function function = FUNCTIONS.get(action); if (function == null) { function = NOOP; } functions.add(function); } } <START> functions.add(NOOP); <END> final Parameter p = new Parameter(parameterName, Collections.unmodifiableList(functions)); raw.append("{" + prs.size() + "}"); prs.add(p); ops.add(p); i = e + 1; } if (i < pattern.length()) { raw.append(pattern.substring(i)); ops.add(new Constant(pattern.substring(i))); } this.pattern = pattern; this.rawPattern = raw.toString(); this.patternOps = Collections.unmodifiableList(ops); this.parameters = Collections.unmodifiableList(prs); }</code><technical_language>a list, I need NOOPs anymore, means reverse if too, add if null</technical_language>

Target:
public ParamertizedString(final String pattern) { final StringBuilder raw = new StringBuilder(); final List<Parameter> prs = new ArrayList<Parameter>(4); final List<Format> ops = new ArrayList<Format>(4); final List<Function> functions = new ArrayList<Function>(); int i = 0; while (i < pattern.length()) { final int b = pattern.indexOf("${", i); if (b < 0) { break; } final int e = pattern.indexOf("}", b + 2); if (e < 0) { break; } raw.append(pattern.substring(i, b)); ops.add(new Constant(pattern.substring(i, b))); String expr = pattern.substring(b + 2, e); String parameterName = ""; if (!expr.contains(".")) { parameterName = expr; } else { int firstDot = expr.indexOf('.'); parameterName = expr.substring(0, firstDot); String actionsStr = expr.substring(firstDot + 1); String[] actions = actionsStr.split("\\."); for (String action : actions) { Function function = FUNCTIONS.get(action); if (function == null) { function = NOOP; } functions.add(function); } } final Parameter p = new Parameter(parameterName, Collections.unmodifiableList(functions)); raw.append("{" + prs.size() + "}"); prs.add(p); ops.add(p); i = e + 1; } if (i < pattern.length()) { raw.append(pattern.substring(i)); ops.add(new Constant(pattern.substring(i))); } this.pattern = pattern; this.rawPattern = raw.toString(); this.patternOps = Collections.unmodifiableList(ops); this.parameters = Collections.unmodifiableList(prs); }
Source:
<code>public void execute() throws Exception { if (!ElasticsearchProcessMonitor.getWasElasticsearchStarted()) { String exceptionMsg = "Elasticsearch is not yet started, check back again later"; logger.info(exceptionMsg); return; } HealthBean healthBean = new HealthBean(); try { healthBean.esprocessdown = 0; if (!ElasticsearchProcessMonitor.isElasticsearchRunning()) { healthBean.esprocessdown = 1; <START> } <END> } catch (Exception e) { resetHealthStats(healthBean); logger.warn("failed to check if Elasticsearch process is running", e); } healthReporter.healthBean.set(healthBean); }</code><technical_language>Add healthBean.esprocessdown = 0; else statement. executed ES process is Up. need set if ES is Running</technical_language>

Target:
public void execute() throws Exception { if (!ElasticsearchProcessMonitor.getWasElasticsearchStarted()) { String exceptionMsg = "Elasticsearch is not yet started, check back again later"; logger.info(exceptionMsg); return; } HealthBean healthBean = new HealthBean(); try { healthBean.esprocessrunning = 0; if (!ElasticsearchProcessMonitor.isElasticsearchRunning()) { logger.info("Elasticsearch process is up & running"); healthBean.esprocessrunning = 1; } } catch (Exception e) { resetHealthStats(healthBean); logger.warn("failed to check if Elasticsearch process is running", e); } healthReporter.healthBean.set(healthBean); }
Source:
<code>public void equalsAndHashCodeEqualTest() throws Exception { <START> MatcherAssert.assertThat( <END> psbyflag.equals( new PsByFlag( new PsByFlag.Pair( KEY, new PsFake(true) ) ) ), Matchers.is(true) ); }</code><technical_language>consider nl.jqno.equalsverifier test equals</technical_language>

Target:
public void equalsAndHashCodeEqualTest() throws Exception { EqualsVerifier.forClass(PsByFlag.class) .suppress(Warning.TRANSIENT_FIELDS) .verify(); }