auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private Optional<SnomedConceptIndexEntry> getCandidate(final Collection<SnomedConceptIndexEntry> candidates, final int rowIndex) { if (StringUtils.isEmpty(topLevelConceptId)) { <START> return FluentIterable.from(candidates).first(); <END> } return FluentIterable.from(candidates).firstMatch(new Predicate<SnomedConceptIndexEntry>() { @Override public boolean apply(final SnomedConceptIndexEntry input) { return isValidCandidate(input, rowIndex); } }); }</code><technical_language>updating search request, this method reduced this single line</technical_language>

Target:
protected Optional<SnomedConceptIndexEntry> getCandidate(final Collection<SnomedConceptIndexEntry> candidates, final int rowIndex) { return FluentIterable.from(candidates).first(); }
Source:
<code>public static ImmutableList<Ds3Request> splitAllMultiResponseRequests( final ImmutableList<Ds3Request> ds3Requests) { if (isEmpty(ds3Requests)) { <START> LOG.info("No requests"); <END> return ImmutableList.of(); } final ImmutableList.Builder<Ds3Request> builder = ImmutableList.builder(); for (final Ds3Request ds3Request : ds3Requests) { builder.addAll(splitMultiResponseRequest(ds3Request)); } return builder.build(); }</code><technical_language>Change this "No requests split" differentiate error message some of others</technical_language>

Target:
public static ImmutableList<Ds3Request> splitAllMultiResponseRequests( final ImmutableList<Ds3Request> ds3Requests) throws ResponseTypeNotFoundException { if (isEmpty(ds3Requests)) { LOG.info("No requests to split"); return ImmutableList.of(); } final ImmutableList.Builder<Ds3Request> builder = ImmutableList.builder(); for (final Ds3Request ds3Request : ds3Requests) { builder.addAll(splitMultiResponseRequest(ds3Request)); } return builder.build(); }
Source:
<code>private static DetailAST getNodeWithParentScope(int literal, String scope, int parentTokenType) { <START> final DetailAST ast1 = new DetailAST(); <END> ast1.setType(parentTokenType); final DetailAST ast2 = new DetailAST(); ast2.setType(TokenTypes.MODIFIERS); final DetailAST ast3 = new DetailAST(); ast3.setType(literal); ast3.setText(scope); ast2.setFirstChild(ast3); ast1.setFirstChild(ast2); final DetailAST ast = new DetailAST(); ast.setType(TokenTypes.OBJBLOCK); ast1.addChild(ast); return ast; }</code><technical_language>In other test, name variables ast, ast2, etc. put in order of variable names. This is breaks pattern. layout similar</technical_language>

Target:
private static DetailAST getNodeWithParentScope(int literal, String scope, int parentTokenType) { final DetailAST ast = getNode(parentTokenType, TokenTypes.MODIFIERS, literal); ast.setText(scope); final DetailAST ast2 = getNode(TokenTypes.OBJBLOCK); ast.getParent().getParent().addChild(ast2); return ast; }
Source:
<code>public void deregisterInvertingProxyAgent(String ccmV2AgentCrn) { if (ccmV2AgentCrn != null) { <START> String requestId = Optional.ofNullable(MDCBuilder.getMdcContextMap() .get(LoggerContextKey.REQUEST_ID.toString())).orElse(UUID.randomUUID().toString()); MDCBuilder.addRequestId(requestId); <END> ccmV2Client.deregisterInvertingProxyAgent(requestId, ccmV2AgentCrn); } else { LOGGER.info("Cluster ccmV2AgentCrn is not initialized, nothing to unregister."); } }</code><technical_language>this a duplication of code in DefaultCcmV2ParameterSupplier. I this moved MDCBuilder</technical_language>

Target:
public void deregisterInvertingProxyAgent(String ccmV2AgentCrn) { if (ccmV2AgentCrn != null) { ccmV2Client.deregisterInvertingProxyAgent(MDCBuilder.getOrGenerateRequestId(), ccmV2AgentCrn); } else { LOGGER.info("Cluster ccmV2AgentCrn is not initialized, nothing to unregister."); } }
Source:
<code>public static GridCoverage2D createCoverageTypeDouble( final String coverageName, final double westLon, final double eastLon, final double southLat, final double northLat, final double[] minPerBand, final double[] maxPerBand, final String[] namePerBand, final WritableRaster raster, final String crsCode ) { final GridCoverageFactory gcf = CoverageFactoryFinder.getGridCoverageFactory(null); Envelope mapExtent; CoordinateReferenceSystem crs = null; <START> if (crsCode.equals(GeometryUtils.DEFAULT_CRS_STR)) { <END> crs = GeometryUtils.DEFAULT_CRS; } else { try { crs = CRS.decode(crsCode); } catch (FactoryException e) { LOGGER.error( "Unable to decode " + crsCode + " CRS", e); throw new RuntimeException( "Unable to initialize " + crsCode + " object", e); } } try { mapExtent = new ReferencedEnvelope( westLon, eastLon, southLat, northLat, crs); } catch (final IllegalArgumentException e) { LOGGER.warn( "Unable to use default CRS", e); mapExtent = new Envelope2D( new DirectPosition2D( westLon, southLat), new DirectPosition2D( eastLon, northLat)); } final GridSampleDimension[] bands = new GridSampleDimension[raster.getNumBands()]; create( namePerBand, raster.getSampleModel(), minPerBand, maxPerBand, bands); return gcf.create( coverageName, raster, mapExtent, bands); }</code><technical_language>check for null || empty || crsCode equals default</technical_language>

Target:
public static GridCoverage2D createCoverageTypeDouble( final String coverageName, final double westLon, final double eastLon, final double southLat, final double northLat, final double[] minPerBand, final double[] maxPerBand, final String[] namePerBand, final WritableRaster raster, final String crsCode ) { final GridCoverageFactory gcf = CoverageFactoryFinder.getGridCoverageFactory(null); Envelope mapExtent; CoordinateReferenceSystem crs = null; if (crsCode == null || crsCode.isEmpty() || crsCode.equals(GeometryUtils.DEFAULT_CRS_STR)) { crs = GeometryUtils.DEFAULT_CRS; } else { try { crs = CRS.decode(crsCode); } catch (FactoryException e) { LOGGER.error( "Unable to decode " + crsCode + " CRS", e); throw new RuntimeException( "Unable to initialize " + crsCode + " object", e); } } try { mapExtent = new ReferencedEnvelope( westLon, eastLon, southLat, northLat, crs); } catch (final IllegalArgumentException e) { LOGGER.warn( "Unable to use default CRS", e); mapExtent = new Envelope2D( new DirectPosition2D( westLon, southLat), new DirectPosition2D( eastLon, northLat)); } final GridSampleDimension[] bands = new GridSampleDimension[raster.getNumBands()]; create( namePerBand, raster.getSampleModel(), minPerBand, maxPerBand, bands); return gcf.create( coverageName, raster, mapExtent, bands); }
Source:
<code>private Span getSpan(TransactionBase tx, final String childId, final VisibilityBindingSet childBindingSet, final String siblingId) { final VariableOrder childVarOrder = getVarOrder(tx, childId); final VariableOrder siblingVarOrder = getVarOrder(tx, siblingId); final List<String> commonVars = getCommonVars(childVarOrder, siblingVarOrder); <START> Bytes scanPrefix = null; <END> if(!commonVars.isEmpty()) { scanPrefix = getRowKey(siblingId, new VariableOrder(commonVars), childBindingSet); } else { scanPrefix = getRowKey(siblingId, siblingVarOrder, childBindingSet); } return Span.prefix(scanPrefix); }</code><technical_language>call this siblingScanPrefix</technical_language>

Target:
private Span getSpan(TransactionBase tx, final String childId, final VisibilityBindingSet childBindingSet, final String siblingId) { final VariableOrder childVarOrder = getVarOrder(tx, childId); final VariableOrder siblingVarOrder = getVarOrder(tx, siblingId); final List<String> commonVars = getCommonVars(childVarOrder, siblingVarOrder); Bytes siblingScanPrefix = null; if(!commonVars.isEmpty()) { siblingScanPrefix = makeRowKey(siblingId, new VariableOrder(commonVars), childBindingSet); } else { siblingScanPrefix = makeRowKey(siblingId, siblingVarOrder, childBindingSet); } return Span.prefix(siblingScanPrefix); }
Source:
<code>public void logPriorTest() { final double[] weights = MathUtils.normalizeFromRealSpace(new double[] {0.2, 0.2, 0.6, 0.1, 0.9, 0.1}); final double[] minorAlleleFractions = new double[] {0.1, 0.2, 0.3, 0.4, 0.5, 0.33}; final double memoryLength = 5e6; AlleleFractionHiddenMarkovModel model = new AlleleFractionHiddenMarkovModel(minorAlleleFractions, weights, memoryLength, AllelicPanelOfNormals.EMPTY_PON, NO_BIAS_OR_OUTLIERS_PARAMS); final SimpleInterval position1 = new SimpleInterval("chr1", 100, 100); final SimpleInterval position2 = new SimpleInterval("chr2", 20000, 20000); for (int n = 0; n < weights.length; n++) { Assert.assertEquals(model.logPriorProbability(n, position1), Math.log(weights[n])); Assert.assertEquals(model.logPriorProbability(n, position2), Math.log(weights[n])); } <START> <END> }</code><technical_language>white space</technical_language>

Target:
public void logPriorTest() { final double[] weights = MathUtils.normalizeFromRealSpace(new double[] {0.2, 0.2, 0.6, 0.1, 0.9, 0.1}); final double[] minorAlleleFractions = new double[] {0.1, 0.2, 0.3, 0.4, 0.5, 0.33}; final double memoryLength = 5e6; final AlleleFractionHiddenMarkovModel model = new AlleleFractionHiddenMarkovModel(minorAlleleFractions, weights, memoryLength, AllelicPanelOfNormals.EMPTY_PON, NO_BIAS_OR_OUTLIERS_PARAMS); final SimpleInterval position1 = new SimpleInterval("chr1", 100, 100); final SimpleInterval position2 = new SimpleInterval("chr2", 20000, 20000); for (int n = 0; n < weights.length; n++) { Assert.assertEquals(model.logPriorProbability(n, position1), Math.log(weights[n])); Assert.assertEquals(model.logPriorProbability(n, position2), Math.log(weights[n])); } }
Source:
<code>public void handleDefaultDeviceResponse(final String deviceIdentification, final String organisationIdentification, final String correlationUid, final String messageType, final ResponseMessageResultType deviceResult, final OsgpException exception) { LOGGER.info("handleDefaultDeviceResponse for MessageType: {}", messageType); ResponseMessageResultType result = ResponseMessageResultType.OK; OsgpException osgpException = exception; try { if (deviceResult == ResponseMessageResultType.NOT_OK || osgpException != null) { LOGGER.error("Device Response not ok.", osgpException); throw osgpException; } } catch (final Exception e) { LOGGER.error("Unexpected Exception", e); result = ResponseMessageResultType.NOT_OK; <START> if (e instanceof OsgpException) { <END> osgpException = (OsgpException) e; } else { osgpException = new TechnicalException(ComponentType.UNKNOWN, "An unknown error occurred", e); } } this.webServiceResponseMessageSender.send(new ResponseMessage(correlationUid, organisationIdentification, deviceIdentification, result, osgpException, null)); }</code><technical_language>fix this sonar issue</technical_language>

Target:
public void handleDefaultDeviceResponse(final String deviceIdentification, final String organisationIdentification, final String correlationUid, final String messageType, final ResponseMessageResultType deviceResult, final OsgpException exception) { LOGGER.info("handleDefaultDeviceResponse for MessageType: {}", messageType); ResponseMessageResultType result = deviceResult; OsgpException osgpException = exception; if (deviceResult == ResponseMessageResultType.NOT_OK && exception == null) { LOGGER.error("Incorrect response received, exception should not be null when result is not ok"); osgpException = new TechnicalException(ComponentType.DOMAIN_TARIFF_SWITCHING, "An unknown error occurred"); } if (deviceResult == ResponseMessageResultType.OK && exception != null) { LOGGER.error("Incorrect response received, result should be set to not ok when exception is not null"); result = ResponseMessageResultType.NOT_OK; } this.webServiceResponseMessageSender.send(new ResponseMessage(correlationUid, organisationIdentification, deviceIdentification, result, osgpException, null)); }
Source:
<code>public static void showMyProfileDialog(Context context, String title, String initialText, String hint, final Callback callback) { LayoutInflater layoutInflater = LayoutInflater.from(context); View promptView = layoutInflater.inflate(org.wordpress.android.R.layout.my_profile_dialog, null); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setView(promptView); final WPTextView textView = (WPTextView) promptView.findViewById(org.wordpress.android.R.id.my_profile_dialog_label); final OpenSansEditText editText = (OpenSansEditText) promptView.findViewById(org.wordpress.android.R.id.my_profile_dialog_input); final WPTextView hintView = (WPTextView) promptView.findViewById(org.wordpress.android.R.id.my_profile_dialog_hint); textView.setText(title); if (hint != null && !hint.isEmpty()) { hintView.setText(hint); } else { hintView.setVisibility(View.GONE); } if (initialText != null && !initialText.isEmpty()) { editText.setText(initialText); editText.setSelection(0, initialText.length()); } <START> alertDialogBuilder.setCancelable(false) <END> .setPositiveButton(org.wordpress.android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { callback.onSuccessfulInput(editText.getText().toString()); } }) .setNegativeButton(org.wordpress.android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = alertDialogBuilder.create(); alert.show(); }</code><technical_language>Minor nit, feel free ignore: I prefer setCancelable(true) hit button leave dialog</technical_language>

Target:
public static void showMyProfileDialog(Context context, String title, String initialText, String hint, final Callback callback) { LayoutInflater layoutInflater = LayoutInflater.from(context); View promptView = layoutInflater.inflate(R.layout.my_profile_dialog, null); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setView(promptView); final WPTextView textView = (WPTextView) promptView.findViewById(R.id.my_profile_dialog_label); final OpenSansEditText editText = (OpenSansEditText) promptView.findViewById(R.id.my_profile_dialog_input); final WPTextView hintView = (WPTextView) promptView.findViewById(R.id.my_profile_dialog_hint); textView.setText(title); if (!TextUtils.isEmpty(hint)) { hintView.setText(hint); } else { hintView.setVisibility(View.GONE); } if (!TextUtils.isEmpty(initialText)) { editText.setText(initialText); editText.setSelection(0, initialText.length()); } alertDialogBuilder.setCancelable(true) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { callback.onSuccessfulInput(editText.getText().toString()); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = alertDialogBuilder.create(); alert.show(); }
Source:
<code>public List<Unit> getOffensiveAa() { <START> updateOffensiveAaUnits(); <END> return offensiveAa; }</code><technical_language>This side effect is striking getter methods tend mutate state. surprising if caller this class, add another caller calls getOffensiveAa *that* change state in a caller expecting. Making side-effect of setting of offensiveAa generally helps. IE: offensiveAa = computeRemainingOffensiveAaUnits(); return offensiveAa; is odd though, if instead this problem solved removing side effects instead calling method computeRemainingOffensiveAaUnits(). In case, place call getter need side effects, call method instead. this lead offensiveAa variable longer needed all. thoughts</technical_language>

Target:
public List<Unit> getOffensiveAa() { return offensiveAa; }
Source:
<code>public static Transition transitionOf(final char ref, final char call) { <START> return transitionIndexMap[baseIndexOf(ref, () -> "ref")][baseIndexOf(call, () -> "call")]; <END> }</code><technical_language>while this is nice, I efficiency of original implementation (two function calls). simply wrap original transitionIndexMap[baseIndexMap[ref]][baseIndexMap[call]]; expression a try-catch? I realize error message suffer a that...but OK</technical_language>

Target:
public static Transition transitionOf(final char ref, final char call) { try { return transitionIndexMap[baseIndexMap[ref]][baseIndexMap[call]]; } catch (IndexOutOfBoundsException e) { throw new IllegalArgumentException(String.format("Base params should be one of {A, C, T, G} but ref=%s and call=%s", ref, call)); } }
Source:
<code>protected Response registerForCallUpdates(final String accountSid, final String callSid, final MultivaluedMap<String, String> data, MediaType responseType) { <START> secure(daos.getAccountsDao().getAccount(accountSid), "RestComm:Read:Calls"); <END> allowOnlySuperAdmin(); final String url = data.getFirst("Url"); final String refresh = data.getFirst("Refresh"); MonitoringServiceResponse liveCalls; try { final Timeout expires = new Timeout(Duration.create(60, TimeUnit.SECONDS)); GetLiveCalls getLiveCalls = new GetLiveCalls(); Future<Object> future = (Future<Object>) ask(monitoringService, getLiveCalls, expires); liveCalls = (MonitoringServiceResponse) Await.result(future, Duration.create(10, TimeUnit.SECONDS)); } catch (Exception exception) { return status(BAD_REQUEST).entity(exception.getMessage()).build(); } if (liveCalls != null) { if (APPLICATION_XML_TYPE == responseType) { final RestCommResponse response = new RestCommResponse(liveCalls); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE == responseType) { Response response = ok(gson.toJson(liveCalls), APPLICATION_JSON).build(); return response; } else { return null; } } else { return null; } }</code><technical_language>@maria-farooq Hmm, this line: > secure(daos.getAccountsDao().getAccount(accountSid), "RestComm:Read:Calls"); checks following: 1. User authenticated 2. Authenticated account is parent of accountSid 3. Authenticated account "Restcomm:Read:Calls" permission (as determined role) Then, check if this user is a SuperAdmin (i.e. top-level account). This means if a SuperAdmin "Restcomm:Read:Calls" granted access. Also, if is another top-level account is parent (or grant-parent) of "accountSid" granted access either. Is this ok ? accept a SuperAdmin absolute powers instance assets rephrase code as: // secure() checkAuthenticatedAccount(); allowOnlySuperAdmin(); suggesting, wondering..</technical_language>

Target:
protected Response registerForCallUpdates(final String accountSid, final String callSid, final MultivaluedMap<String, String> data, MediaType responseType) { checkAuthenticatedAccount(); allowOnlySuperAdmin(); final String url = data.getFirst("Url"); final String refresh = data.getFirst("Refresh"); MonitoringServiceResponse liveCalls; try { final Timeout expires = new Timeout(Duration.create(60, TimeUnit.SECONDS)); GetLiveCalls getLiveCalls = new GetLiveCalls(); Future<Object> future = (Future<Object>) ask(monitoringService, getLiveCalls, expires); liveCalls = (MonitoringServiceResponse) Await.result(future, Duration.create(10, TimeUnit.SECONDS)); } catch (Exception exception) { return status(BAD_REQUEST).entity(exception.getMessage()).build(); } if (liveCalls != null) { if (APPLICATION_XML_TYPE == responseType) { final RestCommResponse response = new RestCommResponse(liveCalls); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE == responseType) { Response response = ok(gson.toJson(liveCalls), APPLICATION_JSON).build(); return response; } else { return null; } } else { return null; } }
Source:
<code>public WorkerThread(final ConcurrentMap<K, PullFuture<V>> pendingPulls, final ServerResolver serverResolver, final InjectionFuture<WorkerMsgSender<K, P>> sender, final int queueSize, final long expireTimeout) { kvCache = CacheBuilder.newBuilder() .concurrencyLevel(1) .expireAfterWrite(expireTimeout, TimeUnit.MILLISECONDS) .build(new CacheLoader<EncodedKey<K>, Wrapped<V>>() { private static final long RETRY_INTERVAL_MS = 5000; @Override public Wrapped<V> load(final EncodedKey<K> encodedKey) { final PullFuture<V> future = new PullFuture<>(); pendingPulls.put(encodedKey.getKey(), future); V value = null; while (value == null) { final String serverId = serverResolver.resolveServer(encodedKey.getHash()); LOG.log(Level.FINEST, "Resolve server for encodedKey. key: {0}, hash: {1}", new Object[]{encodedKey.getKey(), encodedKey.getHash()}); try { sender.get().sendPullMsg(serverId, encodedKey); } catch (final NetworkException e) { LOG.log(Level.FINE, "NetworkException while sending pull msg. Do retry", e); continue; } <START> value = future.getValue(RETRY_INTERVAL_MS); END> } pendingPulls.remove(encodedKey.getKey()); return new Wrapped<>(value); } }); queue = new ArrayBlockingQueue<>(queueSize); this.drainSize = queueSize / 10; this.localOps = new ArrayList<>(drainSize); }</code><technical_language>do retry if fails</technical_language>

Target:
public WorkerThread(final ConcurrentMap<K, PullFuture<V>> pendingPulls, final ServerResolver serverResolver, final InjectionFuture<WorkerMsgSender<K, P>> sender, final int queueSize, final long expireTimeout) { kvCache = CacheBuilder.newBuilder() .concurrencyLevel(1) .expireAfterWrite(expireTimeout, TimeUnit.MILLISECONDS) .build(new CacheLoader<EncodedKey<K>, Wrapped<V>>() { private static final long RETRY_INTERVAL_MS = 5000; @Override public Wrapped<V> load(final EncodedKey<K> encodedKey) { final PullFuture<V> future = new PullFuture<>(); pendingPulls.put(encodedKey.getKey(), future); V value = null; int retryCount = 0; while (value == null) { if (++retryCount > MAX_RETRY_COUNT) { throw new RuntimeException("Fail to load a value for pull"); } final String serverId = serverResolver.resolveServer(encodedKey.getHash()); LOG.log(Level.FINEST, "Resolve server for encodedKey. key: {0}, hash: {1}", new Object[]{encodedKey.getKey(), encodedKey.getHash()}); try { sender.get().sendPullMsg(serverId, encodedKey); } catch (final NetworkException e) { LOG.log(Level.FINE, "NetworkException while sending pull msg. Do retry", e); continue; } value = future.getValue(RETRY_INTERVAL_MS); } pendingPulls.remove(encodedKey.getKey()); return new Wrapped<>(value); } }); queue = new ArrayBlockingQueue<>(queueSize); this.drainSize = queueSize / 10; this.localOps = new ArrayList<>(drainSize); }
Source:
<code>void generateComposite(JsonObject graphConfig, JsonObject graph, StringBuilder compBuilder) throws IOException { boolean isPublic = jboolean(graph, "public"); String kind = jstring(graph, KIND); kind = getSPLCompatibleName(kind); if (isPublic) compBuilder.append("public "); compBuilder.append("composite "); compBuilder.append(kind); <START> if (kind.startsWith("Composite")) { <END> JsonArray inputNames = array(graph, "inputNames"); JsonArray outputNames = array(graph, "outputNames"); compBuilder.append("("); if(inputNames!= null && inputNames.size() > 0){ compBuilder.append("input "); boolean first = true; for(JsonElement inputName : inputNames){ if(!first) compBuilder.append(","); String strInputName = getSPLCompatibleName(inputName.getAsString()); compBuilder.append(strInputName); first = false; } } if(outputNames!= null && outputNames.size() > 0){ if(inputNames!= null && inputNames.size() > 0) compBuilder.append(";"); compBuilder.append("output "); boolean first = true; for(JsonElement outputName : outputNames){ if(!first) compBuilder.append(","); String strOutputName = getSPLCompatibleName(outputName.getAsString()); compBuilder.append(strOutputName); first = false; } } compBuilder.append(")"); } compBuilder.append("\n{\n"); generateCompParams(graph, compBuilder); compBuilder.append("graph\n"); operators(graphConfig, graph, compBuilder); generateCompConfig(graph, graphConfig, compBuilder); compBuilder.append("}\n"); }</code><technical_language>Hmm, a name is a valid operator kind name? Ie. a customer in theory a valid primitive SPL composite called 'Composite'. '$Composite' in a static field a constant</technical_language>

Target:
void generateComposite(JsonObject graphConfig, JsonObject graph, StringBuilder compBuilder) throws IOException { boolean isPublic = jboolean(graph, "public"); String kind = jstring(graph, KIND); kind = getSPLCompatibleName(kind); if (isPublic) compBuilder.append("public "); compBuilder.append("composite "); compBuilder.append(kind); if (jboolean(graph, "generated")) { JsonArray inputNames = array(graph, "inputNames"); JsonArray outputNames = array(graph, "outputNames"); compBuilder.append("("); if(inputNames!= null && inputNames.size() > 0){ compBuilder.append("input "); boolean first = true; for(JsonElement inputName : inputNames){ if(!first) compBuilder.append(","); String strInputName = getSPLCompatibleName(inputName.getAsString()); compBuilder.append(strInputName); first = false; } } if(outputNames!= null && outputNames.size() > 0){ if(inputNames!= null && inputNames.size() > 0) compBuilder.append(";"); compBuilder.append("output "); boolean first = true; for(JsonElement outputName : outputNames){ if(!first) compBuilder.append(","); String strOutputName = getSPLCompatibleName(outputName.getAsString()); compBuilder.append(strOutputName); first = false; } } compBuilder.append(")"); } compBuilder.append("\n{\n"); generateCompParams(graph, compBuilder); compBuilder.append("graph\n"); operators(graphConfig, graph, compBuilder); generateCompConfig(graph, graphConfig, compBuilder); compBuilder.append("}\n"); }
Source:
<code>ResponseEntity<?> changeCaptain(@AuthenticationPrincipal User user, @PathVariable Long teamID, @RequestBody String newCaptainEmail) { Team team = teamService.getTeamById(teamID); if (team.getCaptain().getEmail().equals(newCaptainEmail)) { return createResponseEntity(HttpStatus.NOT_MODIFIED, "This person is already the captain of the team."); } <START> if (!user.getRoles().contains(Role.ROLE_ADMIN) && !user.getEmail().equals(team.getCaptain().getEmail())) { <END> return createResponseEntity(HttpStatus.UNAUTHORIZED, "Only the captain of the team can assign a new captain."); } TeamDTO teamDTO = new TeamDTO(); teamDTO.setTeamName(team.getTeamName()); teamDTO.setCaptainEmail(newCaptainEmail); teamService.update(team.getId(), teamDTO); return createResponseEntity(HttpStatus.OK, "Captain of team " + team.getTeamName() + " successfully changed!"); }</code><technical_language>check if this is present in CurrentUserServiceImpl? Otherwise, consider implementing handle this in @PreAuthorize</technical_language>

Target:
ResponseEntity<?> changeCaptain(@AuthenticationPrincipal User user, @PathVariable Long teamID, @RequestBody String newCaptainEmail) { Team team = teamService.getTeamById(teamID); if (team.getCaptain().getEmail().equals(newCaptainEmail)) { return createResponseEntity(HttpStatus.NOT_MODIFIED, "This person is already the captain of the team."); } teamService.update(team.getId(), null, newCaptainEmail); return createResponseEntity(HttpStatus.OK, "Captain of team " + team.getTeamName() + " successfully changed!"); }
Source:
<code>public void setTimeStamp(String timeStamp) { <START> if (timeStamp != null && !timeStamp.isEmpty()) { <END> this.timeStamp = timeStamp; } else { DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Calendar cal = Calendar.getInstance(); this.timeStamp = dateFormat.format(cal.getTime()); } }</code><technical_language>Optional: Try StringUtil check</technical_language>

Target:
public void setTimeStamp(String timeStamp) { if (StringUtils.isNotEmpty(timeStamp)) { this.timeStamp = timeStamp; } else { this.timeStamp = new SimpleDateFormat(TIMESTAMP_FORMAT).format(Calendar.getInstance().getTime()); } }
Source:
<code>public void loadKeyDSAPassword() throws IOException, GeneralSecurityException { File file = new File(this.getClass().getResource("dsa-password").getFile()); String password = "password"; <START> assertkeyPair(file, password); <END> }</code><technical_language>suggestion assertKeyPair(file, password);</technical_language>

Target:
public void loadKeyDSAPassword() throws IOException, GeneralSecurityException { File file = new File(this.getClass().getResource("dsa-password").getFile()); String password = "password"; assertKeyPairNotNull(file, password); }
Source:
<code>public void scheduleTask(TaskDefinition task) throws SchedulerException { boolean contains = false; <START> for (String taskDef : scheduledTasks) { <END> if (taskDef.equals(task.getName())) { contains = true; break; } } if (!contains) { scheduledTasks.add(task.getName()); } }</code><technical_language>get rid of this class too?? this call? Context.getSchedulerService().scheduleTask(task)</technical_language>

Target:
public void scheduleTask(TaskDefinition task) throws SchedulerException { if (!scheduledTasks.contains(task)) { scheduledTasks.add(task); } }
Source:
<code>public void setOnLongClickListener(OnLongClickListener l) { <START> if (isSensorAvailable) { <END> binding.bearingButton.setOnLongClickListener(l); } binding.answerText.setOnLongClickListener(l); }</code><technical_language>Do need this check? I redundant</technical_language>

Target:
public void setOnLongClickListener(OnLongClickListener l) { binding.bearingButton.setOnLongClickListener(l); binding.answerText.setOnLongClickListener(l); }
Source:
<code>public String readFile(String repositoryId, String fileName, String reference) { checkNotNull(fileName, "The fileName given is null."); GHRepository repo; try { repo = github.getRepository(repositoryId); } catch (IOException e) { LOG.error(gitUsername + ": IOException on readFile while trying to get the repository " + repositoryId + " " + e.getMessage()); <START> throw new CustomWebApplicationException("Could not get repository " + repositoryId + " from GitHub.", HttpStatus.SC_BAD_REQUEST); <END> } return readFileFromRepo(fileName, reference, repo); }</code><technical_language>In past, this bring a refresh org refresh all. rid of those, *hopefully* matter</technical_language>

Target:
public String readFile(String repositoryId, String fileName, String reference) { checkNotNull(fileName, "The fileName given is null."); GHRepository repo; try { repo = github.getRepository(repositoryId); } catch (IOException e) { LOG.error(gitUsername + ": IOException on readFile while trying to get the repository " + repositoryId + " " + e.getMessage(), e); throw new CustomWebApplicationException("Could not get repository " + repositoryId + " from GitHub.", HttpStatus.SC_BAD_REQUEST); } return readFileFromRepo(fileName, reference, repo); }
Source:
<code>private void resetOnPageChangeListener() { if (mOnPageChangeListener != null) { mViewPager.removeOnPageChangeListener(mOnPageChangeListener); } else { mOnPageChangeListener = new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { AnalyticsTracker.track(AnalyticsTracker.Stat.NOTIFICATION_SWIPE_PAGE_CHANGED); <START> AppPrefs.setNotificationsSwipeToNavigateShown(true); <END> Note currentNote = mAdapter.getNoteAtPosition(position); if (currentNote != null) { setActionBarTitleForNote(currentNote); markNoteAsRead(currentNote); } } @Override public void onPageScrollStateChanged(int state) { } }; } mViewPager.addOnPageChangeListener(mOnPageChangeListener); }</code><technical_language>Is avoid this call swipe</technical_language>

Target:
private void resetOnPageChangeListener() { if (mOnPageChangeListener != null) { mViewPager.removeOnPageChangeListener(mOnPageChangeListener); } else { mOnPageChangeListener = new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { AnalyticsTracker.track(AnalyticsTracker.Stat.NOTIFICATION_SWIPE_PAGE_CHANGED); if (!mIsReaderSwipeToNavigateShown) { AppPrefs.setNotificationsSwipeToNavigateShown(true); } Note currentNote = mAdapter.getNoteAtPosition(position); if (currentNote != null) { setActionBarTitleForNote(currentNote); markNoteAsRead(currentNote); } } @Override public void onPageScrollStateChanged(int state) { } }; } mViewPager.addOnPageChangeListener(mOnPageChangeListener); }
Source:
<code>public Review fromDBObject(DBObject dbObject) { Review review = new Review(TranslatorUtils.toLocaleFromLanguageTag(dbObject, LOCALE_KEY), TranslatorUtils.toString(dbObject, REVIEW_KEY)); review.setType(TranslatorUtils.toString(dbObject, TYPE_KEY)); List<DBObject> crewMembers = TranslatorUtils.toDBObjectList(dbObject, PEOPLE_KEY); List<CrewMember> crewMemberList = new ArrayList<CrewMember>(); for (DBObject crewMember : crewMembers) { crewMemberList.add(crewMemberTranslator.fromDBObject(crewMember, new CrewMember())); } <START> review.setPeople(crewMemberList); <END> return review; }</code><technical_language>able a stream collect immutable list</technical_language>

Target:
public Review fromDBObject(DBObject dbObject) { Review review = new Review(TranslatorUtils.toLocaleFromLanguageTag(dbObject, LOCALE_KEY), TranslatorUtils.toString(dbObject, REVIEW_KEY)); review.setType(TranslatorUtils.toString(dbObject, TYPE_KEY)); review.setAuthor(authorTranslator.fromDBObject(dbObject)); return review; }
Source:
<code>public void visit(View rootView) { <START> if (mAlive) { <END> super.getPathfinder().findTargetsInRoot(rootView, super.getPath(), this); } }</code><technical_language>Great</technical_language>

Target:
public void visit(View rootView) { if (mAlive) { getPathfinder().findTargetsInRoot(rootView, getPath(), this); } }
Source:
<code>private boolean isRelevantService(Service service, String role, String name, String version) { return service.getRole().equalsIgnoreCase(role) <START> && (service.getName() == null || service.getName().equalsIgnoreCase(name) && (service.getVersion() == null || service.getVersion().compareTo(new Version(version)) == 0)); <END> }</code><technical_language>Compare == 0 equals for version comparison</technical_language>

Target:
private boolean isRelevantService(Service service, String role, String name, String version) { return service.getRole().equalsIgnoreCase(role) && (service.getName() == null || service.getName().equalsIgnoreCase(name) && (service.getVersion() == null || service.getVersion().equals(new Version(version)))); }
Source:
<code>public void canGetTimestamps() { long ts1 = cluster.getFreshTimestamp(); long ts2 = cluster.timelockService().getFreshTimestamp(); assertThat(ts2).isGreaterThan(ts1); <START> } <END></code><technical_language>Nice, checking access timestamp timelock, numbers consistent. if sense add additional check where, get timelock, if get regular timestamp larger (the idea changes propagate in directions)</technical_language>

Target:
public void canGetTimestamps() { List<Long> timestamps = ImmutableList.of( cluster.getFreshTimestamp(), cluster.timelockService().getFreshTimestamp(), cluster.getFreshTimestamp(), cluster.timelockService().getFreshTimestamp()); long lastTs = -1; for (long ts : timestamps) { assertThat(ts).isGreaterThan(lastTs); lastTs = ts; } }
Source:
<code><START> public static String getExchangeAlias(String exchangeName) { <END> String alias = null; if (StringUtils.isNotBlank(exchangeName)) { List<ExchangeType> exchanges = ExchangeManager.getInstance().getAllExchanges(); if (CollectionUtils.isNotEmpty(exchanges)) { for (ExchangeType ex : exchanges) { if (exchangeName.equalsIgnoreCase(ex.getName())) { alias = ex.getCertificateAlias(); break; } } } } return alias; }</code><technical_language>exchangeManager.getGatewayAlias internalExchangeManager.getGatewayAlias return null default:CIENT_KEY_ALIAS</technical_language>

Target:
public static String getExchangeAlias(String exchangeName) { String alias = null; List<ExchangeType> exchanges = ExchangeManager.getInstance().getAllExchanges(); if (StringUtils.isNotBlank(exchangeName) && CollectionUtils.isNotEmpty(exchanges)) { for (ExchangeType ex : exchanges) { if (exchangeName.equalsIgnoreCase(ex.getName())) { alias = ex.getCertificateAlias(); break; } } } return alias; }
Source:
<code>@Test public void testLargeNumberOfFilesYOUNGESTTrackerDir() throws IOException { <START> templateTestForRecursiveDirs(ConsumeOrder.YOUNGEST, new Comparator<Long>() { <END> @Override public int compare(Long o1, Long o2) { return o2.compareTo(o1); } }, 3, 3, 10, TrackingPolicy.TRACKER_DIR); }</code><technical_language>Comparator.reverseOrder() more compact (the for line 494)</technical_language>

Target:
@Test public void testLargeNumberOfFilesYOUNGESTTrackerDir() throws IOException { templateTestForRecursiveDirs(ConsumeOrder.YOUNGEST, Comparator.reverseOrder(), 3, 3, 10, TrackingPolicy.TRACKER_DIR); }
Source:
<code>private boolean methodBindingsNeedFinder() { for (ViewBindings viewBindings : viewIdMap.values()) { for (Map<ListenerMethod, Set<MethodViewBinding>> listenerMethodSetMap : viewBindings.getMethodBindings().values()) { for (Set<MethodViewBinding> methodViewBindings : listenerMethodSetMap.values()) { for (MethodViewBinding methodViewBinding : methodViewBindings) { for (Parameter parameter : methodViewBinding.getParameters()) { <START> if (!parameter.getType().toString().equals(VIEW.toString())) { <END> return true; } } } } } } return false; }</code><technical_language>This parameter.requiresCast() is logic original method uses</technical_language>

Target:
private boolean methodBindingsNeedFinder() { for (ViewBindings viewBindings : viewIdMap.values()) { for (Map.Entry<ListenerClass, Map<ListenerMethod, Set<MethodViewBinding>>> entry : viewBindings.getMethodBindings().entrySet()) { Map<ListenerMethod, Set<MethodViewBinding>> methodBindings = entry.getValue(); for (ListenerMethod method : getListenerMethods(entry.getKey())) { if (methodBindings.containsKey(method)) { String[] parameterTypes = method.parameters(); for (MethodViewBinding methodViewBinding : methodBindings.get(method)) { for (Parameter parameter : methodViewBinding.getParameters()) { if (parameter.requiresCast(parameterTypes[parameter.getListenerPosition()])) { return true; } } } } } } } return false; }
Source:
<code>public void setUp() { try { final URL location = FileLocator.find(TmfCoreTestPlugin.getDefault().getBundle(), new Path(TEST_TRACE.getFullPath()), null); final File test = new File(FileLocator.toFileURL(location).toURI()); fTrace = new TmfTraceStub(test.toURI().getPath(), ITmfTrace.DEFAULT_TRACE_CACHE_SIZE, false, null); TmfSignalManager.deregister(fTrace); fTrace.indexTrace(true); } catch (final TmfTraceException e) { fail("Exception setting up the trace: " + <START> e.getMessage()); <END> } catch (final URISyntaxException e) { fail("URI syntax exception: " + e.getMessage()); } catch (final IOException e) { fail("I/O exception while setting up the test: " + e.getMessage()); } }</code><technical_language>upload a change prints stack trace call fail</technical_language>

Target:
public static void setUp() { try { final URL location = FileLocator.find(TmfCoreTestPlugin.getDefault().getBundle(), new Path(TEST_TRACE.getFullPath()), null); final File test = new File(FileLocator.toFileURL(location).toURI()); fTrace = new TmfTraceStub(test.toURI().getPath(), ITmfTrace.DEFAULT_TRACE_CACHE_SIZE, false, null); TmfSignalManager.deregister(fTrace); fTrace.indexTrace(true); } catch (final TmfTraceException | URISyntaxException | IOException e) { fail(e.toString()); } }
Source:
<code>public V fetch(K key, Supplier<V> valueProvider) { final Supplier<V> userSuplier = valueProvider; try { return guavaCache.get(key, new Callable<V>() { @Override public V call() throws Exception { return userSuplier.get(); } }); } catch (ExecutionException e) { propagateIfPossible(e); <START> return valueProvider.get(); <END> } }</code><technical_language>@mariofts need throw CacheException here? I get this change</technical_language>

Target:
public V fetch(K key, Supplier<V> valueProvider) { final Supplier<V> userSuplier = valueProvider; try { return guavaCache.get(key, new Callable<V>() { @Override public V call() throws Exception { return userSuplier.get(); } }); } catch (ExecutionException e) { throw new CacheException("Error while trying to fetch key: " + key, e); } }
Source:
<code>public Future<Void> report() { if (reporters.size() == 1) { return new ErrantRecordFuture(Collections.singletonList(reporters.iterator().next().report(this))); } <START> List<Future<RecordMetadata>> futures = new LinkedList<>(); <END> for (ErrorReporter reporter: reporters) { Future<RecordMetadata> future = reporter.report(this); if (!future.isDone()) { futures.add(future); } } if (futures.isEmpty()) { return CompletableFuture.completedFuture(null); } return new ErrantRecordFuture(futures); }</code><technical_language>Suggestion (can't add of deleted line): List<Future<RecordMetadata>> futures = reporters.stream() .map(r -> r.report(this)) .filter(Future::isDone) .collect(Collectors.toCollection(LinkedList::new));</technical_language>

Target:
public Future<Void> report() { if (reporters.size() == 1) { return new ErrantRecordFuture(Collections.singletonList(reporters.iterator().next().report(this))); } List<Future<RecordMetadata>> futures = reporters.stream() .map(r -> r.report(this)) .filter(Future::isDone) .collect(Collectors.toCollection(LinkedList::new)); if (futures.isEmpty()) { return CompletableFuture.completedFuture(null); } return new ErrantRecordFuture(futures); }
Source:
<code>public PdpFeedDetailEntry buildPdpFeedDetailEntry(ConcurStandardAccountingExtractDetailLine line) { PdpFeedDetailEntry currentDetailEntry = new PdpFeedDetailEntry(); currentDetailEntry.setSourceDocNbr(buildSourceDocumentNumber(line.getReportId())); currentDetailEntry.setFsOriginCd(getConcurParameterValue(ConcurParameterConstants.CONCUR_AP_PDP_ORIGINATION_CODE)); currentDetailEntry.setFdocTypCd(getConcurParameterValue(ConcurParameterConstants.CONCUR_SAE_PDP_DOCUMENT_TYPE)); currentDetailEntry.setInvoiceNbr(StringUtils.EMPTY); currentDetailEntry.setPoNbr(StringUtils.EMPTY); currentDetailEntry.setInvoiceDate(formatDate(line.getBatchDate())); List<String> paymentTextStrings = new ArrayList<String>(); paymentTextStrings.add("Report ID: " + line.getReportId()); <START> currentDetailEntry.setPaymentText(paymentTextStrings); <END> return currentDetailEntry; }</code><technical_language>"Report ID: " string a constant prefixed for SAE Request Extract functionality</technical_language>

Target:
public PdpFeedDetailEntry buildPdpFeedDetailEntry(ConcurStandardAccountingExtractDetailLine line) { PdpFeedDetailEntry currentDetailEntry = new PdpFeedDetailEntry(); currentDetailEntry.setSourceDocNbr(buildSourceDocumentNumber(line.getReportId())); currentDetailEntry.setFsOriginCd(getConcurParameterValue(ConcurParameterConstants.CONCUR_AP_PDP_ORIGINATION_CODE)); currentDetailEntry.setFdocTypCd(getConcurParameterValue(ConcurParameterConstants.CONCUR_SAE_PDP_DOCUMENT_TYPE)); currentDetailEntry.setInvoiceNbr(StringUtils.EMPTY); currentDetailEntry.setPoNbr(StringUtils.EMPTY); currentDetailEntry.setInvoiceDate(formatDate(line.getBatchDate())); return currentDetailEntry; }
Source:
<code>private void analyzeHaving(QuerySpecification node, Scope scope) { if (node.getHaving().isPresent()) { Expression predicate = node.getHaving().get(); ExpressionAnalysis expressionAnalysis = analyzeExpression(predicate, scope); expressionAnalysis.getWindowFunctions().stream() .findFirst() .ifPresent(function -> { <START> throw new SemanticException(NESTED_WINDOW, function.getNode(), "HAVING clause cannot not contain window functions"); <END> }); analysis.recordSubqueries(node, expressionAnalysis); Type predicateType = expressionAnalysis.getType(predicate); if (!predicateType.equals(BOOLEAN) && !predicateType.equals(UNKNOWN)) { throw new SemanticException(TYPE_MISMATCH, predicate, "HAVING clause must evaluate to a boolean: actual type %s", predicateType); } analysis.setHaving(node, predicate); } }</code><technical_language>></technical_language>

Target:
private void analyzeHaving(QuerySpecification node, Scope scope) { if (node.getHaving().isPresent()) { Expression predicate = node.getHaving().get(); ExpressionAnalysis expressionAnalysis = analyzeExpression(predicate, scope); expressionAnalysis.getWindowFunctions().stream() .findFirst() .ifPresent(function -> { throw new SemanticException(NESTED_WINDOW, function.getNode(), "HAVING clause cannot contain window functions"); }); analysis.recordSubqueries(node, expressionAnalysis); Type predicateType = expressionAnalysis.getType(predicate); if (!predicateType.equals(BOOLEAN) && !predicateType.equals(UNKNOWN)) { throw new SemanticException(TYPE_MISMATCH, predicate, "HAVING clause must evaluate to a boolean: actual type %s", predicateType); } analysis.setHaving(node, predicate); } }
Source:
<code>public VdcActionParametersBase getParameters(VmPool incoming, org.ovirt.engine.core.common.businessentities.VmPool current) { final int currentVmCount = current.getAssignedVmsCount(); int size = 0; if (incoming.isSetSize()) { if (incoming.getSize() < currentVmCount) { final Fault f = new Fault(); <START> final String faultString = "Requested VM pool size cannot be lower than the current capacity"; <END> f.setReason(faultString); final Response response = Response.status(Response.Status.BAD_REQUEST).entity(f).build(); throw new WebApplicationException(response); } else { size = incoming.getSize() - currentVmCount; } } final org.ovirt.engine.core.common.businessentities.VmPool entity = map(incoming, current); final VM vm = mapToVM(map(entity)); if (incoming.isSetTemplate()) { vm.setVmtGuid(new Guid(incoming.getTemplate().getId())); } else { final VM existing = currentVmCount > 0 ? getEntity(VM.class, SearchType.VM, "Vms: pool=" + incoming.getName()) : null; if (existing != null) { vm.setVmtGuid(existing.getVmtGuid()); } } if (vm.getVmtGuid() != null) { final VmTemplate template = getEntity(VmTemplate.class, VdcQueryType.GetVmTemplate, new GetVmTemplateParameters(vm.getId()), vm.getId().toString()); vm.getStaticData().setMemSizeMb(template.getMemSizeMb()); } final AddVmPoolWithVmsParameters parameters = new AddVmPoolWithVmsParameters(entity, vm, size, -1); parameters.setStorageDomainId(getStorageDomainId(vm.getVmtGuid())); return parameters; }</code><technical_language>this logic reside in api, passing vm_size is backend, can-do-action fail (if applicable)</technical_language>

Target:
public VdcActionParametersBase getParameters(VmPool incoming, org.ovirt.engine.core.common.businessentities.VmPool current) { final int currentVmCount = current.getAssignedVmsCount(); int size = 0; if (incoming.isSetSize()) { size = incoming.getSize() - currentVmCount; } final org.ovirt.engine.core.common.businessentities.VmPool entity = map(incoming, current); final VM vm = mapToVM(map(entity)); if (incoming.isSetTemplate()) { vm.setVmtGuid(new Guid(incoming.getTemplate().getId())); } else { final VM existing = currentVmCount > 0 ? getEntity(VM.class, SearchType.VM, "Vms: pool=" + incoming.getName()) : null; if (existing != null) { vm.setVmtGuid(existing.getVmtGuid()); } } if (vm.getVmtGuid() != null) { final VmTemplate template = getEntity(VmTemplate.class, VdcQueryType.GetVmTemplate, new GetVmTemplateParameters(vm.getId()), vm.getId().toString()); vm.getStaticData().setMemSizeMb(template.getMemSizeMb()); } final AddVmPoolWithVmsParameters parameters = new AddVmPoolWithVmsParameters(entity, vm, size, -1); parameters.setStorageDomainId(getStorageDomainId(vm.getVmtGuid())); return parameters; }