auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected final void addCacheDetails() { assert cache != null; final String cacheType = cache.getType().getL10n(); final String cacheSize = cache.showSize() ? " (" + cache.getSize().getL10n() + ")" : ""; details.add(R.string.cache_type, cacheType + cacheSize); details.add(R.string.cache_geocode, cache.getGeocode()); details.addCacheState(cache); cacheDistance = details.addDistance(cache, cacheDistance); details.addDifficulty(cache); details.addTerrain(cache); details.addEventDate(cache); if (cache.getRating() > 0) { details.addRating(cache); } else { acquireGCVote(); } final int favCount = cache.getFavoritePoints(); if (favCount >= 0) { final int findsCount = cache.getFindsCount(); if (findsCount > 0) { details.add(R.string.cache_favorite, res.getString(R.string.favorite_count_percent, favCount, (float) (favCount * 100) / findsCount)); } else { <START> if (!(cache.getType().isEvent())) { <END> details.add(R.string.cache_favorite, res.getString(R.string.favorite_count, favCount)); } } } final View view = getView(); assert view != null; final Button buttonMore = ButterKnife.findById(view, R.id.more_details); buttonMore.setOnClickListener(arg0 -> { CacheDetailActivity.startActivity(getActivity(), geocode); getActivity().finish(); }); registerForContextMenu(buttonMore); }</code><technical_language>else if {</technical_language>

Target:
protected final void addCacheDetails() { assert cache != null; final String cacheType = cache.getType().getL10n(); final String cacheSize = cache.showSize() ? " (" + cache.getSize().getL10n() + ")" : ""; details.add(R.string.cache_type, cacheType + cacheSize); details.add(R.string.cache_geocode, cache.getGeocode()); details.addCacheState(cache); cacheDistance = details.addDistance(cache, cacheDistance); details.addDifficulty(cache); details.addTerrain(cache); details.addEventDate(cache); if (cache.getRating() > 0) { details.addRating(cache); } else { acquireGCVote(); } final int favCount = cache.getFavoritePoints(); if (favCount >= 0) { final int findsCount = cache.getFindsCount(); if (findsCount > 0) { details.add(R.string.cache_favorite, res.getString(R.string.favorite_count_percent, favCount, (float) (favCount * 100) / findsCount)); } else if (!cache.isEventCache()) { details.add(R.string.cache_favorite, res.getString(R.string.favorite_count, favCount)); } } final View view = getView(); assert view != null; final Button buttonMore = ButterKnife.findById(view, R.id.more_details); buttonMore.setOnClickListener(arg0 -> { CacheDetailActivity.startActivity(getActivity(), geocode); getActivity().finish(); }); registerForContextMenu(buttonMore); }
Source:
<code>public void run() { String previousName = Thread.currentThread().getName(); try { <START> Thread.currentThread().setName(NamedThreadFactory.globalPrefix() + "Repair Coordinator #" + cmd + " id=" + parentSession + " ks=" + keyspace + " tables=" + options.getColumnFamilies()); <END> runMayThrow(); } catch (SkipRepairException e) { skip(e.getMessage()); } catch (Exception | Error e) { notifyError(e); fail(e.getMessage()); } finally { Thread.currentThread().setName(previousName); } }</code><technical_language>Thread names stay same. assume changes rely for debugging. If additional information is required, logged</technical_language>

Target:
public void run() { try { runMayThrow(); } catch (SkipRepairException e) { skip(e.getMessage()); } catch (Exception | Error e) { notifyError(e); fail(e.getMessage()); } }
Source:
<code>@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FormsDao dao = new FormsDao(); Form form = null; List<Form> forms = dao.getFormsFromCursor(dao.getFormsCursor(getIntent().getData())); if (forms.size() == 1) { form = forms.get(0); } else { finish(); } if (viewModelFactory == null) { viewModelFactory = new FormMapActivity.FormMapViewModelFactory(form, new DatabaseInstancesRepository()); } viewModel = ViewModelProviders.of(this, viewModelFactory).get(FormMapViewModel.class); Timber.i("Starting FormMapActivity for form \"%s\" (jrFormId = \"%s\")", viewModel.getFormTitle(), viewModel.getFormId()); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.instance_map_layout); TextView titleView = findViewById(R.id.form_title); titleView.setText(viewModel.getFormTitle()); MapFragment mapToAdd = map; if (mapToAdd == null) { <START> mapToAdd = MapProvider.createMapFragment(getApplicationContext()); <END> } if (mapToAdd != null) { mapToAdd.addTo(this, R.id.map_container, this::initMap, this::finish); } else { finish(); } }</code><technical_language>Yeah I Dagger for this. feels adding machinery in mimic do for here</technical_language>

Target:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); DaggerUtils.getComponent(this).inject(this); FormsDao dao = new FormsDao(); Form form = null; List<Form> forms = dao.getFormsFromCursor(dao.getFormsCursor(getIntent().getData())); if (forms.size() == 1) { form = forms.get(0); } else { finish(); } if (viewModelFactory == null) { viewModelFactory = new FormMapActivity.FormMapViewModelFactory(form, new DatabaseInstancesRepository()); } viewModel = ViewModelProviders.of(this, viewModelFactory).get(FormMapViewModel.class); Timber.i("Starting FormMapActivity for form \"%s\" (jrFormId = \"%s\")", viewModel.getFormTitle(), viewModel.getFormId()); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.instance_map_layout); TextView titleView = findViewById(R.id.form_title); titleView.setText(viewModel.getFormTitle()); MapFragment mapToAdd = mapProvider.createMapFragment(getApplicationContext()); if (mapToAdd != null) { mapToAdd.addTo(this, R.id.map_container, this::initMap, this::finish); } else { finish(); } }
Source:
<code>protected Collection<ID> toCollection(Iterable<ID> ids) { <START> final Collection<ID> idsList = new ArrayList<>(); <END> for (final ID id : ids) { idsList.add(id); } return idsList; }</code><technical_language>technically fix is a kind of waste if Iterable is a Collection. IMHO check instanceof cast avoid pointless conversion. WDYT</technical_language>

Target:
protected Collection<ID> toCollection(Iterable<ID> ids) { if (ids instanceof Collection) { return (Collection<ID>) ids; } final Collection<ID> idsList = new ArrayList<>(); for (final ID id : ids) { idsList.add(id); } return idsList; }
Source:
<code>public boolean ShouldEndAction() { synchronized (_listTasks) { java.util.ArrayList<CommandAsyncTask> CurrentActionTypeTasks = getCurrentTasks(); for (CommandAsyncTask task : CurrentActionTypeTasks) { ENDED state. <START> if (task.getState() != AsyncTaskState.Ended && !task.getVdsmTaskId().equals(Guid.Empty)) { <END> log.infoFormat("Task ID: '{0}' is in state {1}. End action for command {2} will proceed when all the entity's tasks are completed.", task.getVdsmTaskId(), task.getState(), getCommandId()); return false; } } } return true; }</code><technical_language>I is Guid.isNullOrEmpty instead, check !Guid.isNullOrEmpty(task.getVdsmTaskId())</technical_language>

Target:
public boolean ShouldEndAction() { synchronized (_listTasks) { java.util.ArrayList<CommandAsyncTask> CurrentActionTypeTasks = getCurrentTasks(); for (CommandAsyncTask task : CurrentActionTypeTasks) { ENDED state. if (task.getState() != AsyncTaskState.Ended && !Guid.isNullOrEmpty(task.getVdsmTaskId())) { log.infoFormat("Task with DB Task ID '{0}' and VDSM Task ID '{1}' is in state {2}. End action for command {3} will proceed when all the entity's tasks are completed.", task.getParameters().getDbAsyncTask().getTaskId(), task.getVdsmTaskId(), task.getState(), getCommandId()); return false; } else if (Guid.isNullOrEmpty(task.getVdsmTaskId())) { log.infoFormat("task with DB task ID '{0}' has empty vdsm task ID and is about to be cleared", task.getVdsmTaskId()); } } } return true; }
Source:
<code><START> @Override public synchronized void close() throws Exception { <END> if (ch != null) { ch.close(); ch = null; } }</code><technical_language>TcpIgniteClient is thread-safe a close method called time. If is another thread willing perform a request calling a channel method close successfully establish a new connection</technical_language>

Target:
@Override public synchronized void close() throws Exception { closed = true; if (ch != null) { ch.close(); ch = null; } }
Source:
<code>public Response<?> apply(BranchResource rsrc, Input input) throws AuthException, ResourceConflictException, OrmException, IOException { if (!rsrc.getControl().controlForRef(rsrc.getBranchKey()).canDelete()) { throw new AuthException("Cannot delete branch"); } if (dbProvider.get().changes().byBranchOpenAll(rsrc.getBranchKey()) .iterator().hasNext()) { throw new ResourceConflictException("branch " + rsrc.getBranchKey() + " has open changes"); } Repository r = repoManager.openRepository(rsrc.getNameKey()); try { RefUpdate.Result result; RefUpdate u; try { u = r.updateRef(rsrc.getRef()); u.setForceUpdate(true); Optional<String> notValid = validateRefDeletion(rsrc, u); if <START> (notValid.isPresent() == true) { <END> throw new ResourceConflictException(notValid.get()); } result = u.delete(); } catch (IOException e) { log.error("Cannot delete " + rsrc.getBranchKey(), e); throw e; } switch (result) { case NEW: case NO_CHANGE: case FAST_FORWARD: case FORCED: referenceUpdated.fire(rsrc.getNameKey(), u); hooks.doRefUpdatedHook(rsrc.getBranchKey(), u, identifiedUser.get().getAccount()); break; case REJECTED_CURRENT_BRANCH: log.warn("Cannot delete " + rsrc.getBranchKey() + ": " + result.name()); throw new ResourceConflictException("cannot delete current branch"); default: log.error("Cannot delete " + rsrc.getBranchKey() + ": " + result.name()); throw new ResourceConflictException("cannot delete branch: " + result.name()); } } finally { r.close(); } return Response.none(); }</code><technical_language>needed, in Gerrit explicitly compare booleans true</technical_language>

Target:
public Response<?> apply(BranchResource rsrc, Input input) throws AuthException, ResourceConflictException, OrmException, IOException { if (!rsrc.getControl().controlForRef(rsrc.getBranchKey()).canDelete()) { throw new AuthException("Cannot delete branch"); } if (dbProvider.get().changes().byBranchOpenAll(rsrc.getBranchKey()) .iterator().hasNext()) { throw new ResourceConflictException("branch " + rsrc.getBranchKey() + " has open changes"); } Repository r = repoManager.openRepository(rsrc.getNameKey()); try { RefUpdate.Result result; RefUpdate u; try { u = r.updateRef(rsrc.getRef()); u.setForceUpdate(true); result = u.delete(); } catch (IOException e) { log.error("Cannot delete " + rsrc.getBranchKey(), e); throw e; } switch (result) { case NEW: case NO_CHANGE: case FAST_FORWARD: case FORCED: referenceUpdated.fire(rsrc.getNameKey(), u); hooks.doRefUpdatedHook(rsrc.getBranchKey(), u, identifiedUser.get().getAccount()); break; case REJECTED_CURRENT_BRANCH: log.warn("Cannot delete " + rsrc.getBranchKey() + ": " + result.name()); throw new ResourceConflictException("cannot delete current branch"); default: log.error("Cannot delete " + rsrc.getBranchKey() + ": " + result.name()); throw new ResourceConflictException("cannot delete branch: " + result.name()); } } finally { r.close(); } return Response.none(); }
Source:
<code>protected void executeCommand() { HostSetupNetworksParameters parameters = generateSyncAllHostNetworksParameters(); VdcReturnValueBase retVal = <START> getBackend().runInternalAction(VdcActionType.PersistentHostSetupNetworks, <END> parameters, cloneContextAndDetachFromParent()); if (!retVal.getSucceeded()) { auditLogDirector.log(new AuditLogableBase(super.getVdsId()), AuditLogType.HOST_SYNC_ALL_NETWORKS_FAILED); propagateFailure(retVal); } else { auditLogDirector.log(new AuditLogableBase(super.getVdsId()), AuditLogType.HOST_SYNC_ALL_NETWORKS_FINISHED); setSucceeded(true); } }</code><technical_language>this is a command, simply call runInternalAction(...)</technical_language>

Target:
protected void executeCommand() { HostSetupNetworksParameters parameters = generateSyncAllHostNetworksParameters(); VdcReturnValueBase retVal = runInternalAction(VdcActionType.PersistentHostSetupNetworks, parameters, cloneContextAndDetachFromParent()); if (!retVal.getSucceeded()) { propagateFailure(retVal); } else { setSucceeded(true); } }
Source:
<code>public static String escapeSpecialChars(CharSequence s ) { int len = s.length(); if (len == 0) { return ""; } <START> StringBuilder sb = new StringBuilder(s.length() * 2); <END> for (int i = 0; i < len; i++) { char c = s.charAt(i); if ("[](){}.*+?$^|#\\".indexOf(c) != -1) { sb.append("\\"); } sb.append(c); } return sb.toString(); }</code><technical_language>StringBuilder is transient throw-away instance. Please instead java Misc.getThreadLocalBuilder()</technical_language>

Target:
public static String escapeSpecialChars(CharSequence s) { int len = s.length(); StringSink sink = Misc.getThreadLocalBuilder(); for (int i = 0; i < len; i++) { char c = s.charAt(i); if (c == '_') sink.put("."); else if (c == '%') sink.put(".*?"); else if ("[](){}.*+?$^|#\\".indexOf(c) != -1) { sink.put("\\"); sink.put(c); } else sink.put(c); } return Chars.toString(sink); }
Source:
<code>public Future<File> submit(JSONObject submission) throws Exception { File toolkitRoot = super.submit(submission).get(); <START> Path zipOutPath = pack(toolkitRoot.toPath()); <END> JSONObject deployInfo = (JSONObject) submission.get(SUBMISSION_DEPLOY); if (!(deployInfo.containsKey(KEEP_ARTIFACTS) && (boolean)deployInfo.get(KEEP_ARTIFACTS))) delete(toolkitRoot.toPath()); return new CompletedFuture<File>(zipOutPath.toFile()); }</code><technical_language>Try duplicate code, move common code a method called versions of submit</technical_language>

Target:
public Future<File> submit(JSONObject submission) throws Exception { File toolkitRoot = super.submit(submission).get(); Path zipOutPath = pack(toolkitRoot.toPath()); return deleteToolkitAndProduceCompletedFuture(toolkitRoot, (JSONObject)submission.get(SUBMISSION_DEPLOY), zipOutPath); }
Source:
<code>public boolean hasCreatedAt() { boolean result = false; try { <START> result = getItemElement(CREATED_AT) != null; <END> } catch (NoSuchElementException e) return result; }</code><technical_language>getItemElement return null. return element throw exception</technical_language>

Target:
public boolean hasCreatedAt() { boolean result = false; try { result = getItemElement(CREATED_AT).isDisplayed(); } catch (NoSuchElementException e) return result; }
Source:
<code>public ClusterHealthStatus getHealthStatus(String[] indexNames) { try { <START> Response response = lowLevelClient.performRequest( <END> new Request("GET", String.format("/_cluster/health/%s", getIndexesAsString(indexNames)))); try (InputStream is = response.getEntity().getContent()) { Map<String, Object> map = XContentHelper.convertToMap(XContentType.JSON.xContent(), is, true); return ClusterHealthStatus.fromString((String) map.get("status")); } } catch (IOException e) { throw new NuxeoException(e); } }</code><technical_language>Forgotten change lowlLevelClient.performRequest performRequest</technical_language>

Target:
public ClusterHealthStatus getHealthStatus(String[] indexNames) { Response response = performRequest( new Request("GET", String.format("/_cluster/health/%s", getIndexesAsString(indexNames)))); try (InputStream is = response.getEntity().getContent()) { Map<String, Object> map = XContentHelper.convertToMap(XContentType.JSON.xContent(), is, true); return ClusterHealthStatus.fromString((String) map.get("status")); } catch (IOException e) { throw new NuxeoException(e); } }
Source:
<code>public void start() { if (this.running.compareAndSet(false, true)) { <START> caches = new HashMap<>(); <END> for (String context : contexts) { if (!context.startsWith("/")) { context = "/" + context; } try { TreeCache cache = TreeCache.newBuilder(this.source, context).build(); cache.getListenable().addListener(this); cache.start(); caches.put(context, cache); } catch (KeeperException.NoNodeException e) { } catch (Exception e) { log.error("Error initializing listener for context " + context, e); } } } }</code><technical_language><LINK_0> this. in front of field</technical_language>

Target:
public void start() { if (this.running.compareAndSet(false, true)) { this.caches = new HashMap<>(); for (String context : contexts) { if (!context.startsWith("/")) { context = "/" + context; } try { TreeCache cache = TreeCache.newBuilder(this.source, context).build(); cache.getListenable().addListener(this); cache.start(); this.caches.put(context, cache); } catch (KeeperException.NoNodeException e) { } catch (Exception e) { log.error("Error initializing listener for context " + context, e); } } } }
Source:
<code>public GetMapKvpRequestReader(WMS wms, HttpClientConnectionManager manager) { super(GetMapRequest.class); this.wms = wms; this.entityResolverProvider = new EntityResolverProvider(wms.getGeoServer()); <START> RequestConfig requestConfig = RequestConfig.custom().build(); <END> CacheConfiguration cacheCfg = wms.getRemoteResourcesCacheConfiguration(); if (cacheCfg != null && cacheCfg.isEnabled()) { CacheConfig cacheConfig = CacheConfig.custom() .setMaxCacheEntries(cacheCfg.getMaxEntries()) .setMaxObjectSize(cacheCfg.getMaxEntrySize()) .build(); this.httpClient = CachingHttpClientBuilder.create() .setCacheConfig(cacheConfig) .setConnectionManager(manager) .setDefaultRequestConfig(requestConfig) .build(); } else { this.httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build(); } }</code><technical_language>difference this RequestConfig.DEFAULT directly</technical_language>

Target:
public GetMapKvpRequestReader(WMS wms, HttpClientConnectionManager manager) { super(GetMapRequest.class); RequestConfig requestConfig = RequestConfig.DEFAULT; wms.getGeoServer() .addListener( new ConfigurationListenerAdapter() { @Override public void handleServiceChange( ServiceInfo service, List<String> propertyNames, List<Object> oldValues, List<Object> newValues) { if (service instanceof WMSInfo) { WMSInfo info = (WMSInfo) service; CacheConfiguration newCacheCfg = info.getCacheConfiguration(); if (!newCacheCfg.equals(cacheCfg)) { createHttpClient( wms, manager, requestConfig, (CacheConfiguration) newCacheCfg.clone()); } } } }); this.wms = wms; this.entityResolverProvider = new EntityResolverProvider(wms.getGeoServer()); createHttpClient( wms, manager, requestConfig, (CacheConfiguration) wms.getRemoteResourcesCacheConfiguration().clone()); }
Source:
<code>private String getPrintableConnectionsList() { StringBuilder sb = new StringBuilder(); <START> for (storage_server_connections con : getConnectionList()) { <END> sb.append("{ id: "); sb.append(con.getid()); sb.append(", connection: "); sb.append(con.getconnection()); sb.append(", iqn: "); sb.append(con.getiqn()); sb.append(", vfsType: "); sb.append(con.getVfsType()); sb.append(", mountOptions: "); sb.append(con.getMountOptions()); sb.append(", nfsVersion: "); sb.append(con.getNfsVersion()); sb.append(", nfsRetrans: "); sb.append(con.getNfsRetrans()); sb.append(", nfsTimeo: "); sb.append(con.getNfsTimeo()); sb.append(" };"); } return sb.toString(); }</code><technical_language>ah, I love plural form in a singular object Liron, if submitting another patch moves printing logic storage_server_connections, chance change name of class</technical_language>

Target:
private String getPrintableConnectionsList() { StringBuilder sb = new StringBuilder(); for (storage_server_connections con : getConnectionList()) { sb.append(con.toString()); } return sb.toString(); }
Source:
<code>public boolean hasSession(String user) { <START> String sql = "SELECT * FROM " + tableName + " WHERE LOWER(" + col.NAME + ")=?;"; <END> try (PreparedStatement pst = con.prepareStatement(sql)) { pst.setString(1, user); try (ResultSet rs = pst.executeQuery()) { if (rs.next()) { return rs.getInt(col.HAS_SESSION) == 1; } } } catch (SQLException ex) { logSqlException(ex); } return false; }</code><technical_language>SELECT col.HAS_SESSION retrieves want DB</technical_language>

Target:
public boolean hasSession(String user) { String sql = "SELECT " + col.HAS_SESSION + " FROM " + tableName + " WHERE LOWER(" + col.NAME + ")=?;"; try (PreparedStatement pst = con.prepareStatement(sql)) { pst.setString(1, user); try (ResultSet rs = pst.executeQuery()) { if (rs.next()) { return rs.getInt(col.HAS_SESSION) == 1; } } } catch (SQLException ex) { logSqlException(ex); } return false; }
Source:
<code>protected String discoverClientVersion() { <START> return Version.readVersion( "/META-INF/maven/org.sonatype.nexus.client/nexus-client-core/pom.properties", "1.0" ); <END> }</code><technical_language>odd default version, "unknown" clear is a problem instead of pretending older version</technical_language>

Target:
protected String discoverClientVersion() { return Version.readVersion( "META-INF/maven/org.sonatype.nexus.client/nexus-client-core/pom.properties", "unknown" ); }
Source:
<code>private UploadItem getUploadItem(UploadableFile uploadableFile, Place place, String source, SimilarImageInterface similarImageInterface) { fileProcessor.initFileDetails(Objects.requireNonNull(uploadableFile.getFilePath()), context.getContentResolver()); UploadableFile.DateTimeWithSource dateTimeWithSource = uploadableFile.getFileCreatedDate(context); long fileCreatedDate = -1; String createdTimestampSource = ""; if (dateTimeWithSource != null) { fileCreatedDate = dateTimeWithSource.getEpochDate(); createdTimestampSource = dateTimeWithSource.getSource(); } Timber.d("File created date is %d", fileCreatedDate); GPSExtractor gpsExtractor = fileProcessor.processFileCoordinates(similarImageInterface); UploadItem uploadItem = new UploadItem(uploadableFile.getContentUri(), Uri.parse(uploadableFile.getFilePath()), uploadableFile.getMimeType(context), source, gpsExtractor, place, fileCreatedDate, createdTimestampSource); <START> if(place!=null){ <END> uploadItem.title.setTitleText(place.name); uploadItem.descriptions.get(0).setDescriptionText(place.getLongDescription()); uploadItem.descriptions.get(0).setLanguageCode("en"); } if(!items.contains(uploadItem)) { items.add(uploadItem); } return uploadItem; }</code><technical_language>Please clean formatting match current code style :)</technical_language>

Target:
private UploadItem getUploadItem(UploadableFile uploadableFile, Place place, String source, SimilarImageInterface similarImageInterface) { fileProcessor.initFileDetails(Objects.requireNonNull(uploadableFile.getFilePath()), context.getContentResolver()); UploadableFile.DateTimeWithSource dateTimeWithSource = uploadableFile .getFileCreatedDate(context); long fileCreatedDate = -1; String createdTimestampSource = ""; if (dateTimeWithSource != null) { fileCreatedDate = dateTimeWithSource.getEpochDate(); createdTimestampSource = dateTimeWithSource.getSource(); } Timber.d("File created date is %d", fileCreatedDate); GPSExtractor gpsExtractor = fileProcessor .processFileCoordinates(similarImageInterface, context); UploadItem uploadItem = new UploadItem(uploadableFile.getContentUri(), Uri.parse(uploadableFile.getFilePath()), uploadableFile.getMimeType(context), source, gpsExtractor, place, fileCreatedDate, createdTimestampSource); if (place != null) { uploadItem.title.setTitleText(place.name); uploadItem.descriptions.get(0).setDescriptionText(place.getLongDescription()); uploadItem.descriptions.get(0).setLanguageCode("en"); } if (!items.contains(uploadItem)) { items.add(uploadItem); } return uploadItem; }
Source:
<code>private static void initializeUserHomeRuntimes(IProgressMonitor monitor) { String userHome = System.getProperty(USER_HOME); if (userHome != null) { File directory = new File(userHome, JBOSS_RUNTIMES); <START> RuntimeInitializerUtil.initializeRuntimesFromFolder(directory, monitor); <END> if (directory != null && directory.isDirectory()) { RuntimePath path = new RuntimePath(directory.getAbsolutePath()); path.setScanOnEveryStartup(true); RuntimeUIActivator.getDefault().getModel().addRuntimePath(path); } } }</code><technical_language>call RuntimeInitializerUtil.initializeRuntimesFromFolder if directory is null a directory? i.e. put in if block below</technical_language>

Target:
private static void initializeUserHomeRuntimes(IProgressMonitor monitor) { String userHome = System.getProperty(USER_HOME); if (userHome != null) { File directory = new File(userHome, JBOSS_RUNTIMES); if (directory != null && directory.isDirectory()) { RuntimeInitializerUtil.initializeRuntimesFromFolder(directory, monitor); RuntimePath path = new RuntimePath(directory.getAbsolutePath()); path.setScanOnEveryStartup(true); RuntimeUIActivator.getDefault().getModel().addRuntimePath(path); } } }
Source:
<code>private static boolean isEscapedChar(String argValue) { <START> return argValue.length() == 2 && argValue.indexOf('\\') == 0; <END> }</code><technical_language>argValue.charAt(0) == '\'</technical_language>

Target:
private static boolean isEscapedChar(String argValue) { return argValue.length() == 2 && argValue.charAt(0) == '\\'; }
Source:
<code><START> public static MavenRemoteRepository createRemoteRepository(final String id, final String url, final String layout) <END> throws MalformedURLException { return createRemoteRepository(id, new URL(url), layout); }</code><technical_language>here, for non-checked exception</technical_language>

Target:
public static MavenRemoteRepository createRemoteRepository(final String id, final String url, final String layout) throws IllegalArgumentException { try { return createRemoteRepository(id, new URL(url), layout); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid URL", e); } }
Source:
<code>private static UserGroupInformation applyCreds(Credentials credentials) throws IOException { LOG.info("credentials:" + credentials); logCredInformation(credentials); UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); ugi.addCredentials(credentials); ugi.setAuthenticationMethod(UserGroupInformation.AuthenticationMethod.PROXY); <START> System.out.println("Set auth to token"); <END> LOG.info("Applied credentials"); return ugi; }</code><technical_language>meaning System.out here</technical_language>

Target:
private static UserGroupInformation applyCreds(Credentials credentials) throws IOException { logCredInformation(credentials); UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); ugi.addCredentials(credentials); ugi.setAuthenticationMethod(UserGroupInformation.AuthenticationMethod.PROXY); LOG.info("Applied credentials"); return ugi; }
Source:
<code>public boolean login(String user, String password) throws AuthenticationException { try { BasicCookieStore cookieStore = new BasicCookieStore(); HttpClient c = createClient(cookieStore); String entryUrl = getUrl(); HttpPost getDCInfo = new HttpPost(entryUrl <START> + "/manage/resource/getDCInfo"); <END> List<NameValuePair> parameters = new ArrayList<NameValuePair>(2); parameters.add(new BasicNameValuePair("loginName", user)); parameters.add(new BasicNameValuePair("special", "true")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters); getDCInfo.setEntity(entity); String authenticationPage = IOUtils.toString(c.execute(getDCInfo) .getEntity().getContent()); authenticationPage = URLDecoder.decode(authenticationPage); if (authenticationPage.contains(",NON_FEDERATED,")) return super.login(user, password); authenticationPage = extractFederatedPage(authenticationPage); FormLoginHandler h = getHandler(authenticationPage); boolean authenticated = h.login(user, password, c, cookieStore, authenticationPage); if (authenticated) { setCookieCache(cookieStore.getCookies()); return true; }else return false; } catch (Exception e) { throw new AuthenticationException(e); } }</code><technical_language>a configure this "/manage/resource/getDCInfo" default</technical_language>

Target:
public boolean login(String user, String password) throws AuthenticationException { try { BasicCookieStore cookieStore = new BasicCookieStore(); HttpClient c = createClient(cookieStore); String entryUrl = getUrl(); HttpPost getDCInfo = new HttpPost(entryUrl + getFederationInfoUrl()); List<NameValuePair> parameters = new ArrayList<NameValuePair>(2); parameters.add(new BasicNameValuePair("loginName", user)); parameters.add(new BasicNameValuePair("special", "true")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters); getDCInfo.setEntity(entity); String authenticationPage = IOUtils.toString(c.execute(getDCInfo) .getEntity().getContent()); authenticationPage = URLDecoder.decode(authenticationPage); if (authenticationPage.contains(",NON_FEDERATED,")) return super.login(user, password); authenticationPage = extractFederatedPage(authenticationPage); FormLoginHandler h = getHandler(authenticationPage); boolean authenticated = h.login(user, password, c, cookieStore, authenticationPage); if (authenticated) { setCookieCache(cookieStore.getCookies()); return true; }else return false; } catch (Exception e) { throw new AuthenticationException(e); } }
Source:
<code>public static SharedRealm getInstance(RealmConfiguration config, SchemaVersionListener schemaVersionListener, boolean autoChangeNotifications) { Object[] syncUserConf = ObjectServerFacade.getSyncFacadeIfPossible().getUserAndServerUrl(config); String syncUserIdentifier = (String) syncUserConf[0]; String syncRealmUrl = (String) syncUserConf[1]; String syncRealmAuthUrl = (String) syncUserConf[2]; String syncRefreshToken = (String) syncUserConf[3]; <START> Boolean syncClientValidateSsl = (Boolean) syncUserConf[4]; <END> String syncSslTrustCertificatePath = (String) syncUserConf[5]; final boolean enableCaching = false; final boolean enableFormatUpgrade = true; long nativeConfigPtr = nativeCreateConfig( config.getPath(), config.getEncryptionKey(), syncRealmUrl != null ? SchemaMode.SCHEMA_MODE_ADDITIVE.getNativeValue() : SchemaMode.SCHEMA_MODE_MANUAL.getNativeValue(), config.getDurability() == Durability.MEM_ONLY, enableCaching, config.getSchemaVersion(), enableFormatUpgrade, autoChangeNotifications, syncRealmUrl, syncRealmAuthUrl, syncUserIdentifier, syncRefreshToken, (syncClientValidateSsl == null) || syncClientValidateSsl, syncSslTrustCertificatePath); try { ObjectServerFacade.getSyncFacadeIfPossible().wrapObjectStoreSessionIfRequired(config); return new SharedRealm(nativeConfigPtr, config, schemaVersionListener); } finally { nativeCloseConfig(nativeConfigPtr); } }</code><technical_language>Boolean boolean</technical_language>

Target:
public static SharedRealm getInstance(RealmConfiguration config, SchemaVersionListener schemaVersionListener, boolean autoChangeNotifications) { Object[] syncUserConf = ObjectServerFacade.getSyncFacadeIfPossible().getUserAndServerUrl(config); String syncUserIdentifier = (String) syncUserConf[0]; String syncRealmUrl = (String) syncUserConf[1]; String syncRealmAuthUrl = (String) syncUserConf[2]; String syncRefreshToken = (String) syncUserConf[3]; boolean syncClientValidateSsl = (Boolean.TRUE.equals(syncUserConf[4])); String syncSslTrustCertificatePath = (String) syncUserConf[5]; final boolean enableCaching = false; final boolean enableFormatUpgrade = true; long nativeConfigPtr = nativeCreateConfig( config.getPath(), config.getEncryptionKey(), syncRealmUrl != null ? SchemaMode.SCHEMA_MODE_ADDITIVE.getNativeValue() : SchemaMode.SCHEMA_MODE_MANUAL.getNativeValue(), config.getDurability() == Durability.MEM_ONLY, enableCaching, config.getSchemaVersion(), enableFormatUpgrade, autoChangeNotifications, syncRealmUrl, syncRealmAuthUrl, syncUserIdentifier, syncRefreshToken, syncClientValidateSsl, syncSslTrustCertificatePath); try { ObjectServerFacade.getSyncFacadeIfPossible().wrapObjectStoreSessionIfRequired(config); return new SharedRealm(nativeConfigPtr, config, schemaVersionListener); } finally { nativeCloseConfig(nativeConfigPtr); } }
Source:
<code>public boolean equals(Object o) { if (this == o) return true; <START> if (o == null || getClass() != o.getClass()) <END> return false; SearchParameter that = (SearchParameter) o; if (!name.equals(that.name)) return false; return value != null ? value.equals(that.value) : that.value == null; }</code><technical_language>if SubresourceParameter? instanceof here</technical_language>

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof SearchParameter)) return false; SearchParameter that = (SearchParameter) o; if (!name.equals(that.name)) return false; return value != null ? value.equals(that.value) : that.value == null; }
Source:
<code>public static LifecycleInjector createInjector(final GovernatorConfiguration config) { Logger LOG = LoggerFactory.getLogger(Governator.class); LOG.info("Using profiles : " + config.getProfiles()); final Set<Module> candidateModules = new HashSet<>(); for (ModuleListProvider loader : config.getModuleListProviders()) { candidateModules.addAll(loader.get()); } final LifecycleManager manager = new LifecycleManager(); try { Module coreModule = Modules.override( createAutoModule(LOG, config, candidateModules, config.getModules())) .with(config.getOverrideModules()); <START> if (config.isEnabled(GovernatorFeatures.PRINT_BINDINGS)) { <END> for (Element binding : Elements.getElements(coreModule)) { System.out.println(binding); } } LOG.info("Configured override modules : " + config.getOverrideModules()); Injector injector = Guice.createInjector( config.getStage(), new LifecycleModule(), new AbstractModule() { @Override protected void configure() { bind(LifecycleManager.class).toInstance(manager); bind(GovernatorConfiguration.class).toInstance(config); bind(PropertySource.class).toInstance(config.getPropertySource()); } }, coreModule ); manager.notifyStarted(); return new LifecycleInjector(injector, manager); } catch (Throwable e) { e.printStackTrace(System.err); try { manager.notifyStartFailed(e); } catch (Exception e2) { System.err.println("Failed to notify injector creation failure!"); e2.printStackTrace(System.err); } if (config.isEnabled(GovernatorFeatures.SHUTDOWN_ON_ERROR)) throw new RuntimeException(e); return new LifecycleInjector(null, manager); } }</code><technical_language>log debug level</technical_language>

Target:
public static LifecycleInjector createInjector(final GovernatorConfiguration config) { Logger LOG = LoggerFactory.getLogger(Governator.class); LOG.info("Using profiles : " + config.getProfiles()); final Set<Module> candidateModules = new HashSet<>(); for (ModuleListProvider loader : config.getModuleListProviders()) { candidateModules.addAll(loader.get()); } final LifecycleManager manager = new LifecycleManager(); try { Module coreModule = Modules.override( createAutoModule(LOG, config, candidateModules, config.getModules())) .with(config.getOverrideModules()); for (Element binding : Elements.getElements(coreModule)) { LOG.debug("Binding : {}", binding); } LOG.info("Configured override modules : " + config.getOverrideModules()); Injector injector = Guice.createInjector( config.getStage(), new LifecycleModule(), new AbstractModule() { @Override protected void configure() { bind(LifecycleManager.class).toInstance(manager); bind(GovernatorConfiguration.class).toInstance(config); bind(PropertySource.class).toInstance(config.getPropertySource()); } }, coreModule ); manager.notifyStarted(); return new LifecycleInjector(injector, manager); } catch (Throwable e) { e.printStackTrace(System.err); try { manager.notifyStartFailed(e); } catch (Exception e2) { System.err.println("Failed to notify injector creation failure!"); e2.printStackTrace(System.err); } if (config.isEnabled(GovernatorFeatures.SHUTDOWN_ON_ERROR)) throw new RuntimeException(e); return new LifecycleInjector(null, manager); } }
Source:
<code>public KeyValue next() throws IOException { boolean endOfBatch = false; StringWriter sw = new StringWriter(); if (rowIndex > batch.size - 1) { endOfBatch = !rows.nextBatch(batch); rowIndex = 0; } if (endOfBatch) { rows.close(); return null; } try { JsonFieldFiller.processRow(new JSONWriter(sw), batch, schema, rowIndex); } catch (JSONException e) { <START> LOG.error("Unable to parse json {}", sw.toString()); <END> } rowIndex++; return new KeyValue(offset++, sw.toString().getBytes("UTF-8")); }</code><technical_language>Do need return NULL error case</technical_language>

Target:
public KeyValue next() throws IOException { boolean endOfBatch = false; StringWriter sw = new StringWriter(); if (rowIndex > batch.size - 1) { endOfBatch = !rows.nextBatch(batch); rowIndex = 0; } if (endOfBatch) { rows.close(); return null; } try { JsonFieldFiller.processRow(new JSONWriter(sw), batch, schema, rowIndex); } catch (JSONException e) { LOG.error("Unable to parse json {}", sw.toString()); return null; } rowIndex++; return new KeyValue(offset++, sw.toString().getBytes("UTF-8")); }
Source:
<code>protected void updateSensorProperties() { Map<String, String> properties = editProperties(); Bridge bridge = getBridge(); if (bridge == null) { <START> logger.info("updating thing properties failed, no bridge available"); <END> scheduler.schedule(() -> { updateSensorProperties(); }, 5000, TimeUnit.MILLISECONDS); return; } OwBaseBridgeHandler bridgeHandler = (OwBaseBridgeHandler) bridge.getHandler(); try { if (bridgeHandler == null) { throw new OwException("no bridge handler available"); } OwSensorType sensorType = bridgeHandler.getType(sensorIds.get(0)); properties.put(PROPERTY_MODELID, sensorType.toString()); properties.put(PROPERTY_VENDOR, "generic"); logger.trace("updated modelid/vendor to / {}", sensorType.name(), "generic"); } catch (OwException e) { logger.info("updating thing properties failed: {}", e.getMessage()); scheduler.schedule(() -> { updateSensorProperties(); }, 5000, TimeUnit.MILLISECONDS); return; } updateProperties(properties); }</code><technical_language>reduce debug</technical_language>

Target:
protected void updateSensorProperties() { Map<String, String> properties = editProperties(); Bridge bridge = getBridge(); if (bridge == null) { logger.debug("updating thing properties failed, no bridge available"); scheduler.schedule(() -> { updateSensorProperties(); }, 5000, TimeUnit.MILLISECONDS); return; } OwBaseBridgeHandler bridgeHandler = (OwBaseBridgeHandler) bridge.getHandler(); try { if (bridgeHandler == null) { throw new OwException("no bridge handler available"); } OwSensorType sensorType = bridgeHandler.getType(sensorIds.get(0)); properties.put(PROPERTY_MODELID, sensorType.toString()); properties.put(PROPERTY_VENDOR, "Dallas/Maxim"); logger.trace("updated modelid/vendor to / {}", sensorType.name(), "Dallas/Maxim"); } catch (OwException e) { logger.info("updating thing properties failed: {}", e.getMessage()); scheduler.schedule(() -> { updateSensorProperties(); }, 5000, TimeUnit.MILLISECONDS); return; } updateProperties(properties); }
Source:
<code>public void namespacePut( @RequestBody NamespaceInfo namespace, @PathVariable String prefix, UriComponentsBuilder builder) { if ("default".equals(prefix)) { catalog.setDefaultNamespace(namespace); } else { NamespaceInfo nsi = catalog.getNamespaceByPrefix(prefix); if (nsi == null) { throw new RestException("Can't change a non existant namespace (" + prefix + ")", HttpStatus.NOT_FOUND); } String infoName = namespace.getName(); if (infoName != null && !prefix.equals(infoName)) { throw new RestException("Can't change name of namespace", HttpStatus.FORBIDDEN); } new CatalogBuilder(catalog).updateNamespace(nsi, namespace); catalog.save(nsi); <START> WorkspaceInfo workspace = catalog.getWorkspaceByName(namespace.getPrefix()); <END> if (workspace != null) { workspace.setIsolated(namespace.isIsolated()); catalog.save(workspace); } else { throw new RestException(String.format( "Can't find workspace for namespace '%s'.", namespace.getPrefix()), HttpStatus.FORBIDDEN); } } }</code><technical_language>In catalog is a NamespaceWorkspaceConsistencyListener, wondering if code this put there</technical_language>

Target:
public void namespacePut( @RequestBody NamespaceInfo namespace, @PathVariable String prefix, UriComponentsBuilder builder) { if ("default".equals(prefix)) { catalog.setDefaultNamespace(namespace); } else { NamespaceInfo nsi = catalog.getNamespaceByPrefix(prefix); if (nsi == null) { throw new RestException("Can't change a non existant namespace (" + prefix + ")", HttpStatus.NOT_FOUND); } String infoName = namespace.getName(); if (infoName != null && !prefix.equals(infoName)) { throw new RestException("Can't change name of namespace", HttpStatus.FORBIDDEN); } new CatalogBuilder(catalog).updateNamespace(nsi, namespace); catalog.save(nsi); } }
Source:
<code>public ConfigurableColumnTableViewerSupport(TableViewer viewer, TableColumnDescriptor[] columnDescriptors, File stateFile, boolean[] defaultVisibilities) { super(viewer, stateFile, defaultVisibilities); this.viewer = viewer; this.table = viewer.getTable(); this.columnDescriptors = columnDescriptors; <START> initializeViewerSupport(); <END> createConfigureColumnsAction(getHeaderMenu()); }</code><technical_language>this called superconstructor</technical_language>

Target:
public ConfigurableColumnTableViewerSupport(TableViewer viewer, TableColumnDescriptor[] columnDescriptors, File stateFile, boolean[] defaultVisibilities) { super(viewer, stateFile, defaultVisibilities); this.viewer = viewer; this.columnDescriptors = columnDescriptors; createConfigureColumnsAction(getHeaderMenu()); }
Source:
<code>public void tearDown() throws Exception { <START> zkClient.close(); <END> zkClientB.close(); super.tearDown(); }</code><technical_language>Please add null check for case setUp() fails early</technical_language>

Target:
public void tearDown() throws Exception { if (zkClient != null) { zkClient.close(); } if (zkClientB != null) { zkClientB.close(); } super.tearDown(); }
Source:
<code>public void testToString() { Assert.assertEquals( ENTITY_DIMENSION.toString(), "EntityDimension[name='country', longName='country', description='country', dimensionType=TABLE, dataType=Country, cardinality=SMALL, friendlyName='name']" ); Assert.assertEquals( DEGENERATE_DIMENSION.toString(), "DegenerateDimension[columnType=FIELD, name='overallRating', longName='overallRating', description='overallRating', dimensionType=DEGENERATE, dataType=String, cardinality=SMALL, friendlyName='overallRating']" ); Assert.assertEquals( TIME_DIMENSION.toString(), <START> "TimeDimension[timeZone=Pacific Standard Time, timeGrain=DAY, columnType=TEMPORAL, name='recordedTime', longName='recordedTime', description='recordedTime', dimensionType=DEGENERATE, dataType=class java.lang.Long, cardinality=LARGE, friendlyName='recordedTime']" <END> ); }</code><technical_language>timezone "Pacific Standard Time" test fail in local testing I in CST. Replacing TimeZone.getDefault().getDisplayName() fix it</technical_language>

Target:
public void testToString() { Assert.assertEquals( ENTITY_DIMENSION.toString(), "EntityDimension[name='country', longName='country', description='country', dimensionType=ENTITY, dataType=Country, cardinality=SMALL, friendlyName='name']" ); Assert.assertEquals( DEGENERATE_DIMENSION.toString(), "DegenerateDimension[columnType=FIELD, name='overallRating', longName='overallRating', description='overallRating', dimensionType=DEGENERATE, dataType=String, cardinality=SMALL, friendlyName='overallRating']" ); Assert.assertEquals( TIME_DIMENSION.toString(), "TimeDimension[timeZone=Pacific Standard Time, timeGrain=DAY, columnType=TEMPORAL, name='recordedTime', longName='recordedTime', description='recordedTime', dimensionType=DEGENERATE, dataType=class java.lang.Long, cardinality=LARGE, friendlyName='recordedTime']" ); }
Source:
<code>public boolean isStreamedTrace() { if (fSessionInfo.isSnapshotSession()) { <START> return fSessionInfo.getSnapshotInfo().isStreamedSnapshot(); <END> } return fSessionInfo.isStreamedTrace(); }</code><technical_language>lines moved in SessionInfo class instead. user of SessionInfo do check (see SessionConfigGenerator)</technical_language>

Target:
public boolean isStreamedTrace() { return fSessionInfo.isStreamedTrace(); }
Source:
<code>private int setWifiTethering(final boolean enable) { int rval = TETHER_ERROR_MASTER_ERROR; final long ident = Binder.clearCallingIdentity(); try { synchronized (mPublicSync) { mWifiTetherRequested = enable; final WifiManager mgr = getWifiManager(); if (mgr == null) { <START> mLog.e(TAG, "setWifiTethering: <END> failed to get WifiManager!"); return TETHER_ERROR_SERVICE_UNAVAIL; } if ((enable && mgr.startSoftAp(null )) || (!enable && mgr.stopSoftAp())) { rval = TETHER_ERROR_NO_ERROR; } } } finally { Binder.restoreCallingIdentity(ident); } return rval; }</code><technical_language>build fail add TAG</technical_language>

Target:
private int setWifiTethering(final boolean enable) { int rval = TETHER_ERROR_MASTER_ERROR; final long ident = Binder.clearCallingIdentity(); try { synchronized (mPublicSync) { mWifiTetherRequested = enable; final WifiManager mgr = getWifiManager(); if (mgr == null) { mLog.e("setWifiTethering: failed to get WifiManager!"); return TETHER_ERROR_SERVICE_UNAVAIL; } if ((enable && mgr.startSoftAp(null )) || (!enable && mgr.stopSoftAp())) { rval = TETHER_ERROR_NO_ERROR; } } } finally { Binder.restoreCallingIdentity(ident); } return rval; }
Source:
<code>public void testCanDelegateIsEnabled() { assertThat(proxyCache.isEnabled()).isTrue(); RuntimeException runtimeException = new RuntimeException(); when(defaultCache.getCommitUpdate(anyLong())).thenThrow(runtimeException); <START> assertThatThrownBy(() -> proxyCache.getCommitUpdate(0L)).hasCause(runtimeException) .isExactlyInstanceOf(TransactionLockWatchFailedException.class); <END> assertThat(proxyCache.isEnabled()).isFalse(); verify(defaultCache).getCommitUpdate(0L); verifyNoMoreInteractions(defaultCache, fallbackCache); }</code><technical_language>do mind expanding this test hasMessage a number of exceptions class (I I guilty of this too, in effort clearer testing, this done)</technical_language>

Target:
public void testCanDelegateIsEnabled() { when(defaultCache.isEnabled()).thenReturn(true); when(fallbackCache.isEnabled()).thenReturn(false); assertThat(proxyCache.isEnabled()).isTrue(); verify(defaultCache).isEnabled(); RuntimeException runtimeException = new RuntimeException(); when(defaultCache.getCommitUpdate(anyLong())).thenThrow(runtimeException); assertThatThrownBy(() -> proxyCache.getCommitUpdate(0L)).hasCause(runtimeException) .isExactlyInstanceOf(TransactionLockWatchFailedException.class); assertThat(proxyCache.isEnabled()).isFalse(); verify(fallbackCache).isEnabled(); verify(defaultCache).getCommitUpdate(0L); verifyNoMoreInteractions(defaultCache, fallbackCache); }
Source:
<code>private String getHintText(FormEntryPrompt[] questionPrompts) { String hintText = null; try { if (questionPrompts.length > 1) { hintText = questionPrompts[0].getHintText(); for (FormEntryPrompt p : questionPrompts) { String curHintText = p.getHintText(); if (curHintText == null || !curHintText.equals(hintText)) { hintText = null; break; } } } } catch (XPathException exception) { UserfacingErrorHandling.createErrorDialog((CommCareActivity)getContext(), exception.getLocalizedMessage(), true); <START> } catch (Exception e) { <END> Logger.exception("QuestionsView.getHintText", e); e.printStackTrace(); } return hintText; }</code><technical_language>remove Exception catch</technical_language>

Target:
private String getHintText(FormEntryPrompt[] questionPrompts) { String hintText = null; try { if (questionPrompts.length > 1) { hintText = questionPrompts[0].getHintText(); for (FormEntryPrompt p : questionPrompts) { String curHintText = p.getHintText(); if (curHintText == null || !curHintText.equals(hintText)) { hintText = null; break; } } } } catch (XPathException exception) { UserfacingErrorHandling.createErrorDialog((CommCareActivity)getContext(), exception.getLocalizedMessage(), true); } return hintText; }