auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void clearDB() { try { dbOperator.update("DELETE FROM projects"); dbOperator.update("DELETE FROM project_versions"); dbOperator.update("DELETE FROM project_properties"); dbOperator.update("DELETE FROM project_permissions"); dbOperator.update("DELETE FROM project_flows"); dbOperator.update("DELETE FROM project_files"); dbOperator.update("DELETE FROM project_events"); <START> dbOperator.update("DELETE FROM project_flow_files"); <END> } catch (final SQLException e) { e.printStackTrace(); } }</code><technical_language>nit: truncate faster delete <LINK_0></technical_language>

Target:
public void clearDB() { try { dbOperator.update("TRUNCATE TABLE projects"); dbOperator.update("TRUNCATE TABLE project_versions"); dbOperator.update("TRUNCATE TABLE project_properties"); dbOperator.update("TRUNCATE TABLE project_permissions"); dbOperator.update("TRUNCATE TABLE project_flows"); dbOperator.update("TRUNCATE TABLE project_files"); dbOperator.update("TRUNCATE TABLE project_events"); dbOperator.update("TRUNCATE TABLE project_flow_files"); } catch (final SQLException e) { e.printStackTrace(); } }
Source:
<code>public void startEditingHeaderCell(final int uiHeaderRowIndex) { if (!EditableHeaderUtilities.hasEditableHeader(this)) { return; } if (!EditableHeaderUtilities.isEditableHeader(this, uiHeaderRowIndex)) { return; } final BaseGridRendererHelper rendererHelper = gridWidget.getRendererHelper(); final BaseGridRendererHelper.RenderingInformation ri = rendererHelper.getRenderingInformation(); <START> final BaseGridRendererHelper.ColumnInformation ci = rendererHelper.getColumnInformation(rendererHelper.getColumnOffset(this) + this.getWidth() / 2); <END> final EditableHeaderMetaData headerMetaData = (EditableHeaderMetaData) this.getHeaderMetaData().get(uiHeaderRowIndex); final GridBodyCellEditContext context = EditableHeaderUtilities.makeRenderContext(gridWidget, ri, ci, uiHeaderRowIndex); headerMetaData.edit(context); }</code><technical_language>please split this lines avoid long lines in code? java final double columnXCoordinate = rendererHelper.getColumnOffset(this) + this.getWidth() / 2; final BaseGridRendererHelper.ColumnInformation ci = rendererHelper.getColumnInformation(columnXCoordinate);</technical_language>

Target:
public void startEditingHeaderCell(final int uiHeaderRowIndex) { if (!EditableHeaderUtilities.hasEditableHeader(this)) { return; } if (!EditableHeaderUtilities.isEditableHeader(this, uiHeaderRowIndex)) { return; } final BaseGridRendererHelper rendererHelper = gridWidget.getRendererHelper(); final BaseGridRendererHelper.RenderingInformation ri = rendererHelper.getRenderingInformation(); final double columnXCoordinate = rendererHelper.getColumnOffset(this) + this.getWidth() / 2; final BaseGridRendererHelper.ColumnInformation ci = rendererHelper.getColumnInformation(columnXCoordinate); final EditableHeaderMetaData headerMetaData = (EditableHeaderMetaData) this.getHeaderMetaData().get(uiHeaderRowIndex); final GridBodyCellEditContext context = EditableHeaderUtilities.makeRenderContext(gridWidget, ri, ci, uiHeaderRowIndex); headerMetaData.edit(context); }
Source:
<code>private void reportDifference(Object o1, Object o2, final String label) { <START> if (o1 == null) { <END> o1 = "null"; } if (o2 == null) { o2 = "null"; } reportDifference(o1.toString(), o2.toString(), label); }</code><technical_language>eliminate ifs String.valueOf() below. String.valueOf() toString() is is a nice approach in general, in works objects scalars alike</technical_language>

Target:
private static void reportDifference(Object o1, Object o2, final String label) { if (o1 == null) { o1 = "null"; } if (o2 == null) { o2 = "null"; } reportDifference(o1.toString(), o2.toString(), label); }
Source:
<code>public void whenRemoveThenDeleteFromDatabase() throws Exception { final EventType eventType = buildDefaultEventType(); insertEventType(eventType); repository.removeEventType(eventType.getName()); final int rows = template.queryForObject("SELECT count(*) FROM zn_data.event_type", Integer.class); assertThat("Number of rows should encrease", rows, equalTo(0)); final int schemaRows = template.queryForObject("SELECT count(*) FROM zn_data.event_type_schema", Integer.class); <START> assertThat("Number of rows should encrease", schemaRows, equalTo(0)); <END> }</code><technical_language>"... **decrease**"</technical_language>

Target:
public void whenRemoveThenDeleteFromDatabase() throws Exception { final EventType eventType = buildDefaultEventType(); insertEventType(eventType); repository.removeEventType(eventType.getName()); final int rows = template.queryForObject("SELECT count(*) FROM zn_data.event_type", Integer.class); assertThat("Number of rows should encrease", rows, equalTo(0)); final int schemaRows = template.queryForObject("SELECT count(*) FROM zn_data.event_type_schema", Integer.class); assertThat("Number of rows should decrease", schemaRows, equalTo(0)); }
Source:
<code>private void thawVm() { if (!isLiveSnapshotApplicable() || !isCinderDisksExist()) { return; <START> } <END> VDSReturnValue returnValue; try { returnValue = runVdsCommand(VDSCommandType.Thaw, new VdsAndVmIDVDSParametersBase(getVds().getId(), getVmId())); } catch (EngineException e) { handleThawVmFailure(e); return; } if (!returnValue.getSucceeded()) { handleThawVmFailure(new EngineException(EngineError.thawErr)); } }</code><technical_language>Please considert moving this line 421, change this positive condition</technical_language>

Target:
private void thawVm() { if (!shouldFreezeVm()) { return; } VDSReturnValue returnValue; try { returnValue = runVdsCommand(VDSCommandType.Thaw, new VdsAndVmIDVDSParametersBase(getVds().getId(), getVmId())); } catch (EngineException e) { handleThawVmFailure(e); return; } if (!returnValue.getSucceeded()) { handleThawVmFailure(new EngineException(EngineError.thawErr)); } }
Source:
<code>public String getToolTipText(Object element) { final EObject domainObject = (EObject) element; IObservableValue observableValue; try { observableValue = getEMFFormsDatabinding() .getObservableValue(dmr, domainObject); } catch (final DatabindingFailedException ex) { getReportService().report(new DatabindingFailedReport(ex)); return null; } final EStructuralFeature structuralFeature = (EStructuralFeature) observableValue.getValueType(); final EObject eObject = (EObject) ((IObserving) observableValue).getObserved(); final Setting setting = ((InternalEObject) eObject).eSetting(structuralFeature); observableValue.dispose(); final VDiagnostic vDiagnostic = vTableControl.getDiagnostic(); if (vDiagnostic != null) { final String message = DiagnosticMessageExtractor.getMessage(vDiagnostic.getDiagnostic(domainObject, feature)); if (message != null && !message.isEmpty()) { return ECPTooltipModifierHelper.modifyString(message, setting); } } final Object value = eObject.eGet(structuralFeature, true); if (value == null) { return null; } final String tooltip = ECPTooltipModifierHelper.modifyString(String.valueOf(value), setting); if (tooltip == null || tooltip.isEmpty()) { return null; <START> } <END> }</code><technical_language>regular return is missing</technical_language>

Target:
public String getToolTipText(Object element) { final EObject domainObject = (EObject) element; IObservableValue observableValue; try { observableValue = getEMFFormsDatabinding() .getObservableValue(dmr, domainObject); } catch (final DatabindingFailedException ex) { getReportService().report(new DatabindingFailedReport(ex)); return null; } final EStructuralFeature structuralFeature = (EStructuralFeature) observableValue.getValueType(); final EObject eObject = (EObject) ((IObserving) observableValue).getObserved(); final Setting setting = ((InternalEObject) eObject).eSetting(structuralFeature); observableValue.dispose(); final VDiagnostic vDiagnostic = vTableControl.getDiagnostic(); if (vDiagnostic != null) { final String message = DiagnosticMessageExtractor.getMessage(vDiagnostic.getDiagnostic(domainObject, feature)); if (message != null && !message.isEmpty()) { return ECPTooltipModifierHelper.modifyString(message, setting); } } final Object value = eObject.eGet(structuralFeature, true); if (value == null) { return null; } final String tooltip = ECPTooltipModifierHelper.modifyString(String.valueOf(value), setting); if (tooltip == null || tooltip.isEmpty()) { return null; } return tooltip; }
Source:
<code>public static String injectContextDependentValuesForTest(String content) { Date now = new Date(); return content.replace("<!-- test.url -->", TestProperties.TEAMMATES_URL) .replace("<!-- studentmotd.url -->", Config.STUDENT_MOTD_URL) .replace("<!-- version -->", TestProperties.TEAMMATES_VERSION) .replace("<!-- test.student1 -->", TestProperties.TEST_STUDENT1_ACCOUNT) .replace("<!-- test.student1.truncated -->", StringHelper.truncateLongId(TestProperties.TEST_STUDENT1_ACCOUNT)) .replace("<!-- test.student2 -->", TestProperties.TEST_STUDENT2_ACCOUNT) .replace("<!-- test.student2.truncated -->", StringHelper.truncateLongId(TestProperties.TEST_STUDENT2_ACCOUNT)) .replace("<!-- test.instructor -->", TestProperties.TEST_INSTRUCTOR_ACCOUNT) .replace("<!-- test.instructor.truncated -->", StringHelper.truncateLongId(TestProperties.TEST_INSTRUCTOR_ACCOUNT)) .replace("<!-- test.admin -->", TestProperties.TEST_ADMIN_ACCOUNT) .replace("<!-- test.admin.truncated -->", StringHelper.truncateLongId(TestProperties.TEST_ADMIN_ACCOUNT)) .replace("<!-- nexthour.date -->", TimeHelper.formatDate(TimeHelper.getNextHour())) .replace("<!-- now.datetime -->", TimeHelper.formatTime12H(now)) <START> .replace("<!-- now.datetime.comments -->", TimeHelper.formatDateTimeForSessions(now, 0)); <END> }</code><technical_language>Rename now.datetime.sessions</technical_language>

Target:
public static String injectContextDependentValuesForTest(String content) { Date now = new Date(); return content.replace("<!-- test.url -->", TestProperties.TEAMMATES_URL) .replace("<!-- studentmotd.url -->", Config.STUDENT_MOTD_URL) .replace("<!-- version -->", TestProperties.TEAMMATES_VERSION) .replace("<!-- test.student1 -->", TestProperties.TEST_STUDENT1_ACCOUNT) .replace("<!-- test.student1.truncated -->", StringHelper.truncateLongId(TestProperties.TEST_STUDENT1_ACCOUNT)) .replace("<!-- test.student2 -->", TestProperties.TEST_STUDENT2_ACCOUNT) .replace("<!-- test.student2.truncated -->", StringHelper.truncateLongId(TestProperties.TEST_STUDENT2_ACCOUNT)) .replace("<!-- test.instructor -->", TestProperties.TEST_INSTRUCTOR_ACCOUNT) .replace("<!-- test.instructor.truncated -->", StringHelper.truncateLongId(TestProperties.TEST_INSTRUCTOR_ACCOUNT)) .replace("<!-- test.admin -->", TestProperties.TEST_ADMIN_ACCOUNT) .replace("<!-- test.admin.truncated -->", StringHelper.truncateLongId(TestProperties.TEST_ADMIN_ACCOUNT)) .replace("<!-- nexthour.date -->", TimeHelper.formatDate(TimeHelper.getNextHour())) .replace("<!-- now.datetime -->", TimeHelper.formatTime12H(now)) .replace("<!-- now.datetime.sessions -->", TimeHelper.formatDateTimeForSessions(now, 0)); }
Source:
<code>private static String getTokenFileFromClassloader(Class<?> contextClass, VaadinContext context) throws IOException { <START> System.out.println("SSSSSSSSSSSSSSSSSSSSSs " + ((VaadinServletContext) context).getContext()); <END> String tokenResource = VAADIN_SERVLET_RESOURCES + TOKEN_FILE; Lookup lookup = context.getAttribute(Lookup.class); ResourceProvider resourceProvider = lookup .lookup(ResourceProvider.class); List<URL> classResources = resourceProvider .getApplicationResources(contextClass, tokenResource); List<URL> contextResources = resourceProvider .getApplicationResources(context, tokenResource); List<URL> resources = Stream .concat(classResources.stream(), contextResources.stream()) .collect(Collectors.toList()); URL resource = resources.stream() .filter(url -> !url.getPath().endsWith("jar!/" + tokenResource)) .findFirst().orElse(null); if (resource == null && !resources.isEmpty()) { return getPossibleJarResource(contextClass, context, resources); } return resource == null ? null : FrontendUtils.streamToString(resource.openStream()); }</code><technical_language>Debug system out removed</technical_language>

Target:
private static String getTokenFileFromClassloader(Class<?> contextClass, VaadinContext context) throws IOException { String tokenResource = VAADIN_SERVLET_RESOURCES + TOKEN_FILE; Lookup lookup = context.getAttribute(Lookup.class); ResourceProvider resourceProvider = lookup .lookup(ResourceProvider.class); List<URL> classResources = resourceProvider .getApplicationResources(contextClass, tokenResource); List<URL> contextResources = resourceProvider .getApplicationResources(context, tokenResource); List<URL> resources = Stream .concat(classResources.stream(), contextResources.stream()) .collect(Collectors.toList()); URL resource = resources.stream() .filter(url -> !url.getPath().endsWith("jar!/" + tokenResource)) .findFirst().orElse(null); if (resource == null && !resources.isEmpty()) { return getPossibleJarResource(contextClass, context, resources); } return resource == null ? null : FrontendUtils.streamToString(resource.openStream()); }
Source:
<code>private void updateKibanaIndexPatternAsync(final String indexPatternLocation, final String elasticsearchKibanaIndexPatternPath, final boolean force) { asyncESPool.submit(new Runnable() { @Override public void run() { try { ObjectNode stagemonitorPattern = JsonUtils.getMapper().readTree(IOUtils.getResourceAsStream(indexPatternLocation)).deepCopy(); stagemonitorPattern.put("fields", getFields(stagemonitorPattern.get("fields").asText())); JsonNode currentPattern = fetchCurrentKibanaIndexPatternConfiguration(elasticsearchKibanaIndexPatternPath); JsonNode mergedDefinition = JsonMerger.merge(currentPattern, stagemonitorPattern, mergeStrategy().mergeEncodedObjects("fieldFormatMap").encodedArrayWithKey("fields", "name")); <START> sendAsJson((String) "PUT", elasticsearchKibanaIndexPatternPath, (Object) mergedDefinition, force); <END> } catch (IOException e) { logger.error("Error while updating kibana index pattern, definition = {}, pattern path = {}", e, indexPatternLocation, elasticsearchKibanaIndexPatternPath); } catch (IllegalArgumentException e) { logger.error("Error while preparing data for kibana index pattern update, definition = {}, pattern path = {}", e, indexPatternLocation, elasticsearchKibanaIndexPatternPath); } } private JsonNode fetchCurrentKibanaIndexPatternConfiguration(String elasticsearchKibanaIndexPatternPath) throws IOException { try { return getJson(elasticsearchKibanaIndexPatternPath).get("_source"); } catch (FileNotFoundException e) { return JsonUtils.getMapper().createObjectNode(); } } }); }</code><technical_language>Remove type casts</technical_language>

Target:
private void updateKibanaIndexPatternAsync(final String indexPatternLocation, final String elasticsearchKibanaIndexPatternPath, final boolean force) { asyncESPool.submit(new Runnable() { @Override public void run() { try { ObjectNode stagemonitorPattern = JsonUtils.getMapper().readTree(IOUtils.getResourceAsStream(indexPatternLocation)).deepCopy(); stagemonitorPattern.put("fields", getFields(stagemonitorPattern.get("fields").asText())); JsonNode currentPattern = fetchCurrentKibanaIndexPatternConfiguration(elasticsearchKibanaIndexPatternPath); JsonNode mergedDefinition = JsonMerger.merge(currentPattern, stagemonitorPattern, mergeStrategy().mergeEncodedObjects("fieldFormatMap").encodedArrayWithKey("fields", "name")); sendAsJson("PUT", elasticsearchKibanaIndexPatternPath, mergedDefinition, force); } catch (IOException e) { logger.error("Error while updating kibana index pattern, definition = {}, pattern path = {}", e, indexPatternLocation, elasticsearchKibanaIndexPatternPath); } catch (IllegalArgumentException e) { logger.error("Error while preparing data for kibana index pattern update, definition = {}, pattern path = {}", e, indexPatternLocation, elasticsearchKibanaIndexPatternPath); } } private JsonNode fetchCurrentKibanaIndexPatternConfiguration(String elasticsearchKibanaIndexPatternPath) throws IOException { try { return getJson(elasticsearchKibanaIndexPatternPath).get("_source"); } catch (FileNotFoundException e) { return JsonUtils.getMapper().createObjectNode(); } } }); }
Source:
<code>protected void initializeType(File typeDir) { Iterator<File> files = Arrays.asList(typeDir.listFiles((FileFilter)mediaFileFilter)).iterator(); while (files.hasNext()) addMediaElement(typeDir.getName(), files.next()); synchronized (updateLock) { <START> update(createTypeElement(typeDir.getName())); <END> } }</code><technical_language>brackets preceding while in order clear new code is intended part of loop</technical_language>

Target:
protected void initializeType(File typeDir) { Iterator<File> files = Arrays.asList(typeDir.listFiles((FileFilter)mediaFileFilter)).iterator(); while (files.hasNext()) { addMediaElement(typeDir.getName(), files.next()); } synchronized (updateLock) { update(createTypeElement(typeDir.getName())); } }
Source:
<code>private List<ParameterOption> getOptions() { List<ParameterOption> options = new ArrayList<>(); File soundsDir = Paths.get(ConfigConstants.getConfigFolder(), AudioManager.SOUND_DIR).toFile(); if (soundsDir.isDirectory()) { for (String fileName : soundsDir.list()) { if (fileName.contains(".")) { <START> String soundName = StringUtils.capitalize(fileName.substring(0, fileName.indexOf("."))); <END> options.add(new ParameterOption(fileName, soundName)); } } } return options; }</code><technical_language>"last index of" one? I a question: If I multiple audio sinks, supports mp3 streams, other wav streams. IIRC moment supple a compatible format. If I a doorbell mp3 wav in sounds directory, choose correct one? current implementation forces user correct one, I if cut file name drop information (as a List is used, doorbell entries)</technical_language>

Target:
private List<ParameterOption> getOptions() { List<ParameterOption> options = new ArrayList<>(); File soundsDir = Paths.get(ConfigConstants.getConfigFolder(), AudioManager.SOUND_DIR).toFile(); if (soundsDir.isDirectory()) { for (String fileName : soundsDir.list()) { if (fileName.contains(".") && !fileName.startsWith(".")) { String soundName = StringUtils.capitalize(fileName.substring(0, fileName.lastIndexOf("."))); options.add(new ParameterOption(fileName, soundName)); } } } return options; }
Source:
<code>private void validateNotRemovingLabeledNetworks() { Map<String, VdsNetworkInterface> nicsByName = Entities.entitiesByName(params.getInterfaces()); Map<String, VdsNetworkInterface> hostInterfacesByNetworkName = Entities.hostInterfacesByNetworkName(getExistingIfaces().values()); for (String network : removedNetworks) { VdsNetworkInterface nic = hostInterfacesByNetworkName.get(network); <START> final String baseInterfaceName = NetworkUtils.stripVlan(nic); <END> if (nic != null && !removedBonds.containsKey(baseInterfaceName)) { if (NetworkUtils.isVlan(nic)) { nic = nicsByName.get(baseInterfaceName); if (nic == null) { continue; } } Network removedNetwork = getExistingClusterNetworks().get(network); if (NetworkUtils.isLabeled(nic) && removedNetwork != null && nic.getLabels().contains(removedNetwork.getLabel())) { addViolation(VdcBllMessages.ACTION_TYPE_FAILED_CANNOT_REMOVE_LABELED_NETWORK_FROM_NIC, network); } } } }</code><technical_language>if nic is null</technical_language>

Target:
private void validateNotRemovingLabeledNetworks() { Map<String, VdsNetworkInterface> nicsByName = Entities.entitiesByName(params.getInterfaces()); Map<String, VdsNetworkInterface> hostInterfacesByNetworkName = Entities.hostInterfacesByNetworkName(getExistingIfaces().values()); for (String network : removedNetworks) { VdsNetworkInterface nic = hostInterfacesByNetworkName.get(network); final String baseInterfaceName = NetworkUtils.stripVlan(nic); if (!removedBonds.containsKey(baseInterfaceName)) { if (NetworkUtils.isVlan(nic)) { nic = nicsByName.get(baseInterfaceName); if (nic == null) { continue; } } Network removedNetwork = getExistingClusterNetworks().get(network); if (NetworkUtils.isLabeled(nic) && removedNetwork != null && nic.getLabels().contains(removedNetwork.getLabel())) { addViolation(VdcBllMessages.ACTION_TYPE_FAILED_CANNOT_REMOVE_LABELED_NETWORK_FROM_NIC, network); } } } }
Source:
<code>public String createExecution(ExecutionParameters executionParameters) throws CloudFlowException { requireNonNull(executionParameters); Project project = this.projectManager.getProject("yb-test"); Flow flow = project.getFlow("flowPriority2"); final ExecutableFlow exflow = FlowUtils.createExecutableFlow(project, flow); <START> setAzkabanExecutionOptions(executionParameters, exflow); <END> try { this.executorManager.submitExecutableFlow(exflow, executionParameters.getSubmitUser()); } catch (ExecutorManagerException e) { if (e.getReason() != null) { throw new CloudFlowValidationException(e.getMessage()); } else { final String errorMessage = String.format("Failed to create execution of flow with id %s " + "and version %s.", executionParameters.getFlowId(), executionParameters.getFlowVersion()); logger.error(errorMessage, e); throw new CloudFlowException(errorMessage); } } return String.valueOf(exflow.getExecutionId()); }</code><technical_language>project related code checked in, check if project fetched dynamically</technical_language>

Target:
public String createExecution(ExecutionParameters executionParameters) { requireNonNull(executionParameters); Project project = this.projectManager.getProject("yb-test"); Flow flow = project.getFlow("flowPriority2"); final ExecutableFlow exflow = FlowUtils.createExecutableFlow(project, flow); setAzkabanExecutionOptions(executionParameters, exflow); try { this.executorManager.submitExecutableFlow(exflow, executionParameters.getSubmitUser()); } catch (ExecutorManagerException e) { if (e.getReason() != null) { throw new CloudFlowValidationException(e.getMessage()); } else { final String errorMessage = format("Failed to create execution of flow with id %s " + "and version %s.", executionParameters.getFlowId(), executionParameters.getFlowVersion()); logger.error(errorMessage, e); throw new CloudFlowException(errorMessage); } } return String.valueOf(exflow.getExecutionId()); }
Source:
<code><START> public <K, V> Cache<K, V> getCache(String cacheName) { <END> return new Cache<K, V>(service.cache); }</code><technical_language>So, silently ignoring requested cacheName here? correct. JCache CacheManager support multiple caches</technical_language>

Target:
public <K, V> Cache<K, V> getCache(String cacheName) { if (cacheName == null) { cacheName = service.cacheName; } javax.cache.Cache<K, V> cache = service.cacheManager.getCache(cacheName); if (cache == null) { cache = service.cacheManager.createCache(cacheName, new MutableConfiguration<K, V>()); } return new Cache<K, V>(cache); }
Source:
<code>public static void restrictUsername(String username) { <START> Pattern pattern = Pattern.compile("(?i)^(?!.*(dockstore|admin|curator|system|manager)).*$"); <END> Matcher matcher = pattern.matcher(username); if (!matcher.find()) { throw new CustomWebApplicationException("Cannot change username to " + username + " because it contains one or more of the following keywords: dockstore, admin, curator, system, or manager", HttpStatus.SC_BAD_REQUEST); } }</code><technical_language>1. this pattern is (see next item), a static, ideally; regexes expensive. 2. I feel this regex is more complicated need -- lookaheads I think, syntax I up. place, pattern Pattern.compile("dockstore|admin|curator|system|manager")? change line 273 if (matcher.find()) { ? I missing a more complex case though. 3. I leave a backdoor for admins curators. want some of for ourselves</technical_language>

Target:
public static void restrictUsername(String username) { Matcher matcher = USERNAME_CONTAINS_KEYWORD_PATTERN.matcher(username); if (matcher.find()) { throw new CustomWebApplicationException("Cannot change username to " + username + " because it contains one or more of the following keywords: dockstore, admin, curator, system, or manager", HttpStatus.SC_BAD_REQUEST); } }
Source:
<code><START> public static long parseSizeInBytes(String string) { <END> String digits = string; if (digits.length() == 0) { throw new NumberFormatException("Invalid empty string"); } char unit = digits.charAt(digits.length() - 1); if (unit == 'b' || unit == 'B') { digits = digits.substring(0, digits.length() - 1); if (digits.length() == 0) { throw new NumberFormatException(string); } unit = digits.charAt(digits.length() - 1); } long mul; switch (unit) { case 'k': case 'K': mul = KB; break; case 'm': case 'M': mul = MB; break; case 'g': case 'G': mul = GB; break; case 't': case 'T': mul = TB; break; default: if (!Character.isDigit(unit)) { throw new NumberFormatException(string); } mul = 1; } if (mul != 1) { digits = digits.substring(0, digits.length() - 1); if (digits.length() == 0) { throw new NumberFormatException(string); } } try { return Long.parseLong(digits.trim()) * mul; } catch (NumberFormatException e) { throw new NumberFormatException(string); } }</code><technical_language>I some tools suggest remove throws NumberFormatException a runtime exception, this is wrong, part of contract of method there</technical_language>

Target:
public static long parseSizeInBytes(String string) throws NumberFormatException { String digits = string; if (digits.length() == 0) { throw new NumberFormatException("Invalid empty string"); } char unit = digits.charAt(digits.length() - 1); if (unit == 'b' || unit == 'B') { digits = digits.substring(0, digits.length() - 1); if (digits.length() == 0) { throw new NumberFormatException(string); } unit = digits.charAt(digits.length() - 1); } long mul; switch (unit) { case 'k': case 'K': mul = KB; break; case 'm': case 'M': mul = MB; break; case 'g': case 'G': mul = GB; break; case 't': case 'T': mul = TB; break; default: if (!Character.isDigit(unit)) { throw new NumberFormatException(string); } mul = 1; } if (mul != 1) { digits = digits.substring(0, digits.length() - 1); if (digits.length() == 0) { throw new NumberFormatException(string); } } try { return Long.parseLong(digits.trim()) * mul; } catch (NumberFormatException e) { throw new NumberFormatException(string); } }
Source:
<code>public final Optional<Argument> find(String name, StatementContext ctx) { if (name.startsWith(prefix)) { String actualName = name.substring(prefix.length()); int separator = actualName.indexOf('.'); if (separator != -1) { String parentName = actualName.substring(0, separator); String childName = actualName.substring(separator + 1); return childArgumentFinders .computeIfAbsent(parentName.endsWith("?") ? parentName.substring(0, parentName.length() - 1) : parentName, pn -> getValue(pn, ctx).map(v -> { if (Objects.nonNull(v.value)) { return getNestedArgumentFinder(v.value); } if (parentName.endsWith("?")) { <START> return new NullArgumentFinder(); <END> } throw new NullPointerException(); })) .flatMap(arg -> arg.find(childName, ctx)); } if (actualName.endsWith("?")) { actualName = actualName.substring(0, actualName.length() - 1); } return getValue(actualName, ctx) .map(tv -> ctx.findArgumentFor(tv.type, tv.value) .orElseThrow(() -> new UnableToCreateStatementException( String.format("No argument factory registered for type [%s] for element [%s] on [%s]", tv.type, name, object), ctx))); } return Optional.empty(); }</code><technical_language>NullArgumentFinder is redundant config property Arguments.getUntypedNullArgument(). This config property exists Types.OTHER is supported database vendors. Some vendors Types.NULL (even NULL constant is a value, a type), other vendors other values. remove NullArgumentFinder, replace a lambda: java if (parentName.endsWith("?")) { return (name, ctx) -> ctx.getConfig(Arguments.class).getUntypedNullArgument(); }</technical_language>

Target:
public final Optional<Argument> find(String name, StatementContext ctx) { if (name.startsWith(prefix)) { final String actualName = name.substring(prefix.length()); int separator = actualName.indexOf('.'); if (separator != -1) { String parentName = actualName.substring(0, separator); String childName = actualName.substring(separator + 1); return childArgumentFinders .computeIfAbsent(parentName.endsWith("?") ? parentName.substring(0, parentName.length() - 1) : parentName, pn -> getValue(pn, ctx).map(typedValue -> getValueNested(typedValue, parentName, childName))) .flatMap(arg -> arg.find(childName, ctx)); } return getValue(actualName, ctx) .map(tv -> ctx.findArgumentFor(tv.type, tv.value) .orElseThrow(() -> new UnableToCreateStatementException( String.format("No argument factory registered for type [%s] for element [%s] on [%s]", tv.type, name, object), ctx))); } return Optional.empty(); }
Source:
<code>private HttpRequestEndPoint getEndPointCourseStructure(final String courseId) { return new HttpRequestEndPoint() { public String getUrl() { try { PrefManager pref = new PrefManager(MainApplication.instance(), PrefManager.Pref.LOGIN); String username = URLEncoder.encode(pref.getCurrentUserProfile().username, "UTF-8"); String block_counts = URLEncoder.encode("video", "UTF-8"); String requested_fields = URLEncoder.encode("graded,format,student_view_multi_device", "UTF-8"); <START> String student_view_data = URLEncoder.encode("discussion,video", "UTF-8"); <END> String cId = URLEncoder.encode(courseId, "UTF-8"); String url = config.getApiHostURL() + "/api/courses/v1/blocks/?course_id=" + cId + "&username=" + username + "&depth=all&requested_fields=" + requested_fields + "&student_view_data=" + student_view_data + "&block_counts=" + block_counts + "&nav_depth=3"; logger.debug("GET url for enrolling in a Course: " + url); return url; } catch (UnsupportedEncodingException e) { logger.error(e); } return ""; } public String getCacheKey() { return config.getApiHostURL() + "/api/courses/v1/blocks/?course_id=" + courseId; } public Map<String, String> getParameters() { return null; } }; }</code><technical_language>nit: RestApiManager.java in order. order for consistency? "video,discussion"</technical_language>

Target:
private HttpRequestEndPoint getEndPointCourseStructure(final String courseId) { return new HttpRequestEndPoint() { public String getUrl() { PrefManager pref = new PrefManager(MainApplication.instance(), PrefManager.Pref.LOGIN); String url = Uri.parse(config.getApiHostURL() + "/api/courses/v1/blocks/?") .buildUpon() .appendQueryParameter("course_id", courseId) .appendQueryParameter("username", pref.getCurrentUserProfile().username) .appendQueryParameter("depth", "all") .appendQueryParameter("requested_fields", "graded,format,student_view_multi_device") .appendQueryParameter("student_view_data", "video,discussion") .appendQueryParameter("block_counts", "video") .appendQueryParameter("nav_depth", "3") .toString(); logger.debug("GET url for enrolling in a Course: " + url); return url; } public String getCacheKey() { return config.getApiHostURL() + "/api/courses/v1/blocks/?course_id=" + courseId; } public Map<String, String> getParameters() { return null; } }; }
Source:
<code>public synchronized void addChangeListener(MemoryPoolId poolId, Consumer<MemoryPoolInfo> listener) { <START> verify(memoryPoolExists(poolId), format("Memory pool doesn't exist: %s", poolId)); <END> changeListeners.computeIfAbsent(poolId, id -> new ArrayList<>()).add(listener); }</code><technical_language>avoid contractions in error messages</technical_language>

Target:
public synchronized void addChangeListener(MemoryPoolId poolId, Consumer<MemoryPoolInfo> listener) { verify(memoryPoolExists(poolId), "Memory pool does not exist: %s", poolId); changeListeners.computeIfAbsent(poolId, id -> new ArrayList<>()).add(listener); }
Source:
<code>public Optional<Errors> validatePatchRequest(JsonNode payload){ if(payload != null && payload.has(FIELD_OPERATION_PATH) && payload.findValue(FIELD_OPERATION_PATH).asText().equals("notify_settings")) { return validateNotifySettingsRequest(payload).map(Errors::from); } <START> throw new UnsupportedOperationException("Not supported"); <END> }</code><technical_language>throw new UnsupportedOperationException("Not supported");</technical_language>

Target:
public Optional<Errors> validatePatchRequest(JsonNode payload){ Optional<List<String>> pathCheck = requestValidator.checkIfExistsOrEmpty(payload, FIELD_OPERATION, FIELD_OPERATION_PATH); if(pathCheck.isPresent()){ return pathCheck.map(Errors::from); } if(!payload.findValue(FIELD_OPERATION_PATH).asText().equals(FIELD_NOTIFY_SETTINGS)) { return Optional.of(Errors.from(format("Operation [%s] not supported for path [%s]", FIELD_OPERATION, payload.findValue(FIELD_OPERATION_PATH).asText()))); } return validateNotifySettingsRequest(payload).map(Errors::from); }
Source:
<code>private void testGetVariantsByRegionHelper(String testString, int expectedSize) throws URISyntaxException { Response response = given().param("species", "mmusculus_grcm38").get(new URI("/v1/segments/" + testString + "/variants")); response.then().statusCode(200); List queryResponse = JsonPath.from(response.asString()).getList("response"); List<Map> result = JsonPath.from(response.asString()).getJsonObject("response[0].result"); for (Map m : result) { <START> assertFalse(m.containsKey("")); <END> String missingField = String.format("%s required field missing", m.get("name")); assertTrue(missingField, m.containsKey("id")); assertTrue(missingField, m.containsKey("chromosome")); assertTrue(missingField, m.containsKey("start")); assertTrue(missingField, m.containsKey("end")); } }</code><technical_language>empty key present</technical_language>

Target:
private void testGetVariantsByRegionHelper(String testString, int expectedSize) throws URISyntaxException { Response response = given().param("species", "mmusculus_grcm38").get(new URI("/v1/segments/" + testString + "/variants")); response.then().statusCode(200); List queryResponse = JsonPath.from(response.asString()).getList("response"); List<Map> result = JsonPath.from(response.asString()).getJsonObject("response[0].result"); for (Map m : result) { String missingField = String.format("%s required field missing", m.get("name")); assertTrue(missingField, m.containsKey("id")); assertTrue(missingField, m.containsKey("chromosome")); assertTrue(missingField, m.containsKey("start")); assertTrue(missingField, m.containsKey("end")); } }
Source:
<code>public void visitNewClass(NewClassTree tree) { super.visitNewClass(tree); ClassTree classBody = tree.classBody(); if (classBody != null) { TypeTree identifier = tree.identifier(); if (!useThisIdentifier(classBody) && !enumConstants.contains(identifier) && isSAM(classBody)) { Tree member = classBody.members().get(0); <START> if (member.is(Tree.Kind.METHOD) && multipleMethodsDefaultSameSignature(((JavaSymbol.MethodJavaSymbol) ((MethodTree) member).symbol()))) { <END> context.reportIssue(this, identifier, "Make this anonymous inner class a lambda" + context.getJavaVersion().java8CompatibilityMessage()); } } } }</code><technical_language>If passed isSAM() method, means member is necessarily a MethodTree. point of view, need check if is a METHOD</technical_language>

Target:
public void visitNewClass(NewClassTree tree) { super.visitNewClass(tree); ClassTree classBody = tree.classBody(); if (classBody != null) { TypeTree identifier = tree.identifier(); if (!useThisIdentifier(classBody) && !enumConstants.contains(identifier) && isSAM(classBody)) { context.reportIssue(this, identifier, "Make this anonymous inner class a lambda" + context.getJavaVersion().java8CompatibilityMessage()); } } }
Source:
<code>protected void handleMessageInRunContext(final Message jmsRequest, final String replyId) throws JMSException { final JmsMessageReader<REQUEST> messageReader = JmsMessageReader.newInstance(jmsRequest, m_marshaller); final IMessage<REQUEST> request = messageReader.readMessage(); final Destination replyTopic = messageReader.readReplyTo(); final String correlationId = messageReader.readCorrelationId(); createRunContext() .withCorrelationId(correlationId) .withThreadLocal(IMessage.CURRENT, request) .run(new IRunnable() { @Override public void run() throws Exception { try { handleRequest(jmsRequest, request, replyId, replyTopic); } catch (Exception e) { throw BEANS.get(PlatformExceptionTranslator.class).translate(e) <START> .withContextInfo("JMSCorrelationID", correlationId); <END> } } }); }</code><technical_language>In theory, this is JMSCorrelationID. JmsMessageReader generates a new CorrelationID if is received JMS. is more Scout Correlation ID</technical_language>

Target:
protected void handleMessageInRunContext(final Message jmsRequest, final String replyId) throws JMSException { final JmsMessageReader<REQUEST> messageReader = JmsMessageReader.newInstance(jmsRequest, m_marshaller); final IMessage<REQUEST> request = messageReader.readMessage(); final Destination replyTopic = messageReader.readReplyTo(); final String correlationId = messageReader.readCorrelationId(); createRunContext() .withCorrelationId(correlationId) .withThreadLocal(IMessage.CURRENT, request) .run(new IRunnable() { @Override public void run() throws Exception { try { handleRequest(jmsRequest, request, replyId, replyTopic); } catch (Exception e) { throw BEANS.get(PlatformExceptionTranslator.class).translate(e) .withContextInfo("correlationId", correlationId); } } }); }
Source:
<code>public int compareTo(@Nullable ISegment o) { <START> if (o == null) { <END> throw new IllegalArgumentException(); } Comparator<ISegment> comparator = Ordering .from(SegmentComparators.INTERVAL_START_COMPARATOR) .compound(SegmentComparators.INTERVAL_END_COMPARATOR); return comparator.compare(this, o); }</code><technical_language>I thought nicer catch early instead of letting fail in some Ordering such. throw a NPE instead yeah</technical_language>

Target:
public int compareTo(@Nullable ISegment o) { if (o == null) { throw new IllegalArgumentException(); } return COMPARATOR.compare(this, o); }
Source:
<code>public KafkaFuture<ListOffsetsResultInfo> partitionResult(final TopicPartition partition) { if (!futures.containsKey(partition)) { <START> final KafkaFutureImpl<ListOffsetsResultInfo> result = new KafkaFutureImpl<>(); <END> result.completeExceptionally(new IllegalArgumentException( "List Offsets for partition \"" + partition + "\" was not attempted")); return result; } return futures.get(partition); }</code><technical_language>user is access a partition requested. I raise IllegalArgumentException user</technical_language>

Target:
public KafkaFuture<ListOffsetsResultInfo> partitionResult(final TopicPartition partition) { KafkaFuture<ListOffsetsResultInfo> future = futures.get(partition); if (future == null) { throw new IllegalArgumentException( "List Offsets for partition \"" + partition + "\" was not attempted"); } return future; }
Source:
<code>protected Result check() throws Exception { Connection connection = null; try { connection = DriverManager.getConnection( configuration.getDataSourceFactory().getUrl(), configuration.getDataSourceFactory().getUser(), configuration.getDataSourceFactory().getPassword()); connection.setReadOnly(true); Statement statement = connection.createStatement(); statement.execute("select * from pg_stat_database where datname='connector';"); ResultSet resultSet = statement.getResultSet(); resultSet.next(); numBackends = resultSet.getInt("numbackends"); xactCommit = resultSet.getInt("xact_commit"); return connection.isValid(2) ? Result.healthy() : Result.unhealthy("Could not validate the DB connection."); } catch (Exception e) { <START> return Result.unhealthy(e.getMessage()); <END> } finally { if (connection !=null) { connection.close(); } } }</code><technical_language>This bit of loading data moved a separate method, perhaps</technical_language>

Target:
protected Result check() throws Exception { Connection connection = null; try { connection = DriverManager.getConnection( configuration.getDataSourceFactory().getUrl(), configuration.getDataSourceFactory().getUser(), configuration.getDataSourceFactory().getPassword()); connection.setReadOnly(true); updateMetricData(connection); return connection.isValid(2) ? Result.healthy() : Result.unhealthy("Could not validate the DB connection."); } catch (Exception e) { return Result.unhealthy(e.getMessage()); } finally { if (connection != null) { connection.close(); } } }
Source:
<code>public void hydrateAndCompileModelConfigs(ElideDynamicInMemoryCompiler compiler) throws Exception { HandlebarsHydrator hydrator = new HandlebarsHydrator(staticModelDetails); Map<String, String> tableClasses = hydrator.hydrateTableTemplate(this.elideTableConfig); Map<String, String> securityClasses = hydrator.hydrateSecurityTemplate(this.elideSecurityConfig); <START> compiler.useParentClassLoader(getClass().getClassLoader()); <END> for (Map.Entry<String, String> tablePojo : tableClasses.entrySet()) { log.debug("key: " + tablePojo.getKey() + ", value: " + tablePojo.getValue()); compiler.addSource(MODEL_PACKAGE_NAME + tablePojo.getKey(), tablePojo.getValue()); } for (Map.Entry<String, String> secPojo : securityClasses.entrySet()) { log.debug("key: " + secPojo.getKey() + ", value: " + secPojo.getValue()); compiler.addSource(SECURITY_PACKAGE_NAME + secPojo.getKey(), secPojo.getValue()); } compiledObjects = compiler.compileAll(); Set<Class<?>> compiledTableClasses = new HashSet<Class<?>>(); compiledObjects.values().forEach(cls -> { if (cls.getAnnotation(SecurityCheck.class) != null) { dictionary.addSecurityCheck(cls); } else { compiledTableClasses.add(cls); } }); compiledTableClasses.forEach(dictionary::bindEntity); }</code><technical_language>this belongs (like in compiler constructor)</technical_language>

Target:
public void hydrateAndCompileModelConfigs(ElideDynamicInMemoryCompiler compiler) throws Exception { HandlebarsHydrator hydrator = new HandlebarsHydrator(staticModelDetails); Map<String, String> tableClasses = hydrator.hydrateTableTemplate(this.elideTableConfig); Map<String, String> securityClasses = hydrator.hydrateSecurityTemplate(this.elideSecurityConfig); for (Map.Entry<String, String> tablePojo : tableClasses.entrySet()) { log.debug("key: " + tablePojo.getKey() + ", value: " + tablePojo.getValue()); compiler.addSource(MODEL_PACKAGE_NAME + tablePojo.getKey(), tablePojo.getValue()); } for (Map.Entry<String, String> secPojo : securityClasses.entrySet()) { log.debug("key: " + secPojo.getKey() + ", value: " + secPojo.getValue()); compiler.addSource(SECURITY_PACKAGE_NAME + secPojo.getKey(), secPojo.getValue()); } compiledObjects = compiler.compileAll(); Set<Class<?>> compiledTableClasses = new HashSet<Class<?>>(); compiledObjects.values().forEach(cls -> { if (cls.getAnnotation(SecurityCheck.class) != null) { dictionary.addSecurityCheck(cls); } else { compiledTableClasses.add(cls); } }); compiledTableClasses.forEach(dictionary::bindEntity); }
Source:
<code>private void copyTestFileToWorkingDirectory(String filename) throws IOException { String destRoot = System.getProperty("java.io.tmpdir"); if(!(destRoot.endsWith("/") || destRoot.endsWith("\\"))){ destRoot += destRoot.contains("/")? "/" : "\\"; } String dest = destRoot + filename; <START> String src = "org/biojava/nbio/core/sequence/GenbankProxySequenceReader/" + filename; <END> File d = new File(dest); d.delete(); FileOutputStream destination = new FileOutputStream(new File(dest)); InputStream source = this.getClass().getClassLoader().getResourceAsStream(src); int read; byte[] buffer = new byte[1024]; while((read = source.read(buffer)) > 0){ destination.write(buffer, 0, read); } destination.flush(); destination.close(); source.close(); }</code><technical_language>package name class resources in, i.e.: org/biojava/nbio/core/sequence/loader</technical_language>

Target:
private void copyTestFileToWorkingDirectory(String filename) throws IOException { String destRoot = System.getProperty("java.io.tmpdir"); if(!(destRoot.endsWith("/") || destRoot.endsWith("\\"))){ destRoot += destRoot.contains("/")? "/" : "\\"; } String dest = destRoot + filename; String src = "org/biojava/nbio/core/sequence/loader/" + filename; File d = new File(dest); d.delete(); try(FileOutputStream destination = new FileOutputStream(d); InputStream is = this.getClass().getClassLoader().getResourceAsStream(src); ReadableByteChannel source = Channels.newChannel(is)) { destination.getChannel().transferFrom(source, 0, Long.MAX_VALUE); } }
Source:
<code>FeatureId addFeature(final SimpleFeature feature, FeatureWriter<SimpleFeatureType, SimpleFeature> writer) throws IOException { final SimpleFeature toWrite = writer.next(); for ( int i = 0; i < toWrite.getType().getAttributeCount(); i++ ) { String name = toWrite.getType().getDescriptor(i).getLocalName(); toWrite.setAttribute( name, feature.getAttribute(name)); } toWrite.getUserData().putAll(feature.getUserData()); boolean useExisting = Boolean.TRUE.equals(feature.getUserData().get(Hints.USE_PROVIDED_FID)); if(getQueryCapabilities().isUseProvidedFIDSupported() && useExisting) { ((FeatureIdImpl) toWrite.getIdentifier()).setID(feature.getID()); } <START> toWrite.getUserData().put("_original_", feature); <END> writer.write(); feature.getUserData().putAll( toWrite.getUserData() ); feature.getUserData().remove("_original_"); return toWrite.getIdentifier(); }</code><technical_language>Please a constant for "_original_"</technical_language>

Target:
FeatureId addFeature(final SimpleFeature feature, FeatureWriter<SimpleFeatureType, SimpleFeature> writer) throws IOException { final SimpleFeature toWrite = writer.next(); for ( int i = 0; i < toWrite.getType().getAttributeCount(); i++ ) { String name = toWrite.getType().getDescriptor(i).getLocalName(); toWrite.setAttribute( name, feature.getAttribute(name)); } toWrite.getUserData().putAll(feature.getUserData()); boolean useExisting = Boolean.TRUE.equals(feature.getUserData().get(Hints.USE_PROVIDED_FID)); if(getQueryCapabilities().isUseProvidedFIDSupported() && useExisting) { ((FeatureIdImpl) toWrite.getIdentifier()).setID(feature.getID()); } toWrite.getUserData().put(ORIGINAL_FEATURE_KEY, feature); writer.write(); feature.getUserData().putAll( toWrite.getUserData() ); feature.getUserData().remove(ORIGINAL_FEATURE_KEY); return toWrite.getIdentifier(); }
Source:
<code>private Map<String, String> initDriveData() { Map<String, String> drive = new HashMap<String, String>(); DiskImage diskImage = getParameters().getDiskImage(); VmDevice vmDevice = getParameters().getVmDevice(); drive.put("type", "disk"); drive.put("format", diskImage.getvolume_format().toString().toLowerCase()); drive.put("bootOrder", String.valueOf(vmDevice.getBootOrder())); drive.put("propagateErrors", diskImage.getpropagate_errors().toString().toLowerCase()); <START> drive.put("iface", "virtio"); <END> drive.put("shared", Boolean.FALSE.toString()); drive.put("optional", Boolean.FALSE.toString()); drive.put("readonly", String.valueOf(vmDevice.getIsReadOnly())); drive.put("domainID", diskImage.getstorage_id().toString()); drive.put("poolID", diskImage.getstorage_pool_id().toString()); drive.put("volumeID", diskImage.getId().toString()); drive.put("imageID", diskImage.getimage_group_id().toString()); return drive; }</code><technical_language>currently virtio is allowed, i set this disk hardcoding</technical_language>

Target:
private Map<String, String> initDriveData() { Map<String, String> drive = new HashMap<String, String>(); DiskImage diskImage = getParameters().getDiskImage(); VmDevice vmDevice = getParameters().getVmDevice(); drive.put("type", "disk"); drive.put("format", diskImage.getvolume_format().toString().toLowerCase()); drive.put("bootOrder", String.valueOf(vmDevice.getBootOrder())); drive.put("propagateErrors", diskImage.getpropagate_errors().toString().toLowerCase()); drive.put("iface", diskImage.getdisk_interface().toString().toLowerCase()); drive.put("shared", Boolean.FALSE.toString()); drive.put("optional", Boolean.FALSE.toString()); drive.put("readonly", String.valueOf(vmDevice.getIsReadOnly())); drive.put("domainID", diskImage.getstorage_id().toString()); drive.put("poolID", diskImage.getstorage_pool_id().toString()); drive.put("volumeID", diskImage.getId().toString()); drive.put("imageID", diskImage.getimage_group_id().toString()); return drive; }