auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); KazakApplication.injector().inject(this); setContentView(R.layout.activity_login); Firebase.setAndroidContext(this); if (savedInstanceState == null || !savedInstanceState.getBoolean(BUNDLE_NEED_NEW_CACHE)) { <START> Log.v(TAG, "New LoginActivity created, clearing the login cache."); <END> authRepository.clearLoginCache(); } mEmailView = (AutoCompleteTextView) findViewById(R.id.email); populateAutoComplete(); mPasswordView = (EditText) findViewById(R.id.password); mPasswordView.setOnEditorActionListener( new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) { if (id == R.id.login || id == EditorInfo.IME_NULL) { attemptLogin(); return true; } return false; } } ); Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button); mEmailSignInButton.setOnClickListener( new OnClickListener() { @Override public void onClick(View view) { attemptLogin(); } } ); mLoginFormView = findViewById(R.id.login_form); mProgressView = findViewById(R.id.login_progress); loginSubscriptions = new CompositeSubscription(); }</code><technical_language>If this is for debugging, remove it</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); KazakApplication.injector().inject(this); setContentView(R.layout.activity_login); contentRootView = (LinearLayout) findViewById(R.id.login_root_layout); if (savedInstanceState == null || !savedInstanceState.getBoolean(BUNDLE_NEED_NEW_CACHE)) { authRepository.clearLoginCache(); } emailView = (AutoCompleteTextView) findViewById(R.id.email); populateAutoComplete(); passwordView = (EditText) findViewById(R.id.password); passwordView.setOnEditorActionListener( new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) { if (id == R.id.login || id == EditorInfo.IME_NULL) { attemptLogin(); return true; } return false; } } ); Button signIn = (Button) findViewById(R.id.email_sign_in_button); signIn.setOnClickListener( new OnClickListener() { @Override public void onClick(@NonNull View view) { attemptLogin(); } } ); loginFormView = findViewById(R.id.login_form); progressView = findViewById(R.id.login_progress); }
Source:
<code>private String getSerialNumber(byte[] bytes) { byte[] sn = new byte[10]; for (int i = 0; i < 10; i++) { sn[i] = (byte) bytes[i + 8]; } try { return new String(sn, "UTF-8"); } catch (UnsupportedEncodingException e) { <START> e.printStackTrace(); <END> } return ""; }</code><technical_language>please remove TODO printStackTrace() proper logging instead</technical_language>

Target:
private String getSerialNumber(byte[] bytes) { byte[] sn = new byte[10]; for (int i = 0; i < 10; i++) { sn[i] = (byte) bytes[i + 8]; } try { return new String(sn, "UTF-8"); } catch (UnsupportedEncodingException e) { logger.debug("Cannot encode serial number from C message due to encoding issues."); } return ""; }
Source:
<code>private DeferredSerialization dsOf(final ByteBuffer buf) { return new DeferredSerialization() { @Override public ByteBuffer serialize(final ByteBuffer outbuf) throws IOException { outbuf.put(buf); <START> return null; <END> } @Override public void cancel() @Override public int getSerializedSize() { return buf.remaining(); } }; }</code><technical_language>I thought for ssl return bytebuffer</technical_language>

Target:
private DeferredSerialization dsOf(final ByteBuffer buf) { return new DeferredSerialization() { @Override public void serialize(final ByteBuffer outbuf) throws IOException { outbuf.put(buf); } @Override public void cancel() @Override public int getSerializedSize() { return buf.remaining(); } }; }
Source:
<code>private static <T> Optional<T> nullableOptional(Callable<T> callable) { if (!CDI_AVAILABLE) { <START> return Optional.ofNullable(null); <END> } T t; try { t = callable.call(); } catch (Throwable ex) { t = null; } return Optional.ofNullable(t); }</code><technical_language>Minor, Optional.empty() for :)</technical_language>

Target:
private static <T> Optional<T> nullableOptional(Callable<T> callable) { if (!CDI_AVAILABLE) { return Optional.empty(); } T t; try { t = callable.call(); } catch (Throwable ex) { t = null; } return Optional.ofNullable(t); }
Source:
<code><START> public Boolean isBuildSuccessIndicated() { <END> if (getStream() == null) return false; return getStream().contains(BUILD_SUCCESS); }</code><technical_language>null returned</technical_language>

Target:
public boolean isBuildSuccessIndicated() { if (isErrorIndicated() || getStream() == null) { return false; } return getStream().contains(BUILD_SUCCESS); }
Source:
<code>public void setUpZap() throws Exception { super.setUpZap(); Path xmlDir = Files.createDirectories( Paths.get(Constant.getZapHome(), JSFunctionPassiveScanner.FUNC_LIST_DIR)); Path testFile = xmlDir.resolve(JSFunctionPassiveScanner.FUNC_LIST_FILE); Files.write( <START> testFile, Arrays.asList("# Test File", "bypassSecurityTrustScript", "trustAsHtml")); <END> }</code><technical_language>I ok (doing leading $)</technical_language>

Target:
public void setUpZap() throws Exception { super.setUpZap(); Path xmlDir = Files.createDirectories( Paths.get(Constant.getZapHome(), JSFunctionPassiveScanner.FUNC_LIST_DIR)); Path testFile = xmlDir.resolve(JSFunctionPassiveScanner.FUNC_LIST_FILE); Files.write(testFile, Arrays.asList("# Test File", "bypassSecurityTrustHtml", "eval")); }
Source:
<code>private void checkCachedCategories(PoiFiltersHelper poiFiltersHelper) { String fileName = resource.getFileName(); long lastModified = resource.getFileLastModified(); Pair<Long, Map<String, List<String>>> cache = poiFiltersHelper.getCacheByResourceName(fileName); if (cache == null || cache.first != null && cache.first != lastModified) { try { BinaryMapIndexReader reader = getOpenFile(); if (reader != null) { reader.initCategories(); List<BinaryMapPoiReaderAdapter.PoiRegion> regions = reader.getPoiIndexes(); for (BinaryMapPoiReaderAdapter.PoiRegion region : regions) { List<String> categories = region.getCategories(); List<List<String>> subCategories = region.getSubcategories(); for (int i = 0; i < categories.size(); i++) { PoiCategory poiCategory = poiTypes.getPoiCategoryByName(categories.get(i)); <START> Set<String> filters = new HashSet<>(subCategories.get(i)); <END> List<String> keys = poiCategory.getPoiTypesKeys(); filters.removeAll(keys); if (!filters.isEmpty()) { poiCategories.put(categories.get(i), new ArrayList<>(filters)); } } } if (cache == null) { poiFiltersHelper.insertCacheForResource(fileName, lastModified, poiCategories); } else { poiFiltersHelper.updateCacheForResource(fileName, lastModified, poiCategories); } } } catch (IOException e) { log.error("Error initializing categories ", e); } } else if (cache.second != null) { poiCategories = cache.second; } }</code><technical_language>? Iterate in loop check subtype, faster</technical_language>

Target:
private void checkCachedCategories(PoiFiltersHelper poiFiltersHelper) { String fileName = resource.getFileName(); long lastModified = resource.getFileLastModified(); Pair<Long, Map<String, List<String>>> cache = poiFiltersHelper.getCacheByResourceName(fileName); if (cache == null || cache.first != null && cache.first != lastModified) { deltaPoiCategories = new HashMap<>(); try { BinaryMapIndexReader reader = getOpenFile(); if (reader != null) { reader.initCategories(); List<BinaryMapPoiReaderAdapter.PoiRegion> regions = reader.getPoiIndexes(); for (BinaryMapPoiReaderAdapter.PoiRegion region : regions) { calculateDeltaSubcategories(region); } if (cache == null) { poiFiltersHelper.insertCacheForResource(fileName, lastModified, deltaPoiCategories); } else { poiFiltersHelper.updateCacheForResource(fileName, lastModified, deltaPoiCategories); } } } catch (IOException e) { log.error("Error initializing categories ", e); } } else if (cache.second != null) { deltaPoiCategories = cache.second; } }
Source:
<code>public void anotherMethod() { this.anonMethod(new AnonWithEmpty() { private int member; <START> @Override <END> public void fooEmpty() { this.member++; } }); }</code><technical_language>@Override this annotations is needed in test inputs</technical_language>

Target:
public void anotherMethod() { this.anonMethod(new AnonWithEmpty() { private int member; public void fooEmpty() { this.member++; } }); }
Source:
<code>public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_ISSUE_CREATE) { if (resultCode == Activity.RESULT_OK && data.hasExtra("issue")) { final Issue issue = (Issue) data.getSerializableExtra("issue"); <START> mHandler.post(new Runnable() { <END> @Override public void run() { if (mOpenFragment != null) { mOpenFragment.onItemClick(issue); } } }); } } else { super.onActivityResult(requestCode, resultCode, data); } }</code><technical_language>This delay a unsafe. if mOpenFragment is null, need memorize passed issue carry out onItemClick fragment reference. - preferable - do startActivityForResult(IssueActivity.makeIntent(this, mRepoOwner, mRepoName, issue.getNumber()) ourselves</technical_language>

Target:
public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_ISSUE_CREATE) { if (resultCode == Activity.RESULT_OK && data.hasExtra("issue")) { Issue issue = (Issue) data.getSerializableExtra("issue"); Intent intent = IssueActivity.makeIntent(this, mRepoOwner, mRepoName, issue.getNumber()); startActivityForResult(intent, REQUEST_ISSUE_AFTER_CREATE); } } else if (requestCode == REQUEST_ISSUE_AFTER_CREATE) { super.onRefresh(); } else { super.onActivityResult(requestCode, resultCode, data); } }
Source:
<code>@Test public void checkAbilityToChangeOutputStream() throws Exception { file = new File("test"); file.createNewFile(); stream = new FileOutputStream(file); service = buildDefaultService(); service.addOutPutStream(stream); service.start(); <START> assertTrue(file.length() > 0); <END> }</code><technical_language>> assertThat(file.length(), greaterThan(0L))</technical_language>

Target:
@Test public void checkAbilityToChangeOutputStream() throws Exception { testLogFile = new File("test"); testLogFile.createNewFile(); stream = new FileOutputStream(testLogFile); service = buildDefaultService(); service.addOutPutStream(stream); service.start(); assertThat(testLogFile.length(), greaterThan(0L)); }
Source:
<code>public static void mongoInsertSubmission(final DB dbs, final String uniqueId, final String problemId, final String submissionId, final boolean experiment) { <START> LOG.info("Inserting an experiment ", experiment); <END> LOG.info("Database is ", dbs); LOG.info("Problem id: ", problemId); final DBRef myDbRef = new DBRef(dbs, experiment ? EXPERIMENT_COLLECTION : SOLUTION_COLLECTION, new ObjectId(problemId)); final DBCollection collection = dbs.getCollection(experiment ? EXPERIMENT_COLLECTION : SOLUTION_COLLECTION); final DBObject corsor = myDbRef.fetch(); LOG.info("corsor: {}", corsor); LOG.info("uniuq id: {}", uniqueId); final BasicDBObject queryObj = new BasicDBObject(experiment ? uniqueId : SOLUTION_ID, submissionId); if (corsor == null) { LOG.info("Creating a new instance to this old itemid"); queryObj.append(SELF_ID, new ObjectId(problemId)); collection.insert(queryObj); } else { LOG.info("adding a new submission to this old itemid"); collection.update(corsor, new BasicDBObject("$set", queryObj)); } }</code><technical_language>shoudl {}</technical_language>

Target:
public static void mongoInsertSubmission(final DB dbs, final String uniqueId, final String problemId, final String submissionId, final boolean experiment) { LOG.info("Inserting an experiment {}", experiment); LOG.info("Database is {}", dbs); LOG.info("Problem id: {}", problemId); final DBRef myDbRef = new DBRef(dbs, experiment ? EXPERIMENT_COLLECTION : SOLUTION_COLLECTION, new ObjectId(problemId)); final DBCollection collection = dbs.getCollection(experiment ? EXPERIMENT_COLLECTION : SOLUTION_COLLECTION); final DBObject corsor = myDbRef.fetch(); LOG.info("corsor: {}", corsor); LOG.info("uniuq id: {}", uniqueId); final BasicDBObject queryObj = new BasicDBObject(experiment ? uniqueId : SOLUTION_ID, submissionId); if (corsor == null) { LOG.info("Creating a new instance to this old itemid"); queryObj.append(SELF_ID, new ObjectId(problemId)); collection.insert(queryObj); } else { LOG.info("adding a new submission to this old itemid"); collection.update(corsor, new BasicDBObject("$set", queryObj)); } }
Source:
<code>public void testCommandDelegatesToTmcLangs() throws Exception { new RunCheckStyle("somePath", tmcLangsMock).call(); <START> verify(tmcLangsMock, times(1)).runCheckCodeStyle(eq(Paths.get("somePath"))); <END> }</code><technical_language>times(1) is needed</technical_language>

Target:
public void testCommandDelegatesToTmcLangs() throws Exception { new RunCheckStyle("somePath", tmcLangsMock).call(); verify(tmcLangsMock).runCheckCodeStyle(eq(Paths.get("somePath"))); }
Source:
<code>private void persistParameter(T value) { String memento = MementoUtils.encodeStringIntoMemento(value.toString()); <START> IEclipsePreferences store = MulticoreVisualizerUIPlugin.getEclipsePreferenceStore(); <END> if (memento != null) { store.put(m_storeKey, memento); try { store.flush(); } catch (BackingStoreException e) { e.printStackTrace(); } } }</code><technical_language>Move line if</technical_language>

Target:
private void persistParameter(T value) { String memento = MementoUtils.encodeStringIntoMemento(value.toString()); if (memento != null) { IEclipsePreferences store = MulticoreVisualizerUIPlugin.getEclipsePreferenceStore(); store.put(m_storeKey, memento); try { store.flush(); } catch (BackingStoreException e) { e.printStackTrace(); } } }
Source:
<code>protected String fixEntryName(String entryName){ if(entryName.indexOf('\\') > 0) { <START> return entryName.replace('\\', CompressedHelper.SEPARATOR_CHAR); <END> } else { return entryName; } }</code><technical_language>replaceAll instead. *Bump*</technical_language>

Target:
protected String fixEntryName(String entryName){ if(entryName.indexOf('\\') > 0) { return entryName.replaceAll("\\\\", CompressedHelper.SEPARATOR); } else { return entryName; } }
Source:
<code>public void testSshProtoHostWithEmptyPortAndPath() throws Exception { final String str = "ssh://example.com:/path"; URIish u = new URIish(str); assertEquals("ssh", u.getScheme()); assertTrue(u.isRemote()); assertEquals("/path", u.getRawPath()); assertEquals("/path", u.getPath()); assertEquals("example.com", u.getHost()); assertEquals(-1, u.getPort()); assertEquals("ssh://example.com:/path", u.toString()); <START> assertEquals("ssh://example.com:/path", u.toASCIIString()); <END> assertEquals(u, new URIish(str)); }</code><technical_language>explained in URIish, I assertions fails, assertEquals("ssh://example.com/path", u.toString()); assertEquals("ssh://example.com/path", u.toASCIIString()); succeed, I assertEquals(u, new URIish("ssh://example.com/path")); succeed</technical_language>

Target:
public void testSshProtoHostWithEmptyPortAndPath() throws Exception { final String str = "ssh://example.com:/path"; URIish u = new URIish(str); assertEquals("ssh", u.getScheme()); assertTrue(u.isRemote()); assertEquals("/path", u.getRawPath()); assertEquals("/path", u.getPath()); assertEquals("example.com", u.getHost()); assertEquals(-1, u.getPort()); assertEquals("ssh://example.com/path", u.toString()); assertEquals("ssh://example.com/path", u.toASCIIString()); assertEquals(u, new URIish(str)); assertEquals(u, new URIish("ssh://example.com/path")); }
Source:
<code>public int hashCode() { int hash = 5; hash = 79 * hash + (this.path != null ? this.path.hashCode() : 0); <START> return hash; <END> }</code><technical_language>return this.path.hashCode()</technical_language>

Target:
public int hashCode() { return this.path.hashCode(); }
Source:
<code>public void execute(String userName) { FollowModeManager currentFollowModeManager = followModeManager; User userToFollow = findUser(userName); if (currentFollowModeManager == null) { return; } <START> User currentlyFollowedUser = followModeManager.getFollowedUser(); <END> if ((currentlyFollowedUser != null && !currentlyFollowedUser.equals(userToFollow)) || (currentlyFollowedUser == null && userToFollow != null)) { currentFollowModeManager.follow(userToFollow); } actionPerformed(); }</code><technical_language>I prefer move this logic FollowModeManager</technical_language>

Target:
public void execute(String userName) { FollowModeManager currentFollowModeManager = followModeManager; User userToFollow = findUser(userName); if (currentFollowModeManager == null) { return; } currentFollowModeManager.follow(userToFollow); actionPerformed(); }
Source:
<code><START> public static UserFactory getInstance() { <END> if (instance == null) { Realm realm = Realm.getInstance(configuration); RealmLog.error("TTT " + realm.getPath()); UserFactoryStore store = realm.where(UserFactoryStore.class).findFirst(); if (store == null || store.getUserName() == null) { throw new IllegalStateException("Current user has not been set. Call resetInstance() first."); } instance = new UserFactory(store.getUserName()); realm.close(); } return instance; }</code><technical_language>Needs synchronized</technical_language>

Target:
public static synchronized UserFactory getInstance() { if (instance == null) { Realm realm = Realm.getInstance(configuration); UserFactoryStore store = realm.where(UserFactoryStore.class).findFirst(); if (store == null || store.getUserName() == null) { throw new IllegalStateException("Current user has not been set. Call resetInstance() first."); } instance = new UserFactory(store.getUserName()); realm.close(); } RealmLog.debug("UserFactory.getInstance, the default user is " + instance.userName + " ."); return instance; }
Source:
<code>private void endDefaultOperations() { endUnlockOps(); <START> <END> if (getParameters().getBaseTemplateId() != null) { for (Guid vmId : getVmDAO().getVmIdsForVersionUpdate(getParameters().getBaseTemplateId())) { UpdateVmVersionParameters params = new UpdateVmVersionParameters(vmId); params.setSessionId(getParameters().getSessionId()); params.setTransactionScopeOption(TransactionScopeOption.RequiresNew); getBackend().runInternalAction(VdcActionType.UpdateVmVersion, params); } } }</code><technical_language>2 concurrent commands for create template follow regenerate VMs avoid races Vm regenrated in order tought. need this a task runs a quartz job run singular able stop re-fire job</technical_language>

Target:
private void endDefaultOperations() { endUnlockOps(); if (getParameters().getBaseTemplateId() != null) { String jobId = SchedulerUtilQuartzImpl.getInstance().scheduleAOneTimeJob(this, "onTimerHandleVdsRecovering", new Class[0], new Object[0], 0, TimeUnit.SECONDS); updateVmsJobIdMap.put(getParameters().getBaseTemplateId(), jobId); } }
Source:
<code>public Function<Locale, Text> apply(String translationId) { return locale -> { <START> final Map<Locale, Text> translations = getTranslations(translationId); <END> final Text result = translations.get(locale); if (result == null) { return this.translationFallback.apply(locale, translations); } else { return result; } }; }</code><technical_language>this simply call getTranslation</technical_language>

Target:
public Function<Locale, Text> apply(String translationId) { checkNotNull(translationId, "translationId"); return locale -> getTranslation(translationId, locale); }
Source:
<code>public FileWatcher startWatching(Collection<String> paths, double latency, FileWatcherCallback callback) { if (paths.isEmpty()) { return FileWatcher.EMPTY; } FunctionResult result = new FunctionResult(); <START> FileWatcher watch = startWatching(paths.toArray(new String[0]), latency, callback, result); <END> if (result.isFailed()) { throw new NativeException("Failed to start watch. Reason: " + result.getMessage()); } return watch; }</code><technical_language>suggestion FileWatcher watcher = startWatching(paths.toArray(new String[0]), latency, callback, result);</technical_language>

Target:
public FileWatcher startWatching(Collection<String> paths, double latency, FileWatcherCallback callback) { if (paths.isEmpty()) { return FileWatcher.EMPTY; } FunctionResult result = new FunctionResult(); FileWatcher watcher = startWatching(paths.toArray(new String[0]), latency, callback, result); if (result.isFailed()) { throw new NativeException("Failed to start watching. Reason: " + result.getMessage()); } return watcher; }
Source:
<code>public List<BrooklinMetricInfo> getMetricInfos() { List<BrooklinMetricInfo> metrics = new ArrayList<>(); <START> metrics.add(new BrooklinMeterInfo(buildMetricName(NUM_TASK_RESTARTS))); <END> return Collections.unmodifiableList(metrics); }</code><technical_language>move metrics prefix, need modify this. a regex for matching: <metrics prefix> + MetricsAware.KEY_REGEX + <metrics name></technical_language>

Target:
public List<BrooklinMetricInfo> getMetricInfos() { List<BrooklinMetricInfo> metrics = new ArrayList<>(); metrics.add(new BrooklinGaugeInfo(buildMetricName(_metricsPrefix, NUM_TASK_RESTARTS))); return Collections.unmodifiableList(metrics); }
Source:
<code>private void send(LanguageServer server, String filePath, FileChangeType changeType) { DidChangeWatchedFilesParams params = new DidChangeWatchedFilesParams( Collections.singletonList(new FileEvent(prefixURI(filePath), changeType))); <START> LOG.debug("sending " + changeType + " to LS: " + filePath); <END> server.getWorkspaceService().didChangeWatchedFiles(params); }</code><technical_language>parameterized logging LOG.debug("sending LS: {}", changeType, filePath);</technical_language>

Target:
private void send(LanguageServer server, String filePath, FileChangeType changeType) { DidChangeWatchedFilesParams params = new DidChangeWatchedFilesParams( Collections.singletonList(new FileEvent(prefixURI(filePath), changeType))); LOG.debug("sending to LS: {}", changeType, filePath); server.getWorkspaceService().didChangeWatchedFiles(params); }
Source:
<code>public void testHumanTaskListener() { KieSession ksession = createKSession(HUMAN_TASK_LISTENER); AtomicBoolean triggered = new AtomicBoolean(false); TaskLifeCycleEventListener listener = new DefaultTaskEventListener() { @Override public void afterTaskActivatedEvent(TaskEvent event) { <START> triggered.set(true); <END> } }; RuntimeEngine engine = getRuntimeEngine(); TaskService taskService = engine.getTaskService(); ((EventService<TaskLifeCycleEventListener>) taskService).registerTaskEventListener(listener); ProcessInstance pi = ksession.startProcess(HUMAN_TASK_LISTENER_ID); long processInstanceId = pi.getId(); List<Long> idList = taskService.getTasksByProcessInstanceId(processInstanceId); for (long taskId : idList) { taskService.start(taskId, "john"); taskService.complete(taskId, "john", emptyMap()); } assertTrue("Task should have triggered the event", triggered.get()); ksession.abortProcessInstance(processInstanceId); assertProcessInstanceAborted(processInstanceId); }</code><technical_language>beforeTaskActivatedEvent implemented tested a AtomicBoolean</technical_language>

Target:
public void testHumanTaskListener() { KieSession ksession = createKSession(HUMAN_TASK_LISTENER); MutableInt triggered = new MutableInt(0); TaskLifeCycleEventListener listener = new DefaultTaskEventListener() { @Override public void afterTaskActivatedEvent(TaskEvent event) { triggered.increment(); } }; RuntimeEngine engine = getRuntimeEngine(); TaskService taskService = engine.getTaskService(); ((EventService<TaskLifeCycleEventListener>) taskService).registerTaskEventListener(listener); ProcessInstance pi = ksession.startProcess(HUMAN_TASK_LISTENER_ID); long processInstanceId = pi.getId(); List<Long> idList = taskService.getTasksByProcessInstanceId(processInstanceId); for (long taskId : idList) { taskService.start(taskId, "john"); taskService.complete(taskId, "john", emptyMap()); } assertEquals((int) 2, (int) triggered.getValue()); ksession.abortProcessInstance(processInstanceId); assertProcessInstanceAborted(processInstanceId); }
Source:
<code>public DefaultContentDescriptor(String description, boolean mandatory) { <START> this(description, mandatory, null); <END> }</code><technical_language>This consistent default implementation in ContentDescriptor. null (if explicit content type is unknown) for String.class (if feel String.class more consistent parameters types logic) for both</technical_language>

Target:
public DefaultContentDescriptor(String description, boolean mandatory) { this(description, mandatory, String.class); }
Source:
<code>protected Command<GraphCommandExecutionContext, RuleViolation> newGraphCommand(final AbstractCanvasHandler context) { return new AbstractGraphCommand() { @Override protected CommandResult<RuleViolation> check(final GraphCommandExecutionContext context) { return GraphCommandResultBuilder.SUCCESS; } @Override public CommandResult<RuleViolation> execute(final GraphCommandExecutionContext context) { <START> final int ocIndex = uiColumnIndex - DecisionTableUIModelMapperHelper.ROW_INDEX_COLUMN_COUNT - dtable.getInput().size(); <END> dtable.getOutput().add(ocIndex, outputClause); dtable.getRule().forEach(rule -> { final LiteralExpression le = new LiteralExpression(); le.setText(OUTPUT_CLAUSE_DEFAULT_VALUE); rule.getOutputEntry().add(ocIndex, le); }); return GraphCommandResultBuilder.SUCCESS; } @Override public CommandResult<RuleViolation> undo(final GraphCommandExecutionContext context) { final int clauseIndex = dtable.getOutput().indexOf(outputClause); dtable.getRule().forEach(rule -> rule.getOutputEntry().remove(clauseIndex)); dtable.getOutput().remove(outputClause); return GraphCommandResultBuilder.SUCCESS; } }; }</code><technical_language>Please replace ocIndex clauseIndex consistent undo method</technical_language>

Target:
protected Command<GraphCommandExecutionContext, RuleViolation> newGraphCommand(final AbstractCanvasHandler context) { return new AbstractGraphCommand() { @Override protected CommandResult<RuleViolation> check(final GraphCommandExecutionContext context) { return GraphCommandResultBuilder.SUCCESS; } @Override public CommandResult<RuleViolation> execute(final GraphCommandExecutionContext context) { final int clauseIndex = uiColumnIndex - DecisionTableUIModelMapperHelper.ROW_INDEX_COLUMN_COUNT - dtable.getInput().size(); dtable.getOutput().add(clauseIndex, outputClause); dtable.getRule().forEach(rule -> { final LiteralExpression le = new LiteralExpression(); le.setText(OUTPUT_CLAUSE_DEFAULT_VALUE); rule.getOutputEntry().add(clauseIndex, le); }); return GraphCommandResultBuilder.SUCCESS; } @Override public CommandResult<RuleViolation> undo(final GraphCommandExecutionContext context) { final int clauseIndex = dtable.getOutput().indexOf(outputClause); dtable.getRule().forEach(rule -> rule.getOutputEntry().remove(clauseIndex)); dtable.getOutput().remove(outputClause); return GraphCommandResultBuilder.SUCCESS; } }; }
Source:
<code>private ActionListener<SearchResponse> expiredSnapshotsListener(String jobId, long deleteAllBeforeMs, ActionListener<Boolean> listener) { return new ActionListener<>() { @Override public void onResponse(SearchResponse searchResponse) { long nextToKeepMs = deleteAllBeforeMs; try { List<JobSnapshotId> snapshotIds = new ArrayList<>(); for (SearchHit hit : searchResponse.getHits()) { String timestamp = stringFieldValueOrNull(hit, ModelSnapshot.TIMESTAMP.getPreferredName()); if (timestamp == null) { continue; } <START> Long timestampMs = TimeUtils.parseToEpochMs(timestamp); <END> if (timestampMs >= nextToKeepMs) { do { nextToKeepMs += MS_IN_ONE_DAY; } while (timestampMs >= nextToKeepMs); continue; } JobSnapshotId idPair = new JobSnapshotId( stringFieldValueOrNull(hit, Job.ID.getPreferredName()), stringFieldValueOrNull(hit, ModelSnapshotField.SNAPSHOT_ID.getPreferredName())); if (idPair.hasNullValue() == false) { snapshotIds.add(idPair); } } deleteModelSnapshots(new VolatileCursorIterator<>(snapshotIds), listener); } catch (Exception e) { onFailure(e); } } @Override public void onFailure(Exception e) { listener.onFailure(new ElasticsearchException("[" + jobId + "] Search for expired snapshots failed", e)); } }; }</code><technical_language>long instead of Long avoid unboxing in loop</technical_language>

Target:
private ActionListener<SearchResponse> expiredSnapshotsListener(String jobId, long deleteAllBeforeMs, ActionListener<Boolean> listener) { return new ActionListener<>() { @Override public void onResponse(SearchResponse searchResponse) { long nextToKeepMs = deleteAllBeforeMs; try { List<JobSnapshotId> snapshotIds = new ArrayList<>(); for (SearchHit hit : searchResponse.getHits()) { String timestamp = stringFieldValueOrNull(hit, ModelSnapshot.TIMESTAMP.getPreferredName()); if (timestamp == null) { LOGGER.warn("Model snapshot document has a null timestamp field", hit.getId()); continue; } long timestampMs = TimeUtils.parseToEpochMs(timestamp); if (timestampMs >= nextToKeepMs) { do { nextToKeepMs += MS_IN_ONE_DAY; } while (timestampMs >= nextToKeepMs); continue; } JobSnapshotId idPair = new JobSnapshotId( stringFieldValueOrNull(hit, Job.ID.getPreferredName()), stringFieldValueOrNull(hit, ModelSnapshotField.SNAPSHOT_ID.getPreferredName())); if (idPair.hasNullValue() == false) { snapshotIds.add(idPair); } } deleteModelSnapshots(new VolatileCursorIterator<>(snapshotIds), listener); } catch (Exception e) { onFailure(e); } } @Override public void onFailure(Exception e) { listener.onFailure(new ElasticsearchException("[" + jobId + "] Search for expired snapshots failed", e)); } }; }
Source:
<code>public void test() { CommitStatusUpdater.updateCommitStatus(build, taskListener, BuildState.success, STAGE); <START> verify(client).changeBuildStatus(Integer.toString(PROJECT_ID), REVISION, BuildState.success, null, STAGE, Jenkins.getInstance().getRootUrl() + BUILD_URL + BUILD_URL_REDIRECT, null); <END> }</code><technical_language>I DisplayURLProvider.get().getRunURL(build) in GitLabCommitStatusPublisherTest better..</technical_language>

Target:
public void test() { CommitStatusUpdater.updateCommitStatus(build, taskListener, BuildState.success, STAGE); verify(client).changeBuildStatus(Integer.toString(PROJECT_ID), REVISION, BuildState.success, null, STAGE, DisplayURLProvider.get().getRunURL(build), null); }
Source:
<code><START> private DataSetReference.Builder createBasicMetadata(ResultProtos.Result sourceResult, <END> DataSetReference.Builder metaBuilder) { if (sourceResult.hasMetadata()) { handleTitles(sourceResult.getMetadata().getTitleList(), metaBuilder); handleDescription(sourceResult.getMetadata().getDescriptionList(), metaBuilder); handlePublisher(sourceResult.getMetadata().getPublisher(), metaBuilder); handleYear(sourceResult.getMetadata().getDateofacceptance(), metaBuilder); handleFormats(sourceResult.getMetadata().getFormatList(), metaBuilder); handleResourceType(sourceResult.getMetadata(), metaBuilder); } return metaBuilder; }</code><technical_language>Object returned this method is e.g. method return void</technical_language>

Target:
private void createBasicMetadata(ResultProtos.Result sourceResult, DataSetReference.Builder metaBuilder) { if (sourceResult.hasMetadata()) { handleTitles(sourceResult.getMetadata().getTitleList(), metaBuilder); handleDescription(sourceResult.getMetadata().getDescriptionList(), metaBuilder); handlePublisher(sourceResult.getMetadata().getPublisher(), metaBuilder); handleYear(sourceResult.getMetadata().getDateofacceptance(), metaBuilder); handleFormats(sourceResult.getMetadata().getFormatList(), metaBuilder); handleResourceType(sourceResult.getMetadata(), metaBuilder); } }
Source:
<code>boolean removeStorage(DatanodeStorageInfo storage) { int dnIndex = findStorageInfo(storage); if (dnIndex < 0) { return false; } int lastNode = numNodes()-1; setStorageInfo(dnIndex, getStorageInfo(lastNode)); setStorageInfo(lastNode, null); if (storage.getStorageType() == StorageType.PROVIDED <START> && !hasProvidedStorages()) { <END> hasProvidedStorage = false; } return true; }</code><technical_language>this guarantee is false</technical_language>

Target:
boolean removeStorage(DatanodeStorageInfo storage) { int dnIndex = findStorageInfo(storage); if (dnIndex < 0) { return false; } int lastNode = numNodes()-1; setStorageInfo(dnIndex, getStorageInfo(lastNode)); setStorageInfo(lastNode, null); return true; }
Source:
<code>public void modal_curtains_close_correctly() { openTestURL(); openModalWindow(); new Actions(getDriver()) .moveToElement(findElement(By.className("v-window-header"))) <START> .clickAndHold().sendKeys(Keys.ESCAPE).perform(); <END> verifyCurtainsNotPresent(); openModalWindow(); new Actions(getDriver()) .moveToElement(findElement(By.className("v-window-resizebox"))) .clickAndHold().sendKeys(Keys.ESCAPE).perform(); verifyCurtainsNotPresent(); }</code><technical_language>extra validation step in starting drag pressing escape curtain is present. Some Drag Drop cases in framework require a movement mouse drag functionality is started</technical_language>

Target:
public void modal_curtains_close_correctly() { openTestURL(); openModalWindow(); new Actions(getDriver()) .moveToElement(findHeaderElement()) .clickAndHold().moveByOffset(1, 1).perform(); assertTrue(isElementPresent(By.className("v-window-draggingCurtain"))); new Actions(getDriver()).sendKeys(findHeaderElement(), Keys.ESCAPE) .release().perform(); verifyCurtainsNotPresent(); openModalWindow(); new Actions(getDriver()) .moveToElement(findResizingElement()) .clickAndHold().moveByOffset(1, 1).perform(); assertTrue(isElementPresent(By.className("v-window-resizingCurtain"))); new Actions(getDriver()).sendKeys(findResizingElement(), Keys.ESCAPE) .release().perform(); verifyCurtainsNotPresent(); }
Source:
<code>private boolean canDoSnapshot(VM vm) { <START> boolean canSnapshot = true; <END> if(!isLiveSnapshotEnabled() && !ImagesHandler.isVmDown(vm)) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_DATA_CENTER_VERSION_DOESNT_SUPPORT_LIVE_SNAPSHOT); canSnapshot = false; } return canSnapshot; }</code><technical_language>I agree Vered</technical_language>

Target:
private boolean canDoSnapshot(VM vm) { if (!isLiveSnapshotEnabled() && !ImagesHandler.isVmDown(vm)) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_DATA_CENTER_VERSION_DOESNT_SUPPORT_LIVE_SNAPSHOT); return false; } return true; }
Source:
<code>public boolean set(String path, T data, int expectVersion, int options) { String clientPath = path; String serverPath = prependChroot(clientPath); Cache<T> cache = getCache(serverPath); boolean success = false; try { if (cache != null) { cache.lockWrite(); ZkBaseDataAccessor<T>.AccessResult result = <START> _baseAccessor.doSet(_zkclient, serverPath, data, expectVersion, options); <END> success = result._retCode == RetCode.OK; updateCache(cache, result._pathCreated, success, serverPath, data, result._stat); } else { success = _baseAccessor.set(serverPath, data, expectVersion, options); } } catch (Exception e) { } finally { if (cache != null) { cache.unlockWrite(); } } return success; }</code><technical_language>If public API instead of removing, need change this all. In other words, diffs in CacheBaseDataAccessor</technical_language>

Target:
public boolean set(String path, T data, int expectVersion, int options) { String clientPath = path; String serverPath = prependChroot(clientPath); Cache<T> cache = getCache(serverPath); boolean success = false; try { if (cache != null) { cache.lockWrite(); ZkBaseDataAccessor<T>.AccessResult result = _baseAccessor.doSet(serverPath, data, expectVersion, options); success = result._retCode == RetCode.OK; updateCache(cache, result._pathCreated, success, serverPath, data, result._stat); } else { success = _baseAccessor.set(serverPath, data, expectVersion, options); } } catch (Exception e) { } finally { if (cache != null) { cache.unlockWrite(); } } return success; }
Source:
<code>private ClientConnection getConnection() throws IOException { ClientConnection connection = activeConnections.get(inetSocketAddressCache.get(target)); if (connection != null) { return connection; } AddressProvider addressProvider = currentClusterContext.getAddressProvider(); Address address = null; try { address = addressProvider.translate(target); } catch (Exception e) { <START> logger.warning("Failed to translate addresses via address provider: " + e.getMessage()); <END> } if (address == null) { throw new NullPointerException("Address Provider " + addressProvider.getClass() + " could not translate address " + target); } return createSocketConnection(address); }</code><technical_language>logging: "Failed translate address " + target + " address provider: " + e.getMessage()</technical_language>

Target:
private ClientConnection getConnection() throws IOException { ClientConnection connection = activeConnections.get(inetSocketAddressCache.get(target)); if (connection != null) { return connection; } AddressProvider addressProvider = currentClusterContext.getAddressProvider(); Address address = null; try { address = addressProvider.translate(target); } catch (Exception e) { logger.warning("Failed to translate address " + target + " via address provider " + e.getMessage()); } if (address == null) { throw new NullPointerException("Address Provider " + addressProvider.getClass() + " could not translate address " + target); } return createSocketConnection(address); }
Source:
<code>protected int doWork() { IOUtil.assertFileIsReadable(VCF); IOUtil.assertFileIsWritable(OUTPUT); VCFFileReader vcfFileReader = new VCFFileReader(VCF, false); CloseableIterator<VariantContext> variants = vcfFileReader.iterator(); try { final IlluminaAdpcFileWriter adpcFileWriter = new IlluminaAdpcFileWriter(OUTPUT); <START> final List<IlluminaAdpcRecord> adpcRecordList = new ArrayList<>(); <END> while (variants.hasNext()) { final VariantContext context = variants.next(); final float gcScore = getFloatAttribute(context, InfiniumVcfFields.GC_SCORE); for (final Genotype genotype : context.getGenotypes()) { final IlluminaGenotype illuminaGenotype = getIlluminaGenotype(genotype, context); final short rawXIntensity = getShortAttribute(genotype, InfiniumVcfFields.X); final short rawYIntensity = getShortAttribute(genotype, InfiniumVcfFields.Y); final float normalizedXIntensity = getFloatAttribute(genotype, InfiniumVcfFields.NORMX); final float normalizedYIntensity = getFloatAttribute(genotype, InfiniumVcfFields.NORMY); final IlluminaAdpcRecord record = new IlluminaAdpcRecord(rawXIntensity, rawYIntensity, normalizedXIntensity, normalizedYIntensity, gcScore, illuminaGenotype); adpcRecordList.add(record); } } adpcFileWriter.write(adpcRecordList); } catch (IOException e) { log.error(e); return 1; } return 0; }</code><technical_language>static suggestion private final static Log log = Log.getInstance(VcfToAdpc.class);</technical_language>

Target:
protected int doWork() { IOUtil.assertFileIsReadable(VCF); IOUtil.assertFileIsWritable(OUTPUT); VCFFileReader vcfFileReader = new VCFFileReader(VCF, false); try (CloseableIterator<VariantContext> variants = vcfFileReader.iterator(); IlluminaAdpcFileWriter adpcFileWriter = new IlluminaAdpcFileWriter(OUTPUT)) { final List<IlluminaAdpcFileWriter.Record> adpcRecordList = new ArrayList<>(); while (variants.hasNext()) { final VariantContext context = variants.next(); final float gcScore = getFloatAttribute(context, InfiniumVcfFields.GC_SCORE); for (final Genotype genotype : context.getGenotypes()) { final IlluminaGenotype illuminaGenotype = getIlluminaGenotype(genotype, context); final short rawXIntensity = getShortAttribute(genotype, InfiniumVcfFields.X); final short rawYIntensity = getShortAttribute(genotype, InfiniumVcfFields.Y); final float normalizedXIntensity = getFloatAttribute(genotype, InfiniumVcfFields.NORMX); final float normalizedYIntensity = getFloatAttribute(genotype, InfiniumVcfFields.NORMY); final IlluminaAdpcFileWriter.Record record = new IlluminaAdpcFileWriter.Record(rawXIntensity, rawYIntensity, normalizedXIntensity, normalizedYIntensity, gcScore, illuminaGenotype); adpcRecordList.add(record); } } adpcFileWriter.write(adpcRecordList); } catch (Exception e) { log.error(e); return 1; } return 0; }
Source:
<code>public void readVectors(ColumnVector[] vectors, MessageType[] columnSchemas, long current, long total) { for (int i = 0 ; i < columnSchemas.length; i++) { MessageType schema = columnSchemas[i]; State state = getState(schema); readVector(state.column, vectors[i], current, total); } <START> } <END></code><technical_language>a VectorizedRecordReaderImpl is preinitialized columns read (columnSchemas). maintain state</technical_language>

Target:
protected void readVectors(ColumnVector[] vectors, MessageType[] columnSchemas, long current, long total) { for (int i = 0 ; i < columnSchemas.length; i++) { MessageType schema = columnSchemas[i]; State state = getState(schema); readVector(state.column, vectors[i], current, total); } }
Source:
<code>public void filter(ContainerRequestContext requestContext) throws IOException { if (requestContext.getHeaderString(TENANT_HEADER_NAME) != null) { requestContext.abortWith(Response.status(Response.Status.BAD_REQUEST) .type(APPLICATION_JSON_TYPE) .entity(new ApiError(TENANT_HEADER_NOT_ALLOWED)) .build()); } else if (!checkPersona()) { requestContext.abortWith(Response.status(Response.Status.BAD_REQUEST) .type(APPLICATION_JSON_TYPE) .entity(new ApiError(MISSING_TENANT_MSG)) .build()); } else { <START> requestContext.getHeaders().putSingle(TENANT_HEADER_NAME, persona.get().getId()); <END> } }</code><technical_language>Is persona id right use? this users of org push data metrics tenant</technical_language>

Target:
public void filter(ContainerRequestContext requestContext) throws IOException { String path = requestContext.getUriInfo().getPath(); if (path.startsWith("/db") || path.startsWith("/status") || path.equals("/")) { return; } if (requestContext.getHeaderString(TENANT_HEADER_NAME) != null) { requestContext.abortWith(Response.status(Response.Status.BAD_REQUEST) .type(APPLICATION_JSON_TYPE) .entity(new ApiError(TENANT_HEADER_NOT_ALLOWED)) .build()); } else if (!checkPersona()) { requestContext.abortWith(Response.status(Response.Status.BAD_REQUEST) .type(APPLICATION_JSON_TYPE) .entity(new ApiError(MISSING_TENANT_MSG)) .build()); } else { requestContext.getHeaders().putSingle(TENANT_HEADER_NAME, persona.get().getId()); } }
Source:
<code>public LdapProviderType retrieveLdapProviderType(String domain) { Attributes attributes = getDomainAttributes(LdapProviderType.general, domain); if (attributes != null) { if (attributes.get(ADRootDSEAttributes.domainControllerFunctionality.name()) != null) { return LdapProviderType.activeDirectory; } else if (attributes.get(RHDSRootDSEAttributes.netscapemdsuffix.name()) != null) { return LdapProviderType.rhds; } else { <START> return LdapProviderType.ipa; <END> } } else { return LdapProviderType.general; } }</code><technical_language>need add identity check for IPA instead of making default type</technical_language>

Target:
public LdapProviderType retrieveLdapProviderType(String domain) { LdapProviderType retVal = LdapProviderType.general; Attributes attributes = getDomainAttributes(LdapProviderType.general, domain); if (attributes != null) { if (attributes.get(ADRootDSEAttributes.domainControllerFunctionality.name()) != null) { retVal = LdapProviderType.activeDirectory; } else if (attributes.get(RHDSRootDSEAttributes.netscapemdsuffix.name()) != null) { retVal = LdapProviderType.rhds; } else if (attributes.get(IPARootDSEAttributes.namingContexts.name()) != null) { retVal = LdapProviderType.ipa; } } return retVal; }
Source:
<code>public void itCanFireWorkFailureEvent() throws Exception { int initCount = DummyPostCommitEventListener.handledCount(); int initEvtCount = DummyPostCommitEventListener.eventCount(); int initSyncEvntCount = WorkFailureEventListener.getCount(); service.schedule(new SleepAndFailWork(0)); <START> assertTrue(service.awaitCompletion(getDurationMillis(), TimeUnit.MILLISECONDS)); <END> assertEquals(1 + initSyncEvntCount, WorkFailureEventListener.getCount()); eventService.waitForAsyncCompletion(); assertEquals(1 + initCount, DummyPostCommitEventListener.handledCount()); assertEquals(1 + initEvtCount, DummyPostCommitEventListener.eventCount()); }</code><technical_language>hmm change code unit test, hard if break</technical_language>

Target:
public void itCanFireWorkFailureEvent() throws Exception { int initCount = DummyPostCommitEventListener.handledCount(); int initEvtCount = DummyPostCommitEventListener.eventCount(); int initSyncEvntCount = WorkFailureEventListener.getCount(); service.schedule(new SleepAndFailWork(0)); assertTrue(service.awaitCompletion(6000, TimeUnit.MILLISECONDS)); assertEquals(1 + initSyncEvntCount, WorkFailureEventListener.getCount()); eventService.waitForAsyncCompletion(); assertEquals(1 + initCount, DummyPostCommitEventListener.handledCount()); assertEquals(1 + initEvtCount, DummyPostCommitEventListener.eventCount()); }
Source:
<code>public Collection<File> listItems( final Repository repository, final File repositoryBaseDir, final ResourceStoreRequest request, final File target ) throws ItemNotFoundException, LocalStorageException { if ( target.isDirectory() ) { List<File> result = new ArrayList<File>(); File[] files = target.listFiles( new FileFilter() { @Override public boolean accept( File pathname ) { return !pathname.getName().endsWith( HIDDEN_TARGET_SUFFIX ); } } ); if ( files != null ) { for ( int i = 0; i < files.length; i++ ) { if ( files[i].isFile() || files[i].isDirectory() ) { String newPath = ItemPathUtils.concatPaths( request.getRequestPath(), files[i].getName() ); request.pushRequestPath( newPath ); result.add( retrieveItem( repository, repositoryBaseDir, request, files[i] ) ); request.popRequestPath(); } } } else { getLogger().warn( "Cannot list directory in repository {}, path \"{}\"", RepositoryStringUtils.getHumanizedNameString( repository ), target.getAbsolutePath() ); <START> throw new LocalStorageException( "Cannot list directory in repository " + repository + ", path " <END> + target.getAbsolutePath() ); } return result; } else if ( target.isFile() ) { return null; } else { throw new ItemNotFoundException( request, repository ); } }</code><technical_language>This result in double-logging of "Cannot list directory in repository" message, explicit log statement above, another exception handler</technical_language>

Target:
public Collection<File> listItems( final Repository repository, final File repositoryBaseDir, final ResourceStoreRequest request, final File target ) throws ItemNotFoundException, LocalStorageException { if ( target.isDirectory() ) { List<File> result = new ArrayList<File>(); File[] files = target.listFiles( new FileFilter() { @Override public boolean accept( File pathname ) { return !pathname.getName().endsWith( HIDDEN_TARGET_SUFFIX ); } } ); if ( files != null ) { for ( int i = 0; i < files.length; i++ ) { if ( files[i].isFile() || files[i].isDirectory() ) { String newPath = ItemPathUtils.concatPaths( request.getRequestPath(), files[i].getName() ); request.pushRequestPath( newPath ); result.add( retrieveItem( repository, repositoryBaseDir, request, files[i] ) ); request.popRequestPath(); } } } else { throw new LocalStorageException( "Cannot list directory in repository " + repository + ", path " + target.getAbsolutePath() ); } return result; } else if ( target.isFile() ) { return null; } else { throw new ItemNotFoundException( request, repository ); } }