auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static Pair<Float, Float> parsePosition(String line){ Matcher matcher = SSA_POSITION_PATTERN.matcher(line); if(!matcher.find()){ return null; } float x = Float.parseFloat(matcher.group(1)); float y = Float.parseFloat(matcher.group(3)); return new Pair<>(x,y); }

Target:
private static PointF parsePosition(String line) { Matcher matcher = SSA_POSITION_PATTERN.matcher(line); if (!matcher.find()) { return null; } float x = Float.parseFloat(matcher.group(1)); float y = Float.parseFloat(matcher.group(3)); return new PointF(x, y); }
Source:
private void badSupervisors(Map<String, SupervisorDetails> supervisors) { Set<String> cachedSupervisorsKeySet = cachedSupervisors.keySet(); Set<String> supervisorsKeySet = supervisors.keySet(); Set<String> badSupervisorKeys = Sets.difference(cachedSupervisorsKeySet, supervisorsKeySet); HashMap<String, Set<Integer>> badSupervisors = new HashMap<>(); for (String key : badSupervisorKeys) { badSupervisors.put(key, cachedSupervisors.get(key)); } if (blacklistOnBadSlots) { for (Map.Entry<String, SupervisorDetails> entry : supervisors.entrySet()) { String key = entry.getKey(); SupervisorDetails supervisorDetails = entry.getValue(); if (cachedSupervisors.containsKey(key)) { Set<Integer> badSlots = badSlots(supervisorDetails, key); if (badSlots.size() > 0) { badSupervisors.put(key, badSlots); } } else { cachedSupervisors.put(key, supervisorDetails.getAllPorts()); } } } badSupervisorsToleranceSlidingWindow.add(badSupervisors); }

Target:
private void badSupervisors(Map<String, SupervisorDetails> supervisors) { Set<String> cachedSupervisorsKeySet = cachedSupervisors.keySet(); Set<String> supervisorsKeySet = supervisors.keySet(); Set<String> badSupervisorKeys = Sets.difference(cachedSupervisorsKeySet, supervisorsKeySet); HashMap<String, Set<Integer>> badSupervisors = new HashMap<>(); for (String key : badSupervisorKeys) { badSupervisors.put(key, cachedSupervisors.get(key)); } for (Map.Entry<String, SupervisorDetails> entry : supervisors.entrySet()) { String key = entry.getKey(); SupervisorDetails supervisorDetails = entry.getValue(); if (cachedSupervisors.containsKey(key)) { if (blacklistOnBadSlots) { Set<Integer> badSlots = badSlots(supervisorDetails, key); if (badSlots.size() > 0) { badSupervisors.put(key, badSlots); } } } else { cachedSupervisors.put(key, supervisorDetails.getAllPorts()); } } badSupervisorsToleranceSlidingWindow.add(badSupervisors); }
Source:
public Dialog onCreateDialog(Bundle savedInstanceState) { final AlertDialog alertDialog = new AlertDialog.Builder(getContext()) .setTitle(R.string.reset_dialog_title) .setMessage(R.string.confirm_dialog_message_help) .setPositiveButton(android.R.string.ok, null) .setNegativeButton(android.R.string.cancel, null) .create(); alertDialog.setCanceledOnTouchOutside(false); final ViewGroup layout = (ViewGroup) getActivity().getLayoutInflater() .inflate(R.layout.reset_dialog_email_input, null); textInputLayout = (TextInputLayout) layout.findViewById(R.id.input_layout); editText = (TextInputEditText) layout.findViewById(R.id.edit_text); loadingIndicator = layout.findViewById(R.id.loading_indicator); editText.setText(getArguments().getString(EXTRA_LOGIN_EMAIL)); alertDialog.setView(layout); return alertDialog; }

Target:
public Dialog onCreateDialog(Bundle savedInstanceState) { binding = DataBindingUtil.inflate(getActivity().getLayoutInflater(), R.layout.reset_password_dialog, null, false); binding.emailEditText.setText(getArguments().getString(ARG_LOGIN_EMAIL)); final AlertDialog alertDialog = new AlertDialog.Builder(getContext()) .setTitle(R.string.confirm_dialog_title_help) .setMessage(R.string.confirm_dialog_message_help) .setPositiveButton(android.R.string.ok, null) .setNegativeButton(android.R.string.cancel, null) .setView(binding.getRoot()) .create(); alertDialog.setCanceledOnTouchOutside(false); return alertDialog; }
Source:
private synchronized void discardMark() { this.mark = -1; this.markLimit = 0; markBuffers = new ArrayList<>(); }

Target:
private void discardMark() { this.mark = -1; this.markLimit = 0; markBuffers = new ArrayList<>(); }
Source:
public Map<String, Construct> evaluate(BindableEvent e) throws EventException { if (e instanceof MCPlayerInteractAtEntityEvent) { MCPlayerInteractAtEntityEvent event = (MCPlayerInteractAtEntityEvent) e; Map<String, Construct> map = evaluate_helper(e); map.put("player", new CString(event.getPlayer().getName(), Target.UNKNOWN)); map.put("clicked", new CString(event.getEntity().getType().name(), Target.UNKNOWN)); map.put("id", new CInt(event.getEntity().getEntityId(),Target.UNKNOWN)); map.put("position", ObjectGenerator.GetGenerator().vector(event.getClickedPosition(), Target.UNKNOWN)); String data = ""; if(event.getEntity() instanceof MCPlayer) { data = ((MCPlayer)event.getEntity()).getName(); } map.put("data", new CString(data, Target.UNKNOWN)); return map; } else { throw new EventException("Cannot convert e to MCPlayerDropItemEvent"); } }

Target:
public Map<String, Construct> evaluate(BindableEvent e) throws EventException { if (e instanceof MCPlayerInteractAtEntityEvent) { MCPlayerInteractAtEntityEvent event = (MCPlayerInteractAtEntityEvent) e; Map<String, Construct> map = evaluate_helper(e); map.put("player", new CString(event.getPlayer().getName(), Target.UNKNOWN)); map.put("clicked", new CString(event.getEntity().getType().name(), Target.UNKNOWN)); map.put("id", new CInt(event.getEntity().getEntityId(),Target.UNKNOWN)); map.put("position", ObjectGenerator.GetGenerator().vector(event.getClickedPosition(), Target.UNKNOWN)); String data = ""; if(event.getEntity() instanceof MCPlayer) { data = ((MCPlayer)event.getEntity()).getName(); } map.put("data", new CString(data, Target.UNKNOWN)); return map; } else { throw new EventException("Cannot convert e to MCPlayerInteractAtEntityEvent"); } }
Source:
public PermissionManager getPermissionManager() { return permissionManager.get(); }

Target:
public PermissionManager getPermissionManager() { return PermissionManager.getInstance(this); }
Source:
public Message<?> preSend(Message<?> message, MessageChannel channel) { if (this.traceManager.isTracing() || message.getHeaders().containsKey(Trace.NOT_SAMPLED_NAME)) { return SpanMessageHeaders.addSpanHeaders(message, this.traceManager.getCurrentSpan()); } String spanId = getHeader(message, Trace.SPAN_ID_NAME); String traceId = getHeader(message, Trace.TRACE_ID_NAME); String name = "message/" + getChannelName(channel); Trace trace; if (hasText(spanId) && hasText(traceId)) { MilliSpanBuilder span = MilliSpan.builder().traceId(traceId).spanId(spanId); String parentId = getHeader(message, Trace.PARENT_ID_NAME); String processId = getHeader(message, Trace.PROCESS_ID_NAME); String spanName = getHeader(message, Trace.SPAN_NAME_NAME); if (spanName != null) { span.name(spanName); } if (processId != null) { span.processId(processId); } if (parentId != null) { span.parent(parentId); } span.remote(true); trace = this.traceManager.startSpan(name, span.build()); } else { trace = this.traceManager.startSpan(name); } this.traceManagerScopeHolder.set(trace); return StompMessageBuilderHelper.fromMessage(message).setHeadersFromSpan(trace.getSpan()).build(); }

Target:
public Message<?> preSend(Message<?> message, MessageChannel channel) { final TraceManager traceManager = this.traceManager; if (traceManager.isTracing() || message.getHeaders().containsKey(Trace.NOT_SAMPLED_NAME)) { return StompMessageBuilder.fromMessage(message).setHeadersFromSpan(traceManager.getCurrentSpan()).build(); } String spanId = getHeader(message, Trace.SPAN_ID_NAME); String traceId = getHeader(message, Trace.TRACE_ID_NAME); String name = "message/" + getChannelName(channel); Trace trace; if (hasText(spanId) && hasText(traceId)) { MilliSpanBuilder span = MilliSpan.builder().traceId(traceId).spanId(spanId); String parentId = getHeader(message, Trace.PARENT_ID_NAME); String processId = getHeader(message, Trace.PROCESS_ID_NAME); String spanName = getHeader(message, Trace.SPAN_NAME_NAME); if (spanName != null) { span.name(spanName); } if (processId != null) { span.processId(processId); } if (parentId != null) { span.parent(parentId); } span.remote(true); trace = traceManager.startSpan(name, span.build()); } else { trace = traceManager.startSpan(name); } this.traceScopeHolder.set(trace); return StompMessageBuilder.fromMessage(message).setHeadersFromSpan(trace.getSpan()).build(); }
Source:
private boolean fetchRemoteBranch(SubMonitor subMonitor) { subMonitor.setTaskName(Messages.AutoRebaseProcess_FetchingRemoteBranch); List<RefSpec> branchSpecs = new ArrayList<>(1); if (baseChange == null) { Ref refBranch = null; try { refBranch = localRepo.findRef(revisionInfo.getChangeInfo().getBranch()); } catch (IOException e2) { EGerritCorePlugin.logError(e2.getMessage()); return false; } RefSpec refSpecBranch = new RefSpec().setSource(refBranch.getName()).setDestination(Constants.FETCH_HEAD); branchSpecs.add(refSpecBranch); } else { baseChange.getRevision(); branchSpecs.add( new RefSpec().setSource(baseChange.getRevision().getRef()).setDestination(Constants.FETCH_HEAD)); } FetchResult fetchResBranch = null; try { URIish uri = getRemoteURI(); if (uri != null) { fetchResBranch = new FetchOperationUI(localRepo, uri, branchSpecs, 0, false).execute(subMonitor); } else { return false; } } catch (CoreException e) { EGerritCorePlugin.logError(e.getMessage()); } if (fetchResBranch == null) { return false; } else { return true; } }

Target:
private boolean fetchRemoteBranch(SubMonitor subMonitor) { subMonitor.setTaskName(Messages.AutoRebaseProcess_FetchingRemoteBranch); List<RefSpec> branchSpecs = new ArrayList<>(1); RefSpec refSpecBranch; if (baseChange == null) { refSpecBranch = new RefSpec().setSource("refs/heads/" + revisionInfo.getChangeInfo().getBranch()) .setDestination(Constants.FETCH_HEAD); } else { refSpecBranch = new RefSpec().setSource(baseChange.getRevision().getRef()) .setDestination(Constants.FETCH_HEAD); } branchSpecs.add(refSpecBranch); FetchResult fetchResBranch = null; try { URIish uri = getRemoteURI(); if (uri != null) { fetchResBranch = new FetchOperationUI(localRepo, uri, branchSpecs, 0, false).execute(subMonitor); } else { return false; } } catch (CoreException e) { EGerritCorePlugin.logError(e.getMessage()); } if (fetchResBranch == null) { return false; } else { return true; } }
Source:
Object[][] testIntervalListData() { return new Object[][]{ new Object[]{new File("testdata/picard/sam/aligned.sam"), null}, new Object[]{new File("testdata/picard/sam/aligned.sam"), new File("testdata/picard/analysis/directed/CollectHsMetrics/chrM.interval_list")}, new Object[]{new File("testdata/picard/sam/aligned.sam"), new File("testdata/picard/sam/contiguous.interval_list")} }; }

Target:
Object[][] testIntervalListData() { return new Object[][]{ new Object[]{TEST_DIR.resolve("aligned.sam").toFile(), null, OA_TEST_DIR.resolve("aligned_no_intervals.sam").toFile()}, new Object[]{TEST_DIR.resolve("aligned.sam").toFile(), new File("testdata/picard/analysis/directed/CollectHsMetrics/chrM.interval_list"), TEST_DIR.resolve("aligned.sam").toFile()}, new Object[]{TEST_DIR.resolve("aligned.sam").toFile(), TEST_DIR.resolve("contiguous.interval_list").toFile(), OA_TEST_DIR.resolve("aligned_with_intervals.sam").toFile()} }; }
Source:
public static String format(String inField) { Objects.requireNonNull(inField); try { return parse(inField); } catch (IllegalArgumentException ignored) { return Normalizer.normalize(inField, Normalizer.Form.NFC); } }

Target:
public static String format(String inField) { Objects.requireNonNull(inField); return parse(inField).orElse(Normalizer.normalize(inField, Normalizer.Form.NFC)); }
Source:
public void endStateTransfer(String sendingSite) { if (debug) { log.debugf("Ending state transfer from %s", sendingSite); } String currentSendingSite = this.sendingSite.get(); if (sendingSite == null || sendingSite.equals(currentSendingSite)) { this.sendingSite.set(null); commitManager.stopTrack(PUT_FOR_X_SITE_STATE_TRANSFER); } }

Target:
public void endStateTransfer(String sendingSite) { if (debug) { log.debugf("Ending state transfer from %s", sendingSite); } String currentSendingSite = this.sendingSite.get(); if (sendingSite == null || sendingSite.equals(currentSendingSite)) { this.sendingSite.set(null); commitManager.stopTrack(PUT_FOR_X_SITE_STATE_TRANSFER); } else { if (log.isDebugEnabled()) { log.debugf("Received an end request from a non-sender site. Expects %s but got %s", currentSendingSite, sendingSite); } } }
Source:
public void decorate(Object element, IDecoration decoration) { IScript iScript = (IScript) element; ScriptType scriptType = iScript.getType(); String filePath = iScript.getLocation().substring(12); if (scriptType != null) { try { VerifySignature verifySignature = VerifySignature.getInstance(scriptType, iScript.getInputStream(), new FileInputStream(ISignatureHelperConstants.PATH_TO_SIGNATURES + "/" + filePath)); boolean signState; if (verifySignature != null) { signState = verifySignature.verify(); if (signState) decoration.addOverlay(OVERLAY1); else decoration.addOverlay(OVERLAY2); } } catch (FileNotFoundException e) { Logger.error(Activator.PLUGIN_ID, filePath + " Signature File Not found"); } catch (IllegalStateException e) { Logger.error(Activator.PLUGIN_ID, e.getMessage(), e); } catch (ScriptSignatureException e) { Logger.error(Activator.PLUGIN_ID, e.getMessage(), e); } } }

Target:
public void decorate(Object element, IDecoration decoration) { IScript iScript = (IScript) element; ScriptType scriptType = iScript.getType(); if (scriptType != null) { try { VerifySignature verifySignature = VerifySignature.getInstance(scriptType, iScript.getInputStream()); if (verifySignature != null) decoration.addOverlay(verifySignature.verify() ? OVERLAY1 : OVERLAY2); } catch (Exception e) { Logger.error(Activator.PLUGIN_ID, e.getMessage(), e); } } }
Source:
public ValueNode replaceIndexExpression(ResultColumnList childRCL) throws StandardException { if (childRCL == null) { return this; } if (receiver != null) { receiver = receiver.replaceIndexExpression(childRCL); } if (leftOperand != null) { leftOperand = leftOperand.replaceIndexExpression(childRCL); } if (rightOperand != null) { rightOperand = rightOperand.replaceIndexExpression(childRCL); } return this; }

Target:
public ValueNode replaceIndexExpression(ResultColumnList childRCL) throws StandardException { if (childRCL == null) { return this; } if (leftOperand != null) { leftOperand = leftOperand.replaceIndexExpression(childRCL); } if (rightOperand != null) { rightOperand = rightOperand.replaceIndexExpression(childRCL); } return this; }
Source:
public boolean isLocalOnly() { switch (this) { case LOCAL: return true; default: return false; } }

Target:
public boolean isLocalOnly() { return this == LOCAL; }
Source:
public void handleMilliSecondsSpentInputChange( ChangeEvent event ) { try { Long value = millisecondsSpentInput.getValue().isEmpty() ? null : Long.parseLong( millisecondsSpentInput.getValue() ); presenter.onMillisecondsSpentChange( value ); } catch ( NumberFormatException e ) { } }

Target:
public void handleMilliSecondsSpentInputChange( ChangeEvent event ) { boolean isNumeric = millisecondsSpentInput.getValue().matches( "\\d+" ); if (isNumeric) { presenter.onMillisecondsSpentChange( Long.parseLong( millisecondsSpentInput.getValue() ) ); } else { presenter.onMillisecondsSpentChange( 0l ); millisecondsSpentInput.setValue( "0" ); } }
Source:
public void configure(Config config) throws Exception { super.configure(config); if (!(productIndex instanceof ExtentIndex)) { throw new ConfigurationException("[" + getName() + "] index must be of type ExtentIndex. Given type " + productIndex.getClass().getName()); } }

Target:
public void configure(Config config) throws Exception { super.configure(config); if (!(this.getProductIndex() instanceof ExtentIndex)) { throw new ConfigurationException("[" + getName() + "] index must be of type ExtentIndex. Given type " + productIndex.getClass().getName()); } }
Source:
protected void actionPerformed(GuiButton button) throws IOException { if(button.id == 0) { if(PAGE < PAGE_MAX) PAGE++; } if(button.id == 1) { if(PAGE > 1) PAGE--; } }

Target:
protected void actionPerformed(GuiButton button) throws IOException { if (button.id == 0) { if (page < pageMax) { page++; } this.nextPageBtn.enabled = page != pageMax; this.prevPageBtn.enabled = page != 1; sliderProgress = 0.0F; updateSlider(); text = splitLines(StringUtils.translate("book.quickstart." + page), fontRenderer, maxLength); } if (button.id == 1) { if (page > 1) { page--; } this.nextPageBtn.enabled = page != pageMax; this.prevPageBtn.enabled = page != 1; sliderProgress = 0.0F; updateSlider(); text = splitLines(StringUtils.translate("book.quickstart." + page), fontRenderer, maxLength); } }
Source:
private static int getIntegerPort(String stringPort) { if(StringUtils.isBlank(stringPort) || stringPort.length() > 5) { return -1; } int value = 0; for (int i = 0; i < stringPort.length(); i++) { char c = stringPort.charAt(i); if(c < '0' || c > '9') { return -1; } value = 10 * value + ((int)c) - ((int)'0'); } return (value > 65535) ? -1 : value; }

Target:
private static int getIntegerPort(String stringPort) { if(StringUtils.isBlank(stringPort) || stringPort.length() > 5 || !StringUtils.isNumeric(stringPort)) { return -1; } int value = Integer.parseInt(stringPort); return (value > 65535) ? -1 : value; }
Source:
public boolean hasDSpacePermission(Authentication authentication, Serializable targetId, String targetType, DSpaceRestPermission permission) { if (!StringUtils.equals("CLAIMEDTASK", targetType)) { return false; } Request request = requestService.getCurrentRequest(); Context context = ContextUtil.obtainContext(request.getServletRequest()); EPerson ePerson = null; try { ePerson = ePersonService.findByEmail(context, (String) authentication.getPrincipal()); if (ePerson == null) { return false; } Integer dsoId = Integer.parseInt(targetId.toString()); ClaimedTask claimedTask = claimedTaskService.find(context, dsoId); if (claimedTask == null) { return true; } if (claimedTask != null && ePerson.equals(claimedTask.getOwner())) { return true; } } catch (SQLException e) { log.error(e.getMessage(), e); } return false; }

Target:
public boolean hasDSpacePermission(Authentication authentication, Serializable targetId, String targetType, DSpaceRestPermission permission) { if (!StringUtils.equalsIgnoreCase(ClaimedTaskRest.NAME, targetType)) { return false; } Request request = requestService.getCurrentRequest(); Context context = ContextUtil.obtainContext(request.getServletRequest()); EPerson ePerson = null; try { ePerson = ePersonService.findByEmail(context, (String) authentication.getPrincipal()); if (ePerson == null) { return false; } Integer dsoId = Integer.parseInt(targetId.toString()); ClaimedTask claimedTask = claimedTaskService.find(context, dsoId); if (claimedTask == null) { return true; } if (claimedTask != null && ePerson.equals(claimedTask.getOwner())) { return true; } } catch (SQLException e) { log.error(e.getMessage(), e); } return false; }
Source:
protected void initButton(final Button button) { button.setToolTipText("Abandon Merge Branch"); button.setImage(ImageManager.getImage(FrameworkImage.DOT_GREEN)); button.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event e) { refreshEnablement(button); boolean hasMergeBranch = BranchManager.hasMergeBranches(getTeamArt().getWorkingBranch()); if (hasMergeBranch) { List<MergeBranch> br = BranchManager.getMergeBranches(getTeamArt().getWorkingBranch()); if (br.size() > 1) { AWorkbench.popup( "The Working Branch: " + getTeamArt().getWorkingBranch() + " has more than 1 merge conflict. Manually open the merge manager to cancel merge"); } else { BranchManager.purgeBranch(br.get(0)); } button.setText(""); button.getParent().layout(); refreshEnablement(button); } } }); }

Target:
protected void initButton(final Button button) { button.setToolTipText("Abandon Merge Branch"); button.setImage(ImageManager.getImage(FrameworkImage.ABORT_MERGE)); button.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event e) { refreshEnablement(button); boolean hasMergeBranch = BranchManager.hasMergeBranches(getTeamArt().getWorkingBranch()); if (hasMergeBranch) { List<MergeBranch> br = BranchManager.getMergeBranches(getTeamArt().getWorkingBranch()); if (br.size() > 1) { AWorkbench.popup( "The Working Branch: " + getTeamArt().getWorkingBranch() + " has more than 1 merge conflict. Manually open the merge manager to cancel merge"); } else { BranchManager.purgeBranch(br.get(0)); } button.setText(""); button.getParent().layout(); refreshEnablement(button); } } }); }
Source:
int decompressDirect(ByteBuffer src, ByteBuffer dst) throws IOException { assert (this instanceof SnappyDirectDecompressor); ByteBuffer presliced = dst; if (dst.position() > 0) { presliced = dst; dst = dst.slice(); } Buffer originalCompressed = compressedDirectBuf; Buffer originalUncompressed = uncompressedDirectBuf; int originalBufferSize = directBufferSize; compressedDirectBuf = src.slice(); compressedDirectBufLen = src.remaining(); uncompressedDirectBuf = dst; directBufferSize = dst.remaining(); int n = 0; try { n = decompressBytesDirect(); presliced.position(presliced.position() + n); src.position(src.limit()); finished = true; } finally { compressedDirectBuf = originalCompressed; uncompressedDirectBuf = originalUncompressed; compressedDirectBufLen = 0; directBufferSize = originalBufferSize; } return n; }

Target:
int decompressDirect(ByteBuffer src, ByteBuffer dst) throws IOException { assert (this instanceof SnappyDirectDecompressor); ByteBuffer presliced = dst; if (dst.position() > 0) { presliced = dst; dst = dst.slice(); } Buffer originalCompressed = compressedDirectBuf; Buffer originalUncompressed = uncompressedDirectBuf; int originalBufferSize = directBufferSize; compressedDirectBuf = src.slice(); compressedDirectBufLen = src.remaining(); uncompressedDirectBuf = dst; directBufferSize = dst.remaining(); int n = 0; try { n = decompressDirectBuf(); presliced.position(presliced.position() + n); src.position(src.limit()); finished = true; } finally { compressedDirectBuf = originalCompressed; uncompressedDirectBuf = originalUncompressed; compressedDirectBufLen = 0; directBufferSize = originalBufferSize; } return n; }
Source:
protected CompositeJsonFormatter<ILoggingEvent> createFormatter() { LogstashFormatter formatter = new LogstashFormatter(this); formatter.setLineSeparator(getLineSeparator()); return formatter; }

Target:
protected CompositeJsonFormatter<ILoggingEvent> createFormatter() { return new LogstashFormatter(this); }
Source:
protected String getTableName(String streamName) { StringBuilder sb = new StringBuilder(); sb.append(TABLE_PREFIX); sb.append("_"); sb.append(streamName); return sb.toString(); }

Target:
protected String getTableName(String streamName) { StringBuilder sb = new StringBuilder(); sb.append(TABLE_PREFIX); sb.append(TABLE_NAME_SEPARATOR); sb.append(streamName); return sb.toString(); }
Source:
public void shouldNotConvertBeforeGetOnFailedCompletion() throws Exception { final Throwable expectedError = new Throwable(); TestConvertingFutureCallback testCallback = new TestConvertingFutureCallback(); testCallback.onCompletion(expectedError, null); assertEquals(0, testCallback.numberOfConversions()); try { testCallback.get(); } catch (ExecutionException e) { assertEquals(expectedError, e.getCause()); } }

Target:
public void shouldNotConvertBeforeGetOnFailedCompletion() throws Exception { final Throwable expectedError = new Throwable(); TestConvertingFutureCallback testCallback = new TestConvertingFutureCallback(); testCallback.onCompletion(expectedError, null); assertEquals(0, testCallback.numberOfConversions()); try { testCallback.get(); fail("Expected ExecutionException"); } catch (ExecutionException e) { assertEquals(expectedError, e.getCause()); } }
Source:
private boolean rollbackOtherTransaction(long startTs, TransactionService transactionService) { try { transactionService.putUnlessExists(startTs, TransactionConstants.FAILED_COMMIT_TS); return true; } catch (KeyAlreadyExistsException e) { log.error("This isn't a bug but it should be very infrequent. Two transactions tried to roll back someone" + " else's request with start: {}", SafeArg.of("startTs", startTs), new TransactionFailedRetriableException( "Two transactions tried to roll back someone else's request with start: " + startTs, e)); return false; } }

Target:
private boolean rollbackOtherTransaction(long startTs, TransactionService transactionService) { try { transactionService.putUnlessExists(startTs, TransactionConstants.FAILED_COMMIT_TS); return true; } catch (KeyAlreadyExistsException e) { log.info("This isn't a bug but it should be very infrequent. Two transactions tried to roll back someone" + " else's request with start: {}", SafeArg.of("startTs", startTs), new TransactionFailedRetriableException( "Two transactions tried to roll back someone else's request with start: " + startTs, e)); return false; } }
Source:
protected void executeQueryCommand() { final Map<Integer, VmIconIdSizePair> result = new HashMap<>(); final List<VmIconDefault> iconDefaults = vmIconDefaultDao.getAll(); for (VmIconDefault iconDefault : iconDefaults) { result.put(iconDefault.getOsId(), new VmIconIdSizePair(iconDefault.getSmallIconId(), iconDefault.getLargeIconId())); } if (!result.containsKey(OsRepository.DEFAULT_X86_OS)) { throw new RuntimeException("Default icon pair not found."); } setReturnValue(result); }

Target:
protected void executeQueryCommand() { final Map<Integer, VmIconIdSizePair> result = new HashMap<>(); final List<VmIconDefault> iconDefaults = vmIconDefaultDao.getAll(); for (VmIconDefault iconDefault : iconDefaults) { result.put(iconDefault.getOsId(), new VmIconIdSizePair(iconDefault.getSmallIconId(), iconDefault.getLargeIconId())); } if (!result.containsKey(OsRepository.DEFAULT_X86_OS)) { throw new EngineException(EngineError.DefaultIconPairNotFound); } setReturnValue(result); }
Source:
public void returns_project_visibility_public() { OrganizationDto organization = dbTester.organizations().insert(); dbClient.organizationDao().setNewProjectPrivate(dbTester.getSession(), organization, false); dbTester.commit(); userSession.logIn().addPermission(PROVISION_PROJECTS, organization); assertJson(executeRequest(organization).getInput()).isSimilarTo("{\"organization\": {\"projectVisibility\": \"public\"}}"); }

Target:
public void returns_project_visibility_public() { OrganizationDto organization = dbTester.organizations().insert(); dbTester.organizations().setNewProjectPrivate(organization, false); userSession.logIn().addPermission(PROVISION_PROJECTS, organization); assertJson(executeRequest(organization).getInput()).isSimilarTo("{\"organization\": {\"projectVisibility\": \"public\"}}"); }
Source:
public LeaderElectionHealthStatus leaderElectionRateHealthStatus() { return leaderElectionServiceMetrics.proposedLeadership().getFiveMinuteRate() < MAX_ALLOWED_LAST_5_MINUTE_RATE ? LeaderElectionHealthStatus.HEALTHY : LeaderElectionHealthStatus.UNHEALTHY; }

Target:
public LeaderElectionHealthStatus leaderElectionRateHealthStatus() { return leaderElectionServiceMetrics.proposedLeadership().getFiveMinuteRate() <= MAX_ALLOWED_LAST_5_MINUTE_RATE ? LeaderElectionHealthStatus.HEALTHY : LeaderElectionHealthStatus.UNHEALTHY; }
Source:
public void onAddToPlaylistClicked(View v) { final PlaylistType.Item playListItem = new PlaylistType.Item(); playListItem.artistid = artistId; MediaPlayerUtils.queueAudio(this, playListItem); }

Target:
public void onAddToPlaylistClicked(View v) { final PlaylistType.Item playListItem = new PlaylistType.Item(); playListItem.artistid = artistId; MediaPlayerUtils.queue(this, playListItem, PlaylistType.GetPlaylistsReturnType.AUDIO); }
Source:
public String getHashString(RowMap r, PartitionBy by) { if ( by == null ) return UUID.randomUUID().toString(); switch ( by ) { case TABLE: String t = r.getTable(); if ( t == null && partitionByFallback == PartitionBy.DATABASE ) return r.getDatabase(); else return t; case DATABASE: return r.getDatabase(); case PRIMARY_KEY: return r.pkAsConcatString(); case COLUMN: String s = r.buildPartitionKey(partitionColumns); if ( s.length() > 0 ) return s; else return getHashString(r, partitionByFallback); } return null; }

Target:
public String getHashString(RowMap r, PartitionBy by) { switch ( by ) { case TABLE: String t = r.getTable(); if ( t == null && partitionByFallback == PartitionBy.DATABASE ) return r.getDatabase(); else return t; case DATABASE: return r.getDatabase(); case PRIMARY_KEY: return r.pkAsConcatString(); case COLUMN: String s = r.buildPartitionKey(partitionColumns); if ( s.length() > 0 ) return s; else return getHashString(r, partitionByFallback); } return null; }
Source:
public final long argSize() { long size = 0; if (arg2 != null) { size += arg2.readableBytes(); } if (arg3 != null) { size += arg3.readableBytes(); } return size; }

Target:
public final int argSize() { int size = 0; if (arg2 != null) { size += arg2.readableBytes(); } if (arg3 != null) { size += arg3.readableBytes(); } return size; }
Source:
private IZenSymbol find(IEnvironmentGlobal environment, List<Token> tokens, int startIndex, int endIndex) { StringBuilder valueBuilder = new StringBuilder(); for (int i = startIndex; i < endIndex; i++) { Token token = tokens.get(i); valueBuilder.append(token.getValue()); } IMaterial material = getMaterial(valueBuilder.toString()); if (!material.getName().equals("unknown")) { MineTweakerAPI.logInfo("Material wasn't null"); return new MaterialReferenceSymbol(environment, valueBuilder.toString()); } MineTweakerAPI.logInfo("Material was null"); return null; }

Target:
private IZenSymbol find(IEnvironmentGlobal environment, List<Token> tokens, int startIndex, int endIndex) { StringBuilder valueBuilder = new StringBuilder(); for (int i = startIndex; i < endIndex; i++) { Token token = tokens.get(i); valueBuilder.append(token.getValue()); } IMaterial material = getMaterial(valueBuilder.toString()); if (!material.getName().equals("unknown")) { MineTweakerAPI.logInfo("Material wasn't null"); return new MaterialReferenceSymbol(environment, valueBuilder.toString()); } MineTweakerAPI.logError("Material was null"); return null; }
Source:
public String getName() { return "ListBox"; }

Target:
public String getName() { return ListBoxFieldType.NAME; }
Source:
protected void executeCommand() { parameter = getParameters(); String slaveHost = parameter.getSlaveHost(); String slaveUserPassword = parameter.getSlavePassword(); String slaveSShFingerPrint = GlusterUtil.getInstance().getHostSSHFingerPrint(slaveHost); VDSReturnValue sessionCreateReturnValue = null; VDSReturnValue passwordlessSSHCreateReturnValue = runVdsCommand(VDSCommandType.CreatePasswordLessSSHSession, new GlusterSshSessionParameters(slaveHost, slaveSShFingerPrint, parameter.getUserName(), parameter.getSlavePassword())); if (passwordlessSSHCreateReturnValue.getSucceeded()) { sessionCreateReturnValue = runVdsCommand(VDSCommandType.GlusterVolumeGeoRepSessionCreate, new GlusterVolumeGeoRepVDSParamaters(upServer.getId(), masterVolume.getName(), slaveHost, slaveUserPassword, parameter.getSlaveVolumeName(), parameter.isForce())); if (!getSucceeded()) { handleVdsError(AuditLogType.GLUSTER_VOLUME_GEO_REP_CREATE_FAILED, sessionCreateReturnValue.getVdsError().getMessage()); return; } setSucceeded(sessionCreateReturnValue.getSucceeded()); } else { handleVdsError(AuditLogType.GLUSTER_VOLUME_PASSWORD_LESS_SSH_FAILED, passwordlessSSHCreateReturnValue.getVdsError().getMessage()); setSucceeded(false); } getReturnValue().setActionReturnValue(sessionCreateReturnValue); }

Target:
protected void executeCommand() { String slaveHost = parameter.getSlaveHost(); String slaveSShFingerPrint = GlusterUtil.getInstance().getHostSSHFingerPrint(slaveHost); VDSReturnValue sessionCreateReturnValue = null; VDSReturnValue passwordlessSSHCreateReturnValue = runVdsCommand(VDSCommandType.CreatePasswordLessSSHSession, new GlusterSshSessionParameters(slaveHost, slaveSShFingerPrint, parameter.getUserName(), parameter.getSlaveUserPassword())); if (passwordlessSSHCreateReturnValue.getSucceeded()) { sessionCreateReturnValue = runVdsCommand(VDSCommandType.GlusterVolumeGeoRepSessionCreate, new GlusterVolumeGeoRepSessionVDSParameters(upServer.getId(), masterVolume.getName(), slaveHost, parameter.getSlaveVolumeName(), parameter.isForce())); if (!sessionCreateReturnValue.getSucceeded()) { handleVdsError(AuditLogType.GLUSTER_VOLUME_GEO_REP_CREATE_FAILED, sessionCreateReturnValue.getVdsError().getMessage()); return; } setSucceeded(sessionCreateReturnValue.getSucceeded()); } else { handleVdsError(AuditLogType.GLUSTER_VOLUME_PASSWORD_LESS_SSH_FAILED, passwordlessSSHCreateReturnValue.getVdsError().getMessage()); setSucceeded(false); } getReturnValue().setActionReturnValue(sessionCreateReturnValue); }
Source:
DriverChannel next() { DriverChannel[] snapshot = this.channels; switch (snapshot.length) { case 0: return null; case 1: DriverChannel onlyChannel = snapshot[0]; return onlyChannel.preAcquireId() ? onlyChannel : null; default: while (true) { DriverChannel best = null; int bestScore = 0; for (DriverChannel channel : snapshot) { int score = channel.getAvailableIds(); if (score > bestScore) { bestScore = score; best = channel; } } if (best == null) { return null; } else if (best.preAcquireId()) { return best; } } } }

Target:
DriverChannel next() { DriverChannel[] snapshot = this.channels; switch (snapshot.length) { case 0: return null; case 1: DriverChannel onlyChannel = snapshot[0]; return onlyChannel.preAcquireId() ? onlyChannel : null; default: for (int i = 0; i < MAX_ITERATIONS; i++) { DriverChannel best = null; int bestScore = 0; for (DriverChannel channel : snapshot) { int score = channel.getAvailableIds(); if (score > bestScore) { bestScore = score; best = channel; } } if (best == null) { return null; } else if (best.preAcquireId()) { return best; } } LOG.trace("Could not select a channel after iterations", MAX_ITERATIONS); return null; } }
Source:
private void filterBufferAndResetFetchRunnable(Set<StreamPartition<String>> partitions) { scheduledExec.shutdown(); try { if (!scheduledExec.awaitTermination(EXCEPTION_RETRY_DELAY_MS, TimeUnit.MILLISECONDS)) { scheduledExec.shutdownNow(); } } catch (InterruptedException e) { log.info(e, "InterruptedException while shutting down"); } scheduledExec = Executors.newScheduledThreadPool( fetchThreads, Execs.makeThreadFactory("KinesisRecordSupplier-Worker-%d") ); BlockingQueue<OrderedPartitionableRecord<String, String>> newQ = new LinkedBlockingQueue<>(recordBufferSize); records .parallelStream() .filter(x -> !partitions.contains(x.getStreamPartition())) .forEachOrdered(newQ::offer); records = newQ; partitionResources.values().forEach(x -> x.started = false); checkPartitionsStarted = true; }

Target:
private void filterBufferAndResetFetchRunnable(Set<StreamPartition<String>> partitions) throws InterruptedException { scheduledExec.shutdown(); try { if (!scheduledExec.awaitTermination(EXCEPTION_RETRY_DELAY_MS, TimeUnit.MILLISECONDS)) { scheduledExec.shutdownNow(); } } catch (InterruptedException e) { log.warn(e, "InterruptedException while shutting down"); throw e; } scheduledExec = Executors.newScheduledThreadPool( fetchThreads, Execs.makeThreadFactory("KinesisRecordSupplier-Worker-%d") ); BlockingQueue<OrderedPartitionableRecord<String, String>> newQ = new LinkedBlockingQueue<>(recordBufferSize); records .stream() .filter(x -> !partitions.contains(x.getStreamPartition())) .forEachOrdered(newQ::offer); records = newQ; partitionResources.values().forEach(x -> x.started = false); checkPartitionsStarted = true; }
Source:
private void updateD(SolGame game) { ObjectManager om = game.getObjectManager(); List<SolObject> objs = om.getObjects(); List<FarObjData> farObjs = om.getFarObjs(); if (drawable != null) { if (objs.contains(drawable)) { return; } drawable = null; for (FarObjData fod : farObjs) { FarObject fo = fod.fo; if (!(fo instanceof FarDrawable)) { continue; } List<Drawable> drawables = ((FarDrawable) fo).getDrawables(); if (drawables.size() != 3) { continue; } Drawable drawable = drawables.get(0); if (drawable != attackSprite) { continue; } farDrawable = (FarDrawable) fo; return; } throw new AssertionError("The far object data in " + game + " is a FarDrawable object, does not contain 3 elements in drawables, or the first drawable isnt attackSprite"); } if (farDrawable == null) { throw new AssertionError("Far drawable does not exist!"); } if (om.containsFarObj(farDrawable)) { return; } farDrawable = null; for (SolObject o : objs) { if ((o instanceof DrawableObject)) { List<Drawable> drawables = o.getDrawables(); if (drawables.size() != 3) { continue; } Drawable drawable = drawables.get(0); if (drawable != attackSprite) { continue; } this.drawable = (DrawableObject) o; return; } } throw new AssertionError("The SolObject in " + game + " is a DrawableObject without 3 elements in drawables or the first drawable element is not an attackSprite"); }

Target:
private void updateD(SolGame game) { ObjectManager om = game.getObjectManager(); List<SolObject> objs = om.getObjects(); List<FarObjData> farObjs = om.getFarObjs(); if (drawable != null) { if (objs.contains(drawable)) { return; } drawable = null; for (FarObjData fod : farObjs) { FarObject fo = fod.fo; if (!(fo instanceof FarDrawable)) { continue; } List<Drawable> drawables = ((FarDrawable) fo).getDrawables(); if (drawables.size() != 3) { continue; } Drawable drawable = drawables.get(0); if (drawable != attackSprite) { continue; } farDrawable = (FarDrawable) fo; return; } throw new AssertionError("The far object data in game is a FarDrawable object, does not contain 3 elements in drawables, or the first drawable isnt attackSprite"); } if (farDrawable == null) { throw new AssertionError("Far drawable is null!"); } if (om.containsFarObj(farDrawable)) { return; } farDrawable = null; for (SolObject o : objs) { if ((o instanceof DrawableObject)) { List<Drawable> drawables = o.getDrawables(); if (drawables.size() != 3) { continue; } Drawable drawable = drawables.get(0); if (drawable != attackSprite) { continue; } this.drawable = (DrawableObject) o; return; } } throw new AssertionError("The SolObject in game is a DrawableObject without 3 elements in drawables or the first drawable element is not an attackSprite"); }
Source:
public void removeMapping() throws LegalSPITesterException { long nbMappings = 10; tier = factory.newCachingTier(); V originalValue= factory.createValue(1); V newValue= factory.createValue(2); final Store.ValueHolder<V> originalValueHolder = mock(Store.ValueHolder.class); when(originalValueHolder.value()).thenReturn(originalValue); try { List<K> keys = new ArrayList<K>(); for (int i = 0; i < nbMappings; i++) { K key = factory.createKey(i); tier.getOrComputeIfAbsent(key, new Function<K, Store.ValueHolder<V>>() { @Override public Store.ValueHolder<V> apply(final K k) { return originalValueHolder; } }); keys.add(key); } tier.clear(); final Store.ValueHolder<V> newValueHolder = mock(Store.ValueHolder.class); when(newValueHolder.value()).thenReturn(newValue); for (K key : keys) { tier.invalidate(key); Store.ValueHolder<V> newReturnedValueHolder = tier.getOrComputeIfAbsent(key, new Function() { @Override public Object apply(final Object o) { return newValueHolder; } }); if (newReturnedValueHolder != null) { assertThat(newReturnedValueHolder.value(), is(equalTo(newValueHolder.value()))); } } } catch (CacheAccessException e) { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); } }

Target:
public void removeMapping() throws LegalSPITesterException { long nbMappings = 10; tier = factory.newCachingTier(); V originalValue= factory.createValue(1); V newValue= factory.createValue(2); final Store.ValueHolder<V> originalValueHolder = mock(Store.ValueHolder.class); when(originalValueHolder.value()).thenReturn(originalValue); try { List<K> keys = new ArrayList<K>(); for (int i = 0; i < nbMappings; i++) { K key = factory.createKey(i); tier.getOrComputeIfAbsent(key, new Function<K, Store.ValueHolder<V>>() { @Override public Store.ValueHolder<V> apply(final K k) { return originalValueHolder; } }); keys.add(key); } tier.clear(); final Store.ValueHolder<V> newValueHolder = mock(Store.ValueHolder.class); when(newValueHolder.value()).thenReturn(newValue); for (K key : keys) { tier.invalidate(key); Store.ValueHolder<V> newReturnedValueHolder = tier.getOrComputeIfAbsent(key, new Function() { @Override public Object apply(final Object o) { return newValueHolder; } }); assertThat(newReturnedValueHolder.value(), is(equalTo(newValueHolder.value()))); } } catch (CacheAccessException e) { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); } }
Source:
public GroupMembership addGroup(String hrefOrName) { Group group = findGroup(hrefOrName); if (group != null){ return DefaultGroupMembership.create(this, group, getDataStore()); } return null; }

Target:
public GroupMembership addGroup(String hrefOrName) { Assert.hasText(hrefOrName, "hrefOrName cannot be null or empty"); Group group = findGroupInDirectory(hrefOrName, this.getDirectory()); if (group != null){ return DefaultGroupMembership.create(this, group, getDataStore()); } else { throw new IllegalStateException("The specified group was not found in this Account's directory."); } }
Source:
private GeneratedColumns() { toValidate = Collections.emptyMap(); toInject = Collections.emptyMap(); maybeInjectNested = Collections.emptyMap(); expressions = Collections.emptyList(); }

Target:
private GeneratedColumns() { validation = Validation.NONE; nestedReferenceByTopLevelColumnName = Collections.emptyMap(); toInject = Collections.emptyMap(); expressions = Collections.emptyList(); }
Source:
public void convertProductReference() { assertThat(converting(ATTR_NAME_REF_SET)).isNull(); }

Target:
public void convertProductReference() { assertThat(converting(ATTR_NAME_REF)).matches(Pattern.compile("\\S+")); }
Source:
public Map<String, String> getTags() { return null; }

Target:
public Map<String, String> getTags() { return tags; }
Source:
public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { if (!children.get(1).evaluate(tuple, ptr)) { return false; } String[] pattern =decodePath((String)PVarchar.INSTANCE.toObject(ptr)); if (!children.get(0).evaluate(tuple, ptr)) { return false; } PhoenixJson value = (PhoenixJson) PJson.INSTANCE.toObject(ptr); try{ PhoenixJson jsonValue=value.getPhoenixJson(pattern); ptr.set(jsonValue.valueWrapToBytes()); datatype=jsonValue.getValueAsPDataType(); return true; }catch(SQLException e) { return false; } }

Target:
public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { if (!children.get(1).evaluate(tuple, ptr)) { return false; } PhoenixArray pattern =(PhoenixArray)PVarcharArray.INSTANCE.toObject(ptr); if (!children.get(0).evaluate(tuple, ptr)) { return false; } PhoenixJson value = (PhoenixJson) PJson.INSTANCE.toObject(ptr); if(value==null){ ptr.set(PDataType.FALSE_BYTES); return true; } try{ PhoenixJson jsonValue=value.getPhoenixJson((String[])pattern.getArray()); ptr.set(jsonValue.valueWrapToBytes()); return true; }catch(SQLException e) { return false; } }
Source:
public String toStatement() { return statementBuilder.toString(); }

Target:
public String toStatement() { StringBuilder buffer = new StringBuilder(); String columnNames = String.join( ",", (CharSequence[]) getColumns() ); for ( int i = 0; i < getIds().size(); i++ ) { Object[] idTokens = getIds().get( i ); if ( i > 0 ) { if( chunkLimit > 0 && i % chunkLimit == 0 ) { buffer.append( " ) or ( " ); buffer.append( columnNames ); buffer.append( " ) in (" ); } else { buffer.append( "," ); } } buffer.append( "(" ); buffer.append( quoteIdentifier( idTokens ) ); buffer.append( ")" ); } return buffer.toString(); }
Source:
public synchronized void setTaskScheduler(TaskScheduler taskScheduler) { this.internalTaskScheduler = false; this.taskScheduler = taskScheduler; }

Target:
public synchronized void setTaskScheduler(TaskScheduler taskScheduler) { Assert.notNull(taskScheduler, "'taskScheduler' cannot be null"); this.internalTaskScheduler = false; this.taskScheduler = taskScheduler; }
Source:
protected LockProperties getLockingPropertiesSettings() { return null; }

Target:
protected LockProperties getLockingPropertiesSettings() { return new LockProperties().setObtainLock(false); }
Source:
NetworkClient getNetworkClient() throws IOException { Selector selector = new Selector(networkMetrics, time, sslFactory); ConnectionTracker connectionTracker = new ConnectionTracker(maxConnectionsPerPortPlainText, maxConnectionsPerPortSsl, time); return new NetworkClient(selector, connectionTracker, networkConfig, networkRequestMetrics, connectionCheckoutTimeoutMs, time); }

Target:
NetworkClient getNetworkClient() throws IOException { Selector selector = new Selector(networkMetrics, time, sslFactory); ConnectionTracker connectionTracker = new ConnectionTracker(maxConnectionsPerPortPlainText, maxConnectionsPerPortSsl); return new NetworkClient(selector, connectionTracker, networkConfig, connectionCheckoutTimeoutMs, time); }
Source:
public Iterator<Journal.JournalEntry> getJournalEntryIterator() { List<Iterator<Journal.JournalEntry>> componentIters = StreamUtils .map(JournalEntryIterable::getJournalEntryIterator, mDBs.values()); return Iterators.concat(getDbIterator(), getDbInfoIterator(), Iterators.concat(componentIters.iterator())); }

Target:
public Iterator<Journal.JournalEntry> getJournalEntryIterator() { List<Iterator<Journal.JournalEntry>> componentIters = StreamUtils .map(JournalEntryIterable::getJournalEntryIterator, mDBs.values()); return Iterators.concat(getDbIterator(), Iterators.concat(componentIters.iterator())); }
Source:
public MultipleJGitEnvironmentRepository build(MultipleJGitEnvironmentProperties environmentProperties) { MultipleJGitEnvironmentRepository repository = new MultipleJGitEnvironmentRepository(environment, environmentProperties); repository.setTransportConfigCallback(propertiesBasedSshTransportCallback(environmentProperties)); if (server.getDefaultLabel() != null) { repository.setDefaultLabel(server.getDefaultLabel()); } return repository; }

Target:
public MultipleJGitEnvironmentRepository build(MultipleJGitEnvironmentProperties environmentProperties) { MultipleJGitEnvironmentRepository repository = new MultipleJGitEnvironmentRepository(environment, environmentProperties); repository.setTransportConfigCallback(customTransportConfigCallback .orElse(buildTransportConfigCallback(environmentProperties))); if (server.getDefaultLabel() != null) { repository.setDefaultLabel(server.getDefaultLabel()); } return repository; }
Source:
private static Color getDistinctForeground(RGB rgb) { final int luminanceThreshold = 128; final double redFactor = 0.2126; final double greenFactor = 0.7152; final double blueFactor = 0.0722; int luminance = (int) (redFactor * rgb.red + greenFactor * rgb.green + blueFactor * rgb.blue); return Display.getDefault().getSystemColor( luminance > luminanceThreshold ? SWT.COLOR_BLACK : SWT.COLOR_WHITE); }

Target:
private static Color getDistinctForeground(RGB rgb) { final int luminanceThreshold = 128; final double redCoefficient = 0.2126; final double greenCoefficient = 0.7152; final double blueCoefficient = 0.0722; int luminance = (int) (redCoefficient * rgb.red + greenCoefficient * rgb.green + blueCoefficient * rgb.blue); return Display.getDefault().getSystemColor( luminance > luminanceThreshold ? SWT.COLOR_BLACK : SWT.COLOR_WHITE); }