auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void executeVmCommand() { resourceManager.getVmManager(getVmId()).getStatistics().setMigrationProgressPercent(0); <START> try { setSucceeded(initVdss() && perform()); } catch (Exception e) { setSucceeded(false); } <END> if (!getSucceeded()) { cleanupPassthroughVnics(getDestinationVdsId()); } }</code><technical_language>understanding this code some more now: - seems, if perform() is called, runningFailed() called in case of error to: 1) #232 catch Throwable, log it!, proceed running failed. cleanupPassthroughVnics done withing runningFailed method. 2) this code needs broken. Usage of && nice at, wrong. need call cleanupPassthroughVnics if initVdss failed, call runningFailed, run. call cleanup twice. this method like: try { if (!initVdss()) return; } catch (Throwable) { cleanupPass return; } perform();</technical_language>

Target:
protected void executeVmCommand() { getVmManager().getStatistics().setMigrationProgressPercent(0); try { setSucceeded(initVdss() && perform()); } catch (Exception e) { setSucceeded(false); } if (!getSucceeded()) { cleanupPassthroughVnics(getDestinationVdsId()); } }
Source:
<code>private static void testHighLevelEncodeString(String s, String expectedBits) { BitArray bits = new HighLevelEncoder(s.getBytes(StandardCharsets.ISO_8859_1)).encode(); String receivedBits = stripSpace(bits.toString()); assertEquals("highLevelEncode() failed for input string: " + s, stripSpace(expectedBits), receivedBits); try { assertEquals(s, Decoder.highLevelDecode(toBooleanArray(bits))); <START> } catch (FormatException e) { <END> } }</code><technical_language>method throw FormatException. want fail test if unexpected</technical_language>

Target:
private static void testHighLevelEncodeString(String s, String expectedBits) throws FormatException { BitArray bits = new HighLevelEncoder(s.getBytes(StandardCharsets.ISO_8859_1)).encode(); String receivedBits = stripSpace(bits.toString()); assertEquals("highLevelEncode() failed for input string: " + s, stripSpace(expectedBits), receivedBits); assertEquals(s, Decoder.highLevelDecode(toBooleanArray(bits))); }
Source:
<code>public String getMuteReason() { if (muteReason != null) { return muteReason; } <START> else { <END> return ""; } }</code><technical_language>Formatting - elses line</technical_language>

Target:
public String getMuteReason() { return muteReason; }
Source:
<code>public static GatewayConnectionConfig getDefaultConfig() { <START> return GatewayConnectionConfig.defaultConfig; <END> }</code><technical_language>return a singleton object otherwise, changing for client affect other clients too. suggestion return new GatewayConnectionConfig()</technical_language>

Target:
public static GatewayConnectionConfig getDefaultConfig() { return new GatewayConnectionConfig(); }
Source:
<code>public int hashCode() { <START> return Objects.hash(id, getSocketAddress()); <END> }</code><technical_language>host/port instead of socket address</technical_language>

Target:
public int hashCode() { return Objects.hash(id, host, port); }
Source:
<code>private void cleanupConnectionManager(ZkConnectionManager zkConnectionManager) { synchronized (_connectionManagerPool) { <START> zkConnectionManager.close(true); <END> _connectionManagerPool.remove(zkConnectionManager); } }</code><technical_language>skipIfWatched == true, close() call disconnect zkConnectionManager shared watchers exist. remove zkConnectionManager pool a proper check</technical_language>

Target:
private void cleanupConnectionManager(ZkConnectionManager zkConnectionManager) { synchronized (_connectionManagerPool) { if (zkConnectionManager.close(true)) { _connectionManagerPool.remove(zkConnectionManager); } } }
Source:
<code>public void setUp() { mWebViewOnUiThread = new <START> androidx.webkit.WebViewOnUiThread(); <END> mWebViewOnUiThread.getSettings().setJavaScriptEnabled(true); }</code><technical_language>qualify</technical_language>

Target:
public void setUp() { WebkitUtils.checkFeature(WebViewFeature.WEB_MESSAGE_LISTENER); mWebViewOnUiThread = new WebViewOnUiThread(); mWebViewOnUiThread.getSettings().setJavaScriptEnabled(true); }
Source:
<code>default BundleSpecBuilder addResourceWithCopy(Class<?> class1) { String className = class1.getName(); String path = className.replace('.', '/') + ".class"; <START> URL url = BundleSpecBuilder.class.getClassLoader() <END> .getResource(path); if (url == null) { throw new IllegalArgumentException( "Couldn't find class file for " + class1.getName() + ", possibly a synthetic class"); } addResource(path, url); return this; }</code><technical_language>this class' class loader load resource? For example, URL url = class1.getClassLoader().getResource(path);? URL url = class1.getResource(class1.getSimpleName()+".class"); class file resource is in package of class</technical_language>

Target:
default BundleSpecBuilder addResourceWithCopy(Class<?> class1) { String className = class1.getName(); String path = className.replace('.', '/') + ".class"; URL url = class1.getClassLoader() .getResource(path); if (url == null) { throw new IllegalArgumentException( "Couldn't find class file for " + className + ", possibly a synthetic class"); } addResource(path, url); return this; }
Source:
<code>public LogStatistics(String FileName, String delimeter) { this.logFile = new File(FileName); this.delimeter = delimeter; this.outputInitialized = true; <START> FileWriter fileWriter = null; <END> try { fileWriter = new FileWriter(logFile.getAbsoluteFile()); } catch (IOException e) { outputInitialized = false; e.printStackTrace(); } out = new BufferedWriter(fileWriter); }</code><technical_language>logFileWriter</technical_language>

Target:
public LogStatistics(String FileName, String delimeter) { this.logFile = new File(FileName); this.delimeter = delimeter; FileWriter logFileWriter = null; try { logFileWriter = new FileWriter(logFile.getAbsoluteFile()); } catch (IOException e) { e.printStackTrace(); return; } logFileBuffer = new BufferedWriter(logFileWriter); }
Source:
<code>public void afterClass() throws Exception { String testClassName = this.getShortClassName(); <START> System.out.println("AfterClass: " + testClassName + " of TestMaxNumberOfAttempsMasterSwitch called."); <END> super.afterClass(); }</code><technical_language>TestHelper.getTestMethodName() TestHelper.getTestClassName</technical_language>

Target:
public void afterClass() throws Exception { super.afterClass(); }
Source:
<code>public String getRemoteFile() throws InterruptedException, IOException { if (CommonUtils.isBlank(fileName)) { logger.info(LOGGER_TAG, "no file configured"); return null; } FilePath[] src = workspace.list(fileName); if (src.length == 0) { logger.info(LOGGER_TAG, "no files found by path: '" + fileName + "'"); return null; } if (src.length > 1) { logger.info(LOGGER_TAG, "Found multiple matches. Reading first only."); } FilePath source = src[0]; int maxLength = DEFAULT_MAX_SIZE; if (!CommonUtils.isBlank(maxSize)) { maxLength = parseInt(maxSize, 10); } if (source.length() < maxLength) { maxLength = (int) source.length(); } byte[] buffer = new byte[maxLength]; InputStream stream = source.read(); IOUtils.read(stream, buffer); <START> stream.close(); <END> return new String(buffer); }</code><technical_language>a thought. want close stream in finally block perform a basic check. - try { IOUtils.read(stream, buffer); } finally { try { if (stream != null) stream.close(); } catch(IOException e) { /* ignore */ } }</technical_language>

Target:
public String getRemoteFile() throws InterruptedException, IOException { if (CommonUtils.isBlank(fileName)) { logger.info(LOGGER_TAG, "no file configured"); return null; } FilePath[] src = workspace.list(fileName); if (src.length == 0) { logger.info(LOGGER_TAG, "no files found by path: '" + fileName + "'"); return null; } if (src.length > 1) { logger.info(LOGGER_TAG, "Found multiple matches. Reading first only."); } FilePath source = src[0]; int maxLength = DEFAULT_MAX_SIZE; if (!CommonUtils.isBlank(maxSize)) { maxLength = parseInt(maxSize, 10); } if (source.length() < maxLength) { maxLength = (int) source.length(); } byte[] buffer = new byte[maxLength]; InputStream stream = source.read(); try { IOUtils.read(stream, buffer); } finally { try { if (stream != null) { stream.close(); } } catch (IOException e) { } } return new String(buffer); }
Source:
<code>public TaskExecution completeTaskExecution(long executionId, Integer exitCode, Date endTime, String exitMessage) { initialize(); validateExitInformation(executionId, exitCode, endTime); exitMessage = trimExitMessage(exitMessage); taskExecutionDao.completeTaskExecution(executionId, exitCode, endTime, exitMessage); <START> logger.info("Updating: TaskExecution with executionId="+executionId <END> + " with the following {" + "exitCode=" + exitCode + ", endTime=" + endTime + ", exitMessage='" + exitMessage + '\'' + '}'); return taskExecutionDao.getTaskExecution(executionId); }</code><technical_language>I thought this debug prevent unwanted data appearing in log</technical_language>

Target:
public TaskExecution completeTaskExecution(long executionId, Integer exitCode, Date endTime, String exitMessage) { initialize(); validateExitInformation(executionId, exitCode, endTime); exitMessage = trimExitMessage(exitMessage); taskExecutionDao.completeTaskExecution(executionId, exitCode, endTime, exitMessage); logger.debug("Updating: TaskExecution with executionId="+executionId + " with the following {" + "exitCode=" + exitCode + ", endTime=" + endTime + ", exitMessage='" + exitMessage + '\'' + '}'); return taskExecutionDao.getTaskExecution(executionId); }
Source:
<code>private void checkServerReadiness(String machineName, String serverRef, String serverUrl) throws InternalInfrastructureException { if (!livenessChecksPaths.containsKey(serverRef)) { return; } String livenessCheckPath = livenessChecksPaths.get(serverRef); URL url; try { url = UriBuilder.fromUri(serverUrl) .replacePath(livenessCheckPath) .build() .toURL(); } catch (MalformedURLException e) { throw new InternalInfrastructureException("Server " + serverRef + " URL is invalid. Error: " + e.getLocalizedMessage(), e); } long readinessDeadLine = System.currentTimeMillis() + 3000 * 60; while (System.currentTimeMillis() < readinessDeadLine) { LOG.info("Checking agent of machine at {}", serverRef, machineName, System.currentTimeMillis()); if (Thread.currentThread().isInterrupted()) { throw new InternalInfrastructureException("Interrupted"); } if (checkServerConnection(url)) { DockerMachine machine = startSynchronizer.getMachines().get(machineName); machine.setServerStatus(serverRef, ServerStatus.RUNNING); eventService.publish(DtoFactory.newDto(ServerStatusEvent.class) .withIdentity(DtoConverter.asDto(identity)) .withMachineName(machineName) .withServerName(serverRef) .withStatus(ServerStatus.RUNNING) .withServerUrl(serverUrl)); <START> LOG.info("Agent of machine started", serverRef, machineName); <END> return; } try { Thread.sleep(3000); } catch (InterruptedException e) { throw new InternalInfrastructureException("Interrupted"); } } }</code><technical_language>LOG.info("Server ...") i guess</technical_language>

Target:
private void checkServerReadiness(String machineName, String serverRef, String serverUrl) throws InfrastructureException { if (!livenessChecksPaths.containsKey(serverRef)) { return; } String livenessCheckPath = livenessChecksPaths.get(serverRef); URL url; try { url = UriBuilder.fromUri(serverUrl) .replacePath(livenessCheckPath) .build() .toURL(); } catch (MalformedURLException e) { throw new InternalInfrastructureException("Server " + serverRef + " URL is invalid. Error: " + e.getLocalizedMessage(), e); } long readinessDeadLine = System.currentTimeMillis() + 3000 * 60; while (System.currentTimeMillis() < readinessDeadLine) { LOG.info("Checking agent of machine at {}", serverRef, machineName, System.currentTimeMillis()); checkStartInterruption(); if (isHttpConnectionSucceed(url)) { DockerMachine machine = startSynchronizer.getMachines().get(machineName); machine.setServerStatus(serverRef, ServerStatus.RUNNING); eventService.publish(DtoFactory.newDto(ServerStatusEvent.class) .withIdentity(DtoConverter.asDto(identity)) .withMachineName(machineName) .withServerName(serverRef) .withStatus(ServerStatus.RUNNING) .withServerUrl(serverUrl)); LOG.info("Server of machine started", serverRef, machineName); return; } try { Thread.sleep(3000); } catch (InterruptedException e) { throw new InternalInfrastructureException("Interrupted"); } } }
Source:
<code><T extends Operation, R> R processWithTimeout( long timeout, CatalogFunction<T, R> catalog, T request) <START> throws InterruptedException, IngestTimeoutException, ExecutionException { <END> LOGGER.info("Running catalog operation with timeout of {}", timeout); Subject subject = SecurityUtils.getSubject(); if (subject instanceof ddf.security.Subject) { request .getProperties() .put(SecurityConstants.SECURITY_SUBJECT, (ddf.security.Subject) subject); } try { List<Future<R>> futures = executor.invokeAll( Collections.singleton((Callable<R>) () -> catalog.ingest(request)), timeout, TimeUnit.MILLISECONDS); if (!futures.get(0).isDone()) { LOGGER.warn("Ingest task was canceled due to timeout"); throw new IngestTimeoutException("The ingest request timed out 1"); } return futures.get(0).get(); } catch (CancellationException e) { throw new IngestTimeoutException("The ingest request timed out 2"); } }</code><technical_language>This occur enough fill logs info level, right</technical_language>

Target:
<T extends Operation, R> R processWithTimeout( long timeout, CatalogFunction<T, R> catalog, T request) throws InterruptedException, IngestTimeoutException, ExecutionException { LOGGER.trace("Running catalog operation with timeout of {}", timeout); Subject subject = SecurityUtils.getSubject(); if (subject instanceof ddf.security.Subject) { request .getProperties() .put(SecurityConstants.SECURITY_SUBJECT, (ddf.security.Subject) subject); } try { List<Future<R>> futures = executor.invokeAll( Collections.singleton((Callable<R>) () -> catalog.ingest(request)), timeout, TimeUnit.MILLISECONDS); if (!futures.get(0).isDone()) { LOGGER.warn("Ingest task was canceled due to timeout"); throw new IngestTimeoutException("The ingest request timed out 1"); } return futures.get(0).get(); } catch (CancellationException e) { throw new IngestTimeoutException("The ingest request timed out 2"); } }
Source:
<code>static List<Card> buildCards(@NonNull List<Announcement> announcements) { List<Card> cards = new ArrayList<>(); String country = getGeoIPCountry(); Date now = new Date(); for (Announcement announcement : announcements) { if (shouldShow(announcement, country, now)) { switch <START> (announcement.type()) <END> { case "survey": cards.add(new SurveyCard(announcement)); break; case "fundraising": cards.add(new FundraisingCard(announcement)); break; default: cards.add(new AnnouncementCard(announcement)); break; } } } return cards; }</code><technical_language>Optional: consider adding enum for this isolate unmarshalling concerns magic strings</technical_language>

Target:
static List<Card> buildCards(@NonNull List<Announcement> announcements) { List<Card> cards = new ArrayList<>(); String country = GeoUtil.getGeoIPCountry(); Date now = new Date(); for (Announcement announcement : announcements) { if (shouldShow(announcement, country, now)) { switch (announcement.type()) { case Announcement.SURVEY: cards.add(new FundraisingCard(announcement)); break; case Announcement.FUNDRAISING: cards.add(new FundraisingCard(announcement)); break; default: cards.add(new AnnouncementCard(announcement)); break; } } } return cards; }
Source:
<code>private void writeElementValue(Object value, PropertyDefinition propDef) throws XMLStreamException { if (value == null) { if (!propDef.getConstraint(NillableFlag.class).isEnabled()) { log.warn("Non-nillable element " + propDef.getName() + " is null"); } else { writer.writeAttribute(SCHEMA_INSTANCE_NS, "nil", "true"); } } else { TypeDefinition propType = propDef.getPropertyType(); if (value instanceof Iterable && List.class .isAssignableFrom(propType.getConstraint(Binding.class).getBinding()) && propType.getConstraint(ElementType.class).getBinding() != null) { boolean first = true; for (Object element : ((Iterable<?>) value)) { if (first) { first = false; } else { writer.writeCharacters(" "); } writer.writeCharacters(SimpleTypeUtil.convertToXml(element, propType.getConstraint(ElementType.class).getDefinition())); } } else if (value instanceof Double || value instanceof Float || value instanceof BigDecimal) { <START> String representation = DecimalFormatUtil.applyFormatter((Number) value, <END> getDecimalFormatter()); writer.writeCharacters( SimpleTypeUtil.convertToXml(representation, propDef.getPropertyType())); } else { writer.writeCharacters( SimpleTypeUtil.convertToXml(value, propDef.getPropertyType())); } } }</code><technical_language>I continue XML specific conversion if format is configured (instead of String.valueOf(...))</technical_language>

Target:
private void writeElementValue(Object value, PropertyDefinition propDef) throws XMLStreamException { if (value == null) { if (!propDef.getConstraint(NillableFlag.class).isEnabled()) { log.warn("Non-nillable element " + propDef.getName() + " is null"); } else { writer.writeAttribute(SCHEMA_INSTANCE_NS, "nil", "true"); } } else { TypeDefinition propType = propDef.getPropertyType(); if (value instanceof Iterable && List.class .isAssignableFrom(propType.getConstraint(Binding.class).getBinding()) && propType.getConstraint(ElementType.class).getBinding() != null) { boolean first = true; for (Object element : ((Iterable<?>) value)) { if (first) { first = false; } else { writer.writeCharacters(" "); } writer.writeCharacters(SimpleTypeUtil.convertToXml(element, propType.getConstraint(ElementType.class).getDefinition())); } } else if (getDecimalFormatter() != null && (value instanceof Double || value instanceof Float || value instanceof BigDecimal)) { String representation = DecimalFormatUtil.applyFormatter((Number) value, getDecimalFormatter()); writer.writeCharacters( SimpleTypeUtil.convertToXml(representation, propDef.getPropertyType())); } else { writer.writeCharacters( SimpleTypeUtil.convertToXml(value, propDef.getPropertyType())); } } }
Source:
<code>public void visitTable(Connection connection, String name) throws SQLException; } public interface Props { public static final String CONNECTION_KEEPALIVE_PERIOD = "connectionKeepAlivePeriod"; public static final String ID_COLUMN_LENGTH = "idColumnLength"; public static final String READER_POOL_CAPACITY = "readerPoolCapacity"; public static final String WRITER_POOL_CAPACITY = "writerPoolCapacity"; <START> public static final String DB_FIELD_TRACK_CONSTRUCTION = "dbFieldTrackConstruction"; END> }</code><technical_language>this? public static final String FIELD_CONSTRUCTION_TRACKING = "fieldConstructionTracking";</technical_language>

Target:
public void visitTable(Connection connection, String name) throws SQLException; } public interface Props { public static final String CONNECTION_KEEPALIVE_PERIOD = "connectionKeepAlivePeriod"; public static final String ID_COLUMN_LENGTH = "idColumnLength"; public static final String READER_POOL_CAPACITY = "readerPoolCapacity"; public static final String WRITER_POOL_CAPACITY = "writerPoolCapacity"; public static final String FIELD_CONSTRUCTION_TRACKING = "fieldConstructionTracking"; }
Source:
<code>private static String taggedMessagesToJson(Set<TaggedMessagesContainer> messages) { if (messages.isEmpty()) { return emptyJSON; } ObjectMapper mapper = new ObjectMapper(); try { return mapper.writeValueAsString(messages); } catch (JsonProcessingException e) { LOGGER.log(Level.WARNING, "failed to encode to JSON", messages); <START> return null; <END> } }</code><technical_language>this ui blow npe String.length()</technical_language>

Target:
private static String taggedMessagesToJson(Set<TaggedMessagesContainer> messages) { if (messages.isEmpty()) { return JSONable.EMPTY; } ObjectMapper mapper = new ObjectMapper(); try { return mapper.writeValueAsString(messages); } catch (JsonProcessingException e) { LOGGER.log(Level.WARNING, String.format("failed to encode '%s' to JSON: ", messages), e); return JSONable.EMPTY; } }
Source:
<code>public TokenAwarePolicy(LoadBalancingPolicy childPolicy) { <START> this(childPolicy, ReplicaOrdering.TOPOLOGICAL); <END> }</code><technical_language>For consistency existing (3.4.0) behavior, this ReplicaOrdering.RANDOM? Previously shuffled default, this change longer does</technical_language>

Target:
public TokenAwarePolicy(LoadBalancingPolicy childPolicy) { this(childPolicy, ReplicaOrdering.RANDOM); }
Source:
<code><START> public static Versions getVersionsInstance() { <END> return VersionsHolder.INSTANCE; }</code><technical_language>(since Versions is private do interesting it)</technical_language>

Target:
private static Versions getVersionsInstance() { return VersionsHolder.INSTANCE; }
Source:
<code>public void afterStatusChange(Job job, Status before, Status after) { if (after == Status.ERROR) { if (job.getException() != null) { LOG.error("Error", job.getException()); } } if (job.isTerminated()) { LOG.info("Job is finished", job.getId()); try { note.persist(null); } catch (IOException e) { LOG.error(e.toString(), e); } } notebookServer.broadcastNote(note); try { notebookServer.broadcastUpdateNotebookJobInfo(System.currentTimeMillis() - 5000); } catch (IOException ioe) { <START> LOG.error("can not broadcast for job manager {}", ioe.getMessage()); <END> } }</code><technical_language>LOG.error("can broadcast for job manager {}", e) instead</technical_language>

Target:
public void afterStatusChange(Job job, Status before, Status after) { if (after == Status.ERROR) { if (job.getException() != null) { LOG.error("Error", job.getException()); } } if (job.isTerminated()) { LOG.info("Job is finished", job.getId()); try { note.persist(null); } catch (IOException e) { LOG.error(e.toString(), e); } } notebookServer.broadcastNote(note); try { notebookServer.broadcastUpdateNotebookJobInfo(System.currentTimeMillis() - 5000); } catch (IOException e) { LOG.error("can not broadcast for job manager {}", e); } }
Source:
<code>default Mono<Void> subscribeToUpstream(Publisher<? extends Message<?>> upstreamPublisher) { <START> subscribeTo(upstreamPublisher); <END> return Mono.empty(); }</code><technical_language>I highly recommend subscribe returned Mono is subscribed, creating a hot publisher</technical_language>

Target:
default Mono<Void> subscribeToUpstream(Publisher<? extends Message<?>> upstreamPublisher) { return Mono.defer(() -> { subscribeTo(upstreamPublisher); return Mono.empty(); } ); }
Source:
<code>public void testGetExternalResourceInfoProvider() { final Configuration config = new Configuration(); final Map<Class<?>, Iterator<?>> plugins = new HashMap<>(); plugins.put(ExternalResourceDriverFactory.class, IteratorUtils.singletonIterator(new TestingExternalResourceDriverFactory())); final PluginManager testingPluginManagerPluginManager = new TestingPluginManager(plugins); final String driverFactoryClassName = TestingExternalResourceDriverFactory.class.getName(); config.set(ExternalResourceOptions.EXTERNAL_RESOURCE_LIST, Collections.singletonList(RESOURCE_NAME_1)); config.setLong(ExternalResourceOptions.keyWithResourceNameAndSuffix(RESOURCE_NAME_1, ExternalResourceOptions.EXTERNAL_RESOURCE_AMOUNT_SUFFIX), RESOURCE_AMOUNT_1); config.setString(ExternalResourceOptions.keyWithResourceNameAndSuffix(RESOURCE_NAME_1, ExternalResourceOptions.EXTERNAL_RESOURCE_DRIVER_FACTORY_SUFFIX), driverFactoryClassName); <START> final ExternalResourceInfoProvider externalResourceInfoProvider = ExternalResourceUtils.getExternalResourceInfoProvider(config, testingPluginManagerPluginManager); <END> assertNotNull(externalResourceInfoProvider.getExternalResources().get(RESOURCE_NAME_1)); }</code><technical_language>getExternalResourceInfoProvider a bit easier test if method a bit less. could, for example, pass in externalResourceAmountMap externalResourceDrivers. introduce internal method job. set PluginManager things. Moreover, loading of Drivers creation of externalResourceAmountMap tested other methods</technical_language>

Target:
public void testGetExternalResourceInfoProvider() { final Map<String, Long> externalResourceAmountMap = new HashMap<>(); final Map<String, ExternalResourceDriver> externalResourceDrivers = new HashMap<>(); externalResourceAmountMap.put(RESOURCE_NAME_1, RESOURCE_AMOUNT_1); externalResourceDrivers.put(RESOURCE_NAME_1, new TestingExternalResourceDriver()); final StaticExternalResourceInfoProvider externalResourceInfoProvider = (StaticExternalResourceInfoProvider) ExternalResourceUtils.createStaticExternalResourceInfoProvider(externalResourceAmountMap, externalResourceDrivers); assertNotNull(externalResourceInfoProvider.getExternalResources().get(RESOURCE_NAME_1)); }
Source:
<code>private JAXBDecoder(Builder builder) { <START> if (builder.jaxbContextFactory == null) { <END> throw new IllegalStateException("JAXBContextFactory must be non-null"); } this.jaxbContextFactory = builder.jaxbContextFactory; this.namespaceAware = builder.namespaceAware; }</code><technical_language>this in build()</technical_language>

Target:
private JAXBDecoder(Builder builder) { this.jaxbContextFactory = builder.jaxbContextFactory; this.namespaceAware = builder.namespaceAware; }
Source:
<code>protected void store(Command command, Error error) { checkNotClosed(); checkNotDefault(error); <START> CommandId id = getOrGenerateCommandId(command); <END> final CommandRecord.Builder builder = newRecordBuilder(command, ERROR, id); builder.getStatusBuilder() .setError(error); final CommandRecord record = builder.build(); write(id, record); }</code><technical_language>final</technical_language>

Target:
protected void store(Command command, Error error) { checkNotClosed(); checkNotDefault(error); final CommandId id = getOrGenerateCommandId(command); final CommandRecord.Builder builder = newRecordBuilder(command, ERROR, id); builder.getStatusBuilder() .setError(error); final CommandRecord record = builder.build(); write(id, record); }
Source:
<code><START> public static final Operator fromString(final String str) { <END> for (Operator o : Operator.values()) { if (o.value.equals(str)) { return o; } } throw new IllegalArgumentException("Value " + str + " not recognized."); }</code><technical_language>remove final... this method is static</technical_language>

Target:
public static Operator fromString(final String str) { for (Operator o : Operator.values()) { if (o.value.equals(str)) { return o; } } throw new IllegalArgumentException("Value " + str + " not recognized."); }
Source:
<code>public View getPrototypeView(Context context) { View view = View.inflate(context, R.layout.brick_play_sound, null); spinner = view.findViewById(R.id.playsound_spinner); spinnerAdapter = new SpinnerAdapterWithNewOption(context, getSoundNames()); spinner.setAdapter(spinnerAdapter); spinner.setSelection(spinnerAdapter.getPosition(sound != null ? sound.getName() : null)); <START> if (wait) { <END> ((TextView) view.findViewById(R.id.brick_play_sound_label)).setText(R.string.brick_play_sound_and_wait); } return view; }</code><technical_language>if instead of a boolean flag moving responsibility of a subclass parent classe, implement a method "setSoundBrickLabel" called everytime in getView getPrototypeView, is overridden in subclass (play wait brick), in this class, explicitely sets label play sound text</technical_language>

Target:
public View getPrototypeView(Context context) { View view = prepareView(context); spinner = findSpinner(view); spinnerAdapter = new SpinnerAdapterWithNewOption(context, getSoundNames()); spinner.setAdapter(spinnerAdapter); spinner.setSelection(spinnerAdapter.getPosition(sound != null ? sound.getName() : null)); return view; }
Source:
<code>public static String readFileAsString(String path) throws IOException { <START> log.debug("Reading file {}", path); <END> byte[] allBytes = Files.readAllBytes(Paths.get(path)); return new String(allBytes, StandardCharsets.UTF_8); }</code><technical_language>Hmm, do this? I thought a try/catch block</technical_language>

Target:
public static String readFileAsString(String path) throws IOException { try { byte[] allBytes = Files.readAllBytes(Paths.get(path)); return new String(allBytes, StandardCharsets.UTF_8); } catch (IOException ex) { throw new IOException("Unable to read file " + path, ex); } }
Source:
<code>default void inputDetail() { or(mandatory(storageDomain().id()), mandatory(storageDomain().name())); <START> or(optional(disk().name()), optional(disk().alias())); <END> }</code><technical_language>describe new optional parameters: optional(disk().diskProfile().id()) ^ is assuming support disk profile id. If allow id name, then: or(optional(disk().diskProfile().id()), optional(disk().diskProfile().name())) for quota parameter, for Move operation</technical_language>

Target:
default void inputDetail() { or(mandatory(storageDomain().id()), mandatory(storageDomain().name())); or(optional(disk().name()), optional(disk().alias())); optional(diskProfile().id()); optional(quota().id()); }
Source:
<code>private int computeSize(List<ByteBuffer> bufferList) { <START> int size = 0; <END> for (ByteBuffer buffer : bufferList) { if (buffer != null ) { size += buffer.array().length; } } return size; }</code><technical_language>avoid local variable names name class variables</technical_language>

Target:
private int computeSize(List<ByteBuffer> bufferList) { int totalSize = 0; for (ByteBuffer buffer : bufferList) { totalSize += buffer.remaining(); } return totalSize; }
Source:
<code>private void buildUnaryOperation(@Nonnull RegisterSpec destReg, @Nonnull JUnaryOperation unary) { SourcePosition unarySrcPos = RopHelper.getSourcePosition(unary); RegisterSpec srcRegisterSpec = getRegisterSpec(unary.getArg()); RegisterSpecList sources = RegisterSpecList.make(srcRegisterSpec); Rop opcode = null; switch(unary.getOp()) { case NEG: { assert unary.getType() == JPrimitiveTypeEnum.BYTE.getType() || unary.getType() == JPrimitiveTypeEnum.CHAR.getType() || unary.getType() == JPrimitiveTypeEnum.SHORT.getType() || unary.getType() == JPrimitiveTypeEnum.INT.getType() || unary.getType() == JPrimitiveTypeEnum.LONG.getType() || unary.getType() == JPrimitiveTypeEnum.FLOAT.getType() || unary.getType() == JPrimitiveTypeEnum.DOUBLE.getType(); opcode = Rops.opNeg(srcRegisterSpec); break; } case BIT_NOT: { assert unary.getType() == JPrimitiveTypeEnum.BYTE.getType() || unary.getType() == JPrimitiveTypeEnum.CHAR.getType() || unary.getType() == JPrimitiveTypeEnum.SHORT.getType() || unary.getType() == JPrimitiveTypeEnum.INT.getType() || unary.getType() == JPrimitiveTypeEnum.LONG.getType(); opcode = Rops.opNot(srcRegisterSpec); break; } case NOT: { assert unary.getType() == JPrimitiveTypeEnum.BOOLEAN.getType(); addInstruction( new PlainCstInsn( Rops.opXor(sources), unarySrcPos, destReg, sources, <START> CstInteger.make(1))); <END> return; } default: { throw new AssertionError("Unary operation not supported."); } } addInstruction(new PlainInsn(opcode, unarySrcPos, destReg, sources)); }</code><technical_language>CstBoolean.make(true) ? is safe CstBoolean line 913 represent boolean</technical_language>

Target:
private void buildUnaryOperation(@Nonnull RegisterSpec destReg, @Nonnull JUnaryOperation unary) { SourcePosition unarySrcPos = RopHelper.getSourcePosition(unary); RegisterSpec srcRegisterSpec = getRegisterSpec(unary.getArg()); RegisterSpecList sources = RegisterSpecList.make(srcRegisterSpec); Rop opcode = null; switch(unary.getOp()) { case NEG: { assert unary.getType() == JPrimitiveTypeEnum.BYTE.getType() || unary.getType() == JPrimitiveTypeEnum.CHAR.getType() || unary.getType() == JPrimitiveTypeEnum.SHORT.getType() || unary.getType() == JPrimitiveTypeEnum.INT.getType() || unary.getType() == JPrimitiveTypeEnum.LONG.getType() || unary.getType() == JPrimitiveTypeEnum.FLOAT.getType() || unary.getType() == JPrimitiveTypeEnum.DOUBLE.getType(); opcode = Rops.opNeg(srcRegisterSpec); break; } case BIT_NOT: { assert unary.getType() == JPrimitiveTypeEnum.BYTE.getType() || unary.getType() == JPrimitiveTypeEnum.CHAR.getType() || unary.getType() == JPrimitiveTypeEnum.SHORT.getType() || unary.getType() == JPrimitiveTypeEnum.INT.getType() || unary.getType() == JPrimitiveTypeEnum.LONG.getType(); opcode = Rops.opNot(srcRegisterSpec); break; } case NOT: { assert unary.getType() == JPrimitiveTypeEnum.BOOLEAN.getType(); addInstruction( new PlainCstInsn( Rops.opXor(sources), unarySrcPos, destReg, sources, CstBoolean.make(true))); return; } default: { throw new AssertionError("Unary operation not supported."); } } addInstruction(new PlainInsn(opcode, unarySrcPos, destReg, sources)); }
Source:
<code>private synchronized int purgeExpiredRecallRequests(long expirationTime, int purgeSize) { int n = new TapeRecallCatalog().purgeCatalog(expirationTime, purgeSize); if (n == 0) { <START> log.trace("No entries have been purged from tape_recall table"); <END> } else { log.info("{} entries have been purged from tape_recall table", n); } return n; }</code><technical_language>I remove if log number of entries removed, 0</technical_language>

Target:
private synchronized int purgeExpiredRecallRequests(long expirationTime, int purgeSize) { return new TapeRecallCatalog().purgeCatalog(expirationTime, purgeSize); }
Source:
<code><START> private ExternalStatus(int value) { <END> intValue = value; }</code><technical_language>s/value/id</technical_language>

Target:
private ExternalStatus(int value) { id = value; }
Source:
<code>public WorkflowVersion addAliases(@ApiParam(hidden = true) @Auth User user, @ApiParam(value = "workflow version to modify.", required = true) @PathParam("workflowVersionId") Long workflowVersionId, @ApiParam(value = "Comma-delimited list of aliases.", required = true) @QueryParam("aliases") String aliases) { <START> return workflowVersionResource.addAliases(user, workflowVersionId, aliases); <END> }</code><technical_language>need validate workflowVersionId exists</technical_language>

Target:
public WorkflowVersion addAliases(@ApiParam(hidden = true) @Auth User user, @ApiParam(value = "workflow version to modify.", required = true) @PathParam("workflowVersionId") Long workflowVersionId, @ApiParam(value = "Comma-delimited list of aliases.", required = true) @QueryParam("aliases") String aliases) { return addAliasesAndCheck(user, workflowVersionId, aliases, true); }
Source:
<code><START> protected RESTRecord findParticipant(String participantUrl) { <END> if (pendingList != null) { RecordListIterator i = new RecordListIterator(pendingList); AbstractRecord r; while ((r = i.iterate()) != null) { if (r instanceof RESTRecord) { RESTRecord rr = (RESTRecord) r; if (rr.getParticipantURI().equals(participantUrl)) return rr; } } } return null; }</code><technical_language>I this needed protected</technical_language>

Target:
private RESTRecord findParticipant(String participantUrl) { if (pendingList != null) { RecordListIterator i = new RecordListIterator(pendingList); AbstractRecord r; while ((r = i.iterate()) != null) { if (r instanceof RESTRecord) { RESTRecord rr = (RESTRecord) r; if (rr.getParticipantURI().equals(participantUrl)) return rr; } } } return null; }
Source:
<code>public ResolvedTableAlter resolve(Schema schema) throws SchemaSyncError { Database database = schema.findDatabaseOrThrow(this.database); Table oldTable = database.findTableOrThrow(this.table); Table table = oldTable.copy(); if ( newTableName != null && newDatabase != null ) { schema.findDatabaseOrThrow(this.newDatabase); <START> table.name = newTableName; <END> table.database = newDatabase; } for (ColumnMod mod : columnMods) { mod.apply(table); } if ( convertCharset != null ) { for ( StringColumnDef sc : table.getStringColumns() ) { if ( !sc.getCharset().toLowerCase().equals("binary") ) sc.setCharset(convertCharset); } } if ( this.pks != null ) { table.setPKList(this.pks); } table.setDefaultColumnCharsets(); return new ResolvedTableAlter(this.database, this.table, oldTable, table); }</code><technical_language>need check schema.getCaseSensitivity() here</technical_language>

Target:
public ResolvedTableAlter resolve(Schema schema) throws InvalidSchemaError { Database database = schema.findDatabaseOrThrow(this.database); Table oldTable = database.findTableOrThrow(this.table); Table table = oldTable.copy(); if ( newTableName != null && newDatabase != null ) { schema.findDatabaseOrThrow(this.newDatabase); if ( schema.getCaseSensitivity() == CaseSensitivity.CONVERT_TO_LOWER ) newTableName = newTableName.toLowerCase(); table.name = newTableName; table.database = newDatabase; } for (ColumnMod mod : columnMods) { mod.apply(table); } if ( convertCharset != null ) { for ( StringColumnDef sc : table.getStringColumns() ) { if ( !sc.getCharset().toLowerCase().equals("binary") ) sc.setCharset(convertCharset); } } if ( this.pks != null ) { table.setPKList(this.pks); } table.setDefaultColumnCharsets(); return new ResolvedTableAlter(this.database, this.table, oldTable, table); }
Source:
<code><START> public Validator getValidator() { <END> return createValidator( constraintValidatorManager.getDefaultConstraintValidatorFactory(), valueExtractorManager, validatorFactoryScopedContext, methodValidationConfiguration ); }</code><technical_language>related changes this PR, ValidatorFactoryImpl is cleaner, I noticed some getter methods coming interfaces. for example isFailFast(), isTraversableResolverResultCacheEnabled(), getExecutableParameterNameProvider() others. I if pull HibernateValidatorFactory</technical_language>

Target:
public Validator getValidator() { return createValidator( constraintCreationContext.getConstraintValidatorManager().getDefaultConstraintValidatorFactory(), constraintCreationContext, validatorFactoryScopedContext, methodValidationConfiguration ); }
Source:
<code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpSession httpSession = ((HttpServletRequest) request).getSession(); String engineSession = (String) httpSession.getAttribute(ENGINE_SESSION_ID_KEY); <START> boolean authenticated = false; <END> if (engineSession == null) { chain.doFilter(request, response); } else { try { InitialContext ctx = new InitialContext(); BackendLocal backend = (BackendLocal) ctx.lookup("java:global/engine/bll/Backend!org.ovirt.engine.core.common.interfaces.BackendLocal"); VdcQueryParametersBase parameters = new VdcQueryParametersBase(); parameters.setSessionId(engineSession); if (backend.runPublicQuery(VdcQueryType.ValidateSession, parameters).getSucceeded()) { authenticated = true; } ctx.close(); httpSession.setAttribute("authenticated", authenticated); chain.doFilter(request, response); } catch (Exception ex) { } } }</code><technical_language>need for this variable</technical_language>

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpSession httpSession = ((HttpServletRequest) request).getSession(); String engineSession = (String) httpSession.getAttribute(ENGINE_SESSION_ID_KEY); if (engineSession == null) { chain.doFilter(request, response); } else { InitialContext ctx = null; try { ctx = new InitialContext();; BackendLocal backend = (BackendLocal) ctx.lookup("java:global/engine/bll/Backend!org.ovirt.engine.core.common.interfaces.BackendLocal"); VdcQueryParametersBase parameters = new VdcQueryParametersBase(); parameters.setSessionId(engineSession); httpSession.setAttribute("authenticated", backend.runPublicQuery(VdcQueryType.ValidateSession, parameters).getSucceeded()); ctx.close(); chain.doFilter(request, response); } catch (Exception ex) { log.error(String.format("An error has occurred while session validation. Message is %1$s", ex.getMessage())); if (log.isDebugEnabled()) { log.debug("", ex); } ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { try { ctx.close(); } catch (NamingException e) { } } } }
Source:
<code>public B withService(ServiceCreationConfiguration<?, ?> config) { List<ServiceCreationConfiguration<?, ?>> newServiceConfigurations = new ArrayList<>(serviceConfigurations); <START> newServiceConfigurations.removeIf(config.getClass()::isInstance); <END> newServiceConfigurations.add(config); return newBuilderWith(newServiceConfigurations); }</code><technical_language>concerned subclass implications here</technical_language>

Target:
public B withService(ServiceCreationConfiguration<?, ?> config) { List<ServiceCreationConfiguration<?, ?>> newServiceConfigurations = new ArrayList<>(serviceConfigurations); newServiceConfigurations.removeIf(other -> !other.compatibleWith(config) || !config.compatibleWith(other)); newServiceConfigurations.add(config); return newBuilderWith(newServiceConfigurations); }
Source:
<code>protected void <START> postLoad(DAnalysis <END> dAnalysis, Version loadedVersion) { if (loadedVersion.compareTo(MIGRATION_VERSION_FILTER_SORTING) < 0) { List<DDiagram> diagrams = dAnalysis.getOwnedViews().stream().flatMap(view -> view.getOwnedRepresentationDescriptors().stream()).map(desc -> desc.getRepresentation()) .filter(DDiagram.class::isInstance).map(DDiagram.class::cast).collect(Collectors.toList()); for (DDiagram dDiagram : diagrams) { List<FilterDescription> activatedFilters = new ArrayList<>(FilterService.sortFilters(dDiagram.getActivatedFilters())); dDiagram.getActivatedFilters().clear(); dDiagram.getActivatedFilters().addAll(activatedFilters); } } }</code><technical_language>other migration participants : log changes done participant + release note completed</technical_language>

Target:
protected void postLoad(DAnalysis dAnalysis, Version loadedVersion) { if (loadedVersion.compareTo(MIGRATION_VERSION_FILTER_SORTING) < 0) { List<DDiagram> diagrams = dAnalysis.getOwnedViews().stream().flatMap(view -> view.getOwnedRepresentationDescriptors().stream()).map(desc -> desc.getRepresentation()) .filter(DDiagram.class::isInstance).map(DDiagram.class::cast).collect(Collectors.toList()); for (DDiagram dDiagram : diagrams) { List<FilterDescription> activatedFilters = new ArrayList<>(FilterService.sortFilters(dDiagram.getActivatedFilters())); dDiagram.getActivatedFilters().clear(); dDiagram.getActivatedFilters().addAll(activatedFilters); diagramUpdated++; } } }
Source:
<code>Class getReturnType() { <START> return null; <END> }</code><technical_language>throw exception in other extractors</technical_language>

Target:
Class getReturnType() { throw new IllegalArgumentException("Non applicable for Json getters"); }
Source:
<code>static Instant lastModifiedInstant(Path path) { try { return Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS) <START> .toInstant(); <END> } catch (IOException e) { return Instant.ofEpochMilli(path.toFile().lastModified()); } }</code><technical_language>worth a error level trace statement. able recognize a system basic operation leads a IOException</technical_language>

Target:
static Instant lastModifiedInstant(Path path) { try { return Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS) .toInstant(); } catch (IOException e) { LOG.error(MessageFormat .format(JGitText.get().readLastModifiedFailed, path)); return Instant.ofEpochMilli(path.toFile().lastModified()); } }
Source:
<code><START> public List<LeaderboardEntry> getLeaderboard(UUID challengeId){ <END> List<LeaderboardEntry> leaderboard = new ArrayList<>(); List<Object[]> results = repository.findLeaderboardForChallenge(challengeId); for (Object[] resultEntry: results){ LeaderboardEntry entry = new LeaderboardEntry(); Result result = (Result)resultEntry[0]; entry.setUser(new UserShowDto(result.getUser())); entry.setTasksCompleted((Long)resultEntry[1]); entry.setLastLevelFinishDate((ZonedDateTime)resultEntry[2]); leaderboard.add(entry); } return leaderboard; }</code><technical_language>is unit test for this method</technical_language>

Target:
public List<LeaderboardEntryDto> getLeaderboard(UUID challengeId) { List<LeaderboardEntryDto> leaderboard = new ArrayList<>(); List<Object[]> results = repository.findLeaderboardForChallenge(challengeId); for (Object[] resultEntry: results){ LeaderboardEntryDto entry = new LeaderboardEntryDto(); Result result = (Result)resultEntry[0]; entry.setUser(new UserShowDto(result.getUser())); entry.setTasksCompleted((Long)resultEntry[1]); entry.setLastLevelFinishDate((ZonedDateTime)resultEntry[2]); leaderboard.add(entry); } return leaderboard; }
Source:
<code>public void addInstance(CollectionInstance instance) { if (this.instances == null) <START> this.instances = new HashSet<>(); <END> this.instances.add(instance); }</code><technical_language>add brackets if clause move line</technical_language>

Target:
public void addInstance(CollectionInstance instance) { if (this.instances == null) { this.instances = new HashSet<>(); } this.instances.add(instance); }
Source:
<code>public void stop() throws Exception { stopClient(httpClient); if (http2Client.isPresent()) { <START> stopClient(http2Client.get()); <END> } }</code><technical_language>http2Client.map(stopClient)</technical_language>

Target:
public void stop() throws Exception { stopClient(httpClient); http2Client.ifPresent(this::stopClient); }
Source:
<code>protected void drive(float distance) throws AutonomousModeOverException, InterruptedException { float currentEncoder = DriveCode.leftEncoder.get(); <START> DriveCode.allMotors.set(distance/distance); <END> waitUntilAtLeast(DriveCode.leftEncoder, currentEncoder + distance); DriveCode.allMotors.set(0.0f); }</code><technical_language>Distance divided distance</technical_language>

Target:
protected void drive(float distance) throws AutonomousModeOverException, InterruptedException { float startingEncoder = DriveCode.leftEncoder.get(); if (distance > 0) { DriveCode.allMotors.set(driveSpeed.get()); waitUntilAtLeast(DriveCode.leftEncoder, startingEncoder + distance); } else { DriveCode.allMotors.set(-driveSpeed.get()); waitUntilAtMost(DriveCode.leftEncoder, startingEncoder + distance); } DriveCode.allMotors.set(0.0f); }
Source:
<code>public void testCodeSpanParsedToHtml() { StringWriter out = new StringWriter(); DocumentBuilder builder = new CreoleDocumentBuilder(out); builder.beginDocument(); <START> builder.beginDocument(); <END> builder.beginSpan(SpanType.CODE, new Attributes()); builder.characters("** /nthis is code/n **"); builder.endSpan(); builder.endDocument(); assertParsedHtmlMatchesRoundTrip("<p><code>** /nthis is code/n **</code></p>", out.toString()); }</code><technical_language>redundant</technical_language>

Target:
public void testCodeSpanParsedToHtml() { StringWriter out = new StringWriter(); DocumentBuilder builder = new CreoleDocumentBuilder(out); builder.beginDocument(); builder.characters("This class is called "); builder.beginSpan(SpanType.CODE, new Attributes()); builder.characters("** /nCreoleLanguageIntegrationTest/n **"); builder.endSpan(); builder.characters(" and it tests Creole markup."); builder.endDocument(); assertParsedHtmlMatchesRoundTrip( "<p>This class is called <code>** /nCreoleLanguageIntegrationTest/n **</code> and it tests Creole markup.</p>", out.toString()); }
Source:
<code>public void setValue(Object value) { Attribute attribute = getAuthorizedAttribute(); if (attribute == null) { attribute = getAuthorizedNetworkAttribute(); } switch (attribute.getValueType()) { case BINARY: setBinaryValue((byte[]) value); return; case BOOLEAN: setBooleanValue((Boolean) value); return; case INTEGER: setIntegerValue((Integer) value); return; case NUMERIC: setNumericValue((BigDecimal) value); return; case TEXT: setTextValue((String) value); return; case TIMESTAMP: setTimestampValue((Timestamp) value); return; case JSON: <START> setJsonValue((Timestamp) value); <END> return; default: throw new IllegalStateException(String.format("Invalid value type: %s", attribute.getValueType())); } }</code><technical_language>casting thiis a timestamp</technical_language>

Target:
public void setValue(Object value) { Attribute attribute = getAuthorizedAttribute(); if (attribute == null) { attribute = getAuthorizedNetworkAttribute(); } switch (attribute.getValueType()) { case BINARY: setBinaryValue((byte[]) value); return; case BOOLEAN: setBooleanValue((Boolean) value); return; case INTEGER: setIntegerValue((Integer) value); return; case NUMERIC: setNumericValue((BigDecimal) value); return; case TEXT: setTextValue((String) value); return; case TIMESTAMP: setTimestampValue((Timestamp) value); return; case JSON: setJsonValue(value); return; default: throw new IllegalStateException(String.format("Invalid value type: %s", attribute.getValueType())); } }