auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testList() throws StripeException { final ApplicationFee fee = ApplicationFee.retrieve(FEE_ID); <START> final FeeRefundCollection reversals = fee.getRefunds().list(null); <END> assertNotNull(reversals); assertEquals(1, reversals.getData().size()); verifyRequest( APIResource.RequestMethod.GET, String.format("/v1/application_fees/%s/refunds", fee.getId()) ); }</code><technical_language>rename variable resources instead (bad copy paste I think)</technical_language>

Target:
public void testList() throws StripeException { final ApplicationFee fee = getFeeFixture(); final Map<String, Object> params = new HashMap<String, Object>(); params.put("limit", 1); final FeeRefundCollection refunds = fee.getRefunds().list(params); assertNotNull(refunds); verifyRequest( APIResource.RequestMethod.GET, String.format("/v1/application_fees/%s/refunds", fee.getId()), params ); }
Source:
<code>private void commonEvaluateFieldTypeMap(BlockStmt blockStmt, Map<String, KiePMMLOriginalTypeGeneratedType> fieldTypeMap, int expectedMethodCallSize) { List<MethodCallExpr> retrieved = getMethodCallExprList(blockStmt, expectedMethodCallSize, "fieldTypeMap", "put"); for (Map.Entry<String, KiePMMLOriginalTypeGeneratedType> entry : fieldTypeMap.entrySet()) { assertTrue(retrieved.stream() .map(MethodCallExpr::getArguments) .anyMatch(arguments -> { <START> boolean toReturn = arguments.size() == 2; Expression firstArgument = arguments.get(0); Expression secondArgument = arguments.get(1); toReturn &= firstArgument.isStringLiteralExpr() && ((StringLiteralExpr) firstArgument).getValue().equals(entry.getKey()); toReturn &= secondArgument.isObjectCreationExpr() && ((ObjectCreationExpr) secondArgument).getArgument(0).isStringLiteralExpr() && ((StringLiteralExpr) ((ObjectCreationExpr) secondArgument).getArgument(0)).getValue().equals(entry.getValue().getOriginalType()) && ((ObjectCreationExpr) secondArgument).getArgument(1).isStringLiteralExpr() && ((StringLiteralExpr) ((ObjectCreationExpr) secondArgument).getArgument(1)).getValue().equals(entry.getValue().getGeneratedType()); return toReturn; <END> })); } }</code><technical_language>please move this logic a method improve code readability</technical_language>

Target:
private void commonEvaluateFieldTypeMap(BlockStmt blockStmt, Map<String, KiePMMLOriginalTypeGeneratedType> fieldTypeMap, int expectedMethodCallSize) { List<MethodCallExpr> retrieved = getMethodCallExprList(blockStmt, expectedMethodCallSize, "fieldTypeMap", "put"); for (Map.Entry<String, KiePMMLOriginalTypeGeneratedType> entry : fieldTypeMap.entrySet()) { assertTrue(retrieved.stream() .map(MethodCallExpr::getArguments) .anyMatch(arguments -> evaluateFieldTypeMapPopulation(entry, arguments))); } }
Source:
<code>public JsonElement view(@QueryParam("processNumber") String processNumber) { if (processNumber == null || processNumber.isEmpty()) { throw new WebApplicationException(400); } List<Mission> missions; try { final SearchMissionsDTO searchMissions = new SearchMissionsDTO(); searchMissions.setProcessNumber(processNumber); missions = searchMissions.sortedSearch(); } catch (final Exception e) { throw new WebApplicationException(404); } if (missions.isEmpty() || missions.size() > 1) { throw new WebApplicationException(404); } final Mission mission = missions.get(0); <START> final JsonObject obj = super.view(mission).getAsJsonObject(); <END> return obj; }</code><technical_language>return result: super.view(mission).getAsJsonObject(); is need for this variable</technical_language>

Target:
public JsonElement view(@QueryParam("processNumber") String processNumber) { if (processNumber == null || processNumber.isEmpty()) { throw new WebApplicationException(400); } List<Mission> missions; try { final SearchMissionsDTO searchMissions = new SearchMissionsDTO(); searchMissions.setProcessNumber(processNumber); missions = searchMissions.sortedSearch(); } catch (final Exception e) { throw new WebApplicationException(404); } if (missions.isEmpty() || missions.size() > 1) { throw new WebApplicationException(404); } final Mission mission = missions.get(0); return super.view(mission).getAsJsonObject(); }
Source:
<code>public void millisSinceLastSweptUpdatesAsClockUpdates() { metrics.updateProgressForShard(CONS_ZERO, 100); waitForProgressToRecompute(); puncherStore.put(0, 50); assertMillisSinceLastSweptConservativeEquals(50); for (int i = 0; i < 10; i++) { clockTime = i; <START> assertMillisSinceLastSweptConservativeEquals(50); <END> } }</code><technical_language>of problems mentioned in this file, this update :)</technical_language>

Target:
public void millisSinceLastSweptUpdatesAsClockUpdates() { metrics.updateProgressForShard(CONS_ZERO, 100); waitForProgressToRecompute(); puncherStore.put(0, 50); assertMillisSinceLastSweptConservativeEqualsClockTimeMinus(50); for (int i = 0; i < 10; i++) { clockTime = i; assertMillisSinceLastSweptConservativeEqualsClockTimeMinus(50); } }
Source:
<code>private Constraint machineMoveCost(ConstraintFactory factory) { return factory.from(MrProcessAssignment.class) .filter(MrProcessAssignment::isMoved) .penalizeLong(MrConstraints.MACHINE_MOVE_COST, <START> HardSoftLongScore.ofSoft(1L), MrProcessAssignment::getMachineMoveCost); <END> }</code><technical_language>Dtto. aligning. In fact, I file</technical_language>

Target:
private Constraint machineMoveCost(ConstraintFactory factory) { return factory.from(MrProcessAssignment.class) .filter(MrProcessAssignment::isMoved) .penalizeLong(MrConstraints.MACHINE_MOVE_COST, HardSoftLongScore.ONE_SOFT, MrProcessAssignment::getMachineMoveCost); }
Source:
<code>public String getName() { <START> return fType.getName(); <END> }</code><technical_language>fType null, lead auto-NPE. null-check it? (not a good return value, null, empty string?)</technical_language>

Target:
public String getName() { ITmfEventType type = fType; if(type != null) { return type.getName(); } return ""; }
Source:
<code>public List<CommandType> getCommandTypes() { <START> return new ArrayList<>(commandTypes.values()); <END> }</code><technical_language>wondering if [unmodifiable list](<LINK_0> here</technical_language>

Target:
public List<CommandType> getCommandTypes() { return unmodifiableList(new ArrayList<>(commandTypes.values())); }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!areCameraAndRecordAudioPermissionsGranted(this)) { finish(); return; } <START> setContentView(R.layout.activity_capture_selfie_video_new_api); <END> if (null == savedInstanceState) { getFragmentManager().beginTransaction() .replace(R.id.container, Camera2VideoFragment.newInstance()) .commit(); } ToastUtils.showLongToast(getString(R.string.start_video_capture_instruction)); }</code><technical_language>Please rename this layout file removing _new_api</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!areCameraAndRecordAudioPermissionsGranted(this)) { finish(); return; } setContentView(R.layout.activity_capture_selfie_video); if (null == savedInstanceState) { getFragmentManager().beginTransaction() .replace(R.id.container, Camera2VideoFragment.newInstance()) .commit(); } ToastUtils.showLongToast(getString(R.string.start_video_capture_instruction)); }
Source:
<code>public Iterable<ChromeDevtoolsDomain> get() { Stetho.DefaultInspectorModulesBuilder builder = new Stetho.DefaultInspectorModulesBuilder(mContext); if (Build.VERSION.SDK_INT >= DatabaseConstants.MIN_API_LEVEL) { ContentProviderSchema calendarsSchema = new ContentProviderSchema.Builder() .table(new Table.Builder() .uri(CalendarContract.Calendars.CONTENT_URI) .projection(new String[] { CalendarContract.Calendars._ID, CalendarContract.Calendars.NAME, CalendarContract.Calendars.ACCOUNT_NAME, CalendarContract.Calendars.IS_PRIMARY, }) .build()) .build(); ContentProviderSchema eventsSchema = new ContentProviderSchema.Builder() .table(new Table.Builder() .uri(CalendarContract.Events.CONTENT_URI) .projection(new String[]{ CalendarContract.Events._ID, CalendarContract.Events.TITLE, CalendarContract.Events.DESCRIPTION, CalendarContract.Events.ACCOUNT_NAME, CalendarContract.Events.DTSTART, CalendarContract.Events.DTEND, CalendarContract.Events.CALENDAR_ID, }) .build()) .build(); <START> Database database = new Database(); <END> database.add(new SqliteDatabaseDriver(mContext, new DefaultDatabaseFilesProvider(mContext))); database.add(new ContentProviderDatabaseDriver(mContext, calendarsSchema, eventsSchema)); builder.provide(database); } return builder.finish(); }</code><technical_language>for late review, I working stetho-1.2.0 out a improved API support this kind of customization. I approach this a new, stronger API: new DefaultInspectorModulesProvider() .provideDatabaseDriver(new ContentProviderDatabaseDriver(...)) .finish(); This implies default provider is install installed. If default is configured, existing (as of 1.2.0) method .databaseFiles(...) provide a no-op files lister</technical_language>

Target:
public Iterable<ChromeDevtoolsDomain> get() { return new Stetho.DefaultInspectorModulesBuilder(mContext) .provideDatabaseDriver(createContentProviderDatabaseDriver(mContext)) .finish(); }
Source:
<code>} catch (Exception e) { LOG.error("Unable to expose RPS/JSON result field"); <START> resultField = null; <END> }</code><technical_language>future calls in getResult unexpectedly NPE of this. handle this in getResult fail harder in static block a thrown runtime exception error prevent class initializing, server running</technical_language>

Target:
} catch (Exception e) { log.error("Unable to expose RPS/JSON result field"); }
Source:
<code>public XHMMModel(final double eventStartProbability, final double meanEventSize, final double deletionMeanShift, final double duplicationMeaShift) { super(new XHMMEmissionProbabilityCalculator( <START> ParamUtils.isNegativeOrZero(deletionMeanShift, "Deletion coverage shift must be negative."), <END> ParamUtils.isPositiveOrZero(duplicationMeaShift, "Duplication coverage shift must be positive"), EMISSION_SD, RandomGeneratorFactory.createRandomGenerator(new Random(RANDOM_SEED))), eventStartProbability, meanEventSize); }</code><technical_language>Move parameter validation constructor of XHMMEmissionProbabilityCalculator</technical_language>

Target:
public XHMMModel(final double eventStartProbability, final double meanEventSize, final double deletionMeanShift, final double duplicationMeaShift) { super(new XHMMEmissionProbabilityCalculator( deletionMeanShift, duplicationMeaShift, EMISSION_SD, RandomGeneratorFactory.createRandomGenerator(new Random(RANDOM_SEED))), eventStartProbability, meanEventSize); }
Source:
<code>protected void writeNativeFields(Native nativ, JsonGenerator gen) throws IOException { switch (nativ.getRequestOneofCase()) { case REQUEST_NATIVE: <START> writeNativeObject(nativ, gen); <END> break; case REQUEST: gen.writeStringField("request", nativ.getRequest()); break; case REQUESTONEOF_NOT_SET: checkRequired(false); } if (nativ.hasVer()) { gen.writeStringField("ver", nativ.getVer()); } writeEnums("api", nativ.getApiList(), gen); writeEnums("battr", nativ.getBattrList(), gen); }</code><technical_language>Similarly reader side, in writer want transparently support representation in memory/Protobuf model (user put native part in string field requestNative object field request) output same, standards-compliant representation is (even OpenRTB 2.4) ugly JSON-escaped string field. want support a child object representation too, right do is binding output format user's choice of requestNative vs. request; this choice independent, a convenience performance feature: create native request programmatically want requestNative, complete native request JSON (e.g. read a database of campaign data), want copy request. In reader handle external-format choice detection, sniffing token character; in writer do that, solution in this case is adding another boolean option factory. I suggested option named forceReadNativeAsObject, a single option job for reader writer, nativeAsObject. choice for request response, strange standard escaped-JSON form in request send child-object form in response for example (if needs that, create factories - optimize API for common case)</technical_language>

Target:
protected void writeNativeFields(Native nativ, JsonGenerator gen) throws IOException { switch (nativ.getRequestOneofCase()) { case REQUEST_NATIVE: { if(factory().isForceNativeAsObject()) { gen.writeFieldName("request"); nativeWriter().writeNativeRequest(nativ.getRequestNative(), gen); } else { String nativeString = factory().newNativeWriter().writeNativeRequest(nativ.getRequestNative()); gen.writeStringField("request", nativeString); } } break; case REQUEST: gen.writeStringField("request", nativ.getRequest()); break; case REQUESTONEOF_NOT_SET: checkRequired(false); } if (nativ.hasVer()) { gen.writeStringField("ver", nativ.getVer()); } writeEnums("api", nativ.getApiList(), gen); writeEnums("battr", nativ.getBattrList(), gen); }
Source:
<code><START> public static boolean hasLogMessage(String logFileName, String logMessage, Predicate<String>... filters) throws Exception { <END> Path logPath = LoggingUtil.getInServerLogPath(logFileName); return isMessageInLogFile(logPath, logMessage); }</code><technical_language>filters method argument passed isMessageInLogFile argument</technical_language>

Target:
public static boolean hasLogMessage(String logFileName, String logMessage, Predicate<String>... filters) throws Exception { Path logPath = LoggingUtil.getInServerLogPath(logFileName); return isMessageInLogFile(logPath, logMessage, filters); }
Source:
<code>public Response updateIssue(@Context HttpServletRequest request, @PathParam("issueId") long issueId, @FormParam("title") String title, @FormParam("description") String description, @FormParam("assignee") String assigneeNetID, @FormParam("status") Boolean status) throws IOException { Issue issue = issues.findIssueById(getRepositoryEntity(), issueId).get(0); issue.setTitle(title); issue.setDescription(description); if (!assigneeNetID.isEmpty()) { User assignee = users.findByNetId(assigneeNetID); checkCollaborator(assignee); issue.setAssignee(assignee); <START> } <END> if(status != null && status){ issue.setOpen(true); } else if (status != null && !status) { issue.setOpen(false); issue.setClosed(new Date()); } issues.merge(issue); return redirect(issue.getURI()); }</code><technical_language>java } else { issue.setAssignee(null); }</technical_language>

Target:
public Response updateIssue(@Context HttpServletRequest request, @PathParam("issueId") long issueId, @FormParam("title") String title, @FormParam("description") String description, @FormParam("assignee") String assigneeNetID, @FormParam("status") Boolean status) throws IOException { Issue issue = issues.findIssueById(getRepositoryEntity(), issueId).get(0); issue.setTitle(title); issue.setDescription(description); if (!Strings.isNullOrEmpty(assigneeNetID)) { User assignee = users.findByNetId(assigneeNetID); checkCollaborator(assignee); issue.setAssignee(assignee); } else { issue.setAssignee(null); } if(status != null && status){ issue.setOpen(true); } else if (status != null && !status) { issue.setOpen(false); issue.setClosed(new Date()); } issues.merge(issue); return redirect(issue.getURI()); }
Source:
<code>public long getZkBarrierTimeoutMs() { <START> return getLong(ZK_BARRIER_TIMEOUT_MS, DEFAULT_BARRIER_TIMEOUT_MS); <END> }</code><technical_language>int values 600 hours. enough for barrier</technical_language>

Target:
public int getZkBarrierTimeoutMs() { return getInt(ZK_CONSENSUS_TIMEOUT_MS, DEFAULT_CONSENSUS_TIMEOUT_MS); }
Source:
<code>public List<ChangeData> queryChanges(final String queryString) throws OrmException, QueryParseException { final Predicate<ChangeData> visibleToMe = queryBuilder.is_visible(); Predicate<ChangeData> s = compileQuery(queryString, visibleToMe); List<ChangeData> results = new ArrayList<ChangeData>(); HashSet<Change.Id> want = new HashSet<Change.Id>(); for (ChangeData d : ((ChangeDataSource) s).read()) { if (d.hasChange()) { if (visibleToMe.match(d)) { results.add(d); } } else { want.add(d.getId()); } } if (!want.isEmpty()) { for (Change c : db.get().changes().get(want)) { ChangeData d = new ChangeData(c); if (visibleToMe.match(d)) { results.add(d); } } } Collections.sort(results, sortkeyAfter != null ? cmpAfter : cmpBefore); int limit = limit(s); <START> if(results.size() > maxLimit){ <END> setMoreResults(true); } if (limit < results.size()) { results = results.subList(0, limit); } if (sortkeyAfter != null) { Collections.reverse(results); } return results; }</code><technical_language>space if (</technical_language>

Target:
public List<ChangeData> queryChanges(final String queryString) throws OrmException, QueryParseException { final Predicate<ChangeData> visibleToMe = queryBuilder.is_visible(); Predicate<ChangeData> s = compileQuery(queryString, visibleToMe); List<ChangeData> results = new ArrayList<ChangeData>(); HashSet<Change.Id> want = new HashSet<Change.Id>(); for (ChangeData d : ((ChangeDataSource) s).read()) { if (d.hasChange()) { if (visibleToMe.match(d)) { results.add(d); } } else { want.add(d.getId()); } } if (!want.isEmpty()) { for (Change c : db.get().changes().get(want)) { ChangeData d = new ChangeData(c); if (visibleToMe.match(d)) { results.add(d); } } } Collections.sort(results, sortkeyAfter != null ? cmpAfter : cmpBefore); int limit = limit(s); if (results.size() > maxLimit) { moreResults = true; } if (limit < results.size()) { results = results.subList(0, limit); } if (sortkeyAfter != null) { Collections.reverse(results); } return results; }
Source:
<code><START> HL7Parser201305Utils() { <END> }</code><technical_language>this method private other class new HL7Parser201305Utils()</technical_language>

Target:
private HL7Parser201305Utils() { }
Source:
<code>public void setUp() throws Exception { user = accounts.user(); admin = accounts.admin(); initSsh(admin); project = new Project.NameKey("p"); session = new RestSession(server, user); SshSession <START> sshSession = <END> new SshSession(server, admin); createProject(sshSession, project.get()); git = cloneProject(sshSession.getUrl() + "/" + project.get()); db = reviewDbProvider.open(); atrScope.set(atrScope.newContext(reviewDbProvider, sshSession, identifiedUserFactory.create(Providers.of(db), user.getId()))); ProjectConfig cfg = projectCache.checkedGet(allProjects).getConfig(); AccountGroup.UUID anonymousUsers = SystemGroupBackend.getGroup(ANONYMOUS_USERS).getUUID(); grant(cfg, Permission.forLabel("Code-Review"), -2, 2, anonymousUsers, "refs/heads/*"); grant(cfg, Permission.SUBMIT, anonymousUsers, "refs/heads/*"); codeReview = checkNotNull(cfg.getLabelSections().get("Code-Review")); codeReview.setCopyMinScore(false); codeReview.setCopyMaxScore(false); codeReview.setCopyAllScoresOnTrivialRebase(false); codeReview.setCopyAllScoresIfNoCodeChange(false); saveProjectConfig(cfg); }</code><technical_language>SSH session closed: sshSession.close() if this is important though</technical_language>

Target:
public void setUp() throws Exception { user = accounts.user(); admin = accounts.admin(); initSsh(admin); project = new Project.NameKey("p"); session = new RestSession(server, user); SshSession sshSession = new SshSession(server, admin); createProject(sshSession, project.get()); git = cloneProject(sshSession.getUrl() + "/" + project.get()); db = reviewDbProvider.open(); atrScope.set(atrScope.newContext(reviewDbProvider, sshSession, identifiedUserFactory.create(Providers.of(db), user.getId()))); sshSession.close(); ProjectConfig cfg = projectCache.checkedGet(allProjects).getConfig(); AccountGroup.UUID anonymousUsers = SystemGroupBackend.getGroup(ANONYMOUS_USERS).getUUID(); grant(cfg, Permission.forLabel("Code-Review"), -2, 2, anonymousUsers, "refs/heads/*"); grant(cfg, Permission.SUBMIT, anonymousUsers, "refs/heads/*"); codeReview = checkNotNull(cfg.getLabelSections().get("Code-Review")); codeReview.setCopyMinScore(false); codeReview.setCopyMaxScore(false); codeReview.setCopyAllScoresOnTrivialRebase(false); codeReview.setCopyAllScoresIfNoCodeChange(false); saveProjectConfig(cfg); }
Source:
<code>private Map<String, File> createOutputMapFromFile(final File outputMapFile) { final Map<String, File> outputMap = new HashMap<String, File>(); final TabbedTextFileWithHeaderParser parser = new TabbedTextFileWithHeaderParser(outputMapFile); for (final TabbedTextFileWithHeaderParser.Row row : parser) { final String id = row.getField("READ_GROUP_ID"); final String output = row.getField("OUTPUT"); final File outputPath = new File(output); outputMap.put(id, outputPath); } <START> parser.close(); <END> return outputMap; }</code><technical_language>CloserUtil.close</technical_language>

Target:
private static Map<String, File> createOutputMapFromFile(final File outputMapFile) { final Map<String, File> outputMap = new HashMap<String, File>(); final TabbedTextFileWithHeaderParser parser = new TabbedTextFileWithHeaderParser(outputMapFile); for (final TabbedTextFileWithHeaderParser.Row row : parser) { final String id = row.getField("READ_GROUP_ID"); final String output = row.getField("OUTPUT"); final File outputPath = new File(output); outputMap.put(id, outputPath); } CloserUtil.close(parser); return outputMap; }
Source:
<code>public Update createStatement(String sql) { Foreman updateForeman = foreman.createChild(); return new Update(this, statementLocator, statementRewriter, statementBuilder, sql, new ConcreteStatementContext(globalStatementAttributes, MappingRegistry.copyOf(mappingRegistry), updateForeman), timingCollector, updateForeman, <START> collectorFactoryRegistry); <END> }</code><technical_language>I so, registering Update cascade Handle</technical_language>

Target:
public Update createStatement(String sql) { Foreman updateForeman = foreman.createChild(); CollectorFactoryRegistry updateCollectors = collectorFactoryRegistry.createChild(); return new Update(this, statementLocator, statementRewriter, statementBuilder, sql, new ConcreteStatementContext(globalStatementAttributes, MappingRegistry.copyOf(mappingRegistry), updateForeman, updateCollectors), timingCollector, updateForeman, updateCollectors); }
Source:
<code>public void generatePreviewForSliceTheoremPaperUsingAbbr() throws Exception { BstPreviewLayout bstPreviewLayout = new BstPreviewLayout(Paths.get(BstPreviewLayoutTest.class.getResource("abbrv.bst").toURI())); String preview = bstPreviewLayout.generatePreview(getSliceTheoremPaper(), bibDatabase); <START> assertEquals("T. Diez. Slice theorem for fréchet group actions and covariant symplectic field theory. #may# 2014.", preview); <END> }</code><technical_language>#may# displayed properly</technical_language>

Target:
public void generatePreviewForSliceTheoremPaperUsingAbbr() throws Exception { BstPreviewLayout bstPreviewLayout = new BstPreviewLayout(Paths.get(BstPreviewLayoutTest.class.getResource("abbrv.bst").toURI())); String preview = bstPreviewLayout.generatePreview(getSliceTheoremPaper(), bibDatabase); assertEquals("T. Diez. Slice theorem for fréchet group actions and covariant symplectic field theory. May 2014.", preview); }
Source:
<code><START> public VisualEditorEditTemplateDialog selectSuggestedTemplate(int index) { <END> switchToIFrame(); waitForElementVisibleByElement(suggestedWidget); WebElement selected = suggestedTemplates.get(index).findElement(labelBy); selected.click(); switchOutOfIFrame(); PageObjectLogging.log("selectSuggestedTemplate", "Template selected: " + selected.getText(), true); return new VisualEditorEditTemplateDialog(driver); }</code><technical_language>method</technical_language>

Target:
public VisualEditorEditTemplateDialog selectSuggestedTemplate(int index) { switchToIFrame(); try { waitForElementVisibleByElement(suggestedWidget); WebElement selected = suggestedTemplates.get(index).findElement(labelBy); selected.click(); PageObjectLogging.log( "selectSuggestedTemplate", "Suggested template selected: " + selected.getText(), true ); return new VisualEditorEditTemplateDialog(driver); } finally { switchOutOfIFrame(); } }
Source:
<code><START> public TkLogged(final Take take, final Target trget) { <END> this.target = trget; this.origin = take; }</code><technical_language>I this ctor package-visible introduce another one, visible everybody, Target argument</technical_language>

Target:
TkLogged(final Take take, final Target trget) { this.target = trget; this.origin = take; }
Source:
<code>private void lockTouchedVm(Guid vmId) { if (!touchedVms.contains(vmId)) { lock(vmId); touchedVms.add(vmId); <START> touchedVmsOrdered.push(vmId); <END> } }</code><technical_language>tryLock instead of set</technical_language>

Target:
private void lockTouchedVm(Guid vmId) { lockOnce(vmId); touchedVms.push(vmId); }
Source:
<code>private Serializer() { dateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME; <START> localDateFormatter = DateTimeFormatter.ISO_DATE; <END> objectMapper = new ObjectMapper() .registerModule(new JavaTimeModule() .addSerializer(ZonedDateTime.class, new ZonedDateTimeSerializer(dateTimeFormatter)) .addSerializer(LocalDate.class, new LocalDateSerializer(localDateFormatter))) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) .configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); }</code><technical_language>difference two</technical_language>

Target:
private Serializer() { dateTimeFormatter = DateTimeFormatter.ISO_INSTANT; localDateFormatter = DateTimeFormatter.ISO_DATE; objectMapper = new ObjectMapper() .registerModule(new JavaTimeModule() .addSerializer(LocalDate.class, new LocalDateSerializer(localDateFormatter))) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) .configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); }
Source:
<code>public void testEmptyMenu() { SessionWrapper session = mApp.getSession(); MenuLoader menuLoader = new MenuLoader(session.getPlatform(), session, "root", new TestLogger()); this.mChoices = menuLoader.getMenus(); <START> Assert.assertEquals("Number of Menu roots in empty example", this.mChoices, 1); <END> }</code><technical_language>@ctsims Failure due to: this.mChoices -> this.mChoices.length</technical_language>

Target:
public void testEmptyMenu() { SessionWrapper session = mApp.getSession(); MenuLoader menuLoader = new MenuLoader(session.getPlatform(), session, "root", new TestLogger()); this.mChoices = menuLoader.getMenus(); Assert.assertEquals("Number of Menu roots in empty example", this.mChoices.length, 1); }
Source:
<code>public void init() throws DBException { try { <START> prop = getProperties(); <END> fieldCount = Integer.parseInt(prop.getProperty(CoreWorkload.FIELD_COUNT_PROPERTY, CoreWorkload.FIELD_COUNT_PROPERTY_DEFAULT)); String keyClass = prop.getProperty("key.class", "java.lang.String"); String persistentClass = prop.getProperty("persistent.class", "generated.User"); Properties p = DataStoreFactory.createProps(); dataStore = DataStoreFactory.getDataStore(keyClass, persistentClass, p, new Configuration()); synchronized(GoraBenchmarkClient.class) { if(executed) return; executed = true; goraBenchmarkUtils.generateAvroSchema(fieldCount); String dataStoreName = goraBenchmarkUtils.getDataStore(p); goraBenchmarkUtils.generateMappingFile(dataStoreName); goraBenchmarkUtils.generateDataBeans(); } } catch (GoraException e) { } }</code><technical_language>Please format Java code 2 space indents</technical_language>

Target:
public void init() throws DBException { try { synchronized (GoraBenchmarkClient.class) { prop = getProperties(); totalFieldCount = Integer .parseInt(prop.getProperty(CoreWorkload.FIELD_COUNT_PROPERTY, CoreWorkload.FIELD_COUNT_PROPERTY_DEFAULT)); Properties properties = DataStoreFactory.createProps(); if (!executed) { executed = true; GoraBenchmarkUtils.generateAvroSchema(totalFieldCount); String dataStoreName = GoraBenchmarkUtils.getDataBase(properties); GoraBenchmarkUtils.generateMappingFile(dataStoreName); GoraBenchmarkUtils.generateDataBeans(); } String keyClass = prop.getProperty(Constants.KEY_CLASS_KEY, Constants.KEY_CLASS_VALUE); String persistentClass = prop.getProperty(Constants.PERSISTENCE_CLASS_KEY, Constants.PERSISTENCE_CLASS_VALUE); dataStore = DataStoreFactory.getDataStore(keyClass, persistentClass, properties, new Configuration()); } } catch (GoraException e) { LOG.info("There is a problem in initialising the DataStore \n {}", e.getMessage(), e); } }
Source:
<code>public void execute(JobDelegateDataBean data) { try { executeDelegate(data); } catch (Exception e) { Logger.error(this, "An error occurred when running the Job Delegate: " + this.getClass(), e); } finally { try { <START> HibernateUtil.closeSession(); <END> } catch (DotHibernateException e) { Logger.warn(this, e.getMessage(), e); } } }</code><technical_language>removed this HibernateUtil.closeSession(); too</technical_language>

Target:
public void execute(JobDelegateDataBean data) { try { executeDelegate(data); } catch (Exception e) { Logger.error(this, "An error occurred when running the Job Delegate: " + this.getClass(), e); } }
Source:
<code>public void test() throws Exception { Element assertion = null; try { LOGGER.info("Invoking token service to get SAML assertion for " + USERNAME); assertion = wsClient.issueToken(SAMLUtil.SAML2_TOKEN_TYPE); String domElementAsString = DocumentUtil.getDOMElementAsString(assertion); System.out.println("assertion: " + domElementAsString); LOGGER.info("SAML assertion for " + USERNAME + " successfully obtained!"); } catch (WSTrustException wse) { LOGGER.error("Unable to issue assertion: " + wse.getMessage()); wse.printStackTrace(); System.exit(1); } <START> URL wsdl = new URL("http://localhost:8080/picketlink-sts-ws/EchoService?wsdl"); <END> QName serviceName = new QName("<LINK_0>", "EchoServiceService"); Service service = Service.create(wsdl, serviceName); EchoServiceRemote port = service.getPort(new QName("<LINK_0>", "EchoServicePort"), EchoServiceRemote.class); BindingProvider bp = (BindingProvider) port; ClientConfigUtil.setConfigHandlers(bp, "standard-jaxws-client-config.xml", "SAML WSSecurity Client"); bp.getRequestContext().put(SAML2Constants.SAML2_ASSERTION_PROPERTY, assertion); try { port.echo("Test"); } catch (Exception e) { LOGGER.error(e.getMessage(), e); fail(e.getMessage()); } if (wsClient != null) { wsClient.close(); } }</code><technical_language>this hard coded localhost</technical_language>

Target:
public void test() throws Exception { Element assertion = null; try { LOGGER.debug("Invoking token service to get SAML assertion for " + USERNAME); assertion = wsClient.issueToken(SAMLUtil.SAML2_TOKEN_TYPE); String domElementAsString = DocumentUtil.getDOMElementAsString(assertion); LOGGER.debug("assertion: " + domElementAsString); LOGGER.debug("SAML assertion for " + USERNAME + " successfully obtained!"); } catch (WSTrustException wse) { LOGGER.error("Unable to issue assertion: " + wse.getMessage()); wse.printStackTrace(); System.exit(1); } try { URL wsdl = new URL("http://localhost:8080/picketlink-sts-ws/EchoService?wsdl"); QName serviceName = new QName("<LINK_0>", "EchoServiceService"); Service service = Service.create(wsdl, serviceName); EchoServiceRemote port = service.getPort(new QName("<LINK_0>", "EchoServicePort"), EchoServiceRemote.class); BindingProvider bp = (BindingProvider) port; ClientConfigUtil.setConfigHandlers(bp, "standard-jaxws-client-config.xml", "SAML WSSecurity Client"); bp.getRequestContext().put(SAML2Constants.SAML2_ASSERTION_PROPERTY, assertion); port.echo("Test"); } finally { if (wsClient != null) { wsClient.close(); } } }
Source:
<code>public Map createVolume(String sdUUID, String spUUID, String imgUUID, String size, Integer volFormat, Integer preallocate, Integer diskType, String volUUID, String desc, String srcImgUUID, String srcVolUUID) { try { DataCenter dataCenter = getDataCenterById(spUUID); StorageDomain storageDomain = dataCenter.getStorageDomainMap().get(sdUUID); final Volume volume = new Volume(); volume.setId(volUUID); volume.setSize(size); volume.setVolFormat(volFormat); volume.setPreallocate(preallocate); volume.setDiskType(diskType); volume.setImgUUID(imgUUID); volume.setDesc(desc); volume.setSrcImgUUID(srcImgUUID); volume.setSrcVolUUID(srcVolUUID); log.info("Adding volume: for sp: {}, sd: {}", new Object[] { volUUID, spUUID, sdUUID }); storageDomain.getVolumes().put(volUUID, volume); updateDataCenter(dataCenter); final Map resultMap = getOKStatus(); final Task task = new Task(getUuid()); resultMap.put("uuid", task.getId()); <START> final Host host = VdsmManager.getInstance().getSpmMap().get(spUUID); END> syncTask(host, task); TaskProcessor.getInstance().addTask(new TaskRequest(TaskType.FINISH_CREATE_VOLUME, 3000l, task)); return resultMap; } catch (Exception e) { throw error(e); } }</code><technical_language>getter for host expose map world</technical_language>

Target:
public Map createVolume(String sdUUID, String spUUID, String imgUUID, String size, Integer volFormat, Integer preallocate, Integer diskType, String volUUID, String desc, String srcImgUUID, String srcVolUUID) { try { DataCenter dataCenter = getDataCenterById(spUUID); StorageDomain storageDomain = dataCenter.getStorageDomainMap().get(sdUUID); final Volume volume = new Volume(); volume.setId(volUUID); volume.setSize(size); volume.setVolFormat(volFormat); volume.setPreallocate(preallocate); volume.setDiskType(diskType); volume.setImgUUID(imgUUID); volume.setDesc(desc); volume.setSrcImgUUID(srcImgUUID); volume.setSrcVolUUID(srcVolUUID); log.info("Adding volume: for sp: {}, sd: {}", new Object[] { volUUID, spUUID, sdUUID }); storageDomain.getVolumes().put(volUUID, volume); updateDataCenter(dataCenter); final Map resultMap = getOKStatus(); final Task task = new Task(getUuid()); resultMap.put("uuid", task.getId()); syncTask((Host) VdsmManager.getInstance().getSpmHost(spUUID), task); TaskProcessor.getInstance().addTask(new TaskRequest(TaskType.FINISH_CREATE_VOLUME, 3000l, task)); return resultMap; } catch (Exception e) { throw error(e); } }
Source:
<code>public static void init() throws IOException { Path appDataRoot = getAppDataRoot(); <START> if (Files.notExists(appDataRoot)) <END> { LOG.info("Creating application data root directory: {}", appDataRoot.toString()); Files.createDirectory(appDataRoot); } else { if (!Files.isDirectory(appDataRoot)) { throw new IOException( format("Application data root path '%s' is not a directory", appDataRoot.toString())); } if (!Files.isWritable(appDataRoot)) { throw new IOException( format("Application data root directory '%s' is not writable", appDataRoot.toString())); } } LOG.info("Application data directory: {}", appDataRoot.toString()); AppDataRootProvider.setAppDataRoot(appDataRoot); }</code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') Replace this a call "toFile().exists()" method [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
public static void init() throws IOException { Path appDataRoot = getAppDataRoot(); if (!appDataRoot.toFile().exists()) { LOG.info("Creating application data root directory: {}", appDataRoot); Files.createDirectory(appDataRoot); } else { if (!appDataRoot.toFile().isDirectory()) { throw new IOException(format("Application data root path '%s' is not a directory", appDataRoot)); } if (!Files.isWritable(appDataRoot)) { throw new IOException(format("Application data root directory '%s' is not writable", appDataRoot)); } } LOG.info("Application data directory: {}", appDataRoot.toString()); AppDataRootProvider.setAppDataRoot(appDataRoot); }
Source:
<code>protected void setOnViewChanged() { getGeneratedClass()._implements(OnViewChangedListener.class); onViewChanged = getGeneratedClass().method(PUBLIC, getCodeModel().VOID, "onViewChanged"); onViewChanged.annotate(Override.class); onViewChangedBody = onViewChanged.body(); <START> onViewChangedBodyBeforeFindViews = onViewChangedBody.blockSimple(); END> onViewChangedBodyFindViews = onViewChangedBody.blockSimple(); onViewChangedHasViewsParam = onViewChanged.param(HasViews.class, "hasViews"); AbstractJClass notifierClass = getJClass(OnViewChangedNotifier.class); getInitBody().staticInvoke(notifierClass, "registerOnViewChangedListener").arg(_this()); }</code><technical_language>#1585 replace these, right</technical_language>

Target:
protected void setOnViewChanged() { getGeneratedClass()._implements(OnViewChangedListener.class); onViewChanged = getGeneratedClass().method(PUBLIC, getCodeModel().VOID, "onViewChanged"); onViewChanged.annotate(Override.class); onViewChangedBody = onViewChanged.body(); onViewChangedBodyBeforeInjectionBlock = onViewChangedBody.blockVirtual(); onViewChangedBodyInjectionBlock = onViewChangedBody.blockVirtual(); onViewChangedBodyAfterInjectionBlock = onViewChangedBody.blockVirtual(); onViewChangedHasViewsParam = onViewChanged.param(HasViews.class, "hasViews"); AbstractJClass notifierClass = getJClass(OnViewChangedNotifier.class); getInitBodyInjectionBlock().staticInvoke(notifierClass, "registerOnViewChangedListener").arg(_this()); }
Source:
<code>public Boolean thereIsAProjectInTheWorkbench() { final Collection<OrganizationalUnit> organizationalUnits = getOrganizationalUnits(); for ( OrganizationalUnit organizationalUnit : organizationalUnits ) { final Collection<Repository> repositories = organizationalUnit.getRepositories(); <START> for ( Repository repository : repositories ) { <END> final Collection<String> branches = repository.getBranches(); for ( String branch : branches ) { final Set<Project> projects = kieProjectService.getProjects( repository, branch ); if ( projects != null && !projects.isEmpty() ) { return true; } } } } return false; }</code><technical_language>Correct if I wrong; organizationalUnit.getRepositories() returns Repositories OrganizationalUnit current User access Repository not? safe ouService.getOrganizationalUnits() this returns "authorised" OUs. Do need filter Repositories here</technical_language>

Target:
public Boolean thereIsAProjectInTheWorkbench() { return getOrganizationalUnits().stream() .flatMap( organizationalUnit -> organizationalUnit.getRepositories().stream() .filter( repository -> authorizationManager.authorize( repository, sessionInfo.getIdentity() ) ) ) .flatMap( repository -> repository.getBranches().stream() .map( branch -> kieProjectService.getProjects( repository, branch ) ) ) .anyMatch( projects -> projects != null && !projects.isEmpty() ); }
Source:
<code>public void testAdd() { MockEnabledModelResolver resolver = new MockEnabledModelResolver(); ModelResolverDescriptor oldValue = manager.add(resolver, resolver.getClass().getName(), "", ""); assertSame(manager.getAllResolver().iterator().next().getModelResolver(), resolver); <START> assertEquals(oldValue, null); <END> }</code><technical_language>Please assertNull instead</technical_language>

Target:
public void testAdd() { MockEnabledModelResolver resolver = new MockEnabledModelResolver(); ModelResolverDescriptor oldValue = manager.add(resolver, resolver.getClass().getName(), "", ""); assertSame(manager.getAllResolver().iterator().next().getModelResolver(), resolver); assertNull(oldValue); }
Source:
<code>public void dealWithLicenseAction(ResourceRequest request, ResourceResponse response, String action) throws IOException, PortletException { if (PortalConstants.LICENSE_SEARCH.equals(action)) { final String searchText = request.getParameter(PortalConstants.WHAT); try { LicenseService.Iface client = thriftClients.makeLicenseClient(); List<License> licenses = client.getLicenseSummary(); if (!isNullOrEmpty(searchText)) { licenses = FluentIterable.from(licenses).filter(new Predicate<License>() { @Override public boolean apply(License input) { String fullname = input.getFullname(); String shortname = input.getShortname(); <START> return !isNullOrEmpty(fullname) <END> && ((StringUtils.containsIgnoreCase(searchText, fullname) || StringUtils.containsIgnoreCase(searchText, shortname))); } }).toList(); } request.setAttribute(PortalConstants.LICENSE_LIST, licenses); include("/html/utils/ajax/licenseListAjax.jsp", request, response, PortletRequest.RESOURCE_PHASE); } catch (TException e) { log.error("Error getting licenses", e); } } }</code><technical_language>isNullOrEmpty check is necessary if StringUtils.containsIgnoreCase checks for null</technical_language>

Target:
public void dealWithLicenseAction(ResourceRequest request, ResourceResponse response, String action) throws IOException, PortletException { if (PortalConstants.LICENSE_SEARCH.equals(action)) { final String searchText = request.getParameter(PortalConstants.WHAT); try { LicenseService.Iface client = thriftClients.makeLicenseClient(); List<License> licenses = client.getLicenseSummary(); licenses = FluentIterable.from(licenses).filter(new Predicate<License>() { @Override public boolean apply(License input) { String fullname = input.getFullname(); String shortname = input.getShortname(); return (StringUtils.containsIgnoreCase(fullname, searchText) || StringUtils.containsIgnoreCase(shortname, searchText)); } }).toList(); request.setAttribute(PortalConstants.LICENSE_LIST, licenses); include("/html/utils/ajax/licenseListAjax.jsp", request, response, PortletRequest.RESOURCE_PHASE); } catch (TException e) { log.error("Error getting licenses", e); } } }
Source:
<code>private JsonToRowDataConverter createMapConverter( <START> String typeSummary, LogicalType keyType, LogicalType valueType) { <END> if (!LogicalTypeChecks.hasFamily(keyType, LogicalTypeFamily.CHARACTER_STRING)) { throw new UnsupportedOperationException( "JSON format doesn't support non-string as key type of map. " + "The map type is: " + typeSummary); } final JsonToRowDataConverter keyConverter = createConverter(keyType); final JsonToRowDataConverter valueConverter = createConverter(valueType); return jsonNode -> { Iterator<Map.Entry<String, JsonNode>> fields = jsonNode.fields(); Map<Object, Object> result = new HashMap<>(); while (fields.hasNext()) { Map.Entry<String, JsonNode> entry = fields.next(); Object key = keyConverter.convert(TextNode.valueOf(entry.getKey())); Object value = valueConverter.convert(entry.getValue()); result.put(key, value); } return new GenericMapData(result); }; }</code><technical_language>Add more indent for parameters if start a new line</technical_language>

Target:
private JsonToRowDataConverter createMapConverter( String typeSummary, LogicalType keyType, LogicalType valueType) { if (!LogicalTypeChecks.hasFamily(keyType, LogicalTypeFamily.CHARACTER_STRING)) { throw new UnsupportedOperationException( "JSON format doesn't support non-string as key type of map. " + "The type is: " + typeSummary); } final JsonToRowDataConverter keyConverter = createConverter(keyType); final JsonToRowDataConverter valueConverter = createConverter(valueType); return jsonNode -> { Iterator<Map.Entry<String, JsonNode>> fields = jsonNode.fields(); Map<Object, Object> result = new HashMap<>(); while (fields.hasNext()) { Map.Entry<String, JsonNode> entry = fields.next(); Object key = keyConverter.convert(TextNode.valueOf(entry.getKey())); Object value = valueConverter.convert(entry.getValue()); result.put(key, value); } return new GenericMapData(result); }; }
Source:
<code>private void resetWallet() { final WalletLock walletLock = WalletLock.getInstance(); if (WalletLock.getInstance().isWalletLocked(wallet)) { UnlockWalletDialogFragment.show(getSupportFragmentManager(), new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { if (!walletLock.isWalletLocked(wallet)) { resetWallet(); } } }); return; } log.info("Clearing all app data and exiting."); try { Runtime.getRuntime().exec("pm clear "+ getApplicationContext().getPackageName()); <START> } catch (IOException e) { <END> e.printStackTrace(); } }</code><technical_language>a method WalletApplication.eraseAndCreateNewWallet() handles removing wallet. This method remove other files (such logs, want in event is issue wallet reset function). Additionally, create a new empty wallet. Another place handles this is PIN is entered incorrectly times in is in PinRetryController.showResetWalletDialog</technical_language>

Target:
private void resetWallet() { final WalletLock walletLock = WalletLock.getInstance(); if (WalletLock.getInstance().isWalletLocked(wallet)) { UnlockWalletDialogFragment.show(getSupportFragmentManager(), new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { if (!walletLock.isWalletLocked(wallet)) { resetWallet(); } } }); return; } try { getWalletApplication().eraseAndCreateNewWallet(); } catch (Exception e) { e.printStackTrace(); } }
Source:
<code><START> public void put(Map<String, LookupExtractorFactory> lookups) <END> { synchronized (lock) { assertStarted(); for (ImmutableMap.Entry<String, LookupExtractorFactory> entry : lookups.entrySet()) { final String lookupName = entry.getKey(); final LookupExtractorFactory lookupExtractorFactory = entry.getValue(); if (!lookupExtractorFactory.start()) { throw new ISE("start method returned false for lookup [%s]", lookupName); } if (null != lookupMap.putIfAbsent(lookupName, lookupExtractorFactory)) { LOGGER.warn("lookup with name [%s] is not add since it already exist", lookupName); } } } }</code><technical_language>Propose this put(Collection<LookupExtractorFactory> lookups) LookupExtractorFactory a name. If internal handlings of this class a map (probably) fine</technical_language>

Target:
public void put(Map<String, LookupExtractorFactory> lookups) { Map<String, LookupExtractorFactory> faildExtractorFactoryMap = new HashMap<>(); synchronized (lock) { assertStarted(); for (Map.Entry<String, LookupExtractorFactory> entry : lookups.entrySet()) { final String lookupName = entry.getKey(); final LookupExtractorFactory lookupExtractorFactory = entry.getValue(); if (lookupMap.containsKey(lookupName)) { LOGGER.warn("lookup [%s] is not add, another lookup with the same name already exist", lookupName); continue; } if (!lookupExtractorFactory.start()) { faildExtractorFactoryMap.put(lookupName, lookupExtractorFactory); continue; } lookupMap.put(lookupName, lookupExtractorFactory); } if (!faildExtractorFactoryMap.isEmpty()) { throw new ISE( "was not able to start the following lookup(s) [%s]", faildExtractorFactoryMap.keySet().toString() ); } } }
Source:
<code>public int hashCode() { int ppHashCode = 0; Collection<ProductData> providedProducts = this.getProvidedProducts(); <START> <END> if (providedProducts != null) { for (ProductData pProduct : providedProducts) { ppHashCode = 31 * ppHashCode + (pProduct != null ? pProduct.hashCode() : 0); } } HashCodeBuilder builder = new HashCodeBuilder(37, 7) .append(super.hashCode()) .append(this.uuid) .append(this.id) .append(this.name) .append(this.multiplier) .append(this.href) .append(this.attributes) .append(this.content) .append(this.dependentProductIds) .append(this.branding) .append(this.locked) .append(ppHashCode); return builder.toHashCode(); }</code><technical_language>I need manually calculate here. able throw collection HashCodeBuilder do content</technical_language>

Target:
public int hashCode() { HashCodeBuilder builder = new HashCodeBuilder(37, 7) .append(super.hashCode()) .append(this.uuid) .append(this.id) .append(this.name) .append(this.multiplier) .append(this.href) .append(this.attributes) .append(this.content) .append(this.dependentProductIds) .append(this.branding) .append(this.locked) .append(this.providedProducts); return builder.toHashCode(); }
Source:
<code><START> public void trace(final String msg, final Throwable t) { <END> throw new UnsupportedOperationException(); }</code><technical_language>overload of methods throw exception base class actual useful implementation? <LINK_0></technical_language>

Target:
public void trace(final String msg, final Throwable t) { log("TRACE", msg, t); }