auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public ProcessContext<CartOperationRequest> execute(ProcessContext<CartOperationRequest> context) throws Exception { CartOperationRequest request = context.getSeedData(); OrderItemRequestDTO orderItemRequestDTO = request.getItemRequest(); Integer orderItemQuantity = orderItemRequestDTO.getQuantity(); if (!hasQuantity(orderItemQuantity)) { context.stopProcess(); } else if (orderItemQuantity < 0) { throw new IllegalArgumentException("Quantity cannot be negative"); } else if (request.getOrder() == null) { throw new IllegalArgumentException("Order is required when adding item to order"); } else { Product product = determineProduct(orderItemRequestDTO); Sku sku; try { sku = determineSku(product, orderItemRequestDTO.getSkuId(), orderItemRequestDTO.getItemAttributes(), (ActivityMessages) context); addSkuToCart(sku, orderItemRequestDTO, product, request); }catch(InventoryUnavailableException e){ <START> throw e; <END> } if (!hasSameCurrency(orderItemRequestDTO, request, sku)) { throw new IllegalArgumentException("Cannot have items with differing currencies in one cart"); } validateIfParentOrderItemExists(orderItemRequestDTO); } return context; }</code><technical_language>reason catch exception immediately throw changes</technical_language>

Target:
public ProcessContext<CartOperationRequest> execute(ProcessContext<CartOperationRequest> context) throws Exception { CartOperationRequest request = context.getSeedData(); OrderItemRequestDTO orderItemRequestDTO = request.getItemRequest(); Integer orderItemQuantity = orderItemRequestDTO.getQuantity(); if (!hasQuantity(orderItemQuantity)) { context.stopProcess(); } else if (orderItemQuantity < 0) { throw new IllegalArgumentException("Quantity cannot be negative"); } else if (request.getOrder() == null) { throw new IllegalArgumentException("Order is required when adding item to order"); } else { Product product = determineProduct(orderItemRequestDTO); Sku sku = determineSku(product, orderItemRequestDTO.getSkuId(), orderItemRequestDTO.getItemAttributes(), (ActivityMessages) context); addSkuToCart(sku, orderItemRequestDTO, product, request); if (!hasSameCurrency(orderItemRequestDTO, request, sku)) { throw new IllegalArgumentException("Cannot have items with differing currencies in one cart"); } validateIfParentOrderItemExists(orderItemRequestDTO); } return context; }
Source:
<code>private void addEmptyLabelIfNeeded() { <START> if (emptyLabel != null && getComponentCount() == 0) { <END> add(emptyLabel); } }</code><technical_language>emptyLabel violating SRP. Specifically serves purposes: 1) Not-null means display components 2) is display component display element display element flag show display element. a bit notable is mutable 'setEmptyLabel'. Do agree this issue @asvitkine thoughts it? diff, a suggestion, I solve this adding a constructor overload accepts a new parameter, enum "EmptyLabelDisplayMode". existing constructor invoke new parameter EG: public SimpleUnitPanel(final UiContext uiContext, final boolean useSmallIconWrapLayout) { this(uiContext, useSmallIconWrapLayout, EmptyLabelDisplayMode.DO_NOT_DISPLAY); } public SimpleUnitPanel(final UiContext uiContext, final boolean useSmallIconWrapLayout, EmptyLabelDisplayMode emptyLabelDisplayMode) { : : } I 'SimpleUnitPanel' 'empty' label injected. this add method be: private void addEmptyLabelIfNeeded() { if(emptyLabelDisplayMode == DISPLAY_ON_EMPTY_PURCHASE && getComponentCount() == 0) { add(new JLabel("(None)"); } }</technical_language>

Target:
private void addEmptyLabelIfNeeded() { if (style == Style.SMALL_ICONS_WRAPPED_WITH_LABEL_WHEN_EMPTY && getComponentCount() == 0) { add(new JLabel("(None)")); } }
Source:
<code>public HttpResponse doAct(@QueryParameter String dismiss) throws IOException { <START> Jenkins.get().checkPermission(Jenkins.ADMINISTER); <END> if(dismiss!=null) { disable(true); return HttpResponses.redirectViaContextPath("/manage"); } else { return HttpResponses.redirectTo("rule/"); } }</code><technical_language>Strongly restoring this insanity again. Currently do need rely individual admin monitor authors shit together, this negate this</technical_language>

Target:
public HttpResponse doAct(@QueryParameter String dismiss) throws IOException { if(dismiss!=null) { disable(true); return HttpResponses.redirectViaContextPath("/manage"); } else { return HttpResponses.redirectTo("rule/"); } }
Source:
<code>public UpdateRef setNewValue(@Nullable ObjectId newValue) { <START> this.newValue = newValue == null ? null : newValue; <END> return this; }</code><technical_language>I this is this.newValue = newValue; ?</technical_language>

Target:
public UpdateRef setNewValue(@Nullable ObjectId newValue) { this.newValue = newValue; return this; }
Source:
<code>private PrioritizedSplitRunner pollSplit() { if (levelAbsolutePriority) { return pollFirstSplit(); } long expectedScheduledTime = updateLevelTimes(); double worstRatio = 1; int selectedLevel = -1; for (int level = 0; level < LEVELS.length; level++) { if (!levelWaitingSplits.get(level).isEmpty()) { double ratio = levelScheduledTime[level] == 0 ? 0 : expectedScheduledTime / (1.0 * levelScheduledTime[level]); if (selectedLevel == -1 || ratio > worstRatio) { worstRatio = ratio; selectedLevel = level; } } expectedScheduledTime /= levelPriorityMultiplier; } if (selectedLevel == -1) { return null; } <START> <END> return levelWaitingSplits.get(selectedLevel).poll(); }</code><technical_language>Due locking this return null, if a bug deadlock waiting for a split empty. throw if problems in callers, log is broken, retry loop</technical_language>

Target:
private PrioritizedSplitRunner pollSplit() { if (levelAbsolutePriority) { return pollFirstSplit(); } long targetScheduledTime = updateLevelTimes(); double worstRatio = 1; int selectedLevel = -1; for (int level = 0; level < LEVEL_THRESHOLD_SECONDS.length; level++) { if (!levelWaitingSplits.get(level).isEmpty()) { double ratio = levelScheduledTime[level] == 0 ? 0 : targetScheduledTime / (1.0 * levelScheduledTime[level]); if (selectedLevel == -1 || ratio > worstRatio) { worstRatio = ratio; selectedLevel = level; } } targetScheduledTime /= levelTimeMultiplier; } if (selectedLevel == -1) { return null; } PrioritizedSplitRunner result = levelWaitingSplits.get(selectedLevel).poll(); checkState(result != null, "pollSplit cannot return null"); return result; }
Source:
<code>protected boolean checkIfLongSession(MethodTree method) { List<AnnotationTree> annotations = method.modifiers().annotations(); for (AnnotationTree annotationTree : annotations) { if (annotationTree.annotationType().is(Tree.Kind.IDENTIFIER)) { IdentifierTree idf = (IdentifierTree) annotationTree.annotationType(); <START> if (idf.name().equals(ACTIVATE)) { <END> checkIfLongSessionOpened(method); return true; } else if (idf.name().equals(DEACTIVATE)) { checkIfLongSessionClosed(method); return true; } } } return false; }</code><technical_language>base long identifier? org.apache.felix.scr.annotations.Activate? Activate.class.getCanonicalName();</technical_language>

Target:
protected boolean checkIfLongSession(MethodTree method) { List<AnnotationTree> annotations = method.modifiers().annotations(); for (AnnotationTree annotationTree : annotations) { if (annotationTree.annotationType().is(Tree.Kind.IDENTIFIER)) { IdentifierTree idf = (IdentifierTree) annotationTree.annotationType(); if (idf.name().equals(Activate.class.getSimpleName())) { collectLongSessionOpened(method); return true; } else if (idf.name().equals(Deactivate.class.getSimpleName())) { collectLongSessionClosed(method); return true; } } } return false; }
Source:
<code>public ListSessionsResponse(DataInputStream inNet) throws IOException { byte[] data = new byte[PACKET_FIXED_SIZE]; inNet.readFully(data); ByteBuffer bb = ByteBuffer.wrap(data); bb.order(ByteOrder.BIG_ENDIAN); int nbSessions = bb.getInt(); <START> ArrayList<SessionResponse> sl = new ArrayList<>(nbSessions); <END> for (int session = 0; session < nbSessions; session++) { sl.add(session, new SessionResponse(inNet)); } fSessionList = ImmutableList.copyOf(sl); }</code><technical_language>ImmutableList.Builder</technical_language>

Target:
public ListSessionsResponse(DataInputStream inNet) throws IOException { byte[] data = new byte[PACKET_FIXED_SIZE]; inNet.readFully(data); ByteBuffer bb = ByteBuffer.wrap(data); bb.order(ByteOrder.BIG_ENDIAN); int nbSessions = bb.getInt(); Builder<SessionResponse> sl = new ImmutableList.Builder<>(); for (int session = 0; session < nbSessions; session++) { sl.add(new SessionResponse(inNet)); } fSessionList = sl.build(); }
Source:
<code>public BlockCacheConfiguration(AccumuloConfiguration conf, CacheType type, String implName) { switch (type) { case INDEX: this.maxSize = conf.getAsBytes(Property.TSERV_INDEXCACHE_SIZE); break; case DATA: this.maxSize = conf.getAsBytes(Property.TSERV_DATACACHE_SIZE); break; case SUMMARY: this.maxSize = conf.getAsBytes(Property.TSERV_SUMMARYCACHE_SIZE); break; default: <START> this.maxSize = conf.getAsBytes(Property.TSERV_DEFAULT_BLOCKSIZE); <END> break; } this.blockSize = conf.getAsBytes(Property.TSERV_DEFAULT_BLOCKSIZE); }</code><technical_language>I defatult case throw IllegalArgumentException</technical_language>

Target:
public BlockCacheConfiguration(AccumuloConfiguration conf, CacheType type, String implName) { defaultPrefix = getDefaultPrefix(implName); prefix = getPrefix(type, implName); genProps = conf.getAllPropertiesWithPrefix(Property.GENERAL_ARBITRARY_PROP_PREFIX); switch (type) { case INDEX: this.maxSize = conf.getAsBytes(Property.TSERV_INDEXCACHE_SIZE); break; case DATA: this.maxSize = conf.getAsBytes(Property.TSERV_DATACACHE_SIZE); break; case SUMMARY: this.maxSize = conf.getAsBytes(Property.TSERV_SUMMARYCACHE_SIZE); break; default: throw new IllegalArgumentException("Unknown block cache type"); } this.blockSize = conf.getAsBytes(Property.TSERV_DEFAULT_BLOCKSIZE); }
Source:
<code>public int hashCode() { <START> return Objects.hashCode(name.hashCode(), uri.hashCode()); <END> }</code><technical_language>Objects.hashCode(name, uri);, right hash code of a hash code</technical_language>

Target:
public int hashCode() { return Objects.hashCode(name, uri); }
Source:
<code>public void testDatastreamProperties() throws ClientProtocolException, URISyntaxException, IOException { final GraphStore g = getResourceTriples(idMapper.mapDatastreamPath("example:1", "DS1") + "/fcr:metadata"); <START> assertTrue("Unable to find datastream lable in migrated resource RDF assertions.", <END> g.contains(ANY, ANY, NodeFactory.createURI("<LINK_0>"), NodeFactory.createLiteral("Example inline XML datastream"))); }</code><technical_language>Typo "lable"</technical_language>

Target:
public void testDatastreamProperties() throws ClientProtocolException, URISyntaxException, IOException { final GraphStore g = getResourceTriples(idMapper.mapDatastreamPath("example:1", "DS1") + "/fcr:metadata"); assertTrue("Unable to find datastream label in migrated resource RDF assertions.", g.contains(ANY, ANY, NodeFactory.createURI("<LINK_0>"), NodeFactory.createLiteral("Example inline XML datastream"))); }
Source:
<code>public Managed<BigtableConnection> connection( final AsyncFramework async, final ExecutorService executorService ) { return async.managed(new ManagedSetup<BigtableConnection>() { @Override public AsyncFuture<BigtableConnection> construct() throws Exception { return async.call( new BigtableConnectionBuilder(project, instance, credentials, async, <START> executorService, disableBulkMutations, flusIntervalSeconds)); <END> } @Override public AsyncFuture<Void> destruct(final BigtableConnection value) throws Exception { return async.call(() -> { value.close(); return null; }); } }); }</code><technical_language>typo: flus</technical_language>

Target:
public Managed<BigtableConnection> connection( final AsyncFramework async, final ExecutorService executorService ) { return async.managed(new ManagedSetup<BigtableConnection>() { @Override public AsyncFuture<BigtableConnection> construct() throws Exception { return async.call( new BigtableConnectionBuilder(project, instance, credentials, async, executorService, disableBulkMutations, flushIntervalSeconds)); } @Override public AsyncFuture<Void> destruct(final BigtableConnection value) throws Exception { return async.call(() -> { value.close(); return null; }); } }); }
Source:
<code>@Override public JsonWriter value(Boolean value) throws IOException { if (value == null) { return nullValue(); } <START> writeDeferredName(); <END> beforeValue(); sink.writeUtf8(value ? "true" : "false"); pathIndices[stackSize - 1]++; return this; }</code><technical_language>return value(value.booleanValue())</technical_language>

Target:
@Override public JsonWriter value(Boolean value) throws IOException { if (value == null) { return nullValue(); } return value(value.booleanValue()); }
Source:
<code>public Map<String, String> getConnectionFactoryProperties() { <START> DefaultConnectionFactoryBuilder builder = <END> createDefaultConnectionFactoryBuilderIfRequired(); return builder.getConnectionFactoryProperties(); }</code><technical_language>This method behave getConnectionFactoryClass, throw Unsupported exception create a default factory builder is a getter. convenience methods setUser able this method functionality is correct</technical_language>

Target:
public Map<String, String> getConnectionFactoryProperties() { if (connectionFactoryBuilder == null) { connectionFactoryBuilder = createDefaultConnectionFactoryBuilderIfRequired(); } if (connectionFactoryBuilder instanceof DefaultConnectionFactoryBuilder) { return ((DefaultConnectionFactoryBuilder)connectionFactoryBuilder).getConnectionFactoryProperties(); } else { throw new UnsupportedOperationException("ConnectionFactoryBuilder does not support connectionFactoryProperties"); } }
Source:
<code><START> public synchronized void close() <END> { isOpen = false; }</code><technical_language>I other method this synchronisation avoid overlapping with</technical_language>

Target:
public void close() { isOpen = false; }
Source:
<code>private void updateActionAvailability() { VM entity = (VM) getItem().getEntity(); getItem().getTakeVmCommand().setIsAvailable(false); ArrayList<VM> entities = new ArrayList<VM>(); entities.add(entity); getItem().getRunCommand().setIsExecutionAllowed(VdcActionUtils.canExecute(entities, VM.class, VdcActionType.RunVm)); <START> getItem().getPauseCommand().setIsExecutionAllowed(entities.size() > 0 <END> && VdcActionUtils.canExecute(entities, VM.class, VdcActionType.HibernateVm) && AsyncDataProvider.canVmsBePaused(entities)); getItem().getShutdownCommand().setIsExecutionAllowed(VdcActionUtils.canExecute(entities, VM.class, VdcActionType.ShutdownVm)); getItem().getStopCommand().setIsExecutionAllowed(VdcActionUtils.canExecute(entities, VM.class, VdcActionType.StopVm)); getItem().getRebootCommand().setIsExecutionAllowed(AsyncDataProvider.isRebootCommandExecutionAllowed(entities)); if (entity.getVmPoolId() != null) { AsyncDataProvider.getPoolById(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { VmItemBehavior behavior = (VmItemBehavior) target; VmPool pool = (VmPool) returnValue; boolean isManualPool = pool.getVmPoolType() == VmPoolType.Manual; behavior.updateCommandsAccordingToPoolType(isManualPool); } }), entity.getVmPoolId()); } else { updateCommandsAccordingToPoolType(true); } }</code><technical_language>entities.size() is needed is size of 1 because: ArrayList<VM> entities = new ArrayList<VM>(); entities.add(entity); couple of lines above</technical_language>

Target:
private void updateActionAvailability() { VM entity = (VM) getItem().getEntity(); getItem().getTakeVmCommand().setIsAvailable(false); ArrayList<VM> entities = new ArrayList<VM>(); entities.add(entity); getItem().getRunCommand().setIsExecutionAllowed(VdcActionUtils.canExecute(entities, VM.class, VdcActionType.RunVm)); getItem().getPauseCommand().setIsExecutionAllowed(VdcActionUtils.canExecute(entities, VM.class, VdcActionType.HibernateVm) && AsyncDataProvider.canVmsBePaused(entities)); getItem().getShutdownCommand().setIsExecutionAllowed(VdcActionUtils.canExecute(entities, VM.class, VdcActionType.ShutdownVm)); getItem().getStopCommand().setIsExecutionAllowed(VdcActionUtils.canExecute(entities, VM.class, VdcActionType.StopVm)); getItem().getRebootCommand().setIsExecutionAllowed(AsyncDataProvider.isRebootCommandExecutionAllowed(entities)); if (entity.getVmPoolId() != null) { AsyncDataProvider.getPoolById(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { VmItemBehavior behavior = (VmItemBehavior) target; VmPool pool = (VmPool) returnValue; boolean isManualPool = pool.getVmPoolType() == VmPoolType.Manual; behavior.updateCommandsAccordingToPoolType(isManualPool); } }), entity.getVmPoolId()); } else { updateCommandsAccordingToPoolType(true); } }
Source:
<code><START> public void waitForFinish(Duration timeout) { <END> JobConfig jobConfig = new JobConfig(config); long timeoutInMs = timeout.toMillis(); long startTimeInMs = System.currentTimeMillis(); long sleepDurationInMs = Math.min(timeoutInMs, DEFAULT_TIME_TO_SLEEP_DURING_WAIT); long timeElapsed = 0L; ApplicationStatus status; try { while(timeoutInMs < 1 || timeElapsed <= timeoutInMs) { status = getApplicationStatus(jobConfig); if (status == SuccessfulFinish || status == UnsuccessfulFinish) { LOG.info("Application finished with status {}", status); break; } Thread.sleep(sleepDurationInMs); timeElapsed = System.currentTimeMillis() - startTimeInMs; } if(timeElapsed > timeoutInMs) { LOG.error("Waiting to shutdown remote application runner timed out."); throw new TimeoutException("Waiting to shutdown remote application runner timed out."); } } catch (Exception e) { LOG.error("Wait for application finish failed due to", e); throw new SamzaException(e); } }</code><technical_language>return boolean</technical_language>

Target:
public boolean waitForFinish(Duration timeout) { JobConfig jobConfig = new JobConfig(config); boolean finished = true; long timeoutInMs = timeout.toMillis(); long startTimeInMs = System.currentTimeMillis(); long timeElapsed = 0L; long sleepDurationInMs = timeoutInMs < 1 ? DEFAULT_SLEEP_DURATION_MS : Math.min(timeoutInMs, DEFAULT_SLEEP_DURATION_MS); ApplicationStatus status; try { while (timeoutInMs < 1 || timeElapsed <= timeoutInMs) { status = getApplicationStatus(jobConfig); if (status == SuccessfulFinish || status == UnsuccessfulFinish) { LOG.info("Application finished with status {}", status); break; } Thread.sleep(sleepDurationInMs); timeElapsed = System.currentTimeMillis() - startTimeInMs; } if (timeElapsed > timeoutInMs) { LOG.warn("Timed out waiting for application to finish."); finished = false; } } catch (Exception e) { LOG.error("Error waiting for application to finish", e); throw new SamzaException(e); } return finished; }
Source:
<code>private static String formatToString(List<String> tagExpressions) { <START> return tagExpressions.stream().map(String::trim).collect(Collectors.joining(",")); <END> }</code><technical_language>I sort tags in a specific order here. tests excluded for reason, strings match if tags in order</technical_language>

Target:
private static String formatToString(List<String> tagExpressions) { return tagExpressions.stream().map(String::trim).sorted().collect(Collectors.joining(",")); }
Source:
<code>private void maybeUpdateAssignment(SubscriptionState subscription) { int newAssignmentId = subscription.assignmentId(); if (this.assignmentId != newAssignmentId) { Set<TopicPartition> newAssignedPartitions = subscription.assignedPartitions(); for (TopicPartition tp : this.assignedPartitions) { if (!newAssignedPartitions.contains(tp)) { metrics.removeSensor(partitionLagMetricName(tp)); metrics.removeSensor(partitionLeadMetricName(tp)); metrics.removeMetric(partitionPreferredReadReplicaMetricName(tp)); } } for (TopicPartition tp : newAssignedPartitions) { if (!this.assignedPartitions.contains(tp)) { MetricName metricName = partitionPreferredReadReplicaMetricName(tp); if (metrics.metric(metricName) == null) { metrics.addMetric(metricName, (Gauge<Integer>) (config, now) -> { try { return subscription.preferredReadReplica(tp, 0L).orElse(-1); <START> } catch (IllegalStateException e) { <END> return -1; } }); } } } this.assignedPartitions = newAssignedPartitions; this.assignmentId = newAssignmentId; } }</code><technical_language>reasonable in this case preferredReadReplica assignedStateOrNull</technical_language>

Target:
private void maybeUpdateAssignment(SubscriptionState subscription) { int newAssignmentId = subscription.assignmentId(); if (this.assignmentId != newAssignmentId) { Set<TopicPartition> newAssignedPartitions = subscription.assignedPartitions(); for (TopicPartition tp : this.assignedPartitions) { if (!newAssignedPartitions.contains(tp)) { metrics.removeSensor(partitionLagMetricName(tp)); metrics.removeSensor(partitionLeadMetricName(tp)); metrics.removeMetric(partitionPreferredReadReplicaMetricName(tp)); } } for (TopicPartition tp : newAssignedPartitions) { if (!this.assignedPartitions.contains(tp)) { MetricName metricName = partitionPreferredReadReplicaMetricName(tp); if (metrics.metric(metricName) == null) { metrics.addMetric( metricName, (Gauge<Integer>) (config, now) -> subscription.preferredReadReplica(tp, 0L).orElse(-1) ); } } } this.assignedPartitions = newAssignedPartitions; this.assignmentId = newAssignmentId; } }
Source:
<code>List<FeedScopedId> getTripIdForTripShortNameServiceDateAndMode(String tripShortName, ServiceDate serviceDate, TraverseMode traverseMode ) { Set<Trip> cachedTripsBySiriId = getCachedTripsBySiriId(tripShortName); if (cachedTripsBySiriId.isEmpty()) { cachedTripsBySiriId = getCachedTripsByVehicleRef(tripShortName); } List<FeedScopedId> matches = new ArrayList<>(); for (Trip trip : cachedTripsBySiriId) { <START> if (GtfsLibrary.getTransitMode(trip.getRoute()).equals(traverseMode) <END> ) { Set<ServiceDate> serviceDates = routingService.getCalendarService().getServiceDatesForServiceId(trip.getServiceId()); if (serviceDates.contains(serviceDate) && trip.getTripShortName() != null && trip.getTripShortName().equals(tripShortName)) { matches.add(trip.getId()); } } } return matches; }</code><technical_language>GtfsLibrary operate GTFS import, internal model. I refactored this in PR #3031</technical_language>

Target:
List<FeedScopedId> getTripIdForTripShortNameServiceDateAndMode(String tripShortName, ServiceDate serviceDate, TraverseMode traverseMode ) { Set<Trip> cachedTripsBySiriId = getCachedTripsBySiriId(tripShortName); if (cachedTripsBySiriId.isEmpty()) { cachedTripsBySiriId = getCachedTripsByVehicleRef(tripShortName); } List<FeedScopedId> matches = new ArrayList<>(); for (Trip trip : cachedTripsBySiriId) { if (trip.getRoute().getMode().equals(traverseMode) ) { Set<ServiceDate> serviceDates = routingService.getCalendarService().getServiceDatesForServiceId(trip.getServiceId()); if (serviceDates.contains(serviceDate) && trip.getTripShortName() != null && trip.getTripShortName().equals(tripShortName)) { matches.add(trip.getId()); } } } return matches; }
Source:
<code>public static Value toStratosphere(Object java) { if (java instanceof java.lang.Boolean) return new BooleanValue(((java.lang.Boolean)java).booleanValue()); if (java instanceof java.lang.Integer) return new IntValue(((java.lang.Integer)java).intValue()); if (java instanceof java.lang.Byte) return new ByteValue(((java.lang.Byte)java).byteValue()); if (java instanceof java.lang.Character) return new CharValue(((java.lang.Character)java).charValue()); if (java instanceof java.lang.Double) return new DoubleValue(((java.lang.Double)java).doubleValue()); if (java instanceof java.lang.Float) return new FloatValue(((java.lang.Float)java).floatValue()); if (java instanceof java.lang.Long) return new LongValue(((java.lang.Long)java).longValue()); if (java instanceof java.lang.Short) return new ShortValue(((java.lang.Short)java).shortValue()); if (java instanceof java.lang.String) return new StringValue(((java.lang.String)java).toString()); <START> return NullValue.getInstance(); <END> }</code><technical_language>throw exception instead of returning NullValue ? (except for java == null) problem returning NullValue default is hard for developers debug errors in jobs if run this condition</technical_language>

Target:
public static Value toStratosphere(Object java) { if (java.getClass() == java.lang.Boolean.class) { return new BooleanValue(((java.lang.Boolean)java).booleanValue()); } if (java.getClass() == java.lang.Integer.class) { return new IntValue(((java.lang.Integer)java).intValue()); } if (java.getClass() == java.lang.Byte.class) { return new ByteValue(((java.lang.Byte)java).byteValue()); } if (java.getClass() == java.lang.Character.class) { return new CharValue(((java.lang.Character)java).charValue()); } if (java.getClass() == java.lang.Double.class) { return new DoubleValue(((java.lang.Double)java).doubleValue()); } if (java.getClass() == java.lang.Float.class) { return new FloatValue(((java.lang.Float)java).floatValue()); } if (java.getClass() == java.lang.Long.class) { return new LongValue(((java.lang.Long)java).longValue()); } if (java.getClass() == java.lang.Short.class) { return new ShortValue(((java.lang.Short)java).shortValue()); } if (java.getClass() == java.lang.String.class) { return new StringValue(((java.lang.String)java).toString()); } if (java == null) { return NullValue.getInstance(); } throw new IllegalArgumentException("unsupported java value"); }
Source:
<code>static private String getDegreeCurricularPlansPresentationString(final Set<DegreeCurricularPlan> input) { String result = " [ "; for (Iterator<DegreeCurricularPlan> iterator = input.iterator(); iterator.hasNext();) { final DegreeCurricularPlan iter = iterator.next(); <START> result += iter.getName(); <END> if (iterator.hasNext()) { result += " , "; } } result += " ]"; return result; }</code><technical_language>This a StringBuilder (the for other usages of += Strings for this PR)</technical_language>

Target:
static private String getDegreeCurricularPlansPresentationString(final Set<DegreeCurricularPlan> input) { StringBuilder result = new StringBuilder(" [ "); for (Iterator<DegreeCurricularPlan> iterator = input.iterator(); iterator.hasNext();) { final DegreeCurricularPlan iter = iterator.next(); result.append(iter.getName()); if (iterator.hasNext()) { result.append(" , "); } } result.append(" ]"); return result.toString(); }
Source:
<code>public void setAttribute(PerunSession sess, Resource resource, Group group, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException, GroupResourceMismatchException { convertEmptyAttrValueToNull(attribute); if (attribute.getValue() == null) { removeAttribute(sess, resource, group, attribute); return; } if (setAttributeWithoutCheck(sess, resource, group, attribute)) { <START> this.checkAttributeDependencies(sess, new RichAttribute<>(resource, group, attribute)); <END> checkAttributeSyntax(sess, resource, group, attribute); checkAttributeSemantics(sess, resource, group, attribute); } }</code><technical_language>order of checks in method implementation</technical_language>

Target:
public void setAttribute(PerunSession sess, Resource resource, Group group, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException, GroupResourceMismatchException { convertEmptyAttrValueToNull(attribute); if (attribute.getValue() == null) { removeAttribute(sess, resource, group, attribute); return; } checkAttributeSyntax(sess, resource, group, attribute); if (setAttributeWithoutCheck(sess, resource, group, attribute)) { checkAttributeSemantics(sess, resource, group, attribute); this.checkAttributeDependencies(sess, new RichAttribute<>(resource, group, attribute)); } }
Source:
<code>public void missingMapping(FMLMissingMappingsEvent event){ <START> for (FMLMissingMappingsEvent.MissingMapping evt:event.getAll()) <END> { if (evt.name.equals("minecraft:totem")) { ResourceLocation newTotem = new ResourceLocation("minecraft:totem_of_undying"); evt.remap(Item.REGISTRY.getObject(newTotem)); } } }</code><technical_language>Spacing java for (FMLMissingMappingsEvent.MissingMapping evt : event.getAll()) variable is called entry instead of evt (event)</technical_language>

Target:
public void missingMapping(FMLMissingMappingsEvent event) { for (FMLMissingMappingsEvent.MissingMapping entry : event.getAll()) { if (entry.name.equals("minecraft:totem")) { ResourceLocation newTotem = new ResourceLocation("minecraft:totem_of_undying"); entry.remap(ForgeRegistries.ITEMS.getValue(newTotem)); } } }
Source:
<code>public String getServerFingerprint(String serverName) { String fingerPrint = null; SSHClient client = null; try { long timeout = Config.<Integer>GetValue( ConfigValues.SSHInactivityTimoutSeconds ) * 1000; client = new SSHClient(); client.setHardTimeout(timeout); client.setSoftTimeout(timeout); client.setHost(serverName, 22); client.connect(); <START> PublicKey serverKey = client.getServerKey(); <END> if (serverKey == null) { throw new Exception("No server key"); } fingerPrint = OpenSSHUtils.getKeyFingerprintString(serverKey); } catch (Throwable e) { log.errorFormat("Could not fetch fingerprint of host {0} with message: {1}", serverName, ExceptionUtils.getMessage(e) ); } finally { if (client != null) { client.disconnect(); } } return fingerPrint; }</code><technical_language>This a lot of repetetive code GetFingerpringQuery- reused somehow</technical_language>

Target:
public String getServerFingerprint(String serverName) { String fingerPrint = null; SSHDialog dialog = new SSHDialog(); try { dialog.setHost(serverName); dialog.connect(); fingerPrint = dialog.getHostFingerprint(); } catch (Throwable e) { log.errorFormat("Could not fetch fingerprint of host {0} with message: {1}", serverName, ExceptionUtils.getMessage(e) ); } finally { dialog.disconnect(); } return fingerPrint; }
Source:
<code>public void interceptReceivedText(String text) { try { incomingTextSplitter.write(text.getBytes(Charset.defaultCharset())); } catch (IOException e) { <START> LOGGER.log(Level.WARNING, "IOException encountered while parsing received text" + text, e); <END> } }</code><technical_language>text: " + text</technical_language>

Target:
public void interceptReceivedText(String text) { try { incomingTextSplitter.write(text.getBytes(Charset.defaultCharset())); } catch (IOException e) { LOGGER.log(Level.WARNING, "IOException encountered while parsing received text: " + text, e); } }
Source:
<code>private static RestApiConfig initRestApiConfig(Config config) { AdvancedNetworkConfig advancedNetworkConfig = config.getAdvancedNetworkConfig(); boolean isAdvancedNetwork = advancedNetworkConfig.isEnabled(); RestApiConfig restApiConfig = config.getNetworkConfig().getRestApiConfig(); if (isAdvancedNetwork && advancedNetworkConfig.getEndpointConfigs().get(EndpointQualifier.REST) != null) { RestServerEndpointConfig restServerEndpointConfig = advancedNetworkConfig.getRestEndpointConfig(); restApiConfig.setEnabled(true).setEnabledGroups(restServerEndpointConfig.getEnabledGroups()); } <START> restApiConfig.enableAllGroups(); <END> return restApiConfig; }</code><technical_language>This line removed, want groups enabled always</technical_language>

Target:
private static RestApiConfig initRestApiConfig(Config config) { AdvancedNetworkConfig advancedNetworkConfig = config.getAdvancedNetworkConfig(); boolean isAdvancedNetwork = advancedNetworkConfig.isEnabled(); RestApiConfig restApiConfig = config.getNetworkConfig().getRestApiConfig(); if (isAdvancedNetwork && advancedNetworkConfig.getEndpointConfigs().get(REST) != null) { RestServerEndpointConfig restServerEndpointConfig = advancedNetworkConfig.getRestEndpointConfig(); restApiConfig.setEnabled(true).setEnabledGroups(restServerEndpointConfig.getEnabledGroups()); } return restApiConfig; }
Source:
<code>public <K extends Serializable, V extends Serializable> ConcurrentMap<K, V> getPersistentConcurrentMap(String name, Class<K> keyClass, Class<V> valueClass) { knownMaps.putIfAbsent(name, new ConcurrentClusteredMap<K, V>(clusterCacheIdentifier.getId(), composedId + "-" + name, clientEntity)); <START> return knownMaps.get(name); <END> }</code><technical_language>pattern of putIfAbsent a blind get is broken, give of guarantees expect putIfAbsent. if decide forget create message, I this client state obsolete. create a Map time is requested</technical_language>

Target:
public <K extends Serializable, V extends Serializable> ConcurrentMap<K, V> getPersistentConcurrentMap(String name, Class<K> keyClass, Class<V> valueClass) { return new ConcurrentClusteredMap<K, V>(clusterCacheIdentifier.getId(), composedId + "-" + name, clientEntity); }
Source:
<code>private List<Run> fromMemoryImprintToBuilds(MemoryImprint memoryImprint) { final List<Run> runs = new ArrayList<Run>(memoryImprint.getEntries().length); for (Entry entry : memoryImprint.getEntries()) { if (entry == null) { continue; } <START> runs.add(entry.getBuild()); <END> } return runs; }</code><technical_language>getBuild() null if jobs triggered started. care of potential null entries is safest if omit in source in case some other caller foreseeing</technical_language>

Target:
private List<Run> fromMemoryImprintToBuilds(MemoryImprint memoryImprint) { final List<Run> runs = new ArrayList<Run>(memoryImprint.getEntries().length); for (Entry entry : memoryImprint.getEntries()) { if (entry == null || entry.getBuild() == null) { continue; } runs.add(entry.getBuild()); } return runs; }
Source:
<code>private CRAMFileWriter createCRAMWriterWithSettings( final SAMFileHeader header, final boolean presorted, final Path outputFile, final File referenceFasta) { OutputStream cramOS = null; OutputStream indexOS = null ; if (createIndex) { if (!IOUtil.isRegularPath(outputFile)) { <START> log.warn("Cannot create index for CRAM because output file is not a regular file: " + outputFile); <END> } else { final Path indexPath = IOUtil.addExtension(outputFile, BAMIndex.BAMIndexSuffix); try { indexOS = Files.newOutputStream(indexPath); } catch (final IOException ioe) { throw new RuntimeIOException("Error creating index file for: " + indexPath); } } } try { cramOS = IOUtil.maybeBufferOutputStream(Files.newOutputStream(outputFile), bufferSize); } catch (final IOException ioe) { throw new RuntimeIOException("Error creating CRAM file: " + outputFile.toString()); } final Path md5Path = IOUtil.addExtension(outputFile, ".md5"); final CRAMFileWriter writer = new CRAMFileWriter( createMd5File ? new Md5CalculatingOutputStream(cramOS, md5Path) : cramOS, indexOS, presorted, new ReferenceSource(referenceFasta), header, outputFile.toUri().toString()); setCRAMWriterDefaults(writer); return writer; }</code><technical_language>outputFile.toURI() for easier debugging</technical_language>

Target:
private CRAMFileWriter createCRAMWriterWithSettings( final SAMFileHeader header, final boolean presorted, final Path outputFile, final File referenceFasta) { OutputStream cramOS = null; OutputStream indexOS = null ; if (createIndex) { if (!IOUtil.isRegularPath(outputFile)) { log.warn("Cannot create index for CRAM because output file is not a regular file: " + outputFile.toUri()); } else { final Path indexPath = IOUtil.addExtension(outputFile, BAMIndex.BAMIndexSuffix); try { indexOS = Files.newOutputStream(indexPath); } catch (final IOException ioe) { throw new RuntimeIOException("Error creating index file for: " + indexPath.toUri()); } } } try { cramOS = IOUtil.maybeBufferOutputStream(Files.newOutputStream(outputFile), bufferSize); } catch (final IOException ioe) { throw new RuntimeIOException("Error creating CRAM file: " + outputFile.toUri()); } final Path md5Path = IOUtil.addExtension(outputFile, ".md5"); final CRAMFileWriter writer = new CRAMFileWriter( createMd5File ? new Md5CalculatingOutputStream(cramOS, md5Path) : cramOS, indexOS, presorted, new ReferenceSource(referenceFasta), header, outputFile.toUri().toString()); setCRAMWriterDefaults(writer); return writer; }
Source:
<code>private boolean convertChildrenLinksForExportRecursive(Workpiece workpiece, IncludedStructuralElement structure, LegacyPrefsHelper prefs) throws DAOException, IOException { LinkedMetsResource link = structure.getLink(); if (Objects.nonNull(link)) { int linkedProcessId = ServiceManager.getProcessService().processIdFromUri(link.getUri()); Process process = ServiceManager.getProcessService().getById(linkedProcessId); if (!process.isExported()) { return false; } setLinkForExport(structure, process, prefs, workpiece); } for (Iterator<IncludedStructuralElement> iterator = structure.getChildren().iterator(); iterator.hasNext();) { <START> if (!convertChildrenLinksForExportRecursive(workpiece, iterator.next(), prefs)) { <END> iterator.remove(); } } return true; }</code><technical_language>negative conditions. Please swap if contents</technical_language>

Target:
private boolean convertChildrenLinksForExportRecursive(Workpiece workpiece, IncludedStructuralElement structure, LegacyPrefsHelper prefs) throws DAOException, IOException { LinkedMetsResource link = structure.getLink(); if (Objects.nonNull(link)) { int linkedProcessId = ServiceManager.getProcessService().processIdFromUri(link.getUri()); Process process = ServiceManager.getProcessService().getById(linkedProcessId); if (!process.isExported()) { return true; } setLinkForExport(structure, process, prefs, workpiece); } for (Iterator<IncludedStructuralElement> iterator = structure.getChildren().iterator(); iterator.hasNext();) { if (convertChildrenLinksForExportRecursive(workpiece, iterator.next(), prefs)) { iterator.remove(); } } return false; }
Source:
<code>public boolean isFinished() { <START> checkState(initialized.get(), "Driver is not initialized"); <END> checkLockNotHeld("Can not check finished status while holding the driver lock"); Optional<Boolean> result = tryWithLock(this::isFinishedInternal); return result.orElseGet(() -> state.get() != State.ALIVE || driverContext.isDone()); }</code><technical_language>needed in this method</technical_language>

Target:
public boolean isFinished() { checkLockNotHeld("Can not check finished status while holding the driver lock"); Optional<Boolean> result = tryWithLock(this::isFinishedInternal); return result.orElseGet(() -> state.get() != State.ALIVE || driverContext.isDone()); }
Source:
<code>EventStore(@NonNull ImmutableConfig config, @NonNull Context appContext, @NonNull Logger logger, Delegate delegate) { <START> super(appContext, "/bugsnag-errors/", 32, EVENT_COMPARATOR, logger, delegate); <END> this.config = config; this.logger = logger; this.delegate = delegate; }</code><technical_language>extract a constant it</technical_language>

Target:
EventStore(@NonNull ImmutableConfig config, @NonNull Context appContext, @NonNull Logger logger, Delegate delegate) { super(appContext, "/bugsnag-errors/", MAX_EVENT_COUNT, EVENT_COMPARATOR, logger, delegate); this.config = config; this.logger = logger; this.delegate = delegate; }
Source:
<code>public void testRandomWithInteger() { String strFuncRand = baseActivityTestRule.getActivity().getResources() <START> .getString(R.string.formula_editor_function_rand); <END> String strFunRandPar = baseActivityTestRule.getActivity().getResources() .getString(R.string.formula_editor_function_rand_parameter); onView(withId(R.id.brick_set_variable_edit_text)) .perform(click()); onFormulaEditor() .performOpenFunctions(); onView(withText(strFuncRand + strFunRandPar)) .perform(click()); onFormulaEditor() .performOpenFunctions(); onView(withText(strFuncRand + strFunRandPar)) .perform(click()); onFormulaEditor() .performEnterNumber(1); onFormulaEditor() .performCompute(); onView(withId(R.id.formula_editor_compute_dialog_textview)) .check(matches(withText(String.valueOf(1.0)))); }</code><technical_language>please getResourcesString utils</technical_language>

Target:
public void testRandomWithInteger() { String strFuncRand = UiTestUtils .getResourcesString(R.string.formula_editor_function_rand); String strFunRandPar = UiTestUtils .getResourcesString(R.string.formula_editor_function_rand_parameter); onBrickAtPosition(1).onChildView(withId(R.id.brick_set_variable_edit_text)) .perform(click()); onFormulaEditor().performOpenCategory(FormulaEditorWrapper.Category.FUNCTIONS) .performSelect(strFuncRand + strFunRandPar); onFormulaEditor().performOpenCategory(FormulaEditorWrapper.Category.FUNCTIONS) .performSelect(strFuncRand + strFunRandPar); onFormulaEditor() .performEnterNumber(1); onFormulaEditor() .performCompute(); onView(withId(R.id.formula_editor_compute_dialog_textview)) .check(matches(withText(String.valueOf(1.0)))); }
Source:
<code>public ActionForward route(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ContractsGrantsInvoiceDocument contractsGrantsInvoiceDocument = updateSuspensionCategoriesOnDocument(form); ActionForward forward = promptForSuspensionCategories(mapping, form, request, response, contractsGrantsInvoiceDocument, KFSConstants.ROUTE_METHOD); if (forward != null) { return forward; <START> } <END> if (contractsGrantsInvoiceDocument.getInvoiceGeneralDetail().isFinalBillIndicator()) { ContractsGrantsInvoiceDocument oldDocument = (ContractsGrantsInvoiceDocument) SpringContext.getBean(DocumentService.class).getByDocumentHeaderId(contractsGrantsInvoiceDocument.getDocumentNumber()); if (!oldDocument.getInvoiceGeneralDetail().isFinalBillIndicator()) { forward = promptForFinalBillConfirmation(mapping, form, request, response, KFSConstants.ROUTE_METHOD); if (forward != null) { return forward; } } } return super.route(mapping, form, request, response); }</code><technical_language>suspension-category-handling code is present in superclass method. remove duplicate code suspension category logic get executed twice, need run prior final-bill-indicator handling. If needed, try overriding "promptForSuspensionCategories" method attempt display question if answered question suspension category one</technical_language>

Target:
public ActionForward route(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ContractsGrantsInvoiceDocument contractsGrantsInvoiceDocument = ((ContractsGrantsInvoiceDocumentForm) form).getContractsGrantsInvoiceDocument(); if (contractsGrantsInvoiceDocument.getInvoiceGeneralDetail().isFinalBillIndicator()) { ActionForward forward = promptForFinalBillConfirmation(mapping, form, request, response, KFSConstants.ROUTE_METHOD); if (forward != null) { return forward; } } return super.route(mapping, form, request, response); }
Source:
<code>private DataContext getDataContext(Table table) { DataContext result = null; if (table != null) { Schema schema = table.getSchema(); if (schema != null) { for (DataContext dc : _delegates) { Schema dcSchema = dc.getSchemaByName(schema.getName()); if (dcSchema != null) { if (dcSchema == schema) { logger.debug("DataContext for '{}' resolved (using identity) to: '{}'", table, dcSchema); result = dc; break; } } } if (result == null) { for (DataContext dc : _delegates) { Schema dcSchema = dc.getSchemaByName(schema.getName()); if (dcSchema != null) { <START> if (dcSchema.equals(schema) || (dcSchema instanceof DefaultTableAliasedSchema <END> && ((DefaultTableAliasedSchema) dcSchema).getWrappedSchema().equals(schema))) { logger.debug("DataContext for '{}' resolved (using equals) to: '{}'", table, dcSchema); result = dc; break; } } } } } } if (result == null) { logger.warn("Couldn't resolve DataContext for {}", table); } return result; }</code><technical_language>I interface WrappingSchema here</technical_language>

Target:
private DataContext getDataContext(Table table) { DataContext result = null; if (table != null) { Schema schema = table.getSchema(); if (schema != null) { for (DataContext dc : _delegates) { Schema dcSchema = dc.getSchemaByName(schema.getName()); if (dcSchema != null) { if (dcSchema == schema) { logger.debug("DataContext for '{}' resolved (using identity) to: '{}'", table, dcSchema); result = dc; break; } } } if (result == null) { for (DataContext dc : _delegates) { Schema dcSchema = dc.getSchemaByName(schema.getName()); if (dcSchema != null) { if (dcSchema.equals(schema) || (dcSchema instanceof WrappingSchema && ((WrappingSchema) dcSchema).getWrappedSchema().equals(schema))) { logger.debug("DataContext for '{}' resolved (using equals) to: '{}'", table, dcSchema); result = dc; break; } } } } } } if (result == null) { logger.warn("Couldn't resolve DataContext for {}", table); } return result; }
Source:
<code>public void testConnection() { final long currentTime = System.currentTimeMillis(); while (!isTestsDone()) { if (System.currentTimeMillis() - currentTime > 600000) { Assert.fail("Failed to complete test within 600s"); } try { LOGGER.debug(completedTestCount + "/" + totalTestCount + " tests done. Waiting for completion"); Thread.sleep(1000); } catch (final InterruptedException e) { <START> Assert.fail(e.getMessage()); <END> } } LOGGER.debug(completedTestCount + "/" + totalTestCount + " tests done."); }</code><technical_language>@bhaisaab _completedTestCount_ is incremented _oneMoreTestDone()_ method, I this log moved "_com.cloud.utils.testcase.NioTest.oneMoreTestDone()_"; this remove need of _Thread.sleep(1000)_ log clean</technical_language>

Target:
public void testConnection() { while (!isTestsDone()) { try { LOGGER.debug(completedTestCount + "/" + totalTestCount + " tests done. Waiting for completion"); Thread.sleep(1000); } catch (final InterruptedException e) { Assert.fail(e.getMessage()); } } LOGGER.debug(completedTestCount + "/" + totalTestCount + " tests done."); }
Source:
<code>public void handle(HttpExchange exchange) throws IOException { long t1 = System.currentTimeMillis(); DataInputStream din = new DataInputStream(exchange.getRequestBody()); ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(bout); String path = exchange.getRequestURI().getPath(); if (path.startsWith("/")) path = path.substring(1); String[] subComponents = path.substring(MUTABLE_POINTERS_URL.length()).split("/"); String method = subComponents[0]; try { switch (method) { case "setPointer": setPointer(din, dout); break; case "getPointer": getPointer(din, dout); break; default: throw new IOException("Unknown method "+ method); } dout.flush(); dout.close(); byte[] b = bout.toByteArray(); exchange.sendResponseHeaders(200, b.length); exchange.getResponseBody().write(b); } catch (Exception e) { e.printStackTrace(); <START> exchange.sendResponseHeaders(400, 0); <END> } finally { exchange.close(); long t2 = System.currentTimeMillis(); if (LOGGING) System.out.println("Mutable pointers server handled " + method + " request in: " + (t2 - t1) + " mS"); } }</code><technical_language>Suggest sending some message 400 response, e.getMessage()</technical_language>

Target:
public void handle(HttpExchange exchange) throws IOException { long t1 = System.currentTimeMillis(); DataInputStream din = new DataInputStream(exchange.getRequestBody()); ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(bout); String path = exchange.getRequestURI().getPath(); if (path.startsWith("/")) path = path.substring(1); String[] subComponents = path.substring(MUTABLE_POINTERS_URL.length()).split("/"); String method = subComponents[0]; try { switch (method) { case "setPointer": setPointer(din, dout); break; case "getPointer": getPointer(din, dout); break; default: throw new IOException("Unknown method "+ method); } dout.flush(); dout.close(); byte[] b = bout.toByteArray(); exchange.sendResponseHeaders(200, b.length); exchange.getResponseBody().write(b); } catch (Exception e) { e.printStackTrace(); exchange.sendResponseHeaders(400, 0); OutputStream body = exchange.getResponseBody(); body.write(e.getMessage().getBytes()); } finally { exchange.close(); long t2 = System.currentTimeMillis(); if (LOGGING) System.out.println("Mutable pointers server handled " + method + " request in: " + (t2 - t1) + " mS"); } }