auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static Text formatNoChecks(Text template, Map<String, ?> replacements) { if (template instanceof Placeholder) { Object replacement = replacements.get(((Placeholder) template).getKey()); if (replacement != null) { <START> return Texts.of(template.getColor(), template.getStyle(), replacement); <END> } } TextBuilder builder = template.builder(); builder.removeAll(); for (Text child : template.getChildren()) { builder.append(formatNoChecks(child, replacements)); } return builder.build(); }</code><technical_language>click, hover, etc. if replacement is a Text, want return replacement</technical_language>

Target:
private static Text formatNoChecks(Text template, Map<String, ?> replacements) { if (template instanceof Placeholder) { Object replacement = replacements.get(((Placeholder) template).getKey()); if (replacement != null) { List<Object> formats = new ArrayList<Object>(); formats.add(template.getColor()); formats.add(template.getStyle()); Optional<HoverAction<?>> hoverAction = template.getHoverAction(); if (hoverAction.isPresent()) { formats.add(hoverAction.get()); } Optional<ClickAction<?>> clickAction = template.getClickAction(); if (clickAction.isPresent()) { formats.add(clickAction.get()); } Optional<ShiftClickAction<?>> shiftClickAction = template.getShiftClickAction(); if (shiftClickAction.isPresent()) { formats.add(shiftClickAction.get()); } formats.add(replacement); return Texts.of(formats.toArray()); } } TextBuilder builder = template.builder(); builder.removeAll(); for (Text child : template.getChildren()) { builder.append(formatNoChecks(child, replacements)); } return builder.build(); }
Source:
<code>private void refreshCustomizedStateConfig(final HelixDataAccessor accessor) { if (_propertyDataChangedMap.get(HelixConstants.ChangeType.CUSTOMIZED_STATE_CONFIG) .getAndSet(false)) { CustomizedStateConfig customizedStateConfig = accessor.getProperty(accessor.keyBuilder().customizedStateConfig()); if (customizedStateConfig != null) { _aggregationEnabledTypes = new HashSet<>(customizedStateConfig.getAggregationEnabledTypes()); } else { _aggregationEnabledTypes.clear(); } <START> _customizedStateCache.setAggregationEnabledTypes(_aggregationEnabledTypes); <END> LogUtil.logInfo(logger, getClusterEventId(), String .format("Reloaded CustomizedStateConfig for cluster %s, %s pipeline.", getClusterName(), getPipelineName())); } else { LogUtil.logInfo(logger, getClusterEventId(), String .format("No customized state config change for %s cluster, %s pipeline", getClusterName(), getPipelineName())); } }</code><technical_language>explicitly call this refreshCustomizedStateConfig _customizedStateCache.refresh()? _customizedStateCache.setAggregationEnabledTypes refresh ordered, putting is easier for understand maintain</technical_language>

Target:
private void refreshCustomizedStateConfig(final HelixDataAccessor accessor) { if (_propertyDataChangedMap.get(HelixConstants.ChangeType.CUSTOMIZED_STATE_CONFIG) .getAndSet(false)) { CustomizedStateConfig customizedStateConfig = accessor.getProperty(accessor.keyBuilder().customizedStateConfig()); if (customizedStateConfig != null) { _aggregationEnabledTypes = new HashSet<>(customizedStateConfig.getAggregationEnabledTypes()); } else { _aggregationEnabledTypes.clear(); } LogUtil.logInfo(logger, getClusterEventId(), String .format("Reloaded CustomizedStateConfig for cluster %s, %s pipeline.", getClusterName(), getPipelineName())); } else { LogUtil.logInfo(logger, getClusterEventId(), String .format("No customized state config change for %s cluster, %s pipeline", getClusterName(), getPipelineName())); } }
Source:
<code>public void rollback() throws SQLException { checkClosed(); if (autoCommit) { throw new PSQLException(GT.tr("Cannot rollback when autoCommit is enabled."), PSQLState.NO_ACTIVE_SQL_TRANSACTION); } if (queryExecutor.getTransactionState() != TransactionState.IDLE) { executeTransactionCommand(rollbackQuery); } else { <START> LOGGER.log(Level.WARNING, "Rollback requested but no transaction in progress"); <END> } }</code><technical_language>Level.FINE, for debugging anyway</technical_language>

Target:
public void rollback() throws SQLException { checkClosed(); if (autoCommit) { throw new PSQLException(GT.tr("Cannot rollback when autoCommit is enabled."), PSQLState.NO_ACTIVE_SQL_TRANSACTION); } if (queryExecutor.getTransactionState() != TransactionState.IDLE) { executeTransactionCommand(rollbackQuery); } else { LOGGER.log(Level.FINE, "Rollback requested but no transaction in progress"); } }
Source:
<code>public void shouldParseUberConfirmationSegment() { String routingResponse = "{\"booking\":" + "{\"confirmation\":{\"provider\":{\"title\":\"John\",\"subtitle\":\"4.9\",\"imageURL\":\"<LINK_2>\"}," + "\"vehicle\":{\"title\":\"Prius Toyota\",\"subtitle\":\"UBER-PLATE\",\"imageURL\":\"<LINK_0>\"}," + "\"status\":{\"title\":\"Accepted\",\"subtitle\":\"Your request has been accepted by a driver and is 'en route' to the start location.\",\"value\":\"accepted\"}," + "\"purchase\":{\"price\":8.0,\"currency\":\"AUD\",\"productName\":\"uberX\",\"productType\":\"ps_tnc\",\"id\":\"2d1d002b-d4d0-4411-98e1-673b244878b2\"}," + "\"actions\":[{\"title\":\"Cancel Ride\",\"type\":\"CANCEL\",\"internalURL\":\"<LINK_1>\",\"isDestructive\":true}," + "{\"title\":\"Call Driver\",\"type\":\"CALL\",\"externalURL\":\"tel:(555)555-5555\",\"isDestructive\":false}]},\"title\":\"Accepted\"}," + <START> "\"endTime\":1476477040,\"realTime\":true,\"segmentTemplateHashCode\":105079429,\"startTime\":1476476663}"; <END> TripSegment segment = bookingGson().fromJson(routingResponse, TripSegment.class); assertThat(segment.getBooking()).isNotNull(); assertThat(segment.getBooking().getConfirmation()).isNotNull(); }</code><technical_language>Pls put a separate JSON file. Format JSON. In order read JSON string, use: java IOUtils.toString( getClass().getResourceAsStream(path), Charset.defaultCharset() );</technical_language>

Target:
public void shouldParseUberConfirmationSegment() throws IOException { String routingResponse = IOUtils.toString(getClass().getResourceAsStream("/booking-uber.json")); TripSegment segment = bookingGson().fromJson(routingResponse, TripSegment.class); assertThat(segment.getBooking()).isNotNull(); assertThat(segment.getBooking().getConfirmation()).isNotNull(); }
Source:
<code>void loadWhenBindingToConstructorParametersWithCustomDataUnitShouldBind() { MutablePropertySources sources = this.context.getEnvironment().getPropertySources(); Map<String, Object> source = new HashMap<>(); source.put("test.duration", "12"); source.put("test.size", "13"); source.put("test.period", "14"); source.put("test.formattedDuration", "15d"); source.put("test.formattedPeriod", "16y"); sources.addLast(new MapPropertySource("test", source)); load(ConstructorParameterWithUnitConfiguration.class); ConstructorParameterWithUnitProperties bean = this.context .getBean(ConstructorParameterWithUnitProperties.class); assertThat(bean.getDuration()).isEqualTo(Duration.ofDays(12)); assertThat(bean.getSize()).isEqualTo(DataSize.ofMegabytes(13)); <START> assertThat(bean.getFormattedDuration()).isEqualTo(Duration.ofDays(15)); assertThat(bean.getFormattedPeriod()).isEqualTo(Period.ofYears(16)); <END> }</code><technical_language>assertions succeed @DurationFormat @PeriodFormat ConstructorParameterWithUnitProperties. I converter successfully infers style converted. verify format annotations working expected, I necessary trigger a failure trying, for example, bind ISO-8601 a property requires simple style</technical_language>

Target:
void loadWhenBindingToConstructorParametersWithCustomDataUnitShouldBind() { MutablePropertySources sources = this.context.getEnvironment().getPropertySources(); Map<String, Object> source = new HashMap<>(); source.put("test.duration", "12"); source.put("test.size", "13"); source.put("test.period", "14"); sources.addLast(new MapPropertySource("test", source)); load(ConstructorParameterWithUnitConfiguration.class); ConstructorParameterWithUnitProperties bean = this.context .getBean(ConstructorParameterWithUnitProperties.class); assertThat(bean.getDuration()).isEqualTo(Duration.ofDays(12)); assertThat(bean.getSize()).isEqualTo(DataSize.ofMegabytes(13)); assertThat(bean.getPeriod()).isEqualTo(Period.ofYears(14)); }
Source:
<code>private ResultAndError<PullTaskResult> handleBadLocalState(AndroidTransactionParserFactory factory) { Pair<Integer, String> returnCodeAndMessageFromRecovery = recover(requestor, factory); int returnCode = returnCodeAndMessageFromRecovery.first; String failureReason = returnCodeAndMessageFromRecovery.second; if (returnCode == PROGRESS_DONE) { onSuccessfulSync(); return new ResultAndError<>(PullTaskResult.DOWNLOAD_SUCCESS); } else if (returnCode == PROGRESS_RECOVERY_FAIL_SAFE || returnCode == PROGRESS_RECOVERY_FAIL_BAD) { wipeLoginIfItOccurred(); this.publishProgress(PROGRESS_DONE); return new ResultAndError<>(PullTaskResult.UNKNOWN_FAILURE, failureReason); } else { wipeLoginIfItOccurred(); <START> return null; <END> } }</code><technical_language>this return unknown error</technical_language>

Target:
private ResultAndError<PullTaskResult> handleBadLocalState(AndroidTransactionParserFactory factory) throws UnknownSyncError { Pair<Integer, String> returnCodeAndMessageFromRecovery = recover(requestor, factory); int returnCode = returnCodeAndMessageFromRecovery.first; String failureReason = returnCodeAndMessageFromRecovery.second; if (returnCode == PROGRESS_DONE) { onSuccessfulSync(); return new ResultAndError<>(PullTaskResult.DOWNLOAD_SUCCESS); } else if (returnCode == PROGRESS_RECOVERY_FAIL_SAFE || returnCode == PROGRESS_RECOVERY_FAIL_BAD) { wipeLoginIfItOccurred(); this.publishProgress(PROGRESS_DONE); return new ResultAndError<>(PullTaskResult.UNKNOWN_FAILURE, failureReason); } else { throw new UnknownSyncError(); } }
Source:
<code><START> public Arguments setUntypedNullArgument(Argument untypedNullArgument) { <END> if (untypedNullArgument == null) { throw new IllegalArgumentException("the Argument itself may not be null"); } this.untypedNullArgument = untypedNullArgument; return this; }</code><technical_language>Another non-permissible change</technical_language>

Target:
public void setUntypedNullArgument(Argument untypedNullArgument) { if (untypedNullArgument == null) { throw new IllegalArgumentException("the Argument itself may not be null"); } this.untypedNullArgument = untypedNullArgument; }
Source:
<code>public void run_gradle_script_messages_initialized() { <START> final String gradleInstallationName = "Default"; <END> GradleInstallation.installGradle(jenkins, gradleInstallationName, GradleInstallation.LATEST_VERSION); final FreeStyleJob job = jenkins.jobs.create(); job.copyResource(resource("/gradle_plugin/script.gradle"), "build.gradle"); final GradleStep step = job.addBuildStep(GradleStep.class); step.setVersion(gradleInstallationName); step.setTasks("hello"); job.save(); final Build build = job.startBuild(); build.shouldSucceed(); assertThat(build.getConsole(), containsString("Invoke Gradle script")); }</code><technical_language>Extract a method: final String gradleInstallationName = "Default"; GradleInstallation.installGradle(jenkins, gradleInstallationName, GradleInstallation.LATEST_VERSION);</technical_language>

Target:
public void run_gradle_script_messages_initialized() { GradleInstallation.installLatestGradleVersion(jenkins); final FreeStyleJob job = jenkins.jobs.create(); job.copyResource(resource("/gradle_plugin/script.gradle"), "build.gradle"); final GradleStep step = job.addBuildStep(GradleStep.class); step.setVersion(GradleInstallation.DEFAULT_VERSION_NAME); step.setTasks("hello"); job.save(); final Build build = job.startBuild(); build.shouldSucceed(); assertThat(build.getConsole(), containsString("Invoke Gradle script")); }
Source:
<code>public ImmutableList<Artifact> getSources() { <START> return ImmutableList.copyOf(Iterables.transform(importPathSourcePair, p -> p.first)); <END> }</code><technical_language>nit, opt: replace p -> p.first Pair::getFirst (I'm if improvement)</technical_language>

Target:
public ImmutableList<ProtoSource> getSources() { return sources; }
Source:
<code>public MapSqlParameterMapper<GlusterBrickEntity> getBatchMapper() { <START> throw new RuntimeException("Unsupported operation"); <END> }</code><technical_language>please NotImplementedException()</technical_language>

Target:
public MapSqlParameterMapper<GlusterBrickEntity> getBatchMapper() { throw new NotImplementedException("Unsupported operation"); }
Source:
<code>public void setUp() throws Exception { jobState = new JobState() { private static final long serialVersionUID = 1L; @Override public ArrayList<TaskState> getTasks() { <START> ArrayList<TaskState> list = new ArrayList<TaskState>(); <END> for (int i = 0; i < 10; i++) { list.add(mock(TaskState.class)); } return list; } @Override public void update(TaskInfo info) { } @Override public void update(JobInfo jobInfo) { } @Override public JobInfo getJobInfo() { return null; } @Override public Map<TaskId, TaskState> getHMTasks() { return null; } @Override public String getOwner() { return null; } @Override public JobType getType() { return null; } }; }</code><technical_language>Please init ArrayList size</technical_language>

Target:
public void setUp() throws Exception { jobState = new JobState() { private static final long serialVersionUID = 1L; @Override public ArrayList<TaskState> getTasks() { ArrayList<TaskState> list = new ArrayList<TaskState>(10); for (int i = 0; i < 10; i++) { list.add(mock(TaskState.class)); } return list; } @Override public void update(TaskInfo info) { } @Override public void update(JobInfo jobInfo) { } @Override public JobInfo getJobInfo() { return null; } @Override public Map<TaskId, TaskState> getHMTasks() { return null; } @Override public String getOwner() { return null; } @Override public JobType getType() { return null; } }; }
Source:
<code>public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException { if (arguments.length != 1) { throw new UDFArgumentLengthException("The GeocodedDataUDF takes an array with only 1 element as argument"); } ObjectInspector arg1 = arguments[0]; if (arg1.getCategory() != Category.PRIMITIVE) { throw new UDFArgumentTypeException(0, "A string argument was expected but an argument of type " + arg1.getTypeName() + " was given."); } PrimitiveCategory primitiveCategory = ((PrimitiveObjectInspector) arg1).getPrimitiveCategory(); if (primitiveCategory != PrimitiveCategory.STRING) { throw new UDFArgumentTypeException(0, "A string argument was expected but an argument of type " + arg1.getTypeName() + " was given."); } argumentOI = arg1; if (geocode == null) { try { geocode = new Geocode(currentPath); } catch (IOException ex) { LOG.error(ex); throw new RuntimeException(ex); } } ArrayList fieldNames = new ArrayList(); ArrayList fieldObjectInspectors = new ArrayList(); <START> <END> for (String field : Geocode.getFields()) { fieldNames.add(field); if (field.equalsIgnoreCase("latitude") || field.equalsIgnoreCase("longitude")) fieldObjectInspectors.add(PrimitiveObjectInspectorFactory.javaDoubleObjectInspector); else fieldObjectInspectors.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector); } result = new HashMap<String, String>(); return ObjectInspectorFactory.getStandardMapObjectInspector( PrimitiveObjectInspectorFactory.javaStringObjectInspector, PrimitiveObjectInspectorFactory.javaStringObjectInspector); }</code><technical_language>fieldNames fieldObjectInspectors later, do need variables</technical_language>

Target:
public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException { if (arguments.length != 1) { throw new UDFArgumentLengthException("The GeocodedDataUDF takes an array with only 1 element as argument"); } ObjectInspector arg1 = arguments[0]; if (arg1.getCategory() != Category.PRIMITIVE) { throw new UDFArgumentTypeException(0, "A string argument was expected but an argument of type " + arg1.getTypeName() + " was given."); } PrimitiveCategory primitiveCategory = ((PrimitiveObjectInspector) arg1).getPrimitiveCategory(); if (primitiveCategory != PrimitiveCategory.STRING) { throw new UDFArgumentTypeException(0, "A string argument was expected but an argument of type " + arg1.getTypeName() + " was given."); } argumentOI = arg1; if (geocode == null) { try { geocode = new Geocode(); } catch (IOException ex) { LOG.error(ex); throw new RuntimeException(ex); } } result = new HashMap<String, String>(); return ObjectInspectorFactory.getStandardMapObjectInspector( PrimitiveObjectInspectorFactory.javaStringObjectInspector, PrimitiveObjectInspectorFactory.javaStringObjectInspector); }
Source:
<code>private void createTableEnvironment( EnvironmentSettings settings, TableConfig config, CatalogManager catalogManager, ModuleManager moduleManager, FunctionCatalog functionCatalog) { <START> config.addConfiguration(flinkConfig); <END> if (environment.getExecution().isStreamingPlanner()) { streamExecEnv = createStreamExecutionEnvironment(); execEnv = null; final Map<String, String> executorProperties = settings.toExecutorProperties(); executor = lookupExecutor(executorProperties, streamExecEnv); tableEnv = createStreamTableEnvironment( streamExecEnv, settings, config, executor, catalogManager, moduleManager, functionCatalog); } else if (environment.getExecution().isBatchPlanner()) { streamExecEnv = null; execEnv = createExecutionEnvironment(); executor = null; tableEnv = new BatchTableEnvironmentImpl( execEnv, config, catalogManager, moduleManager); } else { throw new SqlExecutionException("Unsupported execution type specified."); } }</code><technical_language>aim of this change</technical_language>

Target:
private void createTableEnvironment( EnvironmentSettings settings, TableConfig config, CatalogManager catalogManager, ModuleManager moduleManager, FunctionCatalog functionCatalog) { if (environment.getExecution().isStreamingPlanner()) { streamExecEnv = createStreamExecutionEnvironment(); execEnv = null; final Map<String, String> executorProperties = settings.toExecutorProperties(); executor = lookupExecutor(executorProperties, streamExecEnv); tableEnv = createStreamTableEnvironment( streamExecEnv, settings, config, executor, catalogManager, moduleManager, functionCatalog); } else if (environment.getExecution().isBatchPlanner()) { streamExecEnv = null; execEnv = createExecutionEnvironment(); executor = null; tableEnv = new BatchTableEnvironmentImpl( execEnv, config, catalogManager, moduleManager); } else { throw new SqlExecutionException("Unsupported execution type specified."); } }
Source:
<code>protected void addMemberCheckNull(Object member, boolean addSeparator) { IfStatement ifStatement= fAst.newIfStatement(); ifStatement.setExpression(createInfixExpression(createMemberAccessExpression(member, true, true), Operator.NOT_EQUALS, fAst.newNullLiteral())); Block thenBlock= fAst.newBlock(); flushBuffer(null); <START> for (String a : getContext().getTemplateParser().getBody()) { <END> addElement(processElement(a, member), thenBlock); } if (addSeparator) addElement(getContext().getTemplateParser().getSeparator(), thenBlock); flushBuffer(thenBlock); if (thenBlock.statements().size() == 1 && !getContext().isForceBlocks()) { ifStatement.setThenStatement((Statement)ASTNode.copySubtree(fAst, (ASTNode)thenBlock.statements().get(0))); } else { ifStatement.setThenStatement(thenBlock); } toStringMethod.getBody().statements().add(ifStatement); }</code><technical_language>change s</technical_language>

Target:
protected void addMemberCheckNull(Object member, boolean addSeparator) { IfStatement ifStatement= fAst.newIfStatement(); ifStatement.setExpression(createInfixExpression(createMemberAccessExpression(member, true, true), Operator.NOT_EQUALS, fAst.newNullLiteral())); Block thenBlock= fAst.newBlock(); flushBuffer(null); for (String s : getContext().getTemplateParser().getBody()) { addElement(processElement(s, member), thenBlock); } if (addSeparator) addElement(getContext().getTemplateParser().getSeparator(), thenBlock); flushBuffer(thenBlock); if (thenBlock.statements().size() == 1 && !getContext().isForceBlocks()) { ifStatement.setThenStatement((Statement)ASTNode.copySubtree(fAst, (ASTNode)thenBlock.statements().get(0))); } else { ifStatement.setThenStatement(thenBlock); } toStringMethod.getBody().statements().add(ifStatement); }
Source:
<code>public synchronized void unsubscribe() { if (dispatcher == null) { LOGGER.warn("attempted to unsubscribe with a null internal " + "subscription - possibly unsubscribing more than once - subject: " + subject); return; } try { <START> dispatcher.unsubscribe(getFormattedSubject()); <END> } catch (IllegalStateException e) { LOGGER.warn("could not unsubscribe from subscription. " + e.getMessage()); } dispatcher = null; }</code><technical_language>close dispatcher</technical_language>

Target:
public synchronized void unsubscribe() { if (dispatcher == null) { LOGGER.warn("attempted to unsubscribe with a null internal " + "subscription - possibly unsubscribing more than once - subject: " + subject); return; } try { dispatcher.unsubscribe(getFormattedSubject()); } catch (IllegalStateException e) { LOGGER.warn("could not unsubscribe from subscription. " + e.getMessage()); } conn.closeDispatcher(dispatcher); dispatcher = null; }
Source:
<code>public Repo<Master> call(long tid, Master master) throws Exception { Utils.idLock.lock(); try { tableInfo.tableId = Utils.getNextId(tableInfo.tableName, master.getInstance(), Table.ID::of); if (tableInfo.props.containsKey(Property.TABLE_OFFLINE_OPTS + "create.initial.splits") && this.splitFile != null) { <START> storeSplitFileNameInZooKeeper(); <END> } return new SetupPermissions(tableInfo); } finally { Utils.idLock.unlock(); } }</code><technical_language>I this needs stored in ZK explicitly. FATE works, step of a FATE op is serialized ZK. if store info want in TableInfo object, TableInfo object serialized in subsequent steps</technical_language>

Target:
public Repo<Master> call(long tid, Master master) throws Exception { Utils.idLock.lock(); try { tableInfo.tableId = Utils.getNextId(tableInfo.tableName, master.getContext(), Table.ID::of); return new SetupPermissions(tableInfo); } finally { Utils.idLock.unlock(); } }
Source:
<code>public void define(WebService.NewController context) { WebService.NewAction action = context.createAction(ACTION) .setPost(true) .setDescription("Update a custom metric.<br /> Requires 'Administer System' permission.") .setSince("5.2") .setHandler(this); action.createParam(PARAM_ID) .setRequired(true) .setDescription("Id of the custom metric to update") .setExampleValue("42"); action.createParam(PARAM_KEY) .setDescription("Key") .setMaximumLength(MAX_KEY_LENGTH) .setDescription("Key") .setExampleValue("team_size"); action.createParam(PARAM_NAME) .setMaximumLength(MAX_NAME_LENGTH) .setDescription("Name") .setExampleValue("Team Size"); action.createParam(PARAM_TYPE) .setDescription("Metric type key") <START> .setPossibleValues(Metric.ValueType.names()) <END> .setExampleValue(Metric.ValueType.INT.name()); action.createParam(PARAM_DESCRIPTION) .setDescription("Description") .setMaximumLength(MAX_DESCRIPTION_LENGTH) .setExampleValue("Size of the team"); action.createParam(PARAM_DOMAIN) .setMaximumLength(MAX_DOMAIN_LENGTH) .setDescription("Domain") .setExampleValue("Tests"); }</code><technical_language>minor: if provide values example is useless IMO</technical_language>

Target:
public void define(WebService.NewController context) { WebService.NewAction action = context.createAction(ACTION) .setPost(true) .setDescription("Update a custom metric.<br /> Requires 'Administer System' permission.") .setSince("5.2") .setHandler(this); action.createParam(PARAM_ID) .setRequired(true) .setDescription("Id of the custom metric to update") .setExampleValue("42"); action.createParam(PARAM_KEY) .setDescription("Key") .setMaximumLength(MAX_KEY_LENGTH) .setDescription("Key") .setExampleValue("team_size"); action.createParam(PARAM_NAME) .setMaximumLength(MAX_NAME_LENGTH) .setDescription("Name"); action.createParam(PARAM_TYPE) .setDescription("Metric type key") .setPossibleValues(Metric.ValueType.names()) .setExampleValue(Metric.ValueType.INT.name()); action.createParam(PARAM_DESCRIPTION) .setDescription("Description") .setMaximumLength(MAX_DESCRIPTION_LENGTH) .setExampleValue("Size of the team"); action.createParam(PARAM_DOMAIN) .setMaximumLength(MAX_DOMAIN_LENGTH) .setDescription("Domain") .setExampleValue("Tests"); }
Source:
<code>public long getMinReplicatedIndex(PipelineID pipelineID) throws IOException { Long minIndex = null; Iterator<RaftGroup> raftGroupIterator = getServer().getGroups().iterator(); <START> while (raftGroupIterator.hasNext()) { <END> RaftGroup group = raftGroupIterator.next(); if (group.getGroupId().getUuid().equals(pipelineID.getId())) { GroupInfoReply reply = getServer() .getGroupInfo(createGroupInfoRequest(pipelineID.getProtobuf())); minIndex = RatisHelper.getMinReplicatedIndex(reply.getCommitInfos()); } } return minIndex == null ? 0 : minIndex.longValue(); }</code><technical_language>getServer().getGroupInfo(..) api do need while loop</technical_language>

Target:
public long getMinReplicatedIndex(PipelineID pipelineID) throws IOException { Long minIndex; GroupInfoReply reply = getServer() .getGroupInfo(createGroupInfoRequest(pipelineID.getProtobuf())); minIndex = RatisHelper.getMinReplicatedIndex(reply.getCommitInfos()); return minIndex == null ? -1 : minIndex.longValue(); }
Source:
<code>private void initWsWorkUnitsSoapProxy(String baseURL, String user, String pass) { wsWorkunitsServiceSoapProxy = new WsWorkunitsServiceSoapProxy(baseURL); <START> fallBackWorkunitsServiceSoapProxy = new org.hpccsystems.ws.client.gen.wsworkunits.v1_56.WsWorkunitsServiceSoapProxy(baseURL); <END> if (wsWorkunitsServiceSoapProxy != null) { WsWorkunitsServiceSoap wsWorkunitsServiceSoap = wsWorkunitsServiceSoapProxy.getWsWorkunitsServiceSoap(); if (user != null && pass != null) Connection.initStub((Stub) wsWorkunitsServiceSoap, user, pass); } if (fallBackWorkunitsServiceSoapProxy != null) { org.hpccsystems.ws.client.gen.wsworkunits.v1_56.WsWorkunitsServiceSoap fallBackWorkunitsServiceSoap = fallBackWorkunitsServiceSoapProxy.getWsWorkunitsServiceSoap(); if (user != null && pass != null) Connection.initStub((Stub) fallBackWorkunitsServiceSoap, user, pass); } }</code><technical_language>delay this instantiation if (wsWorkunitsServiceSoapProxy != null) conditional</technical_language>

Target:
private void initWsWorkUnitsSoapProxy(String baseURL, String user, String pass) { wsWorkunitsServiceSoapProxy = new WsWorkunitsServiceSoapProxy(baseURL); if (wsWorkunitsServiceSoapProxy != null) { WsWorkunitsServiceSoap wsWorkunitsServiceSoap = wsWorkunitsServiceSoapProxy.getWsWorkunitsServiceSoap(); if (user != null && pass != null) Connection.initStub((Stub) wsWorkunitsServiceSoap, user, pass); } fallBackWorkunitsServiceSoapProxy = new org.hpccsystems.ws.client.gen.wsworkunits.v1_56.WsWorkunitsServiceSoapProxy( baseURL); if (fallBackWorkunitsServiceSoapProxy != null) { org.hpccsystems.ws.client.gen.wsworkunits.v1_56.WsWorkunitsServiceSoap fallBackWorkunitsServiceSoap = fallBackWorkunitsServiceSoapProxy .getWsWorkunitsServiceSoap(); if (user != null && pass != null) Connection.initStub((Stub) fallBackWorkunitsServiceSoap, user, pass); } }
Source:
<code>public void testGetCalendarSettings() throws Exception { Calendar cal = new Calendar() ; cal.setName("myCal") ; cal.setCalendarOwner("root"); JsonGeneratorImpl generatorImpl = new JsonGeneratorImpl(); JsonValue json = generatorImpl.createJsonObject(new CalendarResource(cal, CAL_BASE_URI + "/")); byte[] data = json.toString().getBytes("UTF-8"); headers.putSingle("content-type", "application/json"); headers.putSingle("content-length", "" + data.length); login("root"); ByteArrayContainerResponseWriter writer = new ByteArrayContainerResponseWriter(); ContainerResponse response = service(HTTPMethods.GET, CAL_BASE_URI + "/getCalendarSettings", baseURI, headers, data, writer); <START> assertEquals(HTTPStatus.OK, response.getStatus()); <END> }</code><technical_language>add check of dateFormat</technical_language>

Target:
public void testGetCalendarSettings() throws Exception { Calendar cal = new Calendar() ; cal.setName("myCal") ; cal.setCalendarOwner("root"); JsonGeneratorImpl generatorImpl = new JsonGeneratorImpl(); CalendarSetting calendarSetting = calendarService.getCalendarSetting("root"); JsonValue json = generatorImpl.createJsonObject(calendarSetting); byte[] data = json.toString().getBytes("UTF-8"); headers.putSingle("content-type", "application/json"); headers.putSingle("content-length", "" + data.length); login("root"); ByteArrayContainerResponseWriter writer = new ByteArrayContainerResponseWriter(); ContainerResponse response = service(HTTPMethods.GET, CAL_BASE_URI + "/getCalendarSettings", baseURI, headers, data, writer); assertEquals(HTTPStatus.OK, response.getStatus()); assertEquals("MM/dd/yyyy", calendarSetting.getDateFormat()); }
Source:
<code>private UidFetchCommand createUidFetchCommand(int maximumAutoDownloadMessageSize, Long uid, Item... items) { FetchProfile fetchProfile = new FetchProfile(); Collections.addAll(fetchProfile, items); return new UidFetchCommand.Builder() .maximumAutoDownloadMessageSize(maximumAutoDownloadMessageSize) .idSet(Collections.singletonList(uid)) <START> .messageParams(fetchProfile, new HashMap<>(Collections.singletonMap(String.valueOf(uid), <END> (Message) createImapMessage(String.valueOf(uid))))) .build(); }</code><technical_language>a builder mutable data structures. if this parameter needs a mutable hashmap, immutable Map type, is wrong</technical_language>

Target:
private UidFetchCommand createUidFetchCommand(int maximumAutoDownloadMessageSize, Long uid, Item... items) { FetchProfile fetchProfile = new FetchProfile(); Collections.addAll(fetchProfile, items); Map<String, Message> messageMap = Collections.singletonMap(String.valueOf(uid), (Message) createImapMessage(String.valueOf(uid))); return UidFetchCommand.createWithMessageParams(Collections.singleton(uid), maximumAutoDownloadMessageSize, messageMap, fetchProfile, null); }
Source:
<code>private void confirmNotAlreadyJoinedAsInstructor(InstructorAttributes instructorForKey, String googleId, String institute) throws JoinCourseException { if(instructorForKey.googleId ==null || !instructorForKey.googleId.equals(googleId)){ return; } AccountAttributes existingAccount = accountsDb.getAccount(googleId); if (existingAccount != null && existingAccount.isInstructor){ String errorMsg = ""; if (institute != null) { errorMsg = "You have already verified the account"; } else { <START> errorMsg = googleId + " has already joined this course"; <END> } throw new JoinCourseException(Const.StatusCodes.ALREADY_JOINED, errorMsg); } }</code><technical_language>message different? In case, word 'join' in cases. is concept of 'verifying' account</technical_language>

Target:
private void confirmNotAlreadyJoinedAsInstructor(InstructorAttributes instructorForKey, String googleId, String institute) throws JoinCourseException { if(instructorForKey.googleId ==null || !instructorForKey.googleId.equals(googleId)){ return; } AccountAttributes existingAccount = accountsDb.getAccount(googleId); if (existingAccount != null && existingAccount.isInstructor){ throw new JoinCourseException(Const.StatusCodes.ALREADY_JOINED, googleId + " has already joined this course"); } }
Source:
<code>public void compactOnLaunch_shouldCompact() throws IOException { Pair<Long, Long> results = populateTestRealmAndCompactOnLaunch(new CompactOnLaunchCallback() { @Override public boolean shouldCompact(long totalBytes, long usedBytes) { assertTrue(totalBytes > usedBytes); return true; } }); <START> assertTrue(results.first.compareTo(results.second) > 0); <END> }</code><technical_language>assertTrue(results.first > results.second) is easier read</technical_language>

Target:
public void compactOnLaunch_shouldCompact() throws IOException { Pair<Long, Long> results = populateTestRealmAndCompactOnLaunch(new CompactOnLaunchCallback() { @Override public boolean shouldCompact(long totalBytes, long usedBytes) { assertTrue(totalBytes > usedBytes); return true; } }); assertTrue(results.first > results.second); }
Source:
<code>public static File download(File targetDir, URL from) { if (targetDir == null) { targetDir = new File(DRONE_TARGET_DOWNLOADED_DIRECTORY); } String fromUrl = from.toString(); String fileName = fromUrl.substring(fromUrl.lastIndexOf("/") + 1); File target = new File(targetDir + File.separator + fileName); File downloaded = null; synchronized (log) { if (target.exists() && target.isFile()) { downloaded = target; } else if (!targetDir.exists()) { targetDir.mkdirs(); } if (downloaded == null) { for (int i = 0; i < 3; i++) { try { downloaded = runDownloadExecution(from, target.getAbsolutePath(), fileName).await(); } catch (ExecutionException ee) { System.err.print("ERROR: the downloading has failed. "); <START> if (2 - i > 0) { <END> System.err.println("Trying again - number of remaining attempts: " + (2 - i)); continue; } else { System.err.println("For more information see the stacktrace of an exception"); throw ee; } } break; } } } return downloaded; }</code><technical_language>cryptic for taste ;) start int i = 3 improve this if too</technical_language>

Target:
public static File download(File targetDir, URL from) { if (targetDir == null) { targetDir = new File(DRONE_TARGET_DOWNLOADED_DIRECTORY); } String fromUrl = from.toString(); String fileName = fromUrl.substring(fromUrl.lastIndexOf("/") + 1); File target = new File(targetDir + File.separator + fileName); File downloaded = null; synchronized (log) { if (target.exists() && target.isFile()) { downloaded = target; } else if (!targetDir.exists()) { targetDir.mkdirs(); } if (downloaded == null) { for (int i = 2; i >= 0; i--) { try { downloaded = runDownloadExecution(from, target.getAbsolutePath(), fileName).await(); } catch (ExecutionException ee) { System.err.print("ERROR: the downloading has failed. "); if (i != 0) { System.err.println("Trying again - number of remaining attempts: " + i); continue; } else { System.err.println("For more information see the stacktrace of an exception"); throw ee; } } break; } } } return downloaded; }
Source:
<code>private void analyseData(final List<InstanceData> allData) { totalInstances = allData.size(); for (InstanceData instance : allData) { <START> SurveyInstanceDto sid = instance.surveyInstanceDto; <END> if (sid.getApprovedFlag() != null && sid.getApprovedFlag().equalsIgnoreCase("true")) { approvedInstances++; } Date cd = sid.getCollectionDate(); if (firstSubmission == null || cd.before(firstSubmission)) { firstSubmission = cd; } if (lastSubmission == null || cd.after(lastSubmission)) { lastSubmission = cd; } String u = sid.getSubmitterName(); if (instancesByUser.containsKey(u)) { instancesByUser.put(u, instancesByUser.get(u) + 1); } else { instancesByUser.put(u, Integer.valueOf(1)); } String dev = sid.getDeviceIdentifier(); if (instancesByDevice.containsKey(dev)) { instancesByDevice.put(dev, instancesByDevice.get(dev) + 1); } else { instancesByDevice.put(dev, Integer.valueOf(1)); } Long dur = sid.getSurveyalTime(); if (dur != null) { totalDuration += dur; maxDuration = Long.max(maxDuration, dur); minDuration = Long.min(minDuration, dur); } } }</code><technical_language>call survyeInstanceDto instead of sid</technical_language>

Target:
private void analyseData(final List<InstanceData> allData) { totalInstances = allData.size(); for (InstanceData instance : allData) { SurveyInstanceDto sid = instance.surveyInstanceDto; if (sid.getApprovedFlag() != null && sid.getApprovedFlag().equalsIgnoreCase("true")) { approvedInstances++; } Date cd = sid.getCollectionDate(); if (firstSubmission == null || cd.before(firstSubmission)) { firstSubmission = cd; } if (lastSubmission == null || cd.after(lastSubmission)) { lastSubmission = cd; } String u = sid.getSubmitterName(); if (instancesByUser.containsKey(u)) { instancesByUser.put(u, instancesByUser.get(u) + 1); } else { instancesByUser.put(u, Integer.valueOf(1)); } String dev = sid.getDeviceIdentifier(); if (instancesByDevice.containsKey(dev)) { instancesByDevice.put(dev, instancesByDevice.get(dev) + 1); } else { instancesByDevice.put(dev, Integer.valueOf(1)); } Long durationSeconds = sid.getSurveyalTime(); if (durationSeconds != null) { totalDuration += durationSeconds; maxDuration = Long.max(maxDuration, durationSeconds); minDuration = Long.min(minDuration, durationSeconds); } } }
Source:
<code>public PeriodicQueryStorageMetadata(String sparql, VariableOrder varOrder) { <START> Preconditions.checkNotNull(sparql); <END> Preconditions.checkNotNull(varOrder); this.sparql = sparql; this.varOrder = varOrder; }</code><technical_language>this simplified this.sparql = checkNotNull(sparql) others</technical_language>

Target:
public PeriodicQueryStorageMetadata(String sparql, VariableOrder varOrder) { this.sparql = Preconditions.checkNotNull(sparql); this.varOrder = Preconditions.checkNotNull(varOrder); }
Source:
<code>public Users list() { if (isFiltered()) { <START> return mapDbUserCollection(getBackendCollection(VdcQueryType.GetDbUserByUserId, new GetDbUserByUserIdParameters(getCurrent().get(VdcUser.class).getUserId()))); <END> } else { return mapDbUserCollection(getBackendCollection(SearchType.DBUser, getSearchPattern())); } }</code><technical_language>worth fetching user (in query) session (if supplied in parameters for back. comp.), this supply (consistency)</technical_language>

Target:
public Users list() { if (isFiltered()) { return mapDbUserCollection(getBackendCollection(VdcQueryType.GetAllDbUsers, new VdcQueryParametersBase())); } else { return mapDbUserCollection(getBackendCollection(SearchType.DBUser, getSearchPattern())); } }
Source:
<code>public List<AmbryReplica> getReplicaIds() { <START> return clusterManagerCallback.getReplicaIdsForPartition(this) <END> .stream() .map(r -> (AmbryReplica) r) .collect(Collectors.toList()); }</code><technical_language>Instead of copying list requiring a (potentially) unsafe cast. I more of generics in ClusterManagerCallback</technical_language>

Target:
public List<AmbryReplica> getReplicaIds() { return clusterManagerCallback.getReplicaIdsForPartition(this); }
Source:
<code>private Set<PathFilterSet> findAssetPaths(final ResourceResolver resourceResolver, final String pagePath) { final Set<PathFilterSet> filters = new LinkedHashSet<>(); final Resource parentResource = resourceResolver.resolve(pagePath); if (isExcluded(this.pageExclusionPatterns, pagePath)) { if (pagePath.endsWith("/" + NameConstants.NN_CONTENT)) { return filters; } final PageManager pageManager = resourceResolver.adaptTo(PageManager.class); Page page = pageManager.getContainingPage(parentResource); <START> excludedPages.add(page.getPath()); <END> return filters; } final ValueMap parentResourceProperties = parentResource.getValueMap(); for (String key : parentResourceProperties.keySet()) { final Object value = parentResourceProperties.get(key); if (value instanceof String) { addFilter(filters, (String) value, resourceResolver); } else if (value instanceof String[]) { final String[] arrayValue = (String[]) value; for (String stringValue : arrayValue) { addFilter(filters, stringValue, resourceResolver); } } } final Iterator<Resource> children = parentResource.listChildren(); while (children.hasNext()) { final Resource child = children.next(); filters.addAll(findAssetPaths(resourceResolver, child.getPath())); } return filters; }</code><technical_language>A bit of edge case, I test a page exclude path of .*men.* I get a NullPointerException this line blows package creation. reason is finds /content/we-retail/us/en/community/configuration/functions/assignments is "containing page". error full paths of /content/we-retail/us/en/community/configuration /content/we-retail/us/en/community/configuration/functions. such: - is currently exclude a non-page path - folders coming for ride, desired - If exclusion pattern matches a folder path, package creation errors out w/o notification user</technical_language>

Target:
private Set<PathFilterSet> findAssetPaths(final ResourceResolver resourceResolver, final String pagePath) { final Set<PathFilterSet> filters = new LinkedHashSet<>(); final Resource parentResource = resourceResolver.resolve(pagePath); if (isExcluded(this.pageExclusionPatterns, pagePath)) { if (pagePath.endsWith("/" + NameConstants.NN_CONTENT)) { return filters; } final PageManager pageManager = resourceResolver.adaptTo(PageManager.class); Page page = pageManager.getContainingPage(parentResource); if (page != null) { excludedPages.add(page.getPath()); } else { excludedPages.add(parentResource.getPath()); } return filters; } final ValueMap parentResourceProperties = parentResource.getValueMap(); for (String key : parentResourceProperties.keySet()) { final Object value = parentResourceProperties.get(key); if (value instanceof String) { addFilter(filters, (String) value, resourceResolver); } else if (value instanceof String[]) { final String[] arrayValue = (String[]) value; for (String stringValue : arrayValue) { addFilter(filters, stringValue, resourceResolver); } } } final Iterator<Resource> children = parentResource.listChildren(); while (children.hasNext()) { final Resource child = children.next(); filters.addAll(findAssetPaths(resourceResolver, child.getPath())); } return filters; }
Source:
<code>public void testFilledListEventMapping() { final DateTime timestamp = new DateTime(); <START> final Integer eventCode = new Integer(10); <END> final Integer eventCounter = new Integer(1); final Event event = new Event(timestamp, eventCode, eventCounter); final List<Event> listOriginal = new ArrayList<>(); listOriginal.add(event); final List<com.alliander.osgp.adapter.ws.schema.smartmetering.management.Event> listMapped = this.managementMapper .mapAsList(listOriginal, com.alliander.osgp.adapter.ws.schema.smartmetering.management.Event.class); assertNotNull(listMapped); assertNotNull(listMapped.get(0)); assertNotNull(listMapped.get(0).getEventCounter()); assertNotNull(listMapped.get(0).getEventType()); assertNotNull(listMapped.get(0).getTimestamp()); assertEquals(timestamp.getYear(), listMapped.get(0).getTimestamp().getYear()); assertEquals(timestamp.getMonthOfYear(), listMapped.get(0).getTimestamp().getMonth()); assertEquals(timestamp.getDayOfMonth(), listMapped.get(0).getTimestamp().getDay()); assertEquals(timestamp.getHourOfDay(), listMapped.get(0).getTimestamp().getHour()); assertEquals(timestamp.getMinuteOfHour(), listMapped.get(0).getTimestamp().getMinute()); assertEquals(timestamp.getSecondOfMinute(), listMapped.get(0).getTimestamp().getSecond()); assertEquals((int) eventCode, listMapped.get(0).getEventType().ordinal()); assertEquals(eventCounter, listMapped.get(0).getEventCounter()); }</code><technical_language>10 meaning? If so, put in a constant a names describes it</technical_language>

Target:
public void testFilledListEventMapping() { final DateTime timestamp = new DateTime(); final Event event = new Event(timestamp, EVENTCODE, EVENTCOUNTER); final List<Event> listOriginal = new ArrayList<>(); listOriginal.add(event); final List<com.alliander.osgp.adapter.ws.schema.smartmetering.management.Event> listMapped = this.managementMapper .mapAsList(listOriginal, com.alliander.osgp.adapter.ws.schema.smartmetering.management.Event.class); assertNotNull(listMapped); assertNotNull(listMapped.get(0)); assertNotNull(listMapped.get(0).getEventCounter()); assertNotNull(listMapped.get(0).getEventType()); assertNotNull(listMapped.get(0).getTimestamp()); assertEquals(timestamp.getYear(), listMapped.get(0).getTimestamp().getYear()); assertEquals(timestamp.getMonthOfYear(), listMapped.get(0).getTimestamp().getMonth()); assertEquals(timestamp.getDayOfMonth(), listMapped.get(0).getTimestamp().getDay()); assertEquals(timestamp.getHourOfDay(), listMapped.get(0).getTimestamp().getHour()); assertEquals(timestamp.getMinuteOfHour(), listMapped.get(0).getTimestamp().getMinute()); assertEquals(timestamp.getSecondOfMinute(), listMapped.get(0).getTimestamp().getSecond()); assertEquals((int) EVENTCODE, listMapped.get(0).getEventType().ordinal()); assertEquals(EVENTCOUNTER, listMapped.get(0).getEventCounter()); }
Source:
<code>private Long getRssUsageFrom(Process process) { Long rssUsage; try (InputStream inputStream = process.getInputStream(); Reader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) { rssUsage = Long.valueOf(bufferedReader.readLine()); } catch (Exception e) { <START> throw new IllegalStateException("Error in JMX memory stats retrieval", e); <END> } return rssUsage; }</code><technical_language>JMX do this</technical_language>

Target:
private Long getRssUsageFrom(Process process) { Long rssUsage; try (InputStream inputStream = process.getInputStream(); Reader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) { rssUsage = Long.valueOf(bufferedReader.readLine()); } catch (Exception e) { throw new IllegalStateException("Error in rss stats retrieval", e); } return rssUsage; }
Source:
<code>public void checkSearchingReferenceSetsReturnsWellFormed() throws AvroRemoteException { final SearchReferenceSetsRequest req = SearchReferenceSetsRequest.newBuilder().build(); final SearchReferenceSetsResponse resp = client.references.searchReferenceSets(req); final List<ReferenceSet> sets = resp.getReferenceSets(); sets.stream().forEach(rs -> assertThat(rs.getId()).isNotNull()); <START> sets.stream().forEach(rs -> assertThat(rs.getMd5checksum()).isNotNull()); <END> sets.stream().forEach(rs -> assertThat(rs.getSourceAccessions()).isNotNull()); }</code><technical_language>checking this MD5 also</technical_language>

Target:
public void checkSearchingReferenceSetsReturnsWellFormed() throws AvroRemoteException { final SearchReferenceSetsRequest req = SearchReferenceSetsRequest.newBuilder().build(); final SearchReferenceSetsResponse resp = client.references.searchReferenceSets(req); final List<ReferenceSet> sets = resp.getReferenceSets(); sets.stream().forEach(this::checkRefSetConstants); }
Source:
<code>public void onFailure(Throwable caught) { close(); status.setContents("Monitoring is unavailable on this node. Maybe node was started with --disableMonitoring option.<br>"+ <START> "Error message: "+ JSONUtils.getJsonErrorMessage(caught)); <END> }</code><technical_language>Monitoring is unavailable this node. monitoring disabled disableMonitoring option error occurred. More information node logs</technical_language>

Target:
public void onFailure(Throwable caught) { close(); status.setContents("Monitoring is unavailable on this node. <br>" + "Either monitoring was disabled with the disableMonitoring option or an error occurred. <br>" + "More information are available inside the node logs."); }
Source:
<code>protected void onConstructorFound(NewClassTree newClassTree) { Tree mTree = findParentMethod(newClassTree); if (mTree.is(Tree.Kind.METHOD)) { <START> Optional<StatementTree> secureRandomOptional = findSecureRandomInMethod((MethodTree) mTree, returnSymbolOfArgument(newClassTree.arguments().get(0))); <END> if (!secureRandomOptional.isPresent()) { reportIssue(newClassTree, "Use a dynamically-generated, random IV."); } } }</code><technical_language>care StatementTree, existence. findSecureRandomInMethod return a boolean</technical_language>

Target:
protected void onConstructorFound(NewClassTree newClassTree) { Tree mTree = findEnclosingMethod(newClassTree); if (mTree != null) { MethodInvocationVisitor mitVisit = new MethodInvocationVisitor(newClassTree); mTree.accept(mitVisit); if (!mitVisit.secureRandomFound) { reportIssue(newClassTree, "Use a dynamically-generated, random IV."); } } }