auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void refresh(InterpreterContext context) { context.out().clear(); try { context.out.write("%table\n"); for (int i = 0; i < schema.getFieldCount(); ++i) { String field = schema.getFieldName(i).get(); context.out.write(field); if (i != (schema.getFieldCount() - 1)) { context.out.write("\t"); } } context.out.write("\n"); <START> LOGGER.debug("*****************Row size: " + materializedTable.size()); <END> materializedTable.sort((r1, r2) -> { String f1 = r1.getField(0).toString(); String f2 = r2.getField(0).toString(); return f1.compareTo(f2); }); for (Row row : materializedTable) { for (int i = 0; i < row.getArity(); ++i) { Object field = row.getField(i); context.out.write(field.toString()); if (i != (row.getArity() - 1)) { context.out.write("\t"); } } LOGGER.debug("Row:" + row); context.out.write("\n"); } context.out.write("\n%text "); context.out.flush(); } catch (IOException e) { e.printStackTrace(); LOGGER.error("Fail to refresh data", e); } }</code><technical_language>remove</technical_language>

Target:
protected void refresh(InterpreterContext context) { context.out().clear(); try { context.out.write("%table\n"); for (int i = 0; i < schema.getFieldCount(); ++i) { String field = schema.getFieldName(i).get(); context.out.write(field); if (i != (schema.getFieldCount() - 1)) { context.out.write("\t"); } } context.out.write("\n"); LOGGER.debug("*****************Row size: " + materializedTable.size()); materializedTable.sort((r1, r2) -> { String f1 = r1.getField(0).toString(); String f2 = r2.getField(0).toString(); return f1.compareTo(f2); }); for (Row row : materializedTable) { for (int i = 0; i < row.getArity(); ++i) { Object field = row.getField(i); context.out.write(field.toString()); if (i != (row.getArity() - 1)) { context.out.write("\t"); } } context.out.write("\n"); } context.out.flush(); } catch (IOException e) { LOGGER.error("Fail to refresh data", e); } }
Source:
<code>public void logout() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.logout_message) .setPositiveButton(R.string.action_yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { <START> PrefManager.clearToken(); <END> startActivity(new Intent(MifosBaseActivity.this, SplashScreenActivity.class )); finish(); } }) .setNegativeButton(R.string.action_no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }).create().show(); }</code><technical_language>Remove sharedpreferences instead of clearToken() method. logs out, application clear saved 'SharedPreference values'. clearToken() save a blank passcode remaining sharedpreferences remain intact. save Instance Domain convenient for other users login is handled in LoginActivity</technical_language>

Target:
public void logout() { new MaterialDialog.Builder().init(MifosBaseActivity.this) .setMessage(R.string.dialog_logout) .setPositiveButton(getString(R.string.logout), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { PrefManager.clearPrefs(); startActivity(new Intent(MifosBaseActivity.this, SplashScreenActivity.class)); finish(); } }) .setNegativeButton(getString(R.string.cancel)) .createMaterialDialog() .show(); }
Source:
<code><START> public void fetchAllExternalIdsWithUniformPageSizes() throws Exception { <END> final Function<List<Category>, List<String>> externalIdCallBack = categories -> categories.stream() .map(Category::getExternalId) .collect(toList()); final CompletionStage<List<List<String>>> categoryPagesStage = QueryExecutionUtils .queryAll(client(), CategoryQuery.of(), externalIdCallBack, 3); final List<List<String>> categoryPages = SphereClientUtils .blockingWait(categoryPagesStage, Duration.ofMinutes(5)); assertThat(categoryPages).hasSize(5); final List<String> externalIds = categoryPages.stream() .flatMap(List::stream) .collect(toList()); assertThat(externalIds).hasSize(15); IntStream.range(0, externalIds.size()).forEach(index -> assertThat(externalIds).contains(index + "")); }</code><technical_language>changed code provide API, able revert changes</technical_language>

Target:
public void fetchAllExternalIdsWithUniformPageSizes() throws Exception { final CompletionStage<List<String>> categoriesStage = QueryExecutionUtils .queryAll(client(), CategoryQuery.of(), Category::getExternalId, 3); final List<String> externalIds = SphereClientUtils .blockingWait(categoriesStage, Duration.ofMinutes(1)); assertThat(externalIds).hasSize(15); IntStream.range(0, externalIds.size()).forEach(index -> assertThat(externalIds).contains(index + "")); }
Source:
<code>public String evidenceMessage( TokenNameLookup tokenNameLookup, LabelSchemaDescriptor schema ) { <START> assert schema.getPropertyIds().length == propertyValues.values().length; <END> String labelName = tokenNameLookup.labelGetName( schema.getLabelId() ); if ( addedNodeId == NO_SUCH_NODE ) { return format( "Node(%d) already exists with label `%s` and %s", existingNodeId, labelName, propertyString( tokenNameLookup, schema.getPropertyIds() ) ); } else { return format( "Both Node(%d) and Node(%d) have the label `%s` and %s", existingNodeId, addedNodeId, labelName, propertyString( tokenNameLookup, schema.getPropertyIds() ) ); } }</code><technical_language>a specific object for property values i super strange fall backing array get propose propertyValues.size() method instead</technical_language>

Target:
public String evidenceMessage( TokenNameLookup tokenNameLookup, LabelSchemaDescriptor schema ) { assert schema.getPropertyIds().length == propertyValues.size(); String labelName = tokenNameLookup.labelGetName( schema.getLabelId() ); if ( addedNodeId == NO_SUCH_NODE ) { return format( "Node(%d) already exists with label `%s` and %s", existingNodeId, labelName, propertyString( tokenNameLookup, schema.getPropertyIds() ) ); } else { return format( "Both Node(%d) and Node(%d) have the label `%s` and %s", existingNodeId, addedNodeId, labelName, propertyString( tokenNameLookup, schema.getPropertyIds() ) ); } }
Source:
<code>public void testUpdateWithReturnEntity() { final Person updated = new Person(TEST_PERSON.getId(), UPDATED_FIRST_NAME, TEST_PERSON.getLastName(), TEST_PERSON.getHobbies(), TEST_PERSON.getShippingAddresses()); <START> <END> final Person updatedPerson = cosmosTemplate.upsertAndReturnEntity(Person.class.getSimpleName(), updated); final Person findPersonById = cosmosTemplate.findById(Person.class.getSimpleName(), updatedPerson.getId(), Person.class); assertEquals(updatedPerson, updated); }</code><technical_language>Yes, please add asserts back</technical_language>

Target:
public void testUpdateWithReturnEntity() { final Person updated = new Person(TEST_PERSON.getId(), UPDATED_FIRST_NAME, TEST_PERSON.getLastName(), TEST_PERSON.getHobbies(), TEST_PERSON.getShippingAddresses()); updated.set_etag(insertedPerson.get_etag()); final Person updatedPerson = cosmosTemplate.upsertAndReturnEntity(Person.class.getSimpleName(), updated); final Person findPersonById = cosmosTemplate.findById(Person.class.getSimpleName(), updatedPerson.getId(), Person.class); assertEquals(updatedPerson, updated); assertThat(updatedPerson.get_etag()).isEqualTo(findPersonById.get_etag()); }
Source:
<code>public void testPrintTreeJavadocOption() throws Exception { final String expected = new String(Files.readAllBytes(Paths.get( getNonPackagePath("astprinter/expectedInputJavadocComment.txt"))), <START> StandardCharsets.UTF_8) <END> .replaceAll("\\\\r\\\\n", "\\\\n"); exit.checkAssertionAfterwards(() -> { assertEquals(expected, systemOut.getLog().replaceAll("\\\\r\\\\n", "\\\\n")); assertEquals("", systemErr.getLog()); }); Main.main("-j", getNonPackagePath("astprinter/InputJavadocComment.javadoc")); }</code><technical_language>input expected output copied test's input folder</technical_language>

Target:
public void testPrintTreeJavadocOption() throws Exception { final String expected = new String(Files.readAllBytes(Paths.get( getPath("InputMainExpectedInputJavadocComment.txt"))), StandardCharsets.UTF_8) .replaceAll("\\\\r\\\\n", "\\\\n"); exit.checkAssertionAfterwards(() -> { assertEquals(expected, systemOut.getLog().replaceAll("\\\\r\\\\n", "\\\\n")); assertEquals("", systemErr.getLog()); }); Main.main("-j", getPath("InputMainJavadocComment.javadoc")); }
Source:
<code>private static ProcessingEnvironment unwrapProcessingEnvironment(ProcessingEnvironment env) { if (env.getClass().getName() <START> == "com.sun.tools.javac.processing.JavacProcessingEnvironment") { <END> return env; } if (Proxy.isProxyClass(env.getClass())) { @Nullable ProcessingEnvironment unwrapped = unwrapIntelliJ(env); if (unwrapped != null) { return unwrapProcessingEnvironment(unwrapped); } } for (@Nullable Class<?> envClass = env.getClass(); envClass != null; envClass = envClass.getSuperclass()) { @Nullable ProcessingEnvironment unwrapped = unwrapGradle(envClass, env); if (unwrapped != null) { return unwrapProcessingEnvironment(unwrapped); } } throw new IllegalArgumentException( "CheckerFramework only supports Javac processing environment"); }</code><technical_language>result of getName() is guaranteed interned, .equals()</technical_language>

Target:
private static ProcessingEnvironment unwrapProcessingEnvironment(ProcessingEnvironment env) { if (env.getClass().getName() == "com.sun.tools.javac.processing.JavacProcessingEnvironment") { return env; } ProcessingEnvironment unwrappedIntelliJ = unwrapIntelliJ(env); if (unwrappedIntelliJ != null) { return unwrapProcessingEnvironment(unwrappedIntelliJ); } for (Class<?> envClass = env.getClass(); envClass != null; envClass = envClass.getSuperclass()) { ProcessingEnvironment unwrappedGradle = unwrapGradle(envClass, env); if (unwrappedGradle != null) { return unwrapProcessingEnvironment(unwrappedGradle); } } throw new BugInCF("Unexpected processing environment: %s %s", env, env.getClass()); }
Source:
<code>public void useHostIdAndTheUserDontHavePermission() throws DotDataException, DotSecurityException { final Host host = new SiteDataGen().nextPersisted(); final HttpServletRequest request = mock(HttpServletRequest.class); final HttpSession session = mock(HttpSession.class); setAllParametersAndAttributes(request, session); <START> when(request.getParameter("host_id")).thenReturn(host.getIdentifier()); <END> final User user = createBackendUser(); final HostWebAPIImpl hostWebAPI = new HostWebAPIImpl(); try { hostWebAPI.getCurrentHost(request, user); throw new RuntimeException("should throw a DotSecurityException"); } catch (DotSecurityException e) { } verify(request, never()).setAttribute(anyString(), anyObject()); verify(session, never()).setAttribute(anyString(), anyObject()); }</code><technical_language>constant HOST_ID_PARAMETER_NAME</technical_language>

Target:
public void useHostIdAndTheUserDontHavePermission() throws DotDataException, DotSecurityException { final Host host = new SiteDataGen().nextPersisted(); final HttpServletRequest request = mock(HttpServletRequest.class); final HttpSession session = mock(HttpSession.class); setAllParametersAndAttributes(request, session); when(request.getParameter(HOST_ID_PARAMETER_NAME)).thenReturn(host.getIdentifier()); final User user = createBackendUser(); final HostWebAPIImpl hostWebAPI = new HostWebAPIImpl(); try { hostWebAPI.getCurrentHost(request, user); throw new RuntimeException("should throw a DotSecurityException"); } catch (DotSecurityException e) { } verify(request, never()).setAttribute(anyString(), anyObject()); verify(session, never()).setAttribute(anyString(), anyObject()); }
Source:
<code>public void testCommentBeforeCreateTableAs() throws Exception { methodWatcher.executeUpdate("create table test_comment_before_create_as_dep_tbl (col int)"); String createStmt = "create table %s as select * from test_comment_before_create_as_dep_tbl"; try { methodWatcher.executeUpdate("-- some SQL-style comment here\n" + String.format(createStmt, generateTableName())); methodWatcher.executeUpdate(" \n" + String.format(createStmt, generateTableName())); methodWatcher.executeUpdate(" \n-- comments\n" + String.format(createStmt, generateTableName())); } catch (SQLException e) { <START> Assert.fail("No exception should be thrown"); <END> } }</code><technical_language>need catch here, exception bubble if is raised test fail stacktrace message</technical_language>

Target:
public void testCommentBeforeCreateTableAs() throws Exception { methodWatcher.executeUpdate("create table test_comment_before_create_as_dep_tbl (col int)"); String createStmt = "create table %s as select * from test_comment_before_create_as_dep_tbl"; methodWatcher.executeUpdate("-- some SQL-style comment here\n" + String.format(createStmt, generateTableName())); methodWatcher.executeUpdate(" \n" + String.format(createStmt, generateTableName())); methodWatcher.executeUpdate(" \n-- comments\n" + String.format(createStmt, generateTableName())); }
Source:
<code>public Transceiver readAuthors(ArticleIngestionIdentifier ingestionId) { return new Transceiver() { @Override protected Object getData() throws IOException { return parseAuthors(getManuscriptXml(getArticleIngestion(ingestionId))); } @Override protected Calendar getLastModifiedDate() throws IOException { <START> return null; <END> } }; }</code><technical_language>I safe ArticleIngestion object's timestamp return here. previous version return a timestamp for caching purposes, this important enough avoid degrading</technical_language>

Target:
public Transceiver readAuthors(ArticleIngestionIdentifier ingestionId) { ArticleIngestion articleIngestion = getArticleIngestion(ingestionId); return new Transceiver() { @Override protected Object getData() throws IOException { return parseAuthors(getManuscriptXml(articleIngestion)); } @Override protected Calendar getLastModifiedDate() throws IOException { return copyToCalendar(articleIngestion.getLastModified()); } }; }
Source:
<code>public GetUserResult getUserByProperty(final String key, final String value) { final UserDB userDB; try { userDB = getUserDb(); } catch (Exception e) { return new GetUserResult(GetUserResult.State.INTERNAL_ERROR, "Unable to get user database", e); } final Set<User> users = new HashSet<User>(); for (String username : userDB.getUserNames()) { final User user = userDB.getUser(username); final Map<String, String> properties = user.getProperties(); <START> if (properties != null && value.equals(properties.get(key))) { <END> users.add(user); } } if (users.isEmpty()) { return new GetUserResult(GetUserResult.State.UNKNOWN_USER); } return new GetUserResult(users, GetUserResult.State.OK); }</code><technical_language>This support matching of a set of whitespace separated entries in property. properties, need split whitespace check if of values match desired value</technical_language>

Target:
public GetUserResult getUserByProperty(final String key, final String value) { final UserDB userDB; try { userDB = getUserDb(); } catch (Exception e) { return new GetUserResult(GetUserResult.State.INTERNAL_ERROR, "Unable to get user database", e); } final Set<User> users = new HashSet<User>(); for (final User user : userDB.getAllUsers()) { final Map<String, String> properties = user.getProperties(); if (properties == null || properties.get(key) == null) { continue; } final String propertyValue = properties.get(key); if (Arrays.asList(propertyValue.split(" ")).contains(value)) { users.add(user); } } if (users.isEmpty()) { return new GetUserResult(GetUserResult.State.UNKNOWN_USER); } return new GetUserResult(users, GetUserResult.State.OK); }
Source:
<code>protected void endSuccessfully() { if (isStatelessSnapshotExistsForVm()) { getBackend().endAction(VdcActionType.CreateAllSnapshotsFromVm, buildCreateSnapshotParametersForEndAction(), <START> getContext().duplicate().resetCompensationContext().resetExecutionContext().resetLock()); <END> getParameters().setShouldBeLogged(false); getParameters().setRunAsStateless(false); setSucceeded(getBackend().runInternalAction( getActionType(), getParameters(), createContextForRunStatelessVm()).getSucceeded()); if (!getSucceeded()) { getParameters().setShouldBeLogged(true); log.errorFormat("Could not run VM {0} ({1}) in stateless mode", getVm().getName(), getVm().getId()); getReturnValue().setEndActionTryAgain(false); } } else { super.endSuccessfully(); } }</code><technical_language>a method in CommandContext prepare context for end-action phase? this line is in endAction call, right</technical_language>

Target:
protected void endSuccessfully() { if (isStatelessSnapshotExistsForVm()) { getBackend().endAction(VdcActionType.CreateAllSnapshotsFromVm, buildCreateSnapshotParametersForEndAction(), getContext().duplicate().withoutCompensationContext().withoutExecutionContext().withoutLock()); getParameters().setShouldBeLogged(false); getParameters().setRunAsStateless(false); setSucceeded(getBackend().runInternalAction( getActionType(), getParameters(), createContextForRunStatelessVm()).getSucceeded()); if (!getSucceeded()) { getParameters().setShouldBeLogged(true); log.errorFormat("Could not run VM {0} ({1}) in stateless mode", getVm().getName(), getVm().getId()); getReturnValue().setEndActionTryAgain(false); } } else { super.endSuccessfully(); } }
Source:
<code>public void configurePipeline(PipelineConfigurer configurer) throws IllegalArgumentException { super.configurePipeline(configurer); if (this.config.format == null || this.config.format.isEmpty()) { throw new IllegalArgumentException("Format is not specified. Allowed values are DEFAULT, EXCEL, MYSQL," + " RFC4180, PDL & TDF"); } if (!this.config.format.equalsIgnoreCase("DEFAULT") && !this.config.format.equalsIgnoreCase("EXCEL") && !this.config.format.equalsIgnoreCase("MYSQL") && !this.config.format.equalsIgnoreCase("RFC4180") && !this.config.format.equalsIgnoreCase("TDF") && !this.config.format.equalsIgnoreCase("PDL")) { throw new IllegalArgumentException("Format specified is not one of the allowed values. Allowed values are " + "DEFAULT, EXCEL, MYSQL, RFC4180, PDL & TDF"); } Schema inputSchema = configurer.getStageConfigurer().getInputSchema(); if (inputSchema != null) { Schema.Field inputSchemaField = inputSchema.getField(config.field); if (inputSchemaField == null) { throw new IllegalArgumentException( "Field " + config.field + " is not present in the input schema"); } else { <START> if (!inputSchemaField.getSchema().getType().equals(Schema.Type.STRING) && <END> !isNullableString(inputSchemaField.getSchema())) { throw new IllegalArgumentException( "Type for field " + config.field + " must be String"); } } } try { Schema outputSchema = Schema.parseJson(this.config.schema); configurer.getStageConfigurer().setOutputSchema(outputSchema); if (inputSchema != null) { for (Field field : inputSchema.getFields()) { if (outputSchema.getField(field.getName()) != null) { Schema out = outputSchema.getField(field.getName()).getSchema(); Schema in = field.getSchema(); if (!in.equals(out)) { throw new IllegalArgumentException( "Input field '" + field.getName() + "' does not have same output schema as input." ); } } } } } catch (IOException e) { throw new IllegalArgumentException("Format of schema specified is invalid. Please check the format."); } }</code><technical_language>Schema's isNullable getNonNullable methods out here</technical_language>

Target:
public void configurePipeline(PipelineConfigurer configurer) throws IllegalArgumentException { super.configurePipeline(configurer); if (this.config.format == null || this.config.format.isEmpty()) { throw new IllegalArgumentException("Format is not specified. Allowed values are DEFAULT, EXCEL, MYSQL," + " RFC4180, PDL & TDF"); } if (!this.config.format.equalsIgnoreCase("DEFAULT") && !this.config.format.equalsIgnoreCase("EXCEL") && !this.config.format.equalsIgnoreCase("MYSQL") && !this.config.format.equalsIgnoreCase("RFC4180") && !this.config.format.equalsIgnoreCase("TDF") && !this.config.format.equalsIgnoreCase("PDL")) { throw new IllegalArgumentException("Format specified is not one of the allowed values. Allowed values are " + "DEFAULT, EXCEL, MYSQL, RFC4180, PDL & TDF"); } Schema inputSchema = configurer.getStageConfigurer().getInputSchema(); validateInputSchema(inputSchema); configurer.getStageConfigurer().setOutputSchema(parseAndValidateOutputSchema(inputSchema)); }
Source:
<code>protected void executeQueryCommand() { GlusterGeoRepDao geoRepDb = getGeoRepDao(); Guid sessionId = getParameters().getId(); GlusterGeoRepSession session = geoRepDb.getById(sessionId); GlusterVolumeEntity masterVolume = getGlusterVolumeDao().getById(session.getMasterVolumeId()); <START> VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GetGlusterVolumeGeoRepConfigList, new GlusterVolumeGeoRepSessionVDSParameters(getUpServerId(masterVolume.getClusterId()), sessionId, masterVolume.getName())); <END> getQueryReturnValue().setReturnValue((List<GlusterGeoRepSessionConfiguration>)returnValue.getReturnValue()); }</code><technical_language>Is null check for masterVolume required</technical_language>

Target:
protected void executeQueryCommand() { getQueryReturnValue().setReturnValue(getGeoRepDao().getGeoRepSessionConfig(getParameters().getId())); }
Source:
<code>public void testReferenceCounting() { int positionCount = 5; <START> Slice[] baseValues = createExpectedUniqueValues(positionCount); <END> Slice[] identicalValues = createExpectedUniqueValues(positionCount); Slice[] realValues = new Slice[positionCount * 3]; long sliceContentBytes = 0; for (int i = 0; i < positionCount; i++) { realValues[i] = baseValues[i]; realValues[positionCount + i] = baseValues[i]; realValues[positionCount * 2 + i] = identicalValues[i]; sliceContentBytes += i; } long expectedRetainedBytes = ClassLayout.parseClass(SliceArrayBlock.class).instanceSize() + ClassLayout.parseClass(Slice.class).instanceSize() * positionCount * 3 + sizeOf(realValues) + sliceContentBytes * 2; SliceArrayBlock block = new SliceArrayBlock(positionCount * 3, realValues, false); assertEquals(block.getRetainedSizeInBytes(), expectedRetainedBytes); }</code><technical_language>name for Slice[]s nice. baseSlices, baseSlicesCopy, testSlices</technical_language>

Target:
public void testReferenceCounting() { int positionCount = 5; Slice[] baseSlices = createExpectedUniqueValues(positionCount); Slice[] baseSlicesCopy = createExpectedUniqueValues(positionCount); Slice[] testSlices = new Slice[positionCount * 3]; long testSlicesSizeInBytes = 0; for (int i = 0; i < positionCount; i++) { testSlices[i] = baseSlices[i]; testSlices[positionCount + i] = baseSlices[i]; testSlices[positionCount * 2 + i] = baseSlicesCopy[i]; testSlicesSizeInBytes += i; } long expectedRetainedSizeInBytes = ClassLayout.parseClass(SliceArrayBlock.class).instanceSize() + ClassLayout.parseClass(Slice.class).instanceSize() * (testSlices.length - 3) + sizeOf(testSlices) + testSlicesSizeInBytes * 2; SliceArrayBlock block = new SliceArrayBlock(testSlices.length, testSlices, false); assertEquals(block.getRetainedSizeInBytes(), expectedRetainedSizeInBytes); }
Source:
<code>public void setup() throws IOException { Path filePath = Paths.get(this.getClass().getClassLoader().getResource("large_polygon.txt").getPath()); <START> List<String> lines = Files.lines(filePath).collect(Collectors.toList()); <END> String line = lines.get(0); String[] parts = line.split("\\|"); String wkt = parts[0]; geometry = GeoFunctions.stGeometryFromText(Slices.utf8Slice(wkt)); envelope = GeoFunctions.stEnvelope(geometry); zoomLevel = Integer.parseInt(parts[1]); }</code><technical_language>List<String> lines = Files.readAllLines(filePath);</technical_language>

Target:
public void setup() throws IOException { Path filePath = Paths.get(this.getClass().getClassLoader().getResource("large_polygon.txt").getPath()); List<String> lines = Files.readAllLines(filePath); String line = lines.get(0); String[] parts = line.split("\\|"); String wkt = parts[0]; geometry = GeoFunctions.stGeometryFromText(Slices.utf8Slice(wkt)); envelope = GeoFunctions.stEnvelope(geometry); zoomLevel = Integer.parseInt(parts[1]); }
Source:
<code>public static String getPLD(String hostname) { if (hostname.startsWith("[") && hostname.endsWith("]")) { return hostname; } if (IPV4_ADDRESS_PATTERN.matcher(hostname).matches()) { return hostname; } String result = EffectiveTldFinder.getAssignedDomain(hostname, true); if (result == null) { <START> LOGGER.debug(String.format("Hostname %s isn't a valid FQDN", hostname)); <END> return hostname; } else { return result; } }</code><technical_language>@kkrugler, I forgotten forbiddenapis shows automated checks PRs useful. a closer PR Tuesday. happy releasing 0.9 merging it? release 0.9.1 shortly</technical_language>

Target:
public static String getPLD(String hostname) { if (hostname.startsWith("[") && hostname.endsWith("]")) { return hostname; } if (IPV4_ADDRESS_PATTERN.matcher(hostname).matches()) { return hostname; } String result = EffectiveTldFinder.getAssignedDomain(hostname, true); if (result == null) { LOGGER.debug("Hostname isn't a valid FQDN", hostname); return hostname; } else { return result; } }
Source:
<code>void throwExceptionIfError() { if (this.isError()) { throw logger.logExceptionAsError(new TextAnalyticsException( <START> String.format("Error in accessing the property on document id: %s, when %s returned with an error: %s", this.id, this.getClass().getSimpleName(), this.error.getMessage()), <END> this.error.getCode().toString(), null)); } }</code><technical_language>do other String.format changes Locale.ROOT this not</technical_language>

Target:
void throwExceptionIfError() { if (this.isError()) { throw logger.logExceptionAsError(new TextAnalyticsException( String.format(Locale.ROOT, "Error in accessing the property on document id: %s, when %s returned with an error: %s", this.id, this.getClass().getSimpleName(), this.error.getMessage()), this.error.getCode().toString(), null)); } }
Source:
<code>public void store(final Configuration configuration) { try { Resource configurationResource = getConfigurationResource(); if (!configurationResource.isFile()) { <START> LOGGER.warn(String.format("Skip configuration resource store [%s]", configurationResource)); <END> return; } parser.store(configuration, configurationResource.getFile()); } catch (JAXBException | IOException e) { throw new ConfigurationSaveException(e); } }</code><technical_language>Hey, mind changing name of this logger lowercase? else great proceed self-merging this minor change request</technical_language>

Target:
public void store(final Configuration configuration) { try { parser.store(configuration, getConfigurationResource()); } catch (JAXBException | IOException e) { throw new ConfigurationSaveException(e); } }
Source:
<code>public void writeResult(Object result) throws IOException { <START> if (result instanceof String || result instanceof Number || result instanceof Boolean) { <END> writeString(String.valueOf(result)); } else if (result instanceof Date) { Date timeStamp = (Date) result; DateFormat df = new SimpleDateFormat("YYYY/MM/DD hh:mm:ss"); writeResult(df.format(timeStamp)); } else if (result instanceof ComplexAttribute) { ComplexAttribute attr = (ComplexAttribute) result; writeResult(attr.getValue()); } else if (result instanceof Attribute) { Attribute attr = (Attribute) result; writeResult(attr.getValue()); } else if (result instanceof List) { List list = (List) result; if (list.size() == 1) { writeResult(list.get(0)); } else { writeStartArray(); for (int i = 0; i < list.size(); i++) { writeResult(list.get(i)); } writeEndArray(); } } else { writeNull(); } }</code><technical_language>Bellow have: } else { writeNull(); } I recommend: } else if (result == null) { writeNull(); } else { throw new RuntimeException("We handle provided object o type '" + result.getClass() + "'."): } ... this method more resilient, write NULL object is NULL, if handle object throw exception</technical_language>

Target:
public void writeResult(Object result) throws IOException { if (result instanceof String || result instanceof Number || result instanceof Boolean) { writeString(String.valueOf(result)); } else if (result instanceof Date) { Date timeStamp = (Date) result; DateFormat df = new SimpleDateFormat("YYYY/MM/DD hh:mm:ss"); writeResult(df.format(timeStamp)); } else if (result instanceof ComplexAttribute) { ComplexAttribute attr = (ComplexAttribute) result; writeResult(attr.getValue()); } else if (result instanceof Attribute) { Attribute attr = (Attribute) result; writeResult(attr.getValue()); } else if (result instanceof List) { List list = (List) result; if (list.size() == 1) { writeResult(list.get(0)); } else { writeStartArray(); for (int i = 0; i < list.size(); i++) { writeResult(list.get(i)); } writeEndArray(); } } else if (result == null) { writeNull(); } else { throw new RuntimeException( "We can't handle the provided object o type '" + result.getClass() + "'."); } }
Source:
<code>public LineString toLineString(boolean includeElevation) { <START> return toLineString(new GeometryFactory(), includeElevation); <END> }</code><technical_language>create a factory for 2D 3D them</technical_language>

Target:
public LineString toLineString(boolean includeElevation) { Coordinate[] coordinates = new Coordinate[getSize() == 1 ? 2 : getSize()]; for (int i = 0; i < getSize(); i++) { coordinates[i] = includeElevation ? new Coordinate( round6(getLongitude(i)), round6(getLatitude(i)), round2(getElevation(i))) : new Coordinate( round6(getLongitude(i)), round6(getLatitude(i))); } if (getSize() == 1) coordinates[1] = coordinates[0]; return factory.createLineString(new PackedCoordinateSequence.Double(coordinates, includeElevation ? 3 : 2)); }
Source:
<code>PacketStream(Protocol protocol, int id, ProtocolEndpointPair endpointPair) { fProtocol = protocol; fId = id; fEndpointPair = endpointPair; fNbPacketsAtoB = 0; fNbPacketsBtoA = 0; fNbBytesAtoB = 0; fNbBytesBtoA = 0; fStartTime = -1; <START> fStopTime = -1; <END> }</code><technical_language>fEndTime maybe? "start" noun, start of trace, verb. of start is end in this case</technical_language>

Target:
PacketStream(Protocol protocol, int id, ProtocolEndpointPair endpointPair) { fProtocol = protocol; fId = id; fEndpointPair = endpointPair; fNbPacketsAtoB = 0; fNbPacketsBtoA = 0; fNbBytesAtoB = 0; fNbBytesBtoA = 0; fStartTime = Long.MAX_VALUE; fEndTime = Long.MIN_VALUE; }
Source:
<code>public void handle(final DolphinRemotingException e) { <START> LOG.info(" Error in remoting layer: ", e); <END> }</code><technical_language>This error</technical_language>

Target:
public void handle(final DolphinRemotingException e) { LOG.error(" Error in remoting layer: ", e); }
Source:
<code>public void testNonRefAllele() { Assert.assertTrue(NonRef.isNonRefAllele()); Assert.assertTrue(UnspecifiedAlternate.isNonRefAllele()); Assert.assertFalse(T.isNonRefAllele()); Assert.assertFalse(ATIns.isNonRefAllele()); Assert.assertTrue(Allele.NON_REF_ALLELE.isNonRefAllele()); Assert.assertTrue(Allele.UNSPECIFIED_ALTERNATE_ALLELE.isNonRefAllele()); <START> Allele a = Allele.create("<*>"); <END> Assert.assertTrue(a.isNonRefAllele()); }</code><technical_language>UNSPECIFIED_ALTERNATE_ALLELE_STRING here</technical_language>

Target:
public void testNonRefAllele() { Assert.assertTrue(NonRef.isNonRefAllele()); Assert.assertTrue(UnspecifiedAlternate.isNonRefAllele()); Assert.assertFalse(T.isNonRefAllele()); Assert.assertFalse(ATIns.isNonRefAllele()); Assert.assertTrue(Allele.NON_REF_ALLELE.isNonRefAllele()); Assert.assertTrue(Allele.UNSPECIFIED_ALTERNATE_ALLELE.isNonRefAllele()); Allele a = Allele.create(new String("<*>")); Assert.assertTrue(a.isNonRefAllele()); }
Source:
<code>public void basicInvocation(Runnable call) throws Exception { DistributedExecutorService des = createDES(getCache()); <START> des.submit(call); <END> }</code><technical_language>I believe, call get future: des.submit(call).get()</technical_language>

Target:
public void basicInvocation(Runnable call) throws Exception { DistributedExecutorService des = createDES(getCache()); des.submit(call).get(); }
Source:
<code>protected Response doAction(final VdcActionType task, final VdcActionParametersBase params, final Action action, AbstractBackendResource.PollingType pollingType) { awaitGrace(action); try { VdcReturnValueBase actionResult = doAction(task, params); if (actionResult.getJobId() != null) { setJobLink(action, actionResult); } <START> if (actionResult.getHasAsyncTasks() || actionResult.getJobId() != null) { <END> if (expectBlocking(action)) { CreationStatus status = awaitCompletion(actionResult, pollingType); return actionStatus(status, action, addLinks(newModel(id))); } else { return actionAsync(actionResult, action); } } else { return actionSuccess(action, addLinks(newModel(id))); } } catch (Exception e) { return handleError(e, action); } }</code><technical_language>Synchronous command a job id (see ExecutionMessages.properties) - operation "tasks" tab, necessarily action asynchronous operations. I add a flag action result determine if a command async operations (I set true if command callback if async tasks checked today)</technical_language>

Target:
protected Response doAction(final VdcActionType task, final VdcActionParametersBase params, final Action action, AbstractBackendResource.PollingType pollingType) { awaitGrace(action); try { VdcReturnValueBase actionResult = doAction(task, params); if (actionResult.getJobId() != null) { setJobLink(action, actionResult); } if (actionResult.getHasAsyncTasks()) { if (expectBlocking(action)) { CreationStatus status = awaitCompletion(actionResult, pollingType); return actionStatus(status, action, addLinks(newModel(id))); } else { return actionAsync(actionResult, action); } } else { return actionSuccess(action, addLinks(newModel(id))); } } catch (Exception e) { return handleError(e, action); } }
Source:
<code>public void setChainingStrategy(ChainingStrategy strategy) { <START> chainingStrategy = strategy; <END> }</code><technical_language>add a checkNotNull here</technical_language>

Target:
public void setChainingStrategy(ChainingStrategy strategy) { chainingStrategy = checkNotNull(strategy); }
Source:
<code>public String getVersion(){ <START> return group.getSelectedVersionGroup().getVersion(); <END> }</code><technical_language>group.getSelectedVersionGroup() is checked for null, in other cases check is used</technical_language>

Target:
public IHTMLLibraryVersion getVersion(){ return group.getSelectedVersionGroup().getVersion(); }
Source:
<code>private static void handleAPIError(String rBody, int rCode, String requestId) throws InvalidRequestException, AuthenticationException, CardException, APIException { LiveStripeResponseGetter.Error error = APIResource.GSON.fromJson(rBody, LiveStripeResponseGetter.ErrorContainer.class).error; switch (rCode) { case 400: throw new InvalidRequestException(error.message, requestId, error.param, null); case 404: throw new InvalidRequestException(error.message, requestId, error.param, null); case 401: throw new AuthenticationException(error.message); case 402: throw new CardException(error.message, requestId, error.code, error.param, error.decline_code, error.charge, null); default: <START> throw new APIException(error.message, null); <END> } }</code><technical_language>Do return a request ID 500s? record iar in some cases</technical_language>

Target:
private static void handleAPIError(String rBody, int rCode, String requestId) throws InvalidRequestException, AuthenticationException, CardException, APIException { LiveStripeResponseGetter.Error error = APIResource.GSON.fromJson(rBody, LiveStripeResponseGetter.ErrorContainer.class).error; switch (rCode) { case 400: throw new InvalidRequestException(error.message, requestId, error.param, null); case 404: throw new InvalidRequestException(error.message, requestId, error.param, null); case 401: throw new AuthenticationException(error.message, requestId); case 402: throw new CardException(error.message, requestId, error.code, error.param, error.decline_code, error.charge, null); default: throw new APIException(error.message, requestId, null); } }
Source:
<code>private Response getStat(BaseDataAccessor<byte[]> zkBaseDataAccessor, String path) { if (zkBaseDataAccessor.exists(path, AccessOption.PERSISTENT)) { <START> Stat stat = zkBaseDataAccessor.getStat(path, AccessOption.PERSISTENT); <END> Map<String, String> result = ZKUtil.fromStatToMap(stat); result.put("path", path); return JSONRepresentation(result); } else { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND) .entity(String.format("The ZNode at path %s does not exist!", path)).build()); } }</code><technical_language>I getStat return null if path exist. need call exists this line</technical_language>

Target:
private Response getStat(BaseDataAccessor<byte[]> zkBaseDataAccessor, String path) { Stat stat = zkBaseDataAccessor.getStat(path, AccessOption.PERSISTENT); if (stat == null) { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND) .entity(String.format("The ZNode at path %s does not exist!", path)).build()); } Map<String, String> result = ZKUtil.fromStatToMap(stat); result.put("path", path); return JSONRepresentation(result); }
Source:
<code>private static final Element parseXML(InputStream input, Optional<String> encoding) throws SAXException, IOException { <START> try { <END> DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder documentBuilder; try { documentBuilder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { String message = e.getMessage(); throw new RuntimeException(message != null ? message : e.getClass().getSimpleName(), e); } InputSource source = new InputSource(input); encoding.ifPresent((value) -> { source.setEncoding(value); }); return documentBuilder.parse(source).getDocumentElement(); } finally { input.close(); } }</code><technical_language>I hope, right</technical_language>

Target:
private static final Element parseXML(InputStream input, Optional<String> encoding) throws SAXException, IOException { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); InputSource source = new InputSource(input); encoding.ifPresent(value -> source.setEncoding(value)); return factory.newDocumentBuilder().parse(source).getDocumentElement(); } catch (ParserConfigurationException e) { throw new IllegalStateException(e.getMessage(), e); } }
Source:
<code><START> public HashMap<ItemIdentifier, Integer> getItemsAndCount() { <END> return getItemsAndCount(false); }</code><technical_language>change this Map HashMap? implementation get matter in cases</technical_language>

Target:
public Map<ItemIdentifier, Integer> getItemsAndCount() { return getItemsAndCount(false); }
Source:
<code><START> EvalResult evaluate(LDUser user, FeatureStore featureStore) throws EvaluationError { <END> if (user == null || user.getKey() == null) { throw new EvaluationError("User or user key is null"); } List<FeatureRequestEvent> prereqEvents = new ArrayList<>(); JsonElement value = evaluate(user, featureStore, prereqEvents); return new EvalResult(value, prereqEvents); }</code><technical_language>I realized changes solve a specific problem, If moving this pattern of throwing exceptions evaluation consider change board for consistency. example is Line 57 in this file: getOffVariationValue()</technical_language>

Target:
EvalResult evaluate(LDUser user, FeatureStore featureStore) throws EvaluationException { if (user == null || user.getKey() == null) { throw new EvaluationException("User or user key is null"); } List<FeatureRequestEvent> prereqEvents = new ArrayList<>(); JsonElement value = evaluate(user, featureStore, prereqEvents); return new EvalResult(value, prereqEvents); }
Source:
<code>public void init() throws Exception { final EventTypeService eventTypeService = new EventTypeService(eventTypeRepository, topicRepository, partitionResolver, enrichment, uuid, featureToggleService); final EventTypeOptionsValidator eventTypeOptionsValidator = new EventTypeOptionsValidator(TOPIC_RETENTION_MIN_MS, TOPIC_RETENTION_MAX_MS); final EventTypeController controller = new EventTypeController(eventTypeService, featureToggleService, <START> eventTypeOptionsValidator, new DefaultApplicationService()); <END> Mockito.doReturn(randomUUID).when(uuid).randomUUID(); final MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter(objectMapper); doReturn(SecuritySettings.AuthMode.OFF).when(settings).getAuthMode(); doReturn("nakadi").when(settings).getAdminClientId(); doReturn(false).when(featureToggleService).isFeatureEnabled(any()); doReturn(true).when(featureToggleService).isFeatureEnabled(CHECK_PARTITIONS_KEYS); mockMvc = standaloneSetup(controller) .setMessageConverters(new StringHttpMessageConverter(), jackson2HttpMessageConverter) .setCustomArgumentResolvers(new ClientResolver(settings, featureToggleService)) .build(); }</code><technical_language>nice a test exercises new check</technical_language>

Target:
public void init() throws Exception { final EventTypeService eventTypeService = new EventTypeService(eventTypeRepository, topicRepository, partitionResolver, enrichment, uuid, featureToggleService); final EventTypeOptionsValidator eventTypeOptionsValidator = new EventTypeOptionsValidator(TOPIC_RETENTION_MIN_MS, TOPIC_RETENTION_MAX_MS); final NakadiSettings nakadiSettings = new NakadiSettings(0, 0, 0, TOPIC_RETENTION_TIME_MS, 0); final EventTypeController controller = new EventTypeController(eventTypeService, featureToggleService, eventTypeOptionsValidator, applicationService, nakadiSettings); Mockito.doReturn(randomUUID).when(uuid).randomUUID(); final MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter(objectMapper); doReturn(true).when(applicationService).exists(any()); doReturn(SecuritySettings.AuthMode.OFF).when(settings).getAuthMode(); doReturn("nakadi").when(settings).getAdminClientId(); doReturn(false).when(featureToggleService).isFeatureEnabled(any()); doReturn(true).when(featureToggleService).isFeatureEnabled(CHECK_PARTITIONS_KEYS); mockMvc = standaloneSetup(controller) .setMessageConverters(new StringHttpMessageConverter(), jackson2HttpMessageConverter) .setCustomArgumentResolvers(new ClientResolver(settings, featureToggleService)) .build(); }
Source:
<code>private Optional<InputWithData<IndexedInputGate, BufferOrEvent>> waitAndGetNextData(boolean blocking) throws IOException, InterruptedException { while (true) { Optional<IndexedInputGate> inputGateOpt = getInputGate(blocking); if (!inputGateOpt.isPresent()) { return Optional.empty(); } final IndexedInputGate inputGate = inputGateOpt.get(); Optional<BufferOrEvent> nextOpt = inputGate.pollNext(); if (!nextOpt.isPresent()) { inputGate.getAvailableFuture().thenRun(() -> queueInputGate(inputGate, false)); continue; } <START> final BufferOrEvent bufferOrEvent = nextOpt.get(); <END> synchronized (inputGatesWithData) { if (bufferOrEvent.moreAvailable()) { if (bufferOrEvent.morePriorityEvents()) { inputGatesWithData.addPriorityElement(inputGate); } else { inputGatesWithData.add(inputGate); } } else if (!inputGate.isFinished()) { inputGate.getAvailableFuture().thenRun(() -> queueInputGate(inputGate, false)); } if (bufferOrEvent.hasPriority() && !bufferOrEvent.morePriorityEvents()) { inputGate.getPriorityEventAvailableFuture().thenRun(() -> handlePriorityEventAvailable(inputGate)); } final boolean morePriorityEvents = inputGatesWithData.getNumPriorityElements() > 0; if (bufferOrEvent.hasPriority() && !morePriorityEvents) { priorityAvailabilityHelper.resetUnavailable(); } return Optional.of(new InputWithData<>( inputGate, bufferOrEvent, !inputGatesWithData.isEmpty(), morePriorityEvents)); } } }</code><technical_language>nit: extract to: return Optional.of(processBufferOrEvent(nextOpt.get()));</technical_language>

Target:
private Optional<InputWithData<IndexedInputGate, BufferOrEvent>> waitAndGetNextData(boolean blocking) throws IOException, InterruptedException { while (true) { synchronized (inputGatesWithData) { Optional<IndexedInputGate> inputGateOpt = getInputGate(blocking); if (!inputGateOpt.isPresent()) { return Optional.empty(); } final IndexedInputGate inputGate = inputGateOpt.get(); Optional<BufferOrEvent> nextOpt = inputGate.pollNext(); if (!nextOpt.isPresent()) { inputGate.getAvailableFuture().thenRun(() -> queueInputGate(inputGate, false)); continue; } return Optional.of(processBufferOrEvent(inputGate, nextOpt.get())); } } }
Source:
<code>private void createHandleForDateWithDropDown () { containerHandle = gtk_box_new (OS.GTK_ORIENTATION_HORIZONTAL, false, 0); if (containerHandle == 0) error (SWT.ERROR_NO_HANDLES); OS.gtk_container_add (fixedHandle, containerHandle); textEntryHandle = OS.gtk_entry_new (); if (textEntryHandle == 0) error (SWT.ERROR_NO_HANDLES); OS.gtk_container_add (containerHandle, textEntryHandle); OS.gtk_widget_show (containerHandle); OS.gtk_widget_show (textEntryHandle); handle = containerHandle; if (handle == 0) error (SWT.ERROR_NO_HANDLES); <START> if (OS.GTK_VERSION < OS.VERSION(3, 21, 0)) { <END> setFontDescription(defaultFont().handle); } }</code><technical_language>Generally check for GTK dev versions. GTK3.21 is a development version, this call GTK3.22</technical_language>

Target:
private void createHandleForDateWithDropDown () { containerHandle = gtk_box_new (OS.GTK_ORIENTATION_HORIZONTAL, false, 0); if (containerHandle == 0) error (SWT.ERROR_NO_HANDLES); OS.gtk_container_add (fixedHandle, containerHandle); textEntryHandle = OS.gtk_entry_new (); if (textEntryHandle == 0) error (SWT.ERROR_NO_HANDLES); OS.gtk_container_add (containerHandle, textEntryHandle); OS.gtk_widget_show (containerHandle); OS.gtk_widget_show (textEntryHandle); handle = containerHandle; if (handle == 0) error (SWT.ERROR_NO_HANDLES); if (OS.GTK_VERSION < OS.VERSION(3, 22, 0)) { setFontDescription(defaultFont().handle); } }
Source:
<code><START> private String getFromLine() { <END> velocityContext.put("from", args.accountCache.get(fromId).getAccount()); return velocify("#if ($from.fullName || $from.preferredEmail)From"+ "#if ($from.fullName) $from.fullName#endif" + "#if ($from.preferredEmail) <$from.preferredEmail>#endif" + ":\n\n#endif"); }</code><technical_language>this is before. moving a lot of conditional logic is easy statically check references in pure Java code embedded script. ugly. For other header fields in this change, I change code easier follow. this working for me</technical_language>

Target:
protected String getFromLine() { final Account account = args.accountCache.get(fromId).getAccount(); final String name = account.getFullName(); final String email = account.getPreferredEmail(); StringBuilder f = new StringBuilder(); if ((name != null && !name.isEmpty()) || (email != null && !email.isEmpty())) { f.append("From"); if (name != null && !name.isEmpty()) { f.append(" ").append(name); } if (email != null && !email.isEmpty()) { f.append(" <").append(email).append(">"); } f.append(":\n\n"); } return f.toString(); }
Source:
<code>public void onComplete(T result) { if (result != null) { CacheKey cacheKey = new CacheKey(); <START> cacheKey.setBuildAction(this.buildAction); <END> this.cache.put(cacheKey, result); } this.delegate.onComplete(result); }</code><technical_language>cache keys mutable</technical_language>

Target:
public void onComplete(T result) { if (result != null) { this.cache.put(CacheKey.builder().setBuildAction(this.buildAction).build(), result); } this.delegate.onComplete(result); }