auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public static PosetTriplet computePosetInfo(List<PVariable> variables, PBody body, IQueryMetaContext context) { <END> Map<PVariable, Set<TypeJudgement>> typeMap = TypeHelper.inferUnaryTypes(body.getConstraints(), context); PosetTriplet result = new PosetTriplet(); List<Integer> coreIndices = new ArrayList<Integer>(); List<Integer> posetIndices = new ArrayList<Integer>(); List<IInputKey> filtered = new ArrayList<IInputKey>(); boolean posetKey = false; for (int i = 0; i < variables.size(); i++) { posetKey = false; Set<TypeJudgement> judgements = typeMap.get(variables.get(i)); if (judgements.size() == 1) { IInputKey key = judgements.iterator().next().getInputKey(); if (key != null && context.isPosetKey(key)) { posetKey = true; filtered.add(key); } } if (posetKey) { posetIndices.add(i); } else { coreIndices.add(i); } } result.comparator = context.getPosetComparator(filtered); result.coreMask = RecipesHelper.mask(variables.size(), coreIndices); result.posetMask = RecipesHelper.mask(variables.size(), posetIndices); return result; }</code><technical_language>merge common part of methods takes, say, Iterable<Set<IInputKey>></technical_language>

Target:
public static PosetTriplet computePosetInfo(List<PVariable> variables, PBody body, IQueryMetaContext context) { Map<PVariable, Set<TypeJudgement>> typeMap = TypeHelper.inferUnaryTypes(body.getConstraints(), context); List<Set<IInputKey>> keys = new LinkedList<Set<IInputKey>>(); for (int i = 0; i < variables.size(); i++) { Set<IInputKey> _keys = new HashSet<IInputKey>(); PVariable current = variables.get(i); while (current != null) { Set<TypeJudgement> judgements = typeMap.get(current); if (judgements != null) { for (TypeJudgement judgement : judgements) { _keys.add(judgement.getInputKey()); } } current = current.getDirectUnifiedInto(); } keys.add(_keys); } return computePosetInfo(keys, context); }
Source:
<code>private SynchronizationModel createSynchronizationModel(ITypedElement left, ITypedElement right, ITypedElement origin, IProgressMonitor monitor) throws InterruptedException { final IFile leftFile = findFile(left); final IFile rightFile = findFile(right); if (leftFile != null && rightFile != null) { return resolver.resolveLocalModels(leftFile, rightFile, findFile(origin), monitor); } <START> final IStorage leftStorage = StreamAccessorStorage.fromTypedElement(left); <END> final IStorage rightStorage; if (right instanceof IStreamContentAccessor) { rightStorage = StreamAccessorStorage.fromTypedElement(right); } else { rightStorage = null; } final IStorage originStorage; if (origin != null) { originStorage = StreamAccessorStorage.fromTypedElement(origin); } else { originStorage = null; } return loadSingleResource(leftStorage, rightStorage, originStorage); }</code><technical_language>I feel assume leftStorage null. If is so, I recommend adding assertion (core runtime guava, a java "assert") state is ensure faster debugging in case a day. prevent people reading code this anymore. this is place applied I think</technical_language>

Target:
private SynchronizationModel createSynchronizationModel(ITypedElement left, ITypedElement right, ITypedElement origin, IProgressMonitor monitor) throws InterruptedException { final IFile leftFile = findFile(left); final IFile rightFile = findFile(right); if (leftFile != null && rightFile != null) { return resolver.resolveLocalModels(leftFile, rightFile, findFile(origin), monitor); } final IStorage leftStorage = StreamAccessorStorage.fromTypedElement(left); Assert.isNotNull(leftStorage); final IStorage rightStorage; if (right instanceof IStreamContentAccessor) { rightStorage = StreamAccessorStorage.fromTypedElement(right); } else { rightStorage = null; } final IStorage originStorage; if (origin != null) { originStorage = StreamAccessorStorage.fromTypedElement(origin); } else { originStorage = null; } return loadSingleResource(leftStorage, rightStorage, originStorage); }
Source:
<code>protected MapSqlParameterSource createFullParametersMapper(VmDevice entity) { return createIdParameterMapper(entity.getId()) .addValue("device", entity.getDevice()) .addValue("type", entity.getType().getValue()) .addValue("address", entity.getAddress()) .addValue("boot_order", entity.getBootOrder()) .addValue("spec_params", entity.getSpecParams() == null ? null : SerializationFactory .getSerializer() .serialize(entity.getSpecParams())) .addValue("is_managed", entity.getIsManaged()) .addValue("is_plugged", entity.getIsPlugged()) .addValue("is_readonly", entity.getIsReadOnly()) .addValue("alias", entity.getAlias()) <START> .addValue("custom_properties", <END> entity.getCustomProperties() == null ? null : SerializationFactory .getSerializer() .serialize(entity.getCustomProperties())); }</code><technical_language>suggestion: extracting this a method exact code is invoked VM.customProperties modified String Map handy</technical_language>

Target:
protected MapSqlParameterSource createFullParametersMapper(VmDevice entity) { return createIdParameterMapper(entity.getId()) .addValue("device", entity.getDevice()) .addValue("type", entity.getType().getValue()) .addValue("address", entity.getAddress()) .addValue("boot_order", entity.getBootOrder()) .addValue("spec_params", serializeIfNotNull(entity.getSpecParams())) .addValue("is_managed", entity.getIsManaged()) .addValue("is_plugged", entity.getIsPlugged()) .addValue("is_readonly", entity.getIsReadOnly()) .addValue("alias", entity.getAlias()) .addValue("custom_properties", serializeIfNotNull(entity.getCustomProperties())); }
Source:
<code><START> private boolean validateInputSchemaType(Schema.Type inputSchemaType) { <END> if (!Schema.Type.STRING.equals(inputSchemaType) && !Schema.Type.BYTES.equals(inputSchemaType)) { String message = String.format("Unsupported inputType in schema, only Schema.Type.BYTES and Schema.Type.STRING are supported " + "InputType: %s", inputSchemaType.toString()); LOG.error(message); return false; } return true; }</code><technical_language>change this throw exception. caller choose catch log (in getLog), (configurePipeline)</technical_language>

Target:
private void validateInputSchemaType(Schema.Type inputSchemaType) { if (!Schema.Type.STRING.equals(inputSchemaType) && !Schema.Type.BYTES.equals(inputSchemaType)) { throw new IllegalArgumentException(String.format( "Unsupported inputType in schema, only Schema.Type.BYTES and Schema.Type.STRING are supported " + "InputType: %s", inputSchemaType.toString())); } }
Source:
<code>public HandleStatus handle(MessageReference ref) throws Exception { if (filter != null && !filter.match(ref.getMessage())) { return HandleStatus.NO_MATCH; } synchronized (this) { ref.handled(); Message message = ref.getMessage(); synchronized (refs) { refs.put(ref.getMessage().getMessageID(), ref); } Integer partition = null; SimpleString groupdID = message.getGroupID(); if (groupdID != null) { List partitions = kafkaProducer.partitionsFor(topicName); int numPartitions = partitions.size(); <START> partition = Utils.toPositive(Utils.murmur2(groupdID.getData())) % numPartitions; <END> } SimpleString key = message.getLastValueProperty(); ProducerRecord<String, Message> producerRecord = new ProducerRecord<>( topicName, partition, message.getTimestamp(), key == null ? null : key.toString(), message); if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace("KafkaProducerBridge::going to send message: " + message + " from " + this.queue); } pendingAcks.countUp(); try { kafkaProducer.send(producerRecord, new MessageAwareCallback(ref)); } catch (Exception e) { pendingAcks.countDown(); throw e; } return HandleStatus.HANDLED; } }</code><technical_language>expert Artemis explain LVQ is key for partitions</technical_language>

Target:
public HandleStatus handle(MessageReference ref) throws Exception { if (filter != null && !filter.match(ref.getMessage())) { return HandleStatus.NO_MATCH; } synchronized (this) { ref.handled(); Message message = ref.getMessage(); synchronized (refs) { refs.put(ref.getMessage().getMessageID(), ref); } SimpleString key = message.getLastValueProperty(); ProducerRecord<String, Message> producerRecord = new ProducerRecord<>( topicName, null, message.getTimestamp(), key == null ? null : key.toString(), message); if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace("KafkaProducerBridge::going to send message: " + message + " from " + this.queue); } pendingAcks.countUp(); try { kafkaProducer.send(producerRecord, new MessageAwareCallback(ref)); } catch (Exception e) { pendingAcks.countDown(); throw e; } return HandleStatus.HANDLED; } }
Source:
<code>public Map<ByteBuffer, List<ColumnOrSuperColumn>> multiget_slice(String kvsMethodName, TableReference tableRef, List<ByteBuffer> keys, SlicePredicate predicate, ConsistencyLevel consistency_level) throws InvalidRequestException, UnavailableException, TimedOutException, TException { <START> int numberOfQueriedRows = keys.size(); <END> return qosClient.executeRead( () -> client.multiget_slice(kvsMethodName, tableRef, keys, predicate, consistency_level), ThriftQueryWeighers.multigetSlice(numberOfQueriedRows)); }</code><technical_language>i give parameters weigher, extract size (the weigher is responsible for determining weight, this class)</technical_language>

Target:
public Map<ByteBuffer, List<ColumnOrSuperColumn>> multiget_slice(String kvsMethodName, TableReference tableRef, List<ByteBuffer> keys, SlicePredicate predicate, ConsistencyLevel consistency_level) throws InvalidRequestException, UnavailableException, TimedOutException, TException { return qosClient.executeRead( () -> client.multiget_slice(kvsMethodName, tableRef, keys, predicate, consistency_level), ThriftQueryWeighers.multigetSlice(keys)); }
Source:
<code>private void runClassLoaderReleaseHook(ClassLoader classLoader) { AwsSdkMetrics.unregisterMetricAdminMBean(); try { Class<?> fileAgeManagerClazz = Class.forName("com.amazonaws.services.kinesis.producer.FileAgeManager", true, classLoader); Field instanceField = fileAgeManagerClazz.getDeclaredField("instance"); instanceField.setAccessible(true); <START> <END> Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(instanceField, instanceField.getModifiers() & ~Modifier.FINAL); Object fileAgeManager = instanceField.get(null); instanceField.set(null, null); Field executorField = fileAgeManagerClazz.getDeclaredField("executorService"); executorField.setAccessible(true); ExecutorService executorService = (ExecutorService) executorField.get(fileAgeManager); executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.MINUTES); Class<?> credProviderClazz = Class.forName("com.amazonaws.auth.InstanceProfileCredentialsProvider", true, classLoader); Field credProviderInstanceField = credProviderClazz.getDeclaredField("INSTANCE"); credProviderInstanceField.setAccessible(true); modifiersField.setInt(credProviderInstanceField, instanceField.getModifiers() & ~Modifier.FINAL); credProviderInstanceField.set(null, null); } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException | InterruptedException e) { LOG.info("Unable to unregister static fields of KinesisProducer", e); } }</code><technical_language>~~Shouldn't able getClass().getClassLoader()? modify RuntimeContext API.~~</technical_language>

Target:
private void runClassLoaderReleaseHook(ClassLoader classLoader) { AwsSdkMetrics.unregisterMetricAdminMBean(); try { Class<?> fileAgeManagerClazz = Class.forName("com.amazonaws.services.kinesis.producer.FileAgeManager", true, classLoader); Field instanceField = fileAgeManagerClazz.getDeclaredField("instance"); instanceField.setAccessible(true); Object fileAgeManager = instanceField.get(null); Field executorField = fileAgeManagerClazz.getDeclaredField("executorService"); executorField.setAccessible(true); ExecutorService executorService = (ExecutorService) executorField.get(fileAgeManager); executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.MINUTES); } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException | InterruptedException e) { LOG.info("Unable to shutdown thread pool of KinesisProducer/FileAgeManager.", e); } }
Source:
<code><START> public ByteBuffer encode() { <END> int size = 0; for (DataHolder dataHolder : data) { size += dataHolder.size(true); } ByteBuffer bb = ByteBuffer.allocate(size + VLQ.encodedSize(size)); WriteBuffer writeBuffer = new WriteBuffer(bb); writeBuffer.putVlqInt(size); for (DataHolder dataHolder : data) { dataHolder.encode(writeBuffer, true); } return bb; }</code><technical_language>This method call other encode method, right</technical_language>

Target:
public ByteBuffer encode() { int size = calculateSize(); ByteBuffer bb = ByteBuffer.allocate(size + VLQ.encodedSize(size)); return performEncoding(bb, size); }
Source:
<code>public void directConversionToAccessorTest(ArgumentsAccessor accessor) { <START> assertTrue(accessor.size() == 10); <END> int sum = IntStream.range(0, 10).map(i -> accessor.getInteger(i)).sum(); assertEquals(55, sum); }</code><technical_language>assertTrue for equality checks. Instead, please assertEquals</technical_language>

Target:
public void directConversionToAccessorTest(ArgumentsAccessor accessor) { assertEquals(10, accessor.size()); int sum = IntStream.range(0, 10).map(i -> accessor.getInteger(i)).sum(); assertEquals(55, sum); }
Source:
<code>public static Set<SequencingParametersDto> asSequencingParametersDtos(Collection<SequencingParameters> from) { Set<SequencingParametersDto> dtoSet = Sets.newTreeSet(new Comparator<SequencingParametersDto>() { @Override public int compare(SequencingParametersDto o1, SequencingParametersDto o2) { return o1.getName().compareTo(o2.getName()); } }); for (SequencingParameters kd : from) { dtoSet.add(asDto(kd)); <START> } <END> return dtoSet; }</code><technical_language>('kd' again)</technical_language>

Target:
public static Set<SequencingParametersDto> asSequencingParametersDtos(Collection<SequencingParameters> from) { Set<SequencingParametersDto> dtoSet = Sets.newTreeSet(new Comparator<SequencingParametersDto>() { @Override public int compare(SequencingParametersDto o1, SequencingParametersDto o2) { return o1.getName().compareTo(o2.getName()); } }); for (SequencingParameters sp : from) { dtoSet.add(asDto(sp)); } return dtoSet; }
Source:
<code>public static List<ReceiveCommand> filter(List<ReceiveCommand> commands, final Result want) { <START> final List<ReceiveCommand> r = new ArrayList<ReceiveCommand>(commands <END> .size()); for (final ReceiveCommand cmd : commands) { if (cmd.getResult() == want) r.add(cmd); } return r; }</code><technical_language>If drop final qualifier "r" this fit line</technical_language>

Target:
public static List<ReceiveCommand> filter(List<ReceiveCommand> commands, final Result want) { List<ReceiveCommand> r = new ArrayList<ReceiveCommand>(commands.size()); for (final ReceiveCommand cmd : commands) { if (cmd.getResult() == want) r.add(cmd); } return r; }
Source:
<code>public Response distributeTAs(@PathParam("courseCode") String courseCode, @PathParam("editionCode") String editionCode, @PathParam("assignmentId") long assignmentId) { CourseEdition course = courses.find(courseCode, editionCode); Assignment assignment = assignmentsDAO.find(course, assignmentId); if(!(currentUser.isAdmin() || currentUser.isAssisting(course))) { throw new UnauthorizedException(); } List<Delivery> deliveries = deliveriesDAO.getLastDeliveries(assignment); List<Group> groups = Lists.transform(deliveries, Delivery::getGroup); Set<User> TAs = course.getAssistants(); groups.removeAll(Lists.transform(assignment.getAssignedTAS(), AssignedTA::getGroup)); <START> List<AssignedTA> assignedTAS = AssignTAs.assignGroups(TAs, groups, assignment, new Random()); <END> assignedTAS.forEach(this.assignedTAs::persist); return Response.seeOther(assignment.getURI()).build(); }</code><technical_language>do construct Random of assignGroups</technical_language>

Target:
public Response distributeTAs(@PathParam("courseCode") String courseCode, @PathParam("editionCode") String editionCode, @PathParam("assignmentId") long assignmentId) { CourseEdition course = courses.find(courseCode, editionCode); Assignment assignment = assignmentsDAO.find(course, assignmentId); if(!(currentUser.isAdmin() || currentUser.isAssisting(course))) { throw new UnauthorizedException(); } List<Delivery> deliveries = deliveriesDAO.getLastDeliveries(assignment); List<Group> groups = Lists.transform(deliveries, Delivery::getGroup); Set<User> TAs = course.getAssistants(); groups.removeAll(Lists.transform(assignment.getAssignedTAS(), AssignedTA::getGroup)); List<AssignedTA> assignedTAS = assignGroups(TAs, groups, assignment, ThreadLocalRandom.current()); assignedTAS.forEach(this.assignedTAs::persist); return Response.seeOther(assignment.getURI()).build(); }
Source:
<code>public <T> void publish(EventScope scope, String topic, Object sender, T payload) throws UnsupportedOperationException { <START> logger.debug("Trying to publish payload from sender using scope on event bus int topic [{}]", payload, sender, scope, this, topic); <END> if (eventScope.equals(scope)) { publish(topic, sender, payload); } else if (parentEventBus != null) { parentEventBus.publish(scope, topic, sender, payload); } else { logger.warn("Could not publish payload with scope on event bus [{}]", scope, this); throw new UnsupportedOperationException("Could not publish event with scope " + scope); } }</code><technical_language>"in topic" instead of "int topic"</technical_language>

Target:
public <T> void publish(EventScope scope, String topic, Object sender, T payload) throws UnsupportedOperationException { logger.debug("Trying to publish payload from sender using scope on event bus in topic [{}]", payload, sender, scope, this, topic); if (eventScope.equals(scope)) { publish(topic, sender, payload); } else if (parentEventBus != null) { parentEventBus.publish(scope, topic, sender, payload); } else { logger.warn("Could not publish payload with scope on event bus [{}]", scope, this); throw new UnsupportedOperationException("Could not publish event with scope " + scope); } }
Source:
<code>public Multimap<ServiceId, Channel> getAllServiceIdsToChannels() { return channelMap; <START> } <END></code><technical_language>exposing a field here. I is Immutable, technically if changes internal map mutable in future check (and sonar mark this a vulnerability btw)</technical_language>

Target:
public ImmutableMultimap<ServiceId, Channel> getAllServiceIdsToChannels() { return channelMap; }
Source:
<code>private ThreadPool threadPool(Config cfg) { int maxThreads = cfg.getInt("httpd", null, "maxthreads", 25); int minThreads = cfg.getInt("httpd", null, "minthreads", 5); int maxQueued = cfg.getInt("httpd", null, "maxqueued", 50); int idleTimeout = (int)MILLISECONDS.convert(60, SECONDS); int maxCapacity = maxQueued == 0 ? Integer.MAX_VALUE <START> : maxQueued; <END> QueuedThreadPool pool = new QueuedThreadPool( maxThreads, minThreads, idleTimeout, new BlockingArrayQueue<Runnable>( minThreads, minThreads, maxCapacity )); pool.setName("HTTP"); return pool; }</code><technical_language>In case 0 < maxQueued && maxQueued < minThreads maxCapacity smaller minThreads IllegalArgumentException thrown calling new BlockingArrayQueue line 335. I prefer fix Shawn [1] [1] <LINK_0></technical_language>

Target:
private ThreadPool threadPool(Config cfg) { int maxThreads = cfg.getInt("httpd", null, "maxthreads", 25); int minThreads = cfg.getInt("httpd", null, "minthreads", 5); int maxQueued = cfg.getInt("httpd", null, "maxqueued", 50); int idleTimeout = (int)MILLISECONDS.convert(60, SECONDS); int maxCapacity = maxQueued == 0 ? Integer.MAX_VALUE : Math.max(minThreads, maxQueued); QueuedThreadPool pool = new QueuedThreadPool( maxThreads, minThreads, idleTimeout, new BlockingArrayQueue<Runnable>( minThreads, minThreads, maxCapacity )); pool.setName("HTTP"); return pool; }
Source:
<code>private void fillBucket(GlowPlayer player, GlowBlock block) { if (block.getData() != LEVEL_FULL) { return; } if (!setCauldronLevel(block, LEVEL_EMPTY, player, CauldronLevelChangeEvent.ChangeReason.BUCKET_FILL)) { return; } if (player.getGameMode() != GameMode.CREATIVE) { <START> Map<Integer, ItemStack> dummyInventory = player.getInventory() <END> .addItem(new ItemStack(Material.WATER_BUCKET)); if (!dummyInventory.isEmpty()) { player.getWorld() .dropItemNaturally(player.getLocation(), new ItemStack(Material.WATER_BUCKET)); } } player.getItemInHand().setAmount(player.getItemInHand().getAmount() - 1); }</code><technical_language>skip this if bucket amount is 1, set type water bucket</technical_language>

Target:
private void fillBucket(GlowPlayer player, GlowBlock block) { if (block.getData() != LEVEL_FULL) { return; } if (!setCauldronLevel(block, LEVEL_EMPTY, player, CauldronLevelChangeEvent.ChangeReason.BUCKET_FILL)) { return; } if (player.getGameMode() != GameMode.CREATIVE) { if (player.getItemInHand().getAmount() == 1) { player.getItemInHand().setType(Material.WATER_BUCKET); } else { Map<Integer, ItemStack> drops = player.getInventory() .addItem(new ItemStack(Material.WATER_BUCKET)); if (!drops.isEmpty()) { player.getWorld() .dropItemNaturally(player.getLocation(), new ItemStack(Material.WATER_BUCKET)); } player.getItemInHand().setAmount(player.getItemInHand().getAmount() - 1); } } }
Source:
<code>private void carryOntoHistoryInnerLoop(RevCommit c, int carry) { for (;;) { RevCommit[] parents = c.parents; if (parents == null || parents.length == 0) { break; } int e = parents.length - 1; for (int i = 0; i < e; i++) { RevCommit p = parents[i]; if (carryOntoOne(p, carry) == CONTINUE) { stack = new CarryStack(stack, p, carry); } } c = parents[e]; <START> if (carryOntoOne(c, carry) == CONTINUE) { continue; } break; <END> } }</code><technical_language>Style-wise "break" bottom of a for loop often, more test for break condition break line 218 above. Save a line inverting condition leaving "continue" implied. in carryOntoHistory loop</technical_language>

Target:
private void carryOntoHistoryInnerLoop(RevCommit c, int carry) { for (;;) { RevCommit[] parents = c.parents; if (parents == null || parents.length == 0) { break; } int e = parents.length - 1; for (int i = 0; i < e; i++) { RevCommit p = parents[i]; if (carryOntoOne(p, carry) == CONTINUE) { stack = new CarryStack(stack, p, carry); } } c = parents[e]; if (carryOntoOne(c, carry) != CONTINUE) { break; } } }
Source:
<code>protected Response doAction(final VdcActionType task, final VdcActionParametersBase params, final Action action, AbstractBackendResource.PollingType pollingType) { awaitGrace(action); try { VdcReturnValueBase actionResult = doAction(task, params); <START> if (actionResult.getJobId() != null) { <END> setJobLink(action, actionResult); } if (actionResult.getHasAsyncTasks()) { if (expectBlocking(action)) { CreationStatus status = awaitCompletion(actionResult, pollingType); return actionStatus(status, action, addLinks(newModel(id))); } else { return actionAsync(actionResult, action); } } else { return actionSuccess(action, addLinks(newModel(id))); } } catch (Exception e) { return handleError(e, action); } }</code><technical_language>add this in case of async actions? check if action.isAsync() == true, in addition jobId != null check</technical_language>

Target:
protected Response doAction(final VdcActionType task, final VdcActionParametersBase params, final Action action, AbstractBackendResource.PollingType pollingType) { awaitGrace(action); try { VdcReturnValueBase actionResult = doAction(task, params); if (action.isAsync()) { setJobLink(action, actionResult); } if (actionResult.getHasAsyncTasks()) { if (expectBlocking(action)) { CreationStatus status = awaitCompletion(actionResult, pollingType); return actionStatus(status, action, addLinks(newModel(id))); } else { return actionAsync(actionResult, action); } } else { return actionSuccess(action, addLinks(newModel(id))); } } catch (Exception e) { return handleError(e, action); } }
Source:
<code><START> protected boolean canDoAction() { <END> StorageServerConnections connection = getParameters().getStorageServerConnection(); if (connection.getstorage_type() == StorageType.NFS && !new NfsMountPointConstraint().isValid(connection.getconnection(), null)) { return failCanDoAction(VdcBllMessages.VALIDATION_STORAGE_CONNECTION_INVALID); } String connectionId = connection.getid(); oldConnection = getDbFacade().getStorageServerConnectionDao().get(connectionId); if(oldConnection == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_CONNECTION_NOT_EXIST); } return super.canDoAction(); }</code><technical_language>domain status checked? validations of gui validation</technical_language>

Target:
protected boolean canDoAction() { StorageServerConnections newConnectionDetails = getParameters().getStorageServerConnection(); if (newConnectionDetails.getstorage_type() != StorageType.NFS) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_CONNECTION_UNSUPPORTED_ACTION_FOR_STORAGE); } if (newConnectionDetails.getstorage_type() == StorageType.NFS && !new NfsMountPointConstraint().isValid(newConnectionDetails.getconnection(), null)) { return failCanDoAction(VdcBllMessages.VALIDATION_STORAGE_CONNECTION_INVALID); } String connectionId = newConnectionDetails.getid(); oldConnection = getStorageConnDao().get(connectionId); if (oldConnection == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_CONNECTION_NOT_EXIST); } List<StorageServerConnections> connections = getStorageConnDao().getAllForStorage(newConnectionDetails.getconnection()); if (connections != null) { if (connections.size() > 1) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_CONNECTION_BELONGS_TO_SEVERAL_STORAGE_DOMAINS); } else if (connections.size() == 1 && !connections.get(0).getid().equals(oldConnection.getid())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_CONNECTION_ALREADY_EXISTS); } } List<StorageDomain> domains = getStorageDomainsByConnId(newConnectionDetails.getid()); if (domains != null) { if (domains.size() != 1) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_CONNECTION_BELONGS_TO_SEVERAL_STORAGE_DOMAINS); } setStorageDomain(domains.get(0)); if (!isNfsPathEditable(getStorageDomain())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_CONNECTION_UNSUPPORTED_ACTION_FOR_STORAGE); } } return super.canDoAction(); }
Source:
<code>public Map<String, Statistic> provideCatalogMap() { <START> return this.statisticMappings; <END> }</code><technical_language>This return immutable cached version</technical_language>

Target:
public Map<String, Statistic> provideCatalogMap() { return Maps.newHashMap(this.statisticMappings); }
Source:
<code>public Object getValue() { DecimalFormat format = new DecimalFormat("###0.00"); <START> double mean = getBean().getQuantile(1); <END> double lowerCI = getBean().getQuantile(0); double upperCI = getBean().getQuantile(2); return format.format(transformContinuous(mean)) + " (" + format.format(transformContinuous(lowerCI)) + ", " + format.format(transformContinuous(upperCI)) + ")"; }</code><technical_language>Again, determine indices somewhere, assume a fixed set of indices. _will_ change start constructing density plots quantiles</technical_language>

Target:
public Object getValue() { DecimalFormat format = new DecimalFormat("###0.00"); double mean = getBean().getQuantile(getBean().indexOf(0.5)); double lowerCI = getBean().getQuantile(getBean().indexOf(0.025)); double upperCI = getBean().getQuantile(getBean().indexOf(0.975)); return format.format(transformContinuous(mean)) + " (" + format.format(transformContinuous(lowerCI)) + ", " + format.format(transformContinuous(upperCI)) + ")"; }
Source:
<code>private boolean isSuperAdminRole(User user) { <START> return (user.isSuperAdmin() != null && user.isSuperAdmin()) <END> || user.getPermissionList() .equals(Integer.toString(AppRole.SUPER_ADMIN.getLevel())); }</code><technical_language>A fix isolate null handling User.setSuperAdmin() setter subsequent isSuperAdmin() calls return null (and fix other cases getter is called). <LINK_0></technical_language>

Target:
private boolean isSuperAdminRole(User user) { return user.isSuperAdmin() || user.getPermissionList() .equals(Integer.toString(AppRole.SUPER_ADMIN.getLevel())); }
Source:
<code><START> public void removeUserExtSource(PerunSession sess, User user, UserExtSource userExtSource, boolean forceDelete) throws InternalErrorException, UserNotExistsException, UserExtSourceNotExistsException, PrivilegeException, UserExtSourceAlreadyRemovedException { <END> Utils.checkPerunSession(sess); if(!AuthzResolver.isAuthorized(sess, Role.SELF, user)) { throw new PrivilegeException(sess, "removeUserExtSource"); } getUsersManagerBl().checkUserExists(sess, user); userExtSource.setUserId(user.getId()); getUsersManagerBl().checkUserExtSourceExists(sess, userExtSource); getUsersManagerBl().removeUserExtSource(sess, user, userExtSource); }</code><technical_language>Implementation check param forceDelete. If true, continue, false I suggest simply call method (without forced flag). I user able force delete UES (even if in API only), Perun admins</technical_language>

Target:
public void removeUserExtSource(PerunSession sess, User user, UserExtSource userExtSource, boolean forceDelete) throws InternalErrorException, UserNotExistsException, UserExtSourceNotExistsException, PrivilegeException, UserExtSourceAlreadyRemovedException { Utils.checkPerunSession(sess); if (forceDelete) { if(!AuthzResolver.isAuthorized(sess, Role.PERUNADMIN, user)) { throw new PrivilegeException(sess, "removeUserExtSource"); } getUsersManagerBl().checkUserExists(sess, user); userExtSource.setUserId(user.getId()); getUsersManagerBl().checkUserExtSourceExists(sess, userExtSource); getUsersManagerBl().removeUserExtSource(sess, user, userExtSource); } else { removeUserExtSource(sess, user, userExtSource); } }
Source:
<code>Node optimizeSubtree(Node subtree) { if (!subtree.isScript() && !subtree.isBlock()) { return subtree; } boolean codeChanged = false; <START> for (Node child = subtree.getFirstChild(); child != null; child = child.getNext()) { <END> if (isArrayDotPush(child)) { Node next = child.getNext(); if (isArrayDotPush(next)) { Node firstCall = child.getFirstChild(); Node secondCall = next.getFirstChild(); String firstArrayName = firstCall.getFirstChild().getFirstChild().getString(); String secondArrayName = secondCall.getFirstChild().getFirstChild().getString(); if (firstArrayName.equals(secondArrayName)) { Node secondArgument = secondCall.getFirstChild().getNext(); while (secondArgument != null) { Node temp = secondArgument.getNext(); firstCall.addChildToBack(secondArgument.detach()); secondArgument = temp; } subtree.removeChild(next); codeChanged = true; } } } } if (codeChanged) { reportChangeToEnclosingScope(subtree); } return subtree; }</code><technical_language>child, call loop variable statement a bit clearer represents</technical_language>

Target:
Node optimizeSubtree(Node subtree) { if (!subtree.isScript() && !subtree.isBlock()) { return subtree; } boolean codeChanged = false; for (Node statement = subtree.getFirstChild(); statement != null; statement = statement.getNext()) { ArrayDotPushStatementSequence arrayDotPushStatementSequence = asArrayDotPushStatementSequence(statement); if (arrayDotPushStatementSequence != null) { arrayDotPushStatementSequence.combine(subtree); codeChanged = true; } } if (codeChanged) { reportChangeToEnclosingScope(subtree); } return subtree; }
Source:
<code>private String getLanguageCountryCode(Locale locale) { String result = locale.getLanguage(); if (!locale.getCountry().isEmpty()) { <START> result += locale.getCountry(); <END> } return result; }</code><technical_language>Missing -... ex: pt-BR i it, is a - a _? I a -. more reason default functions</technical_language>

Target:
private String getLanguageCountryCode(Locale locale) { String result = locale.getLanguage(); if (!locale.getCountry().isEmpty()) { result += "-" + locale.getCountry(); } return result; }
Source:
<code>private void increaseBuffersInBacklog(BufferConsumer buffer) { assert Thread.holdsLock(buffers); if (buffer != null && buffer.isBuffer()) { buffersInBacklog++; <START> parent.notifyIncreaseBacklog(buffersInBacklog); <END> } }</code><technical_language>lines replaced with: parent.notifyDecreaseBacklog(++buffersInBacklog);</technical_language>

Target:
private void increaseBuffersInBacklog(BufferConsumer buffer) { assert Thread.holdsLock(buffers); if (buffer != null && buffer.isBuffer()) { buffersInBacklog++; } }
Source:
<code>public Set<Type> getTypes() { HashSet<Type> types = new HashSet<Type>(); types.add(BuilderInterceptorInstance.class); <START> types.add(Object.class); <END> return types; }</code><technical_language>I - this immutable set cached in a private static final field</technical_language>

Target:
public Set<Type> getTypes() { return types; }
Source:
<code>void testFirstElement() { Object object = new Object(); Object object2 = new Object(); assertEquals( object, Iterables.first( asList( object, object2 ) ) ); assertEquals( object, Iterables.first( asList( object ) ) ); try { Iterables.first( asList() ); fail( "Should fail" ); } catch ( NoSuchElementException e ) { } assertEquals( object, Iterators.first( asList( object, object2 ).iterator() ) ); assertEquals( object, Iterators.first( asList( object ).iterator() ) ); try { <START> Iterators.first( asList().iterator() ); <END> fail( "Should fail" ); } catch ( NoSuchElementException e ) { } assertEquals( object, Iterables.firstOrNull( asList( object, object2 ) ) ); assertEquals( object, Iterables.firstOrNull( asList( object ) ) ); assertNull( Iterables.firstOrNull( asList() ) ); assertEquals( object, Iterators.firstOrNull( asList( object, object2 ).iterator() ) ); assertEquals( object, Iterators.firstOrNull( asList( object ).iterator() ) ); assertNull( Iterators.firstOrNull( asList().iterator() ) ); }</code><technical_language>for consistency pls assertThrows in other places</technical_language>

Target:
void testFirstElement() { Object object = new Object(); Object object2 = new Object(); assertEquals( object, Iterables.first( asList( object, object2 ) ) ); assertEquals( object, Iterables.first( asList( object ) ) ); assertThrows( NoSuchElementException.class, () -> Iterables.first( asList() ) ); assertEquals( object, Iterators.first( asList( object, object2 ).iterator() ) ); assertEquals( object, Iterators.first( asList( object ).iterator() ) ); assertThrows( NoSuchElementException.class, () -> Iterators.first( asList().iterator() ) ); assertEquals( object, Iterables.firstOrNull( asList( object, object2 ) ) ); assertEquals( object, Iterables.firstOrNull( asList( object ) ) ); assertNull( Iterables.firstOrNull( asList() ) ); assertEquals( object, Iterators.firstOrNull( asList( object, object2 ).iterator() ) ); assertEquals( object, Iterators.firstOrNull( asList( object ).iterator() ) ); assertNull( Iterators.firstOrNull( asList().iterator() ) ); }
Source:
<code>private void summonNecromancer() { necromancer = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new BoundedQueue<>(numberOfPendingFutures), new ThreadFactoryBuilder() .setNameFormat("FastObjectLoaderReaderThread-%d").build()); <START> futureList = new ArrayList<>(); <END> }</code><technical_language>futureList cleaned ? growing in size completed futures</technical_language>

Target:
private void summonNecromancer() { necromancer = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new BoundedQueue<>(numberOfPendingFutures), new ThreadFactoryBuilder() .setNameFormat("FastObjectLoaderReaderThread-%d").build()); lastReadRequest = null; }
Source:
<code>public void stop() { ChangeIndex read = searchIndex.get(); if (read != null) { read.close(); } for (ChangeIndex write : writeIndexes) { if (write != read) { <START> read.close(); <END> } } }</code><technical_language>write.close();</technical_language>

Target:
public void stop() { ChangeIndex read = searchIndex.get(); if (read != null) { read.close(); } for (ChangeIndex write : writeIndexes) { if (write != read) { write.close(); } } }
Source:
<code>protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { HeaderWriterResponse headerWriterResponse = new HeaderWriterResponse(request, response, compositeHeaderWriter); HeaderWriterRequest headerWriterRequest = new HeaderWriterRequest(request, headerWriterResponse); try { filterChain.doFilter(headerWriterRequest, headerWriterResponse); <START> } finally { <END> headerWriterResponse.writeHeaders(); } }</code><technical_language>Thank for cleanup</technical_language>

Target:
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { HeaderWriterResponse headerWriterResponse = new HeaderWriterResponse(request, response, this.headerWriter); HeaderWriterRequest headerWriterRequest = new HeaderWriterRequest(request, headerWriterResponse); try { filterChain.doFilter(headerWriterRequest, headerWriterResponse); } finally { headerWriterResponse.writeHeaders(); } }
Source:
<code>public VideoCopy createCopyInLibrary(Library library, Video video, VideoMedium medium) { return copyRepo.save( library.add( video, medium ) ); <START> } <END></code><technical_language>for BorrowalService: I suspect "spring way" implement search/list methods repository, service, service delegate repository</technical_language>

Target:
public VideoCopy createCopyInLibrary(Library library, Video video, VideoMedium medium) { VideoCopy copy = new VideoCopy(); copy.setLibrary( library ); library.getCopies().add( copy ); copy.setDocument( video ); video.getCopies().add( copy ); copy.setMedium( medium ); return copyRepo.save( copy ); }
Source:
<code><START> void foo() { <END> Integer i = 123456789; Float f = 1.0f; Number n = true ? i : f; Object o1 = new Object(); A a2 = new A(); o1 = true ? o1 : a2; o1 = true ? f : a2; n = true ? (Float) i : f; }</code><technical_language>this missing a test case a primitive ? int i; long l; true ? i : l; //Compliant</technical_language>

Target:
void foo() { long l = 123456789123456789L; Integer i1 = 123456789; int i2 = 123456789; Float f1 = 1.0f; Object o1 = new Object(); A a2 = new A(); Number n = true ? i1 : f1; o1 = true ? o1 : a2; o1 = true ? f1 : a2; n = true ? (Number) i1 : f1; l = true ? i2 : l; float f2 = 0.2f; l = (long) (true ? i2 : f2); n = true ? Long.valueOf(i1) : (Long) l; }
Source:
<code>public void endProcessingNode() { if (nodeCount.decrementAndGet() == 0 && recorder != null) { Node node = rootNode.build(); trace.setTimestamp(node.getTimestamp()); trace.setTransaction(getTransaction()); trace.getNodes().add(node); <START> if (checkForSamplingProperties(node)) { <END> reportingLevel = ReportingLevel.All; } boolean sampled = ContextSampler.isSampled(sampler, trace, reportingLevel); if (sampled && reportingLevel == null) { reportingLevel = ReportingLevel.All; } if (sampled) { recorder.report(trace); } } }</code><technical_language>I reporting level need set spans created - if reporting level changes a Span, require a sub-tracing context created representing sampling scope. way, inject performed child nodes, inherit reporting level sub-tree, other nodes in trace fragment reporting level of parent - if I explained well, try example: Root node in fragment is passed reporting level (or initialises based sampler if based extracted context). this reporting level is All. If child Spans (components) A B created, inheriting trace context reporting level. a child Span is created A B, called A' B'. A' 'sampled' tag set 0. A' B' inject context in separate external service invocations. call A' pass reportingLevel None, while call B' reportingLevel All. reportingLevel stage needs determined Span is created</technical_language>

Target:
public void endProcessingNode() { if (nodeCount.decrementAndGet() == 0 && recorder != null) { Node node = rootNode.build(); trace.setTimestamp(node.getTimestamp()); trace.setTransaction(getTransaction()); trace.getNodes().add(node); if (checkForSamplingProperties(node)) { reportingLevel = ReportingLevel.All; } boolean sampled = sampler.isSampled(trace, reportingLevel); if (sampled && reportingLevel == null) { reportingLevel = ReportingLevel.All; } if (sampled) { recorder.report(trace); } } }
Source:
<code>public HiveTableInstance createImmutable(HiveTableDefinition tableDefinition, TableHandle tableHandle) { checkState(!tableDefinition.isPartitioned(), "Partitioning not supported for immutable tables"); TableName tableName = createImmutableTableName(tableHandle); LOGGER.debug("creating immutable table {}", tableHandle.getName()); String tableDataPath = getImmutableTableHdfsPath(tableDefinition.getDataSource()); uploadTableData(tableDataPath, tableDefinition.getDataSource()); dropTableIgnoreError(tableName); createTable(tableDefinition, tableName, Optional.of(tableDataPath)); markTableAsExternal(tableName); if (analyzeImmutableTables && tableDefinition.getDataSource().getStatistics().isPresent()) { <START> checkState(!tableDefinition.isPartitioned(), "Statisitcs are not yet supported for parititioned tables"); <END> hiveThriftClient.setStatistics(tableName, tableDefinition.getDataSource().getStatistics().get()); } return new HiveTableInstance(tableName, tableDefinition); }</code><technical_language>drop</technical_language>

Target:
public HiveTableInstance createImmutable(HiveTableDefinition tableDefinition, TableHandle tableHandle) { checkState(!tableDefinition.isPartitioned(), "Partitioning not supported for immutable tables"); TableName tableName = createImmutableTableName(tableHandle); LOGGER.debug("creating immutable table {}", tableHandle.getName()); String tableDataPath = getImmutableTableHdfsPath(tableDefinition.getDataSource()); uploadTableData(tableDataPath, tableDefinition.getDataSource()); dropTableIgnoreError(tableName); createTable(tableDefinition, tableName, Optional.of(tableDataPath)); markTableAsExternal(tableName); if (analyzeImmutableTables && tableDefinition.getDataSource().getStatistics().isPresent()) { checkState(!tableDefinition.isPartitioned(), "Statisitcs are not supported for parititioned tables"); hiveThriftClient.setStatistics(tableName, tableDefinition.getDataSource().getStatistics().get()); } return new HiveTableInstance(tableName, tableDefinition); }
Source:
<code>public void onStartup(ServletContext servletContext) throws ServletException { <START> if(servletInitParams.isPresent()) { <END> servletInitParams.get().getInitParams().forEach((key, value) -> servletContext.setInitParameter(key, value)); } ListenerBootstrap config = new ListenerBootstrap(servletContext); deployment = config.createDeployment(); deployment.start(); servletContext.setAttribute(ResteasyProviderFactory.class.getName(), deployment.getProviderFactory()); servletContext.setAttribute(Dispatcher.class.getName(), deployment.getDispatcher()); servletContext.setAttribute(Registry.class.getName(), deployment.getRegistry()); SpringBeanProcessor processor = new SpringBeanProcessor(deployment.getDispatcher(), deployment.getRegistry(), deployment.getProviderFactory()); processor.postProcessBeanFactory(beanFactory); applicationContext.addApplicationListener(processor); }</code><technical_language>missing servletInitParams.ifPresent cleaner</technical_language>

Target:
public void onStartup(ServletContext servletContext) throws ServletException { servletInitParams.ifPresent(params -> params.getInitParams().forEach((key, value) -> servletContext.setInitParameter(key, value))); ListenerBootstrap config = new ListenerBootstrap(servletContext); deployment = config.createDeployment(); deployment.start(); servletContext.setAttribute(ResteasyProviderFactory.class.getName(), deployment.getProviderFactory()); servletContext.setAttribute(Dispatcher.class.getName(), deployment.getDispatcher()); servletContext.setAttribute(Registry.class.getName(), deployment.getRegistry()); SpringBeanProcessor processor = new SpringBeanProcessor(deployment.getDispatcher(), deployment.getRegistry(), deployment.getProviderFactory()); processor.postProcessBeanFactory(beanFactory); applicationContext.addApplicationListener(processor); }
Source:
<code>public void getPermissionsObjectWithChildrenTest() throws Exception { List<ContentObject> children = new ArrayList<>(); children.add(member); when(repoObjLoader.getRepositoryObject(parentPid)).thenReturn(parent); when(parent.getMembers()).thenReturn(children); when(member.getPid()).thenReturn(memberPid); when(memberPermissions.add(result)).thenReturn(true); ArrayList<Map<String, Object>> memberPerms = new ArrayList<Map<String,Object>>(); when(permResult.put("memberPermissions", memberPermissions)).thenReturn(memberPerms); when(aclFactory.getPrincipalRoles(memberPid)).thenReturn(objPrincRoles); when(aclFactory.isMarkedForDeletion(memberPid)).thenReturn(true); when(aclFactory.getEmbargoUntil(memberPid)).thenReturn(testDate); when(aclFactory.getPatronAccess(memberPid)).thenReturn(PatronAccess.authenticated); result = aclRetrievalService.getPermissions(agent, parentPid); String resultJson = generateJson(result); assertTrue(resultJson.contains("pid\":\"" + parentUuid)); assertTrue(resultJson.contains("memberPermissions")); assertTrue(resultJson.contains("markForDeletion\":false")); assertTrue(resultJson.contains("embargoed\":" + testDate.getTime())); assertTrue(resultJson.contains("patronAccess\":\"authenticated")); memberPerms.add(result); <START> Map<String,Object> returnedValues = ((ArrayList<Map<String, Object>>) result.get("memberPermissions")).get(0); <END> assertEquals(memberUuid, returnedValues.get("pid")); assertEquals(objPrincRoles, returnedValues.get("principals")); assertEquals(true, returnedValues.get("markForDeletion")); assertEquals(testDate, returnedValues.get("embargoed")); assertEquals(PatronAccess.authenticated, returnedValues.get("patronAccess")); }</code><technical_language>suggest assuming ArrayList returned switch implementations</technical_language>

Target:
public void getPermissionsObjectWithChildrenTest() throws Exception { List<ContentObject> children = new ArrayList<>(); children.add(member); when(repoObjLoader.getRepositoryObject(parentPid)).thenReturn(parent); when(parent.getMembers()).thenReturn(children); when(member.getPid()).thenReturn(memberPid); when(memberPermissions.add(result)).thenReturn(true); when(objAclFactory.getEmbargoUntil(parentPid)).thenReturn(null); when(objAclFactory.getEmbargoUntil(memberPid)).thenReturn(testDate); when(inheritedAclFactory.getEmbargoUntil(any(PID.class))).thenReturn(null); result = aclRetrievalService.getPermissions(agent, parentPid); assertEquals(parentUuid, result.get("pid")); assertEquals(false, result.get("markForDeletion")); assertNull(result.get("embargo")); assertEquals(objPrincRoles, result.get("principals")); assertEquals(PatronAccess.authenticated, result.get("patronAccess")); assertTrue(result.containsKey("memberPermissions")); Map<String,Object> memberValues = ((List<Map<String, Object>>) result.get("memberPermissions")).get(0); assertEquals(memberUuid, memberValues.get("pid")); assertEquals(false, memberValues.get("markForDeletion")); assertEquals(testDate, memberValues.get("embargo")); assertEquals(objPrincRoles, memberValues.get("principals")); assertEquals(PatronAccess.authenticated, memberValues.get("patronAccess")); }
Source:
<code>public static ArrayList<Long> getPendingDraftsIgnorePostIdList() { ArrayList<Long> idList = new ArrayList<>(); String idListString = getString(DeletablePrefKey.PENDING_DRAFTS_NOTIFICATION_IGNORE_LIST, ""); if (!TextUtils.isEmpty(idListString)) { <START> List<String> items = Arrays.asList(idListString.split("\\s*,\\s*")); <END> for (String item : items) { Long oneId = Long.valueOf(item); idList.add(oneId); } } return idList; }</code><technical_language>this simplified in List<String> items = Arrays.asList(idListString.split(","));</technical_language>

Target:
public static ArrayList<Long> getPendingDraftsIgnorePostIdList() { ArrayList<Long> idList = new ArrayList<>(); String idListString = getString(DeletablePrefKey.PENDING_DRAFTS_NOTIFICATION_IGNORE_LIST, ""); if (!TextUtils.isEmpty(idListString)) { List<String> items = Arrays.asList(idListString.split(",")); for (String item : items) { Long oneId = Long.valueOf(item); idList.add(oneId); } } return idList; }