auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean isAdmin(final String username) { final String sql = "select role from lobby_user where username = ?"; try (Connection con = connection.get(); PreparedStatement ps = con.prepareStatement(sql)) { ps.setString(1, username); try (ResultSet rs = ps.executeQuery()) { if (!rs.next()) { return false; } final String role = rs.getString("role"); <START> return "ADMIN".equals(role) || "MODERATOR".equals(role); <END> } } catch (final SQLException e) { throw new DatabaseException("Error getting admin flag for user: " + username, e); } }</code><technical_language>compile-time dependencies, nice if strings stored in single global constants instead of hardcoding here</technical_language>

Target:
public boolean isAdmin(final String username) { final String sql = "select role from lobby_user where username = ?"; try (Connection con = connection.get(); PreparedStatement ps = con.prepareStatement(sql)) { ps.setString(1, username); try (ResultSet rs = ps.executeQuery()) { if (!rs.next()) { return false; } final String role = rs.getString("role"); return UserRole.ADMIN.equals(role) || UserRole.MODERATOR.equals(role); } } catch (final SQLException e) { throw new DatabaseException("Error getting admin flag for user: " + username, e); } }
Source:
<code>public void setAltitude(double altitude) { this.altitude = altitude; <START> if(altitude > 121.92 && previousAltitude <= 121.92){ <END> myDrone.notifyDroneEvent(DroneInterfaces.DroneEventsType.WARNING_400FT_EXCEEDED); } previousAltitude = altitude; }</code><technical_language>@TShapinsky want store 121.92 a constant, constant name describe is for. I get 121.92m == 400ft, for familiar code, meaningless, arbitrary</technical_language>

Target:
public void setAltitude(double altitude) { this.altitude = altitude; if(altitude > FOUR_HUNDRED_FEET_IN_METERS && previousAltitude <= FOUR_HUNDRED_FEET_IN_METERS){ myDrone.notifyDroneEvent(DroneInterfaces.DroneEventsType.WARNING_400FT_EXCEEDED); } previousAltitude = altitude; }
Source:
<code>public void verifyRequestWithOneToOneRelationship() { String expected = "{\"data\":{\"type\":\"blog\",\"id\":\"1\"," + "\"attributes\":{\"title\":\"title\"}," + "\"relationships\":{\"author\":{\"data\":{\"type\":\"author\",\"id\":\"1\"}}}}}"; String actual = datum( resource( type("blog"), id("1"), attributes( attr("title", "title") ), relationships( <START> toOneRelation("author", <END> linkage(type("author"), id("1")) ) ) ) ).toJSON(); assertEquals(actual, expected); }</code><technical_language>I replace java relation("author", TO_ONE</technical_language>

Target:
public void verifyRequestWithOneToOneRelationship() { String expected = "{\"data\":{\"type\":\"blog\",\"id\":\"1\"," + "\"attributes\":{\"title\":\"title\"}," + "\"relationships\":{\"author\":{\"data\":{\"type\":\"author\",\"id\":\"1\"}}}}}"; String actual = datum( resource( type("blog"), id("1"), attributes( attr("title", "title") ), relationships( relation("author", TO_ONE, linkage(type("author"), id("1")) ) ) ) ).toJSON(); assertEquals(actual, expected); }
Source:
<code>public void init(IEditorSite site, IEditorInput input) { super.init(site, input); TaskData taskData = getModel().getTaskData(); if (taskData != null) { GerritChange change = GerritUtil.getChange(taskData); final ChangeDetailX detail = change.getChangeDetail(); try { review = GerritUtil.toReview(detail); } catch (GerritException e) { <START> throw new RuntimeException(e); <END> } } }</code><technical_language>case page loading fail. exception removed GerritUtil.toReview() instead</technical_language>

Target:
public void init(IEditorSite site, IEditorInput input) { super.init(site, input); TaskData taskData = getModel().getTaskData(); if (taskData != null) { GerritChange change = GerritUtil.getChange(taskData); final ChangeDetailX detail = change.getChangeDetail(); review = GerritUtil.toReview(detail); } }
Source:
<code>public void testRemoveKeyWordsFollowedByNewLineChar() { <START> String selectWithSpace = "SELECT\nid, 'yes', false"; String fromWithSpace = "FROM\ntest.verification_table"; String whereWithSpace = "WHERE\nTRUE"; <END> pagingQueryProvider.setSelectClause( selectWithSpace ); pagingQueryProvider.setFromClause( fromWithSpace ); pagingQueryProvider.setWhereClause( whereWithSpace ); assertEquals("id, 'yes', false", pagingQueryProvider.getSelectClause()); assertEquals("test.verification_table", pagingQueryProvider.getFromClause()); assertEquals("TRUE", pagingQueryProvider.getWhereClause()); }</code><technical_language>here, IMO selectClause, fromClause whereClause ok test method name is explicit enough</technical_language>

Target:
public void testRemoveKeyWordsFollowedByNewLineChar() { String selectClause = "SELECT\nid, 'yes', false"; String fromClause = "FROM\ntest.verification_table"; String whereClause = "WHERE\nTRUE"; pagingQueryProvider.setSelectClause( selectClause ); pagingQueryProvider.setFromClause( fromClause ); pagingQueryProvider.setWhereClause( whereClause ); assertEquals("id, 'yes', false", pagingQueryProvider.getSelectClause()); assertEquals("test.verification_table", pagingQueryProvider.getFromClause()); assertEquals("TRUE", pagingQueryProvider.getWhereClause()); }
Source:
<code>protected void sendHealthCheckResponse(HttpServletResponse resp, HealthCheckResult result) throws IOException { if (result.healthy) { resp.setStatus(HttpServletResponse.SC_OK); } else { <START> resp.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); <END> } sendResponse(resp, result.toJson()); }</code><technical_language>HttpServletResponse.SC_... everywhere, need for HttpStatus here</technical_language>

Target:
protected void sendHealthCheckResponse(HttpServletResponse resp, HealthCheckResult result) throws IOException { if (result.healthy) { resp.setStatus(HttpServletResponse.SC_OK); } else { resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } sendResponse(resp, result.toJson()); }
Source:
<code>public TapTargetBottomBar(LinearLayout tapTargetView, View fadeView, WelcomeActivity activity, int bottomScrollBarResourceId) { super(tapTargetView, fadeView, activity, bottomScrollBarResourceId); bottomScrollBar = activity.findViewById(R.id.pocketpaint_intro_tools_bottom_bar) <START> .findViewById(R.id.pocketpaint_intro_bottom_bar_scroll_view); <END> }</code><technical_language>Please revert changes this file</technical_language>

Target:
public TapTargetBottomBar(LinearLayout tapTargetView, View fadeView, WelcomeActivity activity, int bottomScrollBarResourceId) { super(tapTargetView, fadeView, activity, bottomScrollBarResourceId); bottomScrollBar = (BottomBarHorizontalScrollView) activity.findViewById(R.id.pocketpaint_intro_tools_bottom_bar) .findViewById(R.id.pocketpaint_intro_bottom_bar_scroll_view); }
Source:
<code>private void playerDies() { State.getTrack().getPlayer().die(); <START> sleep(20 * InternalTicker.NANOS_PER_TICK / InternalTicker.E6); <END> letPlayerSurvive(); sleep(LONG); }</code><technical_language>20 is a magic number. Please check tests SAT. <review,configuration</technical_language>

Target:
private void playerDies() { State.getTrack().getPlayer().die(); sleep(SLEEP_FACTOR * InternalTicker.NANOS_PER_TICK / InternalTicker.E6); letPlayerSurvive(); sleep(LONG); }
Source:
<code>private ISYBindingConfig parseConfig(final Item item, <START> final String bindingConfig) { <END> ISYNodeType type; String controller = null; String address = null; ISYControl command = null; if (item instanceof GroupItem) { type = ISYNodeType.GROUP; } else if (item instanceof ContactItem) { type = ISYNodeType.CONTACT; } else if (item instanceof NumberItem) { type = ISYNodeType.NUMBER; } else if (item instanceof StringItem) { type = ISYNodeType.STRING; } else if (item instanceof DimmerItem) { type = ISYNodeType.DIMMER; } else if (item instanceof DateTimeItem) { type = ISYNodeType.HEARTBEAT; } else { type = ISYNodeType.SWITCH; } String[] arr = bindingConfig.split(","); for (String str : arr) { String[] pair = str.split("="); String key = pair[0]; String value = pair[1]; switch (key) { case "ctrl": controller = value.replace('.', ' '); break; case "addr": address = value.replace('.', ' '); break; case "type": if ("thermostat".equalsIgnoreCase(value)) { type = ISYNodeType.THERMOSTAT; } if ("lock".equalsIgnoreCase(value)) { type = ISYNodeType.LOCK; } if ("heartbeat".equalsIgnoreCase(value)) { type = ISYNodeType.HEARTBEAT; } break; case "cmd": try { command = ISYControl.valueOf(value.toUpperCase()); } catch (IllegalArgumentException ie) { this.logger.warn("Unsupported cmd {}", value); command = ISYControl.UNDEFINED; } break; } } if (address == null) { address = controller; } return new ISYBindingConfig(item, type, controller, address, command); }</code><technical_language>throws BindingConfigParseException</technical_language>

Target:
private ISYBindingConfig parseConfig(final Item item, final String bindingConfig) throws BindingConfigParseException { ISYNodeType type; String controller = null; String address = null; ISYControl command = null; if (item instanceof GroupItem) { type = ISYNodeType.GROUP; } else if (item instanceof ContactItem) { type = ISYNodeType.CONTACT; } else if (item instanceof NumberItem) { type = ISYNodeType.NUMBER; } else if (item instanceof StringItem) { type = ISYNodeType.STRING; } else if (item instanceof DimmerItem) { type = ISYNodeType.DIMMER; } else if (item instanceof DateTimeItem) { type = ISYNodeType.HEARTBEAT; } else { type = ISYNodeType.SWITCH; } String[] arr = bindingConfig.split(","); for (String str : arr) { String[] pair = str.split("="); String key = pair[0]; String value = pair[1]; switch (key) { case "ctrl": controller = value.replace('.', ' '); break; case "addr": address = value.replace('.', ' '); break; case "type": if ("thermostat".equalsIgnoreCase(value)) { type = ISYNodeType.THERMOSTAT; } if ("lock".equalsIgnoreCase(value)) { type = ISYNodeType.LOCK; } if ("heartbeat".equalsIgnoreCase(value)) { type = ISYNodeType.HEARTBEAT; } break; case "cmd": try { command = ISYControl.valueOf(value.toUpperCase()); } catch (IllegalArgumentException ie) { throw new BindingConfigParseException("Unsupported cmd " + value.toString()); } break; } } if (address == null) { address = controller; } return new ISYBindingConfig(item, type, controller, address, command); }
Source:
<code>private void onResult() { if (script != null && comments != null) { if (comments.getHistory().size() > 1) { historyTable.display(comments.getHistory()); historyPanel.setVisible(true); } else { historyPanel.setVisible(false); } if (contentTable instanceof SideBySideTable && script.getEdits().isEmpty() && !script.getPatchHeader().isEmpty()) { contentTable.removeFromParent(); contentTable = new UnifiedDiffTable(); contentTable.fileList = fileList; contentPanel.add(contentTable); History.newItem(Link.toPatchUnified(patchKey), false); } contentTable.display(patchKey, idSideA, idSideB, script); contentTable.display(comments); contentTable.finishDisplay(); <START> showPatch(!script.getEdits().isEmpty()); <END> script = null; comments = null; if (!isCurrentView()) { display(); } } }</code><technical_language>FWIW, if this is false, prior 3 lines pointless. worth putting if block. Also, this true, header empty. conditions of boolean expression line 391 (above): !(script.getEdits().isEmpty() && script.getPatchHeader().isEmpty()) show "No Differences" is a mode change a pure rename/copy</technical_language>

Target:
private void onResult() { if (script != null && comments != null) { if (comments.getHistory().size() > 1) { historyTable.display(comments.getHistory()); historyPanel.setVisible(true); } else { historyPanel.setVisible(false); } boolean hasDifferences = !script.getEdits().isEmpty() && !script.getPatchHeader().isEmpty(); boolean modeChange = script.getEdits().isEmpty() && !script.getPatchHeader().isEmpty(); if (contentTable instanceof SideBySideTable && modeChange) { contentTable.removeFromParent(); contentTable = new UnifiedDiffTable(); contentTable.fileList = fileList; contentPanel.add(contentTable); History.newItem(Link.toPatchUnified(patchKey), false); } if (hasDifferences) { contentTable.display(patchKey, idSideA, idSideB, script); contentTable.display(comments); contentTable.finishDisplay(); } showPatch(hasDifferences); script = null; comments = null; if (!isCurrentView()) { display(); } } }
Source:
<code>public static boolean runCipherToolScriptAndCheckStatus(String carbonHome, String[] cmdArray) throws IOException { boolean foundTheMessage = false; BufferedReader br = null; Process process = null; try { log.info("Running the ciphertool.sh .."); File commandDir = new File(carbonHome + "/bin"); ProcessBuilder processBuilder = new ProcessBuilder(cmdArray); processBuilder.directory(commandDir); process = processBuilder.start(); br = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; while ((line = br.readLine()) != null) { log.info(line); if (line.contains("Encryption is done Successfully")) { foundTheMessage = true; } } return foundTheMessage; } catch (IOException ex) { <START> log.error("Error when reading the InputStream when running shell script ", ex); <END> throw new IOException("Error when reading the InputStream when running shell script ", ex); } finally { if (br != null) { br.close(); } if (process != null) { process.destroy(); } } }</code><technical_language>Catch re-throwing excetion</technical_language>

Target:
public static boolean runCipherToolScriptAndCheckStatus(String carbonHome, String[] cmdArray) throws PasswordEncryptionIntegrationTestException { boolean foundTheMessage = false; BufferedReader br = null; Process process = null; try { log.info("Running the ciphertool.sh .."); File commandDir = new File(carbonHome + "/bin"); ProcessBuilder processBuilder = new ProcessBuilder(cmdArray); processBuilder.directory(commandDir); process = processBuilder.start(); br = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; while ((line = br.readLine()) != null) { log.info(line); if (line.contains("Encryption is done Successfully")) { foundTheMessage = true; } } return foundTheMessage; } catch (IOException ex) { log.error("Error when reading the InputStream when running shell script ", ex); throw new PasswordEncryptionIntegrationTestException("Error when reading the InputStream when running shell script ", ex); } finally { if (br != null) { try { br.close(); } catch (IOException e) { log.warn("error while closing the buffered reader"); } } if (process != null) { process.destroy(); } } }
Source:
<code>public void startVisit(final Patient patient, @Nullable final StartVisitResponseListenerCallback callbackListener) { final Visit visit = new Visit(); visit.setStartDatetime(DateUtils.convertTime(System.currentTimeMillis(), DateUtils.OPEN_MRS_REQUEST_FORMAT)); visit.setPatient(patient); LocationDAO.findLocationByName(OpenMRS.getInstance().getLocation()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(location -> { visit.setLocation(location); }); <START> <END> visit.setVisitType(new VisitType(null, OpenMRS.getInstance().getVisitTypeUUID())); Call<Visit> call = restApi.startVisit(visit); call.enqueue(new Callback<Visit>() { @Override public void onResponse(Call<Visit> call, Response<Visit> response) { if (response.isSuccessful()) { Visit newVisit = response.body(); visitDAO.saveOrUpdate(newVisit, patient.getId()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(id -> { if(callbackListener != null) { callbackListener.onStartVisitResponse(id); } }); } else { if(callbackListener != null) { callbackListener.onErrorResponse(response.message()); } } } @Override public void onFailure(Call<Visit> call, Throwable t) { if(callbackListener != null) { callbackListener.onErrorResponse(t.getMessage()); } } }); }</code><technical_language>this visit.setLocation() called retrofit call. I is a lot of usage of this method want async task i leave was</technical_language>

Target:
public void startVisit(final Patient patient, @Nullable final StartVisitResponseListenerCallback callbackListener) { final Visit visit = new Visit(); visit.setStartDatetime(DateUtils.convertTime(System.currentTimeMillis(), DateUtils.OPEN_MRS_REQUEST_FORMAT)); visit.setPatient(patient); visit.setLocation(locationDAO.findLocationByName(OpenMRS.getInstance().getLocation())); visit.setVisitType(new VisitType(null, OpenMRS.getInstance().getVisitTypeUUID())); Call<Visit> call = restApi.startVisit(visit); call.enqueue(new Callback<Visit>() { @Override public void onResponse(Call<Visit> call, Response<Visit> response) { if (response.isSuccessful()) { Visit newVisit = response.body(); visitDAO.saveOrUpdate(newVisit, patient.getId()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(id -> { if(callbackListener != null) { callbackListener.onStartVisitResponse(id); } }); } else { if(callbackListener != null) { callbackListener.onErrorResponse(response.message()); } } } @Override public void onFailure(Call<Visit> call, Throwable t) { if(callbackListener != null) { callbackListener.onErrorResponse(t.getMessage()); } } }); }
Source:
<code>public List<Biome.SpawnListEntry> getSpawns(List<Biome.SpawnListEntry> defaults, World world, EnumCreatureType creatureType, BlockPos pos) { for (MapGenStructure structure : structureMap.values()) { <START> if (structure instanceof ISpawningStructure && structure.isInsideStructure(pos)) <END> { return ((ISpawningStructure) structure).getSpawns(Collections.unmodifiableList(defaults), world, creatureType, pos); } } return defaults; }</code><technical_language>usage of isInsideStructure isPositionInStructure here, is check if a position is in of components of a structure, currently advancement location predicate. While is for determining if a position is eligible for spawning, default behavior check if position is surrounding bounds of a structure</technical_language>

Target:
public List<Biome.SpawnListEntry> getSpawns(List<Biome.SpawnListEntry> defaults, World world, EnumCreatureType creatureType, BlockPos pos) { for (MapGenStructure structure : structureMap.values()) { if (structure instanceof ISpawningStructure && structure.isPositionInStructure(world,pos)) { return ((ISpawningStructure) structure).getSpawns(Collections.unmodifiableList(defaults), world, creatureType, pos); } } return defaults; }
Source:
<code>public ReplicaList normalizeByRange() { if (Iterables.all(this, Replica::isFull)) { <START> ReplicaList normalized = new ReplicaList(size()); <END> for (Replica replica: this) { normalized.addAll(replica.normalizeByRange()); } return normalized; } else { throw new UnsupportedOperationException("transient replicas are currently unsupported"); } }</code><technical_language>want invert a bit pass this call replica.normalizeByRange</technical_language>

Target:
public ReplicaList normalizeByRange() { if (Iterables.all(this, Replica::isFull)) { ReplicaList normalized = new ReplicaList(size()); for (Replica replica: this) { replica.addNormalizeByRange(normalized); } return normalized; } else { throw new UnsupportedOperationException("transient replicas are currently unsupported"); } }
Source:
<code>public Optional<User> getBlockNotifier(BlockPos pos) { final int intKey = blockPosToInt(pos); final PlayerTracker intTracker = this.trackedIntBlockPositions.get(intKey); if (intTracker != null) { final int notifierIndex = intTracker.notifierIndex; return getValidatedUser(intKey, notifierIndex); } else { final short shortKey = blockPosToShort(pos); final PlayerTracker shortTracker = this.trackedShortBlockPositions.get(shortKey); if (shortTracker != null) { <START> final int notifierIndex = shortTracker.notifierIndex; <END> return getValidatedUser(shortKey, notifierIndex); } } return Optional.empty(); }</code><technical_language>notifierIndex eliminated here</technical_language>

Target:
public Optional<User> getBlockNotifier(BlockPos pos) { final int intKey = blockPosToInt(pos); final PlayerTracker intTracker = this.trackedIntBlockPositions.get(intKey); if (intTracker != null) { return getValidatedUser(intKey, intTracker.notifierIndex); } else { final short shortKey = blockPosToShort(pos); final PlayerTracker shortTracker = this.trackedShortBlockPositions.get(shortKey); if (shortTracker != null) { return getValidatedUser(shortKey, shortTracker.notifierIndex); } } return Optional.empty(); }
Source:
<code>public void loadReadme(boolean refresh) { Consumer consumer = result -> { Log.d("TEST-RE", "readme flatMap called"); setContentShown(true); TextView readmeView = (TextView) mContentView.findViewById(R.id.readme); View progress = mContentView.findViewById(R.id.pb_readme); if (result != null) mImageGetter.encode(getContext(), mRepository.getId(), <START> String.valueOf(result)); <END> if (result != null) { readmeView.setMovementMethod(UiUtils.CHECKING_LINK_METHOD); mImageGetter.bind(readmeView, String.valueOf(result), mRepository.getId()); } else { readmeView.setText(R.string.repo_no_readme); readmeView.setTypeface(Typeface.DEFAULT, Typeface.ITALIC); } readmeView.setVisibility(View.VISIBLE); progress.setVisibility(View.GONE); }; RepositoryService.loadReadme(getActivity(), mRepository.getOwner().getLogin(), mRepository.getName(), StringUtils.isBlank(mRef) ? mRepository.getDefaultBranch() : mRef, refresh) .subscribe(consumer, e -> {}); }</code><technical_language>This moved if block (line 125). In fact, wrong though: sole reason for existence of HttpImageGetter#encode is happen in a background thread for readmes, a costly operation. do in UI thread, UI hangs for large readmes. Also, do need setContentShown() all? present in previous code. general idea is - for PR indicator: show spinning wheel starting load, hide spinning wheel result is present - for readme: show spinning wheel starting load, run encode() data is present (in background thread!), hide spinning wheel call bind() done)</technical_language>

Target:
public void loadReadme(boolean refresh) { RepositoryService.loadReadme( (BaseActivity) getActivity(), mRepository.getOwner().getLogin(), mRepository.getName(), StringUtils.isBlank(mRef) ? mRepository.getDefaultBranch() : mRef, refresh ).doOnNext(result -> { setContentShown(true); TextView readmeView = (TextView) mContentView.findViewById(R.id.readme); View progress = mContentView.findViewById(R.id.pb_readme); if (result != null) mImageGetter.encode(getContext(), mRepository.getId(), String.valueOf(result)); if (result != null) { readmeView.setMovementMethod(UiUtils.CHECKING_LINK_METHOD); mImageGetter.bind(readmeView, String.valueOf(result), mRepository.getId()); } else { readmeView.setText(R.string.repo_no_readme); readmeView.setTypeface(Typeface.DEFAULT, Typeface.ITALIC); } readmeView.setVisibility(View.VISIBLE); progress.setVisibility(View.GONE); }).subscribe(consumer -> {}, error -> {}); }
Source:
<code>public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (backupsEnabled == null ? 0 : backupsEnabled.hashCode()); result = prime * result + (privateNetworking == null ? 0 : privateNetworking.hashCode()); <START> result = prime * result + (shouldAutoCreateKeyPair ? 1231 : 1237); <END> result = prime * result + (sshKeyIds == null ? 0 : sshKeyIds.hashCode()); return result; }</code><technical_language>Wow...where constants from? ;-)</technical_language>

Target:
public int hashCode() { return Objects.hashCode(super.hashCode(), backupsEnabled, privateNetworking, autoCreateKeyPair, sshKeyIds); }
Source:
<code>private HostVO getNuageVspHost(long physicalNetworkId) { HostVO nuageVspHost; List<NuageVspDeviceVO> nuageVspDevices = _nuageVspDao.listByPhysicalNetwork(physicalNetworkId); if (nuageVspDevices != null && (!nuageVspDevices.isEmpty())) { NuageVspDeviceVO config = nuageVspDevices.iterator().next(); nuageVspHost = _hostDao.findById(config.getHostId()); _hostDao.loadDetails(nuageVspHost); } else { <START> throw new CloudRuntimeException("Nuage VSD is not configured on physical network " + physicalNetworkId); <END> } return nuageVspHost; }</code><technical_language>Please add identifying information Nuage VSP device error message</technical_language>

Target:
private HostVO getNuageVspHost(long physicalNetworkId) { HostVO nuageVspHost; List<NuageVspDeviceVO> nuageVspDevices = _nuageVspDao.listByPhysicalNetwork(physicalNetworkId); if (nuageVspDevices != null && (!nuageVspDevices.isEmpty())) { NuageVspDeviceVO config = nuageVspDevices.iterator().next(); nuageVspHost = _hostDao.findById(config.getHostId()); _hostDao.loadDetails(nuageVspHost); } else { throw new CloudRuntimeException("There is no Nuage VSP device configured on physical network " + physicalNetworkId); } return nuageVspHost; }
Source:
<code>private Type deriveTargetType(SendSignalAction node) { Type targetPinType = null; if (node.getOnPort() != null) { targetPinType = node.getOnPort().getClass_(); } else { if (node.getTarget() != null) { Type currentTargetPinType = node.getTarget().getType(); if (currentTargetPinType instanceof Class && canReceive((Class)currentTargetPinType, node.getSignal())) { targetPinType = currentTargetPinType; } } if(targetPinType == null){ InputPin currentTargetPin = node.getTarget(); if (currentTargetPin == null) { node.setTarget(UMLFactory.eINSTANCE.createInputPin()); } UMLContentProvider provider = new UMLContentProvider(node.getTarget(), UMLPackage.eINSTANCE.getTypedElement_Type()); <START> TreeSelectorDialog dialog = new TreeSelectorDialog(PlatformUI.getWorkbench().getDisplay().getActiveShell()); <END> dialog.setTitle("Select type"); dialog.setDescription("Select type for target input pin"); dialog.setContentProvider(provider); dialog.setLabelProvider(new UMLLabelProvider()); int userResponse = dialog.open(); if (userResponse == Window.OK) { Object[] result = dialog.getResult(); if (result != null && result.length > 0 && result[0] instanceof Type) { targetPinType = (Type) result[0]; } } node.setTarget(currentTargetPin); } } return targetPinType; }</code><technical_language>this code called UI Thread? Otherwise, this exceptions</technical_language>

Target:
private Type deriveTargetType(SendSignalAction node) { Type targetPinType = null; if (node.getOnPort() != null) { targetPinType = node.getOnPort().getClass_(); } else { if (node.getTarget() != null) { Type currentTargetPinType = node.getTarget().getType(); if (currentTargetPinType instanceof Class && canReceive((Class) currentTargetPinType, node.getSignal())) { targetPinType = currentTargetPinType; } } if (targetPinType == null && Display.getCurrent() !=null) { InputPin currentTargetPin = node.getTarget(); if (currentTargetPin == null) { node.setTarget(UMLFactory.eINSTANCE.createInputPin()); } UMLContentProvider provider = new UMLContentProvider(node.getTarget(), UMLPackage.eINSTANCE.getTypedElement_Type()); TreeSelectorDialog dialog = new TreeSelectorDialog(PlatformUI.getWorkbench().getDisplay().getActiveShell()); dialog.setTitle("Select type"); dialog.setDescription("Select type for target input pin"); dialog.setContentProvider(provider); dialog.setLabelProvider(new UMLLabelProvider()); int userResponse = dialog.open(); if (userResponse == Window.OK) { Object[] result = dialog.getResult(); if (result != null && result.length > 0 && result[0] instanceof Type) { targetPinType = (Type) result[0]; } } node.setTarget(currentTargetPin); } } return targetPinType; }
Source:
<code>public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { switch (localName) { case COLOR_SETTINGS_TAG: colorSettings = new ArrayList<>(); break; case COLOR_SETTING_TAG: fg = null; bg = null; tickColor = null; filter = null; break; case FG_TAG: fg = getRGBfromAttributes(attributes); break; case BG_TAG: bg = getRGBfromAttributes(attributes); break; case TICK_TAG: tickColor = getRGBfromAttributes(attributes); break; default: if (filterContentHandler != null) { filterContentHandler.startElement(uri, localName, qName, attributes); } break; case <START> FILTER_TAG: <END> filterContentHandler = new TmfFilterContentHandler(); break; } }</code><technical_language>why</technical_language>

Target:
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { switch (localName) { case COLOR_SETTINGS_TAG: colorSettings = new ArrayList<>(); break; case COLOR_SETTING_TAG: fg = null; bg = null; tickColor = null; filter = null; break; case FG_TAG: fg = getRGBfromAttributes(attributes); break; case BG_TAG: bg = getRGBfromAttributes(attributes); break; case TICK_TAG: tickColor = getRGBfromAttributes(attributes); break; case FILTER_TAG: filterContentHandler = new TmfFilterContentHandler(); break; default: if (filterContentHandler != null) { filterContentHandler.startElement(uri, localName, qName, attributes); } } }
Source:
<code>public void invalidateOutputContent() { <START> Optional<String> text = block.getOutputAnchor().getStringType(); <END> if (text.isPresent()) { rightArgument.setText(text.get()); } }</code><technical_language>rewrite this ifPresent</technical_language>

Target:
public void invalidateOutputContent() { Optional<String> text = block.getOutputAnchor().getStringType(); text.ifPresent(a -> rightArgument.setText(a)); }
Source:
<code>public void testSslNoClientAuthenticationJks() { SslConfiguration serverConfig = SslConfiguration.builder() .trustStorePath(TestConstants.CA_TRUST_STORE_PATH) .keyStorePath(TestConstants.SERVER_KEY_STORE_JKS_PATH) .keyStorePassword(TestConstants.SERVER_KEY_STORE_JKS_PASSWORD) .build(); SslConfiguration clientConfig = SslConfiguration.builder() .trustStorePath(TestConstants.CA_TRUST_STORE_PATH) .build(); <START> runSslConnectionTest(serverConfig, clientConfig, false); <END> }</code><technical_language>nit: instead of boolean here, enum (would test clearer) methods runSslConnectionTestWithoutClientAuth, etc</technical_language>

Target:
public void testSslNoClientAuthenticationJks() { TrustStoreConfiguration serverTrustStoreConfig = TrustStoreConfiguration.of(TestConstants.CA_TRUST_STORE_PATH); KeyStoreConfiguration serverKeyStoreConfig = KeyStoreConfiguration.of( TestConstants.SERVER_KEY_STORE_JKS_PATH, TestConstants.SERVER_KEY_STORE_JKS_PASSWORD); SslConfiguration serverConfig = SslConfiguration.of(serverTrustStoreConfig, serverKeyStoreConfig); TrustStoreConfiguration clientTrustStoreConfig = TrustStoreConfiguration.of(TestConstants.CA_TRUST_STORE_PATH); SslConfiguration clientConfig = SslConfiguration.of(clientTrustStoreConfig); runSslConnectionTest(serverConfig, clientConfig, ClientAuth.NO_CLIENT_AUTH); }
Source:
<code>private LettucePoolingClientConfiguration buildLettuceClientConfiguration() { final LettucePoolingClientConfigurationBuilder builder = LettucePoolingClientConfiguration.builder(); <START> builder.commandTimeout(Duration.ofMillis(readPropertyValue(propertyPrefix + "timeout", int.class, 1000))); <END> if (readPropertyValue(propertyPrefix + "ssl", boolean.class, false)) { builder.useSsl(); } int poolMax = readPropertyValue(propertyPrefix + "pool.max", int.class, 256); GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); poolConfig.setMaxTotal(poolMax); poolConfig.setBlockWhenExhausted(false); builder.poolConfig(poolConfig); return builder.build(); }</code><technical_language>Previous version of timeout -1. impact for current user this -1 default part of gravitee.yml</technical_language>

Target:
private LettucePoolingClientConfiguration buildLettuceClientConfiguration() { final LettucePoolingClientConfigurationBuilder builder = LettucePoolingClientConfiguration.builder(); int timeout = readPropertyValue(propertyPrefix + "timeout", int.class, DEFAULT_COMMAND_TIMEOUT); if (timeout < 0) { timeout = DEFAULT_COMMAND_TIMEOUT; } builder.commandTimeout(Duration.ofMillis(timeout)); if (readPropertyValue(propertyPrefix + "ssl", boolean.class, false)) { builder.useSsl(); } int poolMax = readPropertyValue(propertyPrefix + "pool.max", int.class, 256); GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); poolConfig.setMaxTotal(poolMax); poolConfig.setBlockWhenExhausted(false); builder.poolConfig(poolConfig); return builder.build(); }
Source:
<code>private void grow(int newCapacity) { if (newCapacity > array.length) { <START> int newLength = (int) Math.min(Math.max(2L * (long) array.length, (long) newCapacity), 2147483639L); <END> array = Arrays.copyOf(array, newLength); } }</code><technical_language>define a constant MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;</technical_language>

Target:
private void grow(int newCapacity) { if (array.length == MAX_ARRAY_SIZE) { throw new IllegalStateException("Array reached maximum size"); } if (newCapacity > array.length) { int newLength = (int) Math.min(Math.max(2L * (long) array.length, (long) newCapacity), MAX_ARRAY_SIZE); array = Arrays.copyOf(array, newLength); } }
Source:
<code>public void insertHeaderWithNullValue() { final Map<String, Object> props = new HashMap<>(); props.put("header", "AAA"); <START> props.put("literal.value", null); <END> xform.configure(props); final SourceRecord record = new SourceRecord(null, null, "test", 0, null, null, null, null, null, null); final SourceRecord transformedRecord = xform.apply(record); Headers expected = new ConnectHeaders().add("AAA", null); assertEquals(1, transformedRecord.headers().size()); assertEquals(expected, transformedRecord.headers()); }</code><technical_language>removing this line, default is null. define a property a null in a Java properties file, is default chosen a null value. This test verify literal.value is provided, a null header is used</technical_language>

Target:
public void insertHeaderWithNullValue() { final Map<String, Object> props = new HashMap<>(); props.put("header", "AAA"); xform.configure(props); final SourceRecord record = new SourceRecord(null, null, "test", 0, null, null, null, null, null, null); final SourceRecord transformedRecord = xform.apply(record); Headers expected = new ConnectHeaders().add("AAA", null); assertEquals(1, transformedRecord.headers().size()); assertEquals(expected, transformedRecord.headers()); }
Source:
<code>private <T> void addtoResultsWithNullCheck(Set<T> allResults, Collection<? extends T> configObjects) { if (configObjects.contains(null)) { <START> System.err.println("Null found in results."); <END> } else { allResults.addAll(configObjects); } }</code><technical_language>Consider error logging instead of println</technical_language>

Target:
private <T> void addtoResultsWithNullCheck(Set<T> allResults, Collection<? extends T> configObjects) { if (configObjects.contains(null)) { OseeLog.log(AbstractAtsConfigQueryImpl.class, Level.SEVERE, "Null found in results"); } else { allResults.addAll(configObjects); } }
Source:
<code>public final Github github() { <START> return null; <END> }</code><technical_language>throw UnsupportedOperationException a method is implemented</technical_language>

Target:
public final Github github() { throw new UnsupportedOperationException(); }
Source:
<code><START> public Map<String, Set<String>> listPortNames(Archive archive) { <END> try (URLClassLoader moduleClassLoader = new BootClassLoaderFactory(archive, parent).createClassLoader()) { ResourcePatternResolver moduleResourceLoader = new PathMatchingResourcePatternResolver(moduleClassLoader); Set<String> inboundPorts = new HashSet<>(); Set<String> outboundPorts = new HashSet<>(); Map<String, Set<String>> portsMap = new HashMap<>(); Resource[] whitelistLegacyDescriptors = moduleResourceLoader.getResources(WHITELIST_LEGACY_PROPERTIES); Resource[] whitelistDescriptors = moduleResourceLoader.getResources(WHITELIST_PROPERTIES); for (Resource resource : concatArrays(whitelistLegacyDescriptors, whitelistDescriptors)) { Properties properties = new Properties(); properties.load(resource.getInputStream()); inboundPorts.addAll(Arrays.asList(StringUtils .delimitedListToStringArray(properties.getProperty(CONFIGURATION_PROPERTIES_INBOUND_PORTS), ",", " "))); portsMap.put("inbound", inboundPorts); outboundPorts.addAll(Arrays.asList(StringUtils .delimitedListToStringArray(properties.getProperty(CONFIGURATION_PROPERTIES_OUTBOUND_PORTS), ",", " "))); portsMap.put("outbound", outboundPorts); } return portsMap; } catch (Exception e) { throw new RuntimeException("Exception trying to list configuration properties for application " + archive, e); } }</code><technical_language>private protected resolvePortNamesFromContainerImage is private</technical_language>

Target:
private Map<String, Set<String>> listPortNames(Archive archive) { try (URLClassLoader moduleClassLoader = new BootClassLoaderFactory(archive, parent).createClassLoader()) { ResourcePatternResolver moduleResourceLoader = new PathMatchingResourcePatternResolver(moduleClassLoader); Set<String> inboundPorts = new HashSet<>(); Set<String> outboundPorts = new HashSet<>(); Map<String, Set<String>> portsMap = new HashMap<>(); Resource[] whitelistLegacyDescriptors = moduleResourceLoader.getResources(WHITELIST_LEGACY_PROPERTIES); Resource[] whitelistDescriptors = moduleResourceLoader.getResources(WHITELIST_PROPERTIES); for (Resource resource : concatArrays(whitelistLegacyDescriptors, whitelistDescriptors)) { Properties properties = new Properties(); properties.load(resource.getInputStream()); inboundPorts.addAll(Arrays.asList(StringUtils .delimitedListToStringArray(properties.getProperty(CONFIGURATION_PROPERTIES_INBOUND_PORTS), ",", " "))); portsMap.put("inbound", inboundPorts); outboundPorts.addAll(Arrays.asList(StringUtils .delimitedListToStringArray(properties.getProperty(CONFIGURATION_PROPERTIES_OUTBOUND_PORTS), ",", " "))); portsMap.put("outbound", outboundPorts); } return portsMap; } catch (Exception e) { throw new AppMetadataResolutionException("Exception trying to list configuration properties for application " + archive, e); } }
Source:
<code>public <T> ReportedConfigurations add(ReportedConfigurationType type, T actual, T expected, boolean inSync) { <START> String actualValue = actual != null ? actual.toString() : "null"; <END> String expectedValue = expected != null ? expected.toString() : "null"; reportedConfigurationList.add(new ReportedConfiguration(type, actualValue, expectedValue, inSync)); return this; }</code><technical_language>replace this with: String.valueOf(actual);</technical_language>

Target:
public <T> ReportedConfigurations add(ReportedConfigurationType type, T actual, T expected, boolean inSync) { String actualValue = actual == null ? null : actual.toString(); String expectedValue = expected == null ? null : expected.toString(); reportedConfigurationList.add(new ReportedConfiguration(type, actualValue, expectedValue, inSync)); return this; }
Source:
<code>private void saveContributionsToDB(List<Contribution> contributions) { Timber.e("Fetched: "+contributions.size()+" contributions "+" saving to db"); <START> ExecutorUtils.get().submit(() -> repository.save(contributions)); <END> repository.set("last_fetch_timestamp",System.currentTimeMillis()); }</code><technical_language>this a Single too, a Completeable if care return ehich is void</technical_language>

Target:
private void saveContributionsToDB(List<Contribution> contributions) { Timber.e("Fetched: "+contributions.size()+" contributions "+" saving to db"); repository.save(contributions).subscribeOn(ioThreadScheduler).subscribe(); repository.set("last_fetch_timestamp",System.currentTimeMillis()); }
Source:
<code>private Element thr() { <START> return element(BlogConstants.BLOG_REPLY_TO,attribute(BlogNamespace.BLOG_REF.getPrefix(), BlogNamespace.BLOG_REF.getUrl() + entity.getPostUuid())); <END> }</code><technical_language>import static avoid BlogConstants</technical_language>

Target:
private Element thr() { return element(BlogConstants.BLOG_REPLY_TO,attribute(BlogConstants.BLOG_REF, BlogConstants.BLOG_REF_VALUE + entity.getPostUuid())); }
Source:
<code>public void setTitle(CharSequence text) { <START> if (title == null) { <END> mLateInit = true; mLateInitTitle = text; return; } title.setText(text); }</code><technical_language>if (title == null && text != null) (and similarly for setContent)</technical_language>

Target:
public void setTitle(CharSequence text) { if (text == null) { text = ""; } if (title == null) { return; } title.setText(text); }
Source:
<code>public void onFinishButtonClicked() { selected.put(page, view.getSelectedImport()); OrganizeImports organizeImports = dtoFactory.createDto(OrganizeImports.class); organizeImports.setResourceUri(file.getLocation().toString()); organizeImports.setChoices(new ArrayList<>(selected.values())); clientServerEventService .sendFileTrackingSuspendEvent() .then( successful -> { client .organizeImports(organizeImports) .then( result -> { <START> applyWorkspaceEditAction.applyWorkspaceEdit(result.getWorkspaceEdit()); <END> clientServerEventService.sendFileTrackingResumeEvent(); view.hide(); }) .catchError( error -> { String title = locale.failedToProcessOrganizeImports(); String message = error.getMessage(); notificationManager.notify(title, message, FAIL, FLOAT_MODE); clientServerEventService.sendFileTrackingResumeEvent(); view.hide(); }); }); }</code><technical_language>if this line wrong, file tracking is resumed</technical_language>

Target:
public void onFinishButtonClicked() { selected.put(page, view.getSelectedImport()); OrganizeImportParams organizeImports = dtoFactory.createDto(OrganizeImportParams.class); organizeImports.setResourceUri(file.getLocation().toString()); organizeImports.setChoices(new ArrayList<>(selected.values())); clientServerEventService .sendFileTrackingSuspendEvent() .then( successful -> { client .organizeImports(organizeImports) .then( result -> { try { applyWorkspaceEditAction.applyWorkspaceEdit(result.getWorkspaceEdit()); } finally { clientServerEventService.sendFileTrackingResumeEvent(); view.hide(); } }) .catchError( error -> { try { String title = locale.failedToProcessOrganizeImports(); String message = error.getMessage(); notificationManager.notify(title, message, FAIL, FLOAT_MODE); } finally { clientServerEventService.sendFileTrackingResumeEvent(); view.hide(); } }); }); }
Source:
<code>public float getProgress() throws IOException, InterruptedException { if (recordReadersCount < 1) { return 1.0f; } return ((float) currentRecordReader.getProgress() / (float) recordReadersCount) <START> + ((float) currentRecordReaderIndex / (float) recordReadersCount); <END> }</code><technical_language>idea: weight this size reported split</technical_language>

Target:
public float getProgress() throws IOException, InterruptedException { if (recordReadersCount < 1) { return 1.0f; } return (currentRecordReader.getProgress() / splitLengths[currentRecordReaderIndex]) + (cumulativeSplitLengths[currentRecordReaderIndex] / totalSplitLengths); }
Source:
<code>public void onFinish(final ISuite suite) { if (!DRY_RUN_ENABLED) { return; } final String[] sortedTests = observedTests.toArray(new String[0]); Arrays.sort(sortedTests); <START> LOG.info("DRY-RUN: Listing ["+ sortedTests.length +"] tests that would have run"); <END> for (final String testNameAndParams : sortedTests) { LOG.info(testNameAndParams); } }</code><technical_language>Please [slf4j interpolation](<LINK_0> embedding variables log messages</technical_language>

Target:
public void onFinish(final ISuite suite) { if (!DRY_RUN_ENABLED) { return; } if (LOG.isInfoEnabled()) { LOG.info("DRY-RUN: Listing tests that would have run", observedTests.size()); try (Stream<String> stream = observedTests.stream()) { stream.sorted().forEach(LOG::info); } } }
Source:
<code>void onAdd(ClickEvent e) { String hashtag = hashtagTextBox.getText(); <START> while (hashtag.startsWith("#")) { <END> hashtag = hashtag.substring(1); } if (!hashtag.isEmpty()) { addHashtag(hashtag); } }</code><technical_language>If string retrieved hashtagTextBox is "#test1,#test2", remove hashtag hashtag. do check in RESTApi instead</technical_language>

Target:
void onAdd(ClickEvent e) { String hashtag = hashtagTextBox.getText(); if (!hashtag.isEmpty()) { addHashtag(hashtag); } }
Source:
<code>public void destroy() { executor.shutdown(); try { if (!executor.awaitTermination(SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS)) { executor.shutdownNow(); if (!executor.awaitTermination(SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS)) { <START> LOGGER.error("Thread pool didn't terminate"); <END> } } } catch (InterruptedException e) { executor.shutdownNow(); Thread.currentThread().interrupt(); } }</code><technical_language>this logged a level instead? helpful add a message telling a system admin consequences recover? <LINK_0></technical_language>

Target:
public void destroy() { executor.shutdown(); try { if (!executor.awaitTermination(SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS)) { executor.shutdownNow(); if (!executor.awaitTermination(SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS)) { LOGGER.error( "Identity node initialization thread didn't terminate. This thread will continue until a system restart."); } } } catch (InterruptedException e) { executor.shutdownNow(); Thread.currentThread().interrupt(); } }
Source:
<code>public String getDefinitionSetId() { <START> return BPMNDefinitionSet.class.getName(); <END> }</code><technical_language>minor please BindableAdapterUtils.getDefinitionSetId for this, if some point change generate ids... easier. thx</technical_language>

Target:
public String getDefinitionSetId() { return BindableAdapterUtils.getDefinitionSetId(BPMNDefinitionSet.class); }
Source:
<code>public void testDefaultName() throws IOException { when(event.getThrowableProxy()).thenReturn(throwableProxy); when(throwableProxy.getThrowable()).thenReturn(new Exception("test error")); provider.writeTo(generator, event); <START> verify(generator).writeStringField(eq(StackHashJsonProvider.FIELD_NAME), anyString()); <END> }</code><technical_language>verify arg parsed a hex integer</technical_language>

Target:
public void testDefaultName() throws IOException { when(event.getThrowableProxy()).thenReturn(throwableProxy); when(throwableProxy.getThrowable()).thenReturn(new Exception("test error")); provider.writeTo(generator, event); ArgumentCaptor<String> hashCaptor = ArgumentCaptor.forClass(String.class); verify(generator).writeStringField(eq(StackHashJsonProvider.FIELD_NAME), hashCaptor.capture()); Assert.assertTrue("Did not produce an hexadecimal integer: "+hashCaptor.getValue(), HEX_PATTERN.matcher(hashCaptor.getValue()).matches()); }