auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private SingleFieldConstraint getLHSBoundField(IPattern pat, String var) { if (pat instanceof FromCompositeFactPattern) { pat = ((FromCompositeFactPattern) pat).getFactPattern(); } if (pat instanceof CompositeFactPattern) { IFactPattern[] patterns = ((CompositeFactPattern) pat).getPatterns(); if (patterns != null) { for (IPattern iPattern : patterns) { SingleFieldConstraint fieldConstraint = getLHSBoundField(iPattern, var); if (fieldConstraint != null) { return fieldConstraint; } } } } if (pat instanceof FactPattern) { final FactPattern p = (FactPattern) pat; for (int j = 0; j < p.getFieldConstraints().length; j++) { if (p.getFieldConstraints()[j] instanceof SingleFieldConstraint) { SingleFieldConstraint fc = (SingleFieldConstraint) p.getFieldConstraints()[j]; List<String> fieldBindings = getFieldBinding(fc); if (fieldBindings.contains(var)) { return fc; } } } } return null; }

Target:
private SingleFieldConstraint getLHSBoundField(IPattern pat, String var) { if (pat instanceof FromCompositeFactPattern) { pat = ((FromCompositeFactPattern) pat).getFactPattern(); } if (pat instanceof CompositeFactPattern) { final IFactPattern[] patterns = ((CompositeFactPattern) pat).getPatterns(); if (patterns != null) { for (IPattern iPattern : patterns) { SingleFieldConstraint fieldConstraint = getLHSBoundField(iPattern, var); if (fieldConstraint != null) { return fieldConstraint; } } } } if (pat instanceof FactPattern) { final FactPattern p = (FactPattern) pat; for (int j = 0; j < p.getFieldConstraints().length; j++) { if (p.getFieldConstraints()[j] instanceof SingleFieldConstraint) { SingleFieldConstraint fc = (SingleFieldConstraint) p.getFieldConstraints()[j]; List<String> fieldBindings = getFieldBinding(fc); if (fieldBindings.contains(var)) { return fc; } } } } return null; }
Source:
public int size() { return size; }

Target:
public int size() { return timeStamps.size(); }
Source:
private void sendSuccessfullyUpdatedAccountsNotification(List<Account> updatedAccounts) { Map<String, Object> model = new HashMap<>(); model.put("accounts", updatedAccounts); model.put("today", LocalDate.now(UTC)); final String subjectMessageKey = "subject.account.updatedRemainingDays"; final String templateName = "updated_accounts"; final Mail toOffice= Mail.builder() .withRecipient(NOTIFICATION_OFFICE) .withSubject(subjectMessageKey) .withTemplate(templateName, model) .build(); mailService.send(toOffice); final Mail toTechnical = Mail.builder() .withRecipient(true) .withSubject(subjectMessageKey) .withTemplate(templateName, model) .build(); mailService.send(toTechnical); }

Target:
private void sendSuccessfullyUpdatedAccountsNotification(List<Account> updatedAccounts) { Map<String, Object> model = new HashMap<>(); model.put("accounts", updatedAccounts); model.put("today", LocalDate.now(UTC)); final String subjectMessageKey = "subject.account.updatedRemainingDays"; final String templateName = "updated_accounts"; final Mail mailToOffice= Mail.builder() .withRecipient(NOTIFICATION_OFFICE) .withSubject(subjectMessageKey) .withTemplate(templateName, model) .build(); mailService.send(mailToOffice); final Mail mailToTechnical = Mail.builder() .withTechnicalRecipient(true) .withSubject(subjectMessageKey) .withTemplate(templateName, model) .build(); mailService.send(mailToTechnical); }
Source:
private static Response buildServerError(Exception exception) { log.warn("", exception); String message = exception.getMessage(); if (message == null) { message = exception.toString(); } String stack = ""; for (StackTraceElement s : exception.getStackTrace()) { stack += s + "\n"; } JSONObject body = new JSONObject(); String response; try { body.put("error", "A java exception was thrown."); body.put("message", message); body.put("stack", stack); response = body.toString(); } catch(JSONException ex) { log.error("[buildServerError]", "failed to construct a json response"); response = "{\"error\": \"Failed to serialize java exception. Please see spawn logs for more details.\"}"; } return Response.serverError().entity(response).build(); }

Target:
private static Response buildServerError(Exception exception) { log.warn("", exception); String message = exception.getMessage(); if (message == null) { message = exception.toString(); } String stack = Throwables.getStackTraceAsString(exception); final String response = "{" + "\"error\": \"A java exception was thrown." + "\"message\": \"" + StringEscapeUtils.escapeEcmaScript(message) + "\"" + "\"stack\": \"" + StringEscapeUtils.escapeEcmaScript(stack) + "\"" + "\"}"; return Response.serverError().entity(response).build(); }
Source:
public ICompletionProposal[] getCompletionProposals() { List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>(); String[] strings = completionMap.get(acKey); for (int i = 0; i < strings.length; i++) { if (!strings[i].startsWith(prefix)) continue; String proposal = strings[i] + "=\"\""; proposals.add(new CompletionProposal(proposal, offset - prefix.length(), prefix.length(), proposal.length() - 1, null, strings[i], null, null)); } return (ICompletionProposal[]) proposals.toArray(new ICompletionProposal[proposals.size()]); }

Target:
public ICompletionProposal[] getCompletionProposals() { List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>(); String[] strings = completionMap.get(acKey); for (String string: strings){ if (!string.startsWith(prefix)){ continue; } String proposal = string + "=\"\""; proposals.add(new CompletionProposal(proposal, offset - prefix.length(), prefix.length(), proposal.length() - 1, null, string, null, null)); } return (ICompletionProposal[]) proposals.toArray(new ICompletionProposal[proposals.size()]); }
Source:
public void addCustomHeader(final String key, final String value) { this.customHeaders.add(new Map.Entry<String, String>() { public String getKey() { return key; } public String getValue() { return value; } public String setValue(String value) { return null; } }); }

Target:
public void addCustomHeader(final String key, final String value) { this.customHeaders.add(new AbstractMap.SimpleEntry<>(key, value)); }
Source:
public int read() throws IOException { final int b = is.read(); if (b != '\r') { return b; } final int future = is.read(); if (future == '\n') { return '\n'; } is.unread(future); return b; }

Target:
public int read() throws IOException { final int read = read(single, 0, 1); return read == 1 ? single[0] : -1; }
Source:
public void testEqualsAndHashCodeOfTagClass() { final Object tag = getTagsAfterExecution(" final EqualsVerifierReport ev = EqualsVerifier.forClass(tag.getClass()) .usingGetClass().report(); assertEquals("Error: " + ev.getMessage(), EqualsVerifierReport.SUCCESS, ev); }

Target:
public void testEqualsAndHashCodeOfTagClass() { final Object tag = getTagsAfterExecutionOnDefaultFilter(" final EqualsVerifierReport ev = EqualsVerifier.forClass(tag.getClass()) .usingGetClass().report(); assertEquals("Error: " + ev.getMessage(), EqualsVerifierReport.SUCCESS, ev); }
Source:
public Object invoke(Object proxy, final Method method, Object[] args) { try { final SwaggerMethodParser methodParser; final HttpRequest request; if (method.isAnnotationPresent(ResumeOperation.class)) { OperationDescription opDesc = ImplUtils.findFirstOfType(args, OperationDescription.class); Method resumeMethod = determineResumeMethod(method, opDesc.getMethodName()); methodParser = getMethodParser(resumeMethod); request = createHttpRequest(opDesc, methodParser, args); final Type returnType = methodParser.getReturnType(); return handleResumeOperation( request, opDesc, methodParser, returnType, startTracingSpan(resumeMethod, Context.NONE)); } else { methodParser = getMethodParser(method); request = createHttpRequest(methodParser, args); Context context = methodParser.setContext(args).addData("caller-method", methodParser.getFullyQualifiedMethodName()); context = startTracingSpan(method, context); if (request.getBody() != null) { request.setBody(validateLength(request)); } final Mono<HttpResponse> asyncResponse = send(request, context); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleHttpResponse(request, asyncDecodedResponse, methodParser, methodParser.getReturnType(), context); } } catch (Exception e) { throw logger.logExceptionAsError(new RuntimeException( "Error occurs during sending request and deserializing response. Error Details: "+ e.getMessage(), e)); } }

Target:
public Object invoke(Object proxy, final Method method, Object[] args) { try { final SwaggerMethodParser methodParser; final HttpRequest request; if (method.isAnnotationPresent(ResumeOperation.class)) { OperationDescription opDesc = ImplUtils.findFirstOfType(args, OperationDescription.class); Method resumeMethod = determineResumeMethod(method, opDesc.getMethodName()); methodParser = getMethodParser(resumeMethod); request = createHttpRequest(opDesc, methodParser, args); final Type returnType = methodParser.getReturnType(); return handleResumeOperation( request, opDesc, methodParser, returnType, startTracingSpan(resumeMethod, Context.NONE)); } else { methodParser = getMethodParser(method); request = createHttpRequest(methodParser, args); Context context = methodParser.setContext(args).addData("caller-method", methodParser.getFullyQualifiedMethodName()); context = startTracingSpan(method, context); if (request.getBody() != null) { request.setBody(validateLength(request)); } final Mono<HttpResponse> asyncResponse = send(request, context); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleHttpResponse(request, asyncDecodedResponse, methodParser, methodParser.getReturnType(), context); } } catch (IOException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }
Source:
public Integer getPermissions() { return Utils.asInteger(this.get("permissions")); }

Target:
public String getPermissions() { return (String) this.get("permissions"); }
Source:
private String getTaskUrl(String reviewUrlToFind) { for (Map.Entry<String, List<String>> mapping : taskReviewsMap.entrySet()) { for (String reviewUrl : mapping.getValue()) { if (reviewUrlToFind.equals(reviewUrl)) { return mapping.getKey(); } } } return null; }

Target:
private String getTaskUrl(String reviewUrlToFind) { for (Map.Entry<String, List<String>> mapping : taskReviewsMap.entrySet()) { int index = mapping.getValue().indexOf(reviewUrlToFind); if (index != -1) { return mapping.getKey(); } } return null; }
Source:
public void emit(Event event) { if (event instanceof ServiceMetricEvent) { ServiceMetricEvent metricEvent = (ServiceMetricEvent) event; try { ganglia.announce( sanitize(metricEvent.getService() + "_" + metricEvent.getMetric()), metricEvent.getValue().doubleValue(), metricEvent.getService() ); } catch (GangliaException e) { log.error(e, "Dropping event [%s]. Unable to send to Ganglia.", event); } } }

Target:
public void emit(Event event) { if (event instanceof ServiceMetricEvent) { ServiceMetricEvent metricEvent = (ServiceMetricEvent) event; String name = sanitize(metricEvent.getService() + "_" + metricEvent.getMetric()); Histogram histogram = registry.histogram(name); histogram.update(metricEvent.getValue().longValue()); try { ganglia.announce( name, histogram.getSnapshot().get95thPercentile(), metricEvent.getService() ); } catch (GangliaException e) { log.error(e, "Dropping event [%s]. Unable to send to Ganglia.", event); } } }
Source:
private void acceptConnections() throws IOException { Socket socket = null; boolean error = false; try { socket = serverSocket.accept(); socket.setSoTimeout(self.tickTime * self.initLimit); socket.setTcpNoDelay(nodelay); BufferedInputStream is = new BufferedInputStream(socket.getInputStream()); LearnerHandler fh = new LearnerHandler(socket, is, Leader.this); fh.start(); } catch (SocketException e) { error = true; if (stop.get()) { LOG.info("Exception while shutting down acceptor", e); } else { throw e; } } catch (SaslException e) { LOG.error("Exception while connecting to quorum learner", e); error = true; } catch (Exception e) { error = true; throw e; } finally { if (error && socket != null && !socket.isClosed()) { try { socket.close(); } catch (IOException e) { LOG.warn("Error closing socket", e); } } } }

Target:
private void acceptConnections() throws IOException { Socket socket = null; boolean error = false; try { socket = serverSocket.accept(); socket.setSoTimeout(self.tickTime * self.initLimit); socket.setTcpNoDelay(nodelay); BufferedInputStream is = new BufferedInputStream(socket.getInputStream()); LearnerHandler fh = new LearnerHandler(socket, is, Leader.this); fh.start(); } catch (SocketException e) { error = true; if (stop.get()) { LOG.warn("Exception while shutting down acceptor.", e); } else { throw e; } } catch (SaslException e) { LOG.error("Exception while connecting to quorum learner", e); error = true; } catch (Exception e) { error = true; throw e; } finally { if (error && socket != null && !socket.isClosed()) { try { socket.close(); } catch (IOException e) { LOG.warn("Error closing socket: " + socket, e); } } } }
Source:
public void visitToken(DetailAST ast) { final DetailAST startToken; DetailAST brace; switch (ast.getType()) { case TokenTypes.CTOR_DEF: case TokenTypes.METHOD_DEF: startToken = skipAnnotationOnlyLines(ast); brace = ast.findFirstToken(TokenTypes.SLIST); break; case TokenTypes.INTERFACE_DEF: case TokenTypes.CLASS_DEF: case TokenTypes.ANNOTATION_DEF: case TokenTypes.ENUM_DEF: case TokenTypes.ENUM_CONSTANT_DEF: startToken = skipAnnotationOnlyLines(ast); final DetailAST objBlock = ast.findFirstToken(TokenTypes.OBJBLOCK); brace = objBlock; if (objBlock != null) { brace = objBlock.getFirstChild(); } break; case TokenTypes.LITERAL_CASE: case TokenTypes.LITERAL_DEFAULT: startToken = ast; brace = null; if (ast.getNextSibling() != null) { brace = ast.getNextSibling().findFirstToken(TokenTypes.SLIST); } break; case TokenTypes.LITERAL_ELSE: startToken = ast; final DetailAST candidate = ast.getFirstChild(); brace = null; if (candidate.getType() == TokenTypes.SLIST) { brace = candidate; } break; case TokenTypes.LITERAL_SWITCH: startToken = ast; brace = ast.findFirstToken(TokenTypes.LCURLY); break; default: startToken = ast; brace = ast.findFirstToken(TokenTypes.SLIST); break; } if (brace != null) { verifyBrace(brace, startToken); } }

Target:
public void visitToken(DetailAST ast) { final DetailAST startToken; final DetailAST brace; switch (ast.getType()) { case TokenTypes.CTOR_DEF: case TokenTypes.METHOD_DEF: startToken = skipAnnotationOnlyLines(ast); brace = ast.findFirstToken(TokenTypes.SLIST); break; case TokenTypes.INTERFACE_DEF: case TokenTypes.CLASS_DEF: case TokenTypes.ANNOTATION_DEF: case TokenTypes.ENUM_DEF: case TokenTypes.ENUM_CONSTANT_DEF: startToken = skipAnnotationOnlyLines(ast); brace = findBraceForTypeDefinition(ast); break; case TokenTypes.LITERAL_CASE: case TokenTypes.LITERAL_DEFAULT: startToken = ast; brace = findBraceForCaseGroup(ast); break; case TokenTypes.LITERAL_WHILE: case TokenTypes.LITERAL_CATCH: case TokenTypes.LITERAL_SYNCHRONIZED: case TokenTypes.LITERAL_FOR: case TokenTypes.LITERAL_TRY: case TokenTypes.LITERAL_FINALLY: case TokenTypes.LITERAL_DO: case TokenTypes.LITERAL_IF: case TokenTypes.STATIC_INIT: case TokenTypes.LAMBDA: startToken = ast; brace = ast.findFirstToken(TokenTypes.SLIST); break; case TokenTypes.LITERAL_ELSE: startToken = ast; brace = findBraceForElse(ast); break; default: startToken = ast; brace = ast.findFirstToken(TokenTypes.LCURLY); break; } if (brace != null) { verifyBrace(brace, startToken); } }
Source:
T bufferedIndexedGet(ByteBuffer copyValueBuffer, int startOffset, int endOffset) { final int size = endOffset > startOffset ? endOffset - startOffset : copyValueBuffer.get(startOffset - Ints.BYTES); lastReadSize = size; copyValueBuffer.clear(); copyValueBuffer.position(startOffset); return strategy.fromByteBuffer(copyValueBuffer, size); }

Target:
T bufferedIndexedGet(ByteBuffer copyValueBuffer, int startOffset, int endOffset) { int size = endOffset - startOffset; if (size == 0 && (NullHandling.replaceWithDefault() || copyValueBuffer.get(startOffset - Integer.BYTES) == NULL_VALUE_SIZE_MARKER)) { return null; } lastReadSize = size; copyValueBuffer.clear(); copyValueBuffer.position(startOffset); return strategy.fromByteBuffer(copyValueBuffer, size); }
Source:
public RemoteOperationResult(Exception e) { mException = e; if (e instanceof OperationCancelledException) { mCode = ResultCode.CANCELLED; } else if (e instanceof SocketException) { mCode = ResultCode.WRONG_CONNECTION; } else if (e instanceof SocketTimeoutException) { mCode = ResultCode.TIMEOUT; } else if (e instanceof ConnectTimeoutException) { mCode = ResultCode.TIMEOUT; } else if (e instanceof MalformedURLException) { mCode = ResultCode.INCORRECT_ADDRESS; } else if (e instanceof UnknownHostException) { mCode = ResultCode.HOST_NOT_AVAILABLE; } else if (e instanceof AccountNotFoundException) { mCode = ResultCode.ACCOUNT_NOT_FOUND; } else if (e instanceof AccountsException) { mCode = ResultCode.ACCOUNT_EXCEPTION; } else if (e instanceof SSLException || e instanceof RuntimeException) { CertificateCombinedException se = getCertificateCombinedException(e); if (se != null) { mException = se; if (se.isRecoverable()) { mCode = ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED; } } else if (e instanceof RuntimeException) { mCode = ResultCode.HOST_NOT_AVAILABLE; } else { mCode = ResultCode.SSL_ERROR; } } else if (e instanceof JSONException) { mCode = ResultCode.JSON_EXCEPTION; } else { mCode = ResultCode.UNKNOWN_ERROR; } }

Target:
public RemoteOperationResult(Exception e) { mException = e; if (e instanceof OperationCancelledException) { mCode = ResultCode.CANCELLED; } else if (e instanceof SocketException) { mCode = ResultCode.WRONG_CONNECTION; } else if (e instanceof SocketTimeoutException) { mCode = ResultCode.TIMEOUT; } else if (e instanceof ConnectTimeoutException) { mCode = ResultCode.TIMEOUT; } else if (e instanceof MalformedURLException) { mCode = ResultCode.INCORRECT_ADDRESS; } else if (e instanceof UnknownHostException) { mCode = ResultCode.HOST_NOT_AVAILABLE; } else if (e instanceof AccountNotFoundException) { mCode = ResultCode.ACCOUNT_NOT_FOUND; } else if (e instanceof AccountsException) { mCode = ResultCode.ACCOUNT_EXCEPTION; } else if (e instanceof SSLException || e instanceof RuntimeException) { CertificateCombinedException se = getCertificateCombinedException(e); if (se != null) { mException = se; if (se.isRecoverable()) { mCode = ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED; } } else if (e instanceof RuntimeException) { mCode = ResultCode.HOST_NOT_AVAILABLE; } else { mCode = ResultCode.SSL_ERROR; } } else { mCode = ResultCode.UNKNOWN_ERROR; } }
Source:
private ShowSourceForm(String action, boolean showReloadButton) { $$$setupUI$$$(); this.action = action; this.showReloadButton = showReloadButton; resetButton.addActionListener(__ -> onResetCallbacks.forEach(Runnable::run)); reloadButton.addActionListener(__ -> onReloadCallbacks.forEach(Runnable::run)); onReloadCallbacks.add(() -> { reloadButton.setEnabled(false); TimerTask task = new TimerTask() { public void run() { reloadButton.setEnabled(true); } }; Timer timer = new Timer(); long delayMillis = 5000L; timer.schedule(task, delayMillis); }); if (!showReloadButton) reloadButton.setVisible(false); }

Target:
private ShowSourceForm(String action, boolean showReloadButton) { $$$setupUI$$$(); this.action = action; this.showReloadButton = showReloadButton; resetButton.addActionListener(__ -> onResetCallbacks.forEach(Runnable::run)); reloadButton.addActionListener(__ -> onReloadCallbacks.forEach(Runnable::run)); onReloadCallbacks.add(() -> { reloadButton.setEnabled(false); reloadTimerElapsed = false; reloadOperationCompleted = false; Timer t = new Timer(5000, (e) -> markReloadTimerElapsed()); t.setRepeats(false); t.start(); }); if (!showReloadButton) reloadButton.setVisible(false); }
Source:
private synchronized void scheduleUpdate() { schedExecutor.schedule(() -> updatePartitionInfo(), 0, TimeUnit.MILLISECONDS); }

Target:
private synchronized void scheduleUpdate() { schedExecutor.schedule(this::updatePartitionInfo, 0, TimeUnit.MILLISECONDS); }
Source:
public void testChronologizeWithStartTimestampAndEndTimestampBeforeAnyValuesChangeInKeyInRecord() { long record = Variables.register("record", client.create()); String key = Variables.register("key", TestData.getString()); int testSize = Variables.register("testSize", 5); Set<Object> initValues = Variables.register("initValues", Sets.newHashSet()); Timestamp startTimestamp = Variables.register("startTimestamp", Timestamp.now()); for (int i = 0; i < 100000000; i++); Timestamp endTimestamp = Variables.register("endTimestamp", Timestamp.now()); for (int i = 0; i < testSize; i++) { Object value = null; while (value == null || initValues.contains(value)) { value = TestData.getObject(); } initValues.add(value); client.add(key, value, record); } Map<Timestamp, Set<Object>> result = client.chronologize( key, record, startTimestamp, endTimestamp); assertTrue(result.isEmpty()); }

Target:
public void testChronologizeWithStartTimestampAndEndTimestampBeforeAnyValuesChangeInKeyInRecord() { long record = Variables.register("record", client.create()); String key = Variables.register("key", TestData.getString()); int testSize = Variables.register("testSize", 5); Set<Object> initValues = Variables.register("initValues", Sets.newHashSet()); Timestamp startTimestamp = Variables.register("startTimestamp", Timestamp.now()); StandardActions.wait(200, TimeUnit.MILLISECONDS); Timestamp endTimestamp = Variables.register("endTimestamp", Timestamp.now()); StandardActions.wait(200, TimeUnit.MILLISECONDS); for (int i = 0; i < testSize; i++) { Object value = null; while (value == null || initValues.contains(value)) { value = TestData.getObject(); } initValues.add(value); client.add(key, value, record); } Map<Timestamp, Set<Object>> result = client.chronologize(key, record, startTimestamp, endTimestamp); result = Variables.register("result", result); assertTrue(result.isEmpty()); }
Source:
public int build(OutputStream out, OutputStream err, IProgressMonitor monitor) { int status = STATUS_ERROR_LAUNCH; try { SubMonitor progress = SubMonitor.convert(monitor, ManagedMakeMessages.getResourceString("MakeBuilder.Invoking_Command") + getCommandLine(), getNumCommands()); ICommandLauncher launcher = createLauncher(); launcher.showCommand(true); fProcess = launcher.execute(fCmd.getCommand(), fCmd.getArgs(), mapToStringArray(fCmd.getEnvironment()), fCmd.getCWD(), progress); if (fProcess != null) { try { fProcess.getOutputStream().close(); } catch (IOException e) { } int st = launcher.waitAndRead(wrap(out), wrap(err), progress.split(getNumCommands())); switch (st) { case ICommandLauncher.OK: status = fProcess.exitValue() == 0 ? STATUS_OK : STATUS_ERROR_BUILD; break; case ICommandLauncher.COMMAND_CANCELED: status = STATUS_CANCELLED; break; case ICommandLauncher.ILLEGAL_COMMAND: default: status = STATUS_ERROR_LAUNCH; break; } } fErrMsg = launcher.getErrorMessage(); if (fErrMsg != null && !fErrMsg.isEmpty()) { printMessage(fErrMsg, err); } } catch (CoreException e) { ManagedBuilderCorePlugin.log(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, "Error launching command [" + fCmd.getCommand() + "]", e)); status = STATUS_ERROR_LAUNCH; } finally { monitor.done(); } return status; }

Target:
public int build(OutputStream out, OutputStream err, IProgressMonitor monitor) { int status = STATUS_ERROR_LAUNCH; SubMonitor progress = SubMonitor.convert(monitor, ManagedMakeMessages.getResourceString("MakeBuilder.Invoking_Command") + getCommandLine(), getNumCommands() + 1); try { ICommandLauncher launcher = createLauncher(); launcher.showCommand(true); fProcess = launcher.execute(fCmd.getCommand(), fCmd.getArgs(), mapToStringArray(fCmd.getEnvironment()), fCmd.getCWD(), progress.split(1)); if (fProcess != null) { try { fProcess.getOutputStream().close(); } catch (IOException e) { } int st = launcher.waitAndRead(wrap(out), wrap(err), progress.split(getNumCommands())); switch (st) { case ICommandLauncher.OK: status = fProcess.exitValue() == 0 ? STATUS_OK : STATUS_ERROR_BUILD; break; case ICommandLauncher.COMMAND_CANCELED: status = STATUS_CANCELLED; break; case ICommandLauncher.ILLEGAL_COMMAND: default: status = STATUS_ERROR_LAUNCH; break; } } fErrMsg = launcher.getErrorMessage(); if (fErrMsg != null && !fErrMsg.isEmpty()) { printMessage(fErrMsg, err); } } catch (CoreException e) { ManagedBuilderCorePlugin.log(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, "Error launching command [" + fCmd.getCommand() + "]", e)); status = STATUS_ERROR_LAUNCH; } finally { progress.done(); } return status; }
Source:
protected <T, I> List<I> getServices(Class<T> clazz, Class<I> implementationClass) { final ServiceReference<@Nullable T> serviceReferences[] = getServices(clazz); if (serviceReferences == null) { new MissingServiceAnalyzer(System.out, bundleContext).printMissingServiceDetails(clazz); return Collections.emptyList(); } return Arrays .stream(serviceReferences) .map(this::unrefService) .filter(implementationClass::isInstance) .map(implementationClass::cast) .collect(Collectors.toList()) ; }

Target:
protected <T, I extends T> List<I> getServices(Class<T> clazz, Class<I> implementationClass) { final ServiceReference<@Nullable T> serviceReferences[] = getServices(clazz); if (serviceReferences == null) { new MissingServiceAnalyzer(System.out, bundleContext).printMissingServiceDetails(clazz); return Collections.emptyList(); } return Arrays .stream(serviceReferences) .map(this::unrefService) .filter(implementationClass::isInstance) .map(implementationClass::cast) .collect(Collectors.toList()) ; }
Source:
ConjureTimelockService getConjureTimelockService() { Preconditions.checkState(isDialogue(ConjureTimelockServiceBlocking.class), "Dialogue service provider attempted to provide a non-Dialogue class." + " This is an AtlasDB bug."); ConjureTimelockServiceBlocking longTimeoutService = dialogueClientFactory.get(ConjureTimelockServiceBlocking.class, TIMELOCK_LONG_TIMEOUT); ConjureTimelockServiceBlocking shortTimeoutService = dialogueClientFactory.get(ConjureTimelockServiceBlocking.class, TIMELOCK_SHORT_TIMEOUT); ShortAndLongTimeoutServices<ConjureTimelockService> shortAndLongTimeoutServices = ImmutableShortAndLongTimeoutServices.<ConjureTimelockServiceBlocking>builder() .longTimeout(longTimeoutService) .shortTimeout(shortTimeoutService) .build() .map(proxy -> FastFailoverProxy.newProxyInstance(ConjureTimelockServiceBlocking.class, () -> proxy)) .map(DialogueAdaptingConjureTimelockService::new); return new TimeoutSensitiveConjureTimelockService(shortAndLongTimeoutServices); }

Target:
ConjureTimelockService getConjureTimelockService() { ConjureTimelockServiceBlocking longTimeoutService = dialogueClientFactory.get(ConjureTimelockServiceBlocking.class, TIMELOCK_LONG_TIMEOUT); ConjureTimelockServiceBlocking shortTimeoutService = dialogueClientFactory.get(ConjureTimelockServiceBlocking.class, TIMELOCK_SHORT_TIMEOUT); ShortAndLongTimeoutServices<ConjureTimelockService> shortAndLongTimeoutServices = ImmutableShortAndLongTimeoutServices.<ConjureTimelockServiceBlocking>builder() .longTimeout(longTimeoutService) .shortTimeout(shortTimeoutService) .build() .map(proxy -> FastFailoverProxy.newProxyInstance(ConjureTimelockServiceBlocking.class, () -> proxy)) .map(DialogueAdaptingConjureTimelockService::new); return new TimeoutSensitiveConjureTimelockService(shortAndLongTimeoutServices); }
Source:
private void hotUnplugMemory(VM newVm) { final VM vmFromDb = getVm(); final List<VmDevice> vmMemoryDevices = vmDeviceDao.getVmDeviceByVmIdTypeAndDevice( getVmId(), VmDeviceGeneralType.MEMORY, VmDeviceType.MEMORY); final int oldMemoryMb = vmFromDb.getMemSizeMb(); final int oldMinMemoryMb = vmFromDb.getMinAllocatedMem(); final List<VmDevice> memoryDevicesToUnplug = MemoryUtils.computeMemoryDevicesToHotUnplug( vmMemoryDevices, oldMemoryMb, getParameters().getVm().getMemSizeMb()); if (memoryDevicesToUnplug.isEmpty()) { logNoDeviceToHotUnplug(vmMemoryDevices); if (!vmFromDb.isHostedEngine()) { newVmStatic.setMemSizeMb(oldMemoryMb); newVmStatic.setMinAllocatedMem(oldMinMemoryMb); } return; } final int totalHotUnpluggedMemoryMb = memoryDevicesToUnplug.stream() .mapToInt(deviceToHotUnplug -> { final ActionReturnValue hotUnplugReturnValue = runInternalAction( ActionType.HotUnplugMemoryWithoutVmUpdate, new HotUnplugMemoryWithoutVmUpdateParameters( deviceToHotUnplug.getId(), newVm.getMinAllocatedMem()), cloneContextAndDetachFromParent()); return hotUnplugReturnValue.getSucceeded() ? VmDeviceCommonUtils.getSizeOfMemoryDeviceMb(deviceToHotUnplug).get() : 0; }) .sum(); if (!vmFromDb.isHostedEngine()) { newVmStatic.setMemSizeMb(oldMemoryMb - totalHotUnpluggedMemoryMb); newVmStatic.setMinAllocatedMem(totalHotUnpluggedMemoryMb > 0 ? newVm.getMinAllocatedMem() : oldMinMemoryMb); } }

Target:
private void hotUnplugMemory(VM newVm) { final List<VmDevice> vmMemoryDevices = vmDeviceDao.getVmDeviceByVmIdTypeAndDevice( getVmId(), VmDeviceGeneralType.MEMORY, VmDeviceType.MEMORY); final int oldMemoryMb = oldVm.getMemSizeMb(); final int oldMinMemoryMb = oldVm.getMinAllocatedMem(); final List<VmDevice> memoryDevicesToUnplug = MemoryUtils.computeMemoryDevicesToHotUnplug( vmMemoryDevices, oldMemoryMb, getParameters().getVm().getMemSizeMb()); if (memoryDevicesToUnplug.isEmpty()) { logNoDeviceToHotUnplug(vmMemoryDevices); if (!oldVm.isHostedEngine()) { newVmStatic.setMemSizeMb(oldMemoryMb); newVmStatic.setMinAllocatedMem(oldMinMemoryMb); } return; } final int totalHotUnpluggedMemoryMb = memoryDevicesToUnplug.stream() .mapToInt(deviceToHotUnplug -> { final ActionReturnValue hotUnplugReturnValue = runInternalAction( ActionType.HotUnplugMemoryWithoutVmUpdate, new HotUnplugMemoryWithoutVmUpdateParameters( deviceToHotUnplug.getId(), newVm.getMinAllocatedMem()), cloneContextAndDetachFromParent()); return hotUnplugReturnValue.getSucceeded() ? VmDeviceCommonUtils.getSizeOfMemoryDeviceMb(deviceToHotUnplug).get() : 0; }) .sum(); if (!oldVm.isHostedEngine()) { newVmStatic.setMemSizeMb(oldMemoryMb - totalHotUnpluggedMemoryMb); newVmStatic.setMinAllocatedMem(totalHotUnpluggedMemoryMb > 0 ? newVm.getMinAllocatedMem() : oldMinMemoryMb); } }
Source:
public Long toLong(Timestamp value, Schema schema, LogicalType type) { if (value.getNanos() - (value.getNanos() / 1000000 * 1000000) > 0) { throw new UnsupportedOperationException("micros-precise is unsupported"); } return value.getSeconds() * 1000 + value.getNanos() / 1000000; }

Target:
public Long toLong(Timestamp value, Schema schema, LogicalType type) { return ProtoConversions.toLong(value, TimestampPrecise.Micros); }
Source:
public CommandResult runCommand(String script) throws IOException { if (script == null) { return null; } KitodoServiceLoader<CommandInterface> serviceLoader = new KitodoServiceLoader<>(CommandInterface.class, ConfigCore.getParameter("moduleFolder")); CommandInterface commandInterface = serviceLoader.loadModule(); CommandResult commandResult = commandInterface.runCommand(generateId(), script); if (commandResult.getMessages().get(0).contains("IOException")) { throw new IOException(); } return commandResult; }

Target:
public CommandResult runCommand(String script) throws IOException { if (script == null) { return null; } KitodoServiceLoader<CommandInterface> serviceLoader = new KitodoServiceLoader<>(CommandInterface.class, ConfigCore.getParameter("moduleFolder")); CommandInterface commandInterface = serviceLoader.loadModule(); CommandResult commandResult = commandInterface.runCommand(generateId(), script); if (commandResult.getMessages().get(0).contains("IOException")) { throw new IOException(commandResult.getMessages().get(1)); } return commandResult; }
Source:
public static ArrayList<SerialPortInfo> listSerialPortsInfo() { ArrayList<SerialPortInfo> ports = new ArrayList<SerialPortInfo>(); Enumeration<CommPortIdentifier> comPorts = CommPortIdentifier.getPortIdentifiers(); while (comPorts.hasMoreElements()) { CommPortIdentifier identifier = (CommPortIdentifier)comPorts.nextElement(); ports.add(new SerialPortInfo(identifier.getName())); } return ports; }

Target:
public static ArrayList<SerialPortInfo> listSerialPortsInfo() { ArrayList<SerialPortInfo> ports = new ArrayList<SerialPortInfo>(); @SuppressWarnings("unchecked") Enumeration<CommPortIdentifier> comPorts = CommPortIdentifier.getPortIdentifiers(); if (comPorts == null) return ports; while (comPorts.hasMoreElements()) { CommPortIdentifier identifier = (CommPortIdentifier)comPorts.nextElement(); if (identifier == null) continue; ports.add(new SerialPortInfo(identifier.getName())); } return ports; }
Source:
public AsyncResult<Void> waitForLocks(UUID requestId, Set<LockDescriptor> lockDescriptors, TimeLimit timeout) { AsyncResult<Void> result = waitRequests.computeIfAbsent(requestId, ignored -> { OrderedLocks orderedLocks = locks.getAll(lockDescriptors); return lockAcquirer.waitForLocks(requestId, orderedLocks, timeout); }); result.onComplete(() -> { waitRequests.remove(requestId); }); return result; }

Target:
public AsyncResult<Void> waitForLocks(UUID requestId, Set<LockDescriptor> lockDescriptors, TimeLimit timeout) { return awaitedLocks.getExistingOrAwait( requestId, () -> awaitLocks(requestId, lockDescriptors, timeout)); }
Source:
void idIsGeneratedUUID() { class Entity { @GeneratedValue(strategy = GenerationStrategy.UNIQUE) @Id UUID id; } Entity entity = new Entity(); CouchbaseDocument converted = new CouchbaseDocument(); converter.write(entity, converted); assertThat(converted.getId()).isEqualTo(entity.id.toString()); System.out.println(entity.id); }

Target:
void idIsGeneratedUUID() { class Entity { @GeneratedValue(strategy = GenerationStrategy.UNIQUE) @Id UUID id; } Entity entity = new Entity(); CouchbaseDocument converted = new CouchbaseDocument(); converter.write(entity, converted); assertThat(converted.getId()).isEqualTo(entity.id.toString()); }
Source:
public void seal() throws IOException { LOGGER.info("Sealing the segment for column: " + _fstIndexFile.getAbsolutePath()); FST<Long> fst = _fstBuilder.done(); FileOutputStream fileOutputStream = new FileOutputStream(_fstIndexFile); OutputStreamDataOutput d = new OutputStreamDataOutput(fileOutputStream); fst.save(d); fileOutputStream.close(); }

Target:
public void seal() throws IOException { LOGGER.info("Sealing FST index: " + _fstIndexFile.getAbsolutePath()); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(_fstIndexFile); FST<Long> fst = _fstBuilder.done(); OutputStreamDataOutput d = new OutputStreamDataOutput(fileOutputStream); fst.save(d); } finally { if (fileOutputStream != null) { fileOutputStream.close(); } } }
Source:
protected boolean validatePage() { boolean validProjectName = true; if (resourceExistsInWorkspace()) { validProjectName = false; } if (!StringUtil.isEmpty(getProjectName()) && validProjectName && isMacOrWindowsOS()) { if (resourceExistsOnDisk()) { validProjectName = false; } } if (validProjectName) { return super.validatePage(); } else { return false; } }

Target:
protected boolean validatePage() { boolean validProjectName = true; if (isMacOrWindowsOS() && resourceExistsInWorkspace()) { validProjectName = false; } if (!StringUtil.isEmpty(getProjectName()) && validProjectName && isMacOrWindowsOS()) { if (resourceExistsOnDisk()) { validProjectName = false; } } if (validProjectName) { return super.validatePage(); } else { return false; } }
Source:
@Test void testJoinWithHints() { final RelHint noHashJoinHint = RelHint.builder("NO_HASH_JOIN").build(); final RelBuilder builder = RelBuilder.create(config().build()); final RelNode original = builder.scan("EMP") .scan("DEPT") .join(JoinRelType.INNER, builder.equals( builder.field(2, 0, "DEPTNO"), builder.field(2, 1, "DEPTNO"))) .hints(noHashJoinHint) .project( builder.field("ENAME"), builder.field("DNAME")) .build(); final RelFieldTrimmer fieldTrimmer = new RelFieldTrimmer(null, builder); final RelNode trimmed = fieldTrimmer.trim(original); final String expected = "" + "LogicalProject(ENAME=[$1], DNAME=[$4])\n" + " LogicalJoin(condition=[=($2, $3)], joinType=[inner])\n" + " LogicalProject(EMPNO=[$0], ENAME=[$1], DEPTNO=[$7])\n" + " LogicalTableScan(table=[[scott, EMP]])\n" + " LogicalProject(DEPTNO=[$0], DNAME=[$1])\n" + " LogicalTableScan(table=[[scott, DEPT]])\n"; assertThat(trimmed, hasTree(expected)); assertTrue(original.getInput(0) instanceof Join); final Join originalJoin = (Join) original.getInput(0); assertTrue(originalJoin.getHints().contains(noHashJoinHint)); assertTrue(trimmed.getInput(0) instanceof Join); final Join join = (Join) trimmed.getInput(0); assertTrue(join.getHints().contains(noHashJoinHint)); }

Target:
@Test void testJoinWithHints() { final RelHint noHashJoinHint = RelHint.builder("no_hash_join").build(); final RelBuilder builder = RelBuilder.create(config().build()); builder.getCluster().setHintStrategies( HintStrategyTable.builder() .hintStrategy("no_hash_join", HintPredicates.JOIN) .build()); final RelNode original = builder.scan("EMP") .scan("DEPT") .join(JoinRelType.INNER, builder.equals( builder.field(2, 0, "DEPTNO"), builder.field(2, 1, "DEPTNO"))) .hints(noHashJoinHint) .project( builder.field("ENAME"), builder.field("DNAME")) .build(); final RelFieldTrimmer fieldTrimmer = new RelFieldTrimmer(null, builder); final RelNode trimmed = fieldTrimmer.trim(original); final String expected = "" + "LogicalProject(ENAME=[$1], DNAME=[$4])\n" + " LogicalJoin(condition=[=($2, $3)], joinType=[inner])\n" + " LogicalProject(EMPNO=[$0], ENAME=[$1], DEPTNO=[$7])\n" + " LogicalTableScan(table=[[scott, EMP]])\n" + " LogicalProject(DEPTNO=[$0], DNAME=[$1])\n" + " LogicalTableScan(table=[[scott, DEPT]])\n"; assertThat(trimmed, hasTree(expected)); assertTrue(original.getInput(0) instanceof Join); final Join originalJoin = (Join) original.getInput(0); assertTrue(originalJoin.getHints().contains(noHashJoinHint)); assertTrue(trimmed.getInput(0) instanceof Join); final Join join = (Join) trimmed.getInput(0); assertTrue(join.getHints().contains(noHashJoinHint)); }
Source:
public void removeBotForce(int x) { BotForce botToRemove = botForces.get(x); botForceTemplates.remove(botToRemove); super.removeBotForce(x); }

Target:
public void removeBotForce(int x) { if((x >= 0) && (x < botForces.size())) { BotForce botToRemove = botForces.get(x); botForceTemplates.remove(botToRemove); } super.removeBotForce(x); }
Source:
private void printStatistics() { final String messagePrefix; if (isPutCommand) { messagePrefix = "Putting"; } else { messagePrefix = "Getting"; } System.out.print(String.format("\r%s Statistics: (%d/%d MB), files (%d/%d), Time (%.03f sec), MBps (%.03f), Highest MBps (%.03f sec)", messagePrefix, content, numberOfMB, numberOfFiles, totalNumberOfFiles, time, mbps, highestMbps)); }

Target:
private void printStatistics() { final String messagePrefix; if (isPutCommand) { messagePrefix = "Putting"; } else { messagePrefix = "Getting"; } System.out.print(String.format("\r%s Statistics: (%d/%d MB), files (%d/%d), Time (%.03f sec), MBps (%.03f), Highest MBps (%.03f)", messagePrefix, content, numberOfMB, numberOfFiles, totalNumberOfFiles, time, mbps, highestMbps)); }
Source:
public ITmfStateSystem getStateSystem() { return fSS; }

Target:
public @NonNull ITmfStateSystem getStateSystem() { return fSS; }
Source:
public RTPEncodingDesc( MediaStreamTrackDesc track, long primarySSRC, long rtxSSRC) { this(track, 0, primarySSRC, rtxSSRC, -1 , -1 , -1 , null ); }

Target:
public RTPEncodingDesc( MediaStreamTrackDesc track, long primarySSRC, long rtxSSRC) { this(track, 0, primarySSRC, rtxSSRC, NO_HEIGHT , -1 , -1 , null ); }
Source:
private DashboardData buildDashboardData(String baseRequestId) { LOGGER.info("build dashboard data for {}", baseRequestId); DashboardData data = new DashboardData(); PreparedStatement pst = null; ResultSet rs = null; try { pst = db.getConnection().prepareStatement(RESPONSE_QUERY); pst.setString(1, "%" + baseRequestId + "%"); rs = pst.executeQuery(); while (rs.next()) { String requestId = rs.getString(1); String requestDate = rs.getString(2); String response = naivelyFormatXML(rs.getString(3)); if (requestId.endsWith("OUTPUT")) { LOGGER.info("setting outputXML {}", response); data.setOutputXML(response); data.setCompletedTimestamp(requestDate); } else if (requestId.startsWith("REQ_")) { LOGGER.info("setting requestXML {}", response); data.setRequestXML(response); } else { LOGGER.info("setting responseXML {}", response); data.setResponseXML(response); } } } catch (SQLException ex) { LOGGER.error("failed to select responses for request ids like " + baseRequestId, ex); } finally { closeStatement(pst); closeResultSet(rs); } return data; }

Target:
private DashboardData buildDashboardData(String baseRequestId) { LOGGER.debug("build dashboard data for {}", baseRequestId); DashboardData data = new DashboardData(); PreparedStatement pst = null; ResultSet rs = null; try { pst = db.getConnection().prepareStatement(RESPONSE_QUERY); pst.setString(1, "%" + baseRequestId + "%"); rs = pst.executeQuery(); while (rs.next()) { String requestId = rs.getString(1); String requestDate = rs.getString(2); String response = rs.getString(3); if (requestId.endsWith("OUTPUT")) { LOGGER.debug("setting outputXML {}", response); data.setOutputXML(response); data.setCompletedTimestamp(requestDate); } else if (requestId.startsWith("REQ_")) { LOGGER.debug("setting requestXML {}", response); data.setRequestXML(response); } else { LOGGER.debug("setting responseXML {}", response); data.setResponseXML(response); } } } catch (SQLException ex) { LOGGER.error("failed to select responses for request ids like " + baseRequestId, ex); } finally { closeStatement(pst); closeResultSet(rs); } return data; }
Source:
protected void endSuccessfullySynchronous() { VM vm = getVm(); if (vm != null) { VmHandler.UnLockVm(vm.getId()); this.endDefaultOps(vm); setSucceeded(true); } else { setCommandShouldBeLogged(false); log.warn("ExportVmCommand::EndSuccessfullySynchronous: Vm is null - not performing full EndAction"); } }

Target:
protected void endSuccessfullySynchronous() { VM vm = getVm(); VmHandler.UnLockVm(vm.getId()); this.endDefaultOps(vm); setSucceeded(true); }
Source:
protected TextBuilder(Text text) { checkNotNull(text, "text"); this.color = text.color; this.style = text.style; this.children = Lists.newArrayList(text.children); this.clickAction = text.clickAction.orNull(); this.hoverAction = text.hoverAction.orNull(); this.shiftClickAction = text.shiftClickAction.orNull(); }

Target:
public TextBuilder(Text text) { checkNotNull(text, "text"); this.color = text.color; this.style = text.style; this.children = Lists.newArrayList(text.children); this.clickAction = text.clickAction.orNull(); this.hoverAction = text.hoverAction.orNull(); this.shiftClickAction = text.shiftClickAction.orNull(); }
Source:
public Blob watermarkWithImage(Blob inBlob, int x, int y, float scale) throws NuxeoException { Blob result = null; PDDocument pdfDoc = null; PDPageContentStream contentStream = null; scale = (scale <= 0f) ? 1.0f : scale; try { BufferedImage tmp_image = ImageIO.read(inBlob.getStream()); pdfDoc = PDDocument.load(blob.getStream()); PDXObjectImage ximage = new PDPixelMap(pdfDoc, tmp_image); List allPages = pdfDoc.getDocumentCatalog().getAllPages(); for (Object allPage : allPages) { PDPage page = (PDPage) allPage; contentStream = new PDPageContentStream(pdfDoc, page, true, true); contentStream.endMarkedContentSequence(); contentStream.drawXObject(ximage, x, y, ximage.getWidth() * scale, ximage.getHeight() * scale); contentStream.close(); contentStream = null; } result = PDFUtils.saveInTempFile(pdfDoc); } catch (IOException | COSVisitorException e) { throw new NuxeoException(e); } finally { if (contentStream != null) { try { contentStream.close(); } catch (IOException e) { } } PDFUtils.closeSilently(pdfDoc); } return result; }

Target:
public Blob watermarkWithImage(Blob inBlob, int x, int y, float scale) throws NuxeoException { Blob result; PDPageContentStream contentStream; scale = (scale <= 0f) ? 1.0f : scale; try (PDDocument pdfDoc = PDDocument.load(blob.getStream())) { BufferedImage tmp_image = ImageIO.read(inBlob.getStream()); PDXObjectImage ximage = new PDPixelMap(pdfDoc, tmp_image); List allPages = pdfDoc.getDocumentCatalog().getAllPages(); for (Object allPage : allPages) { PDPage page = (PDPage) allPage; contentStream = new PDPageContentStream(pdfDoc, page, true, true); contentStream.endMarkedContentSequence(); contentStream.drawXObject(ximage, x, y, ximage.getWidth() * scale, ximage.getHeight() * scale); contentStream.close(); } result = PDFUtils.saveInTempFile(pdfDoc); } catch (IOException | COSVisitorException e) { throw new NuxeoException(e); } return result; }
Source:
private void updateChargers() { WirelessChargerController wcc = WirelessChargerController.instance; chargers.clear(); lastChangeCount = wcc.getChangeCount(); final BlockCoord bc = new BlockCoord(te); wcc.getChargers(te.getWorldObj(), bc, chargers); Collections.sort(chargers, new Comparator<IWirelessCharger>() { @Override public int compare(IWirelessCharger o1, IWirelessCharger o2) { int dist1 = o1.getLocation().distance(bc); int dist2 = o2.getLocation().distance(bc); return dist1 - dist2; } }); }

Target:
private void updateChargers() { WirelessChargerController wcc = WirelessChargerController.instance; chargers.clear(); lastChangeCount = wcc.getChangeCount(); final BlockCoord bc = new BlockCoord(te); wcc.getChargers(te.getWorldObj(), bc, chargers); Collections.sort(chargers, new Comparator<IWirelessCharger>() { @Override public int compare(IWirelessCharger o1, IWirelessCharger o2) { int dist1 = o1.getLocation().distanceSquared(bc); int dist2 = o2.getLocation().distanceSquared(bc); return dist1 - dist2; } }); }
Source:
public void testGetAllForVMFilteredWithPermissions() { List<DiskImage> disks = dao.getAllForVm(EXISTING_VM_ID, PRIVILEGED_USER_ID, true); assertEquals("VM should have two disks", 2, disks.size()); }

Target:
public void testGetAllForVMFilteredWithPermissions() { List<DiskImage> disks = dao.getAllForVm(EXISTING_VM_ID, PRIVILEGED_USER_ID, true); assertFullGetAllForVMResult(disks); }
Source:
public List<RichGroup> getAllRichGroupsWithAttributesByNames(PerunSession sess, Vo vo, List<String> attrNames)throws InternalErrorException, VoNotExistsException{ Utils.checkPerunSession(sess); this.getPerunBl().getVosManagerBl().checkVoExists(sess, vo); return this.getGroupsManagerBl().getAllRichGroupsWithAttributesByNames(sess, vo, attrNames); }

Target:
public List<RichGroup> getAllRichGroupsWithAttributesByNames(PerunSession sess, Vo vo, List<String> attrNames) throws InternalErrorException, VoNotExistsException, PrivilegeException { Utils.checkPerunSession(sess); this.getPerunBl().getVosManagerBl().checkVoExists(sess, vo); if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, vo) && !AuthzResolver.isAuthorized(sess, Role.VOOBSERVER, vo) && !AuthzResolver.isAuthorized(sess, Role.GROUPADMIN)) { throw new PrivilegeException(sess, "getAllRichGroupsWithAttributesByNames"); } List<RichGroup> richGroups = getGroupsManagerBl().getAllRichGroupsWithAttributesByNames(sess, vo, attrNames); if (AuthzResolver.hasRole(sess.getPerunPrincipal(), Role.GROUPADMIN)) { Iterator<RichGroup> i = richGroups.iterator(); while (i.hasNext()) { if (!AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, i.next())) { i.remove(); } } } return getGroupsManagerBl().filterOnlyAllowedAttributes(sess, richGroups); }
Source:
private void updateRelevantVms() { List<VM> vms = getVmsDiskPluggedTo(); for (VM vm : vms) { if (vm.getStatus().isUpOrPaused() || vms.size() == 1) { try { VDSReturnValue ret = extendVmDiskSize(vm, getParameters().getNewSize()); if (!ret.getSucceeded()) { updateAuditLogFailedToUpdateVM(vm.getName()); } } catch (VdcBLLException e) { log.warnFormat("Failed to update VM '{0}' with the new volume size due to error: {1}." + "VM should be restarted to detect the new size.", vm.getName(), ExceptionUtils.getMessage(e)); updateAuditLogFailedToUpdateVM(vm.getName()); } } } }

Target:
private void updateRelevantVms() { List<VM> vms = getVmsDiskPluggedTo(); for (VM vm : vms) { try { VDSReturnValue ret = extendVmDiskSize(vm, getParameters().getNewSize()); if (!ret.getSucceeded()) { updateAuditLogFailedToUpdateVM(vm.getName()); } } catch (VdcBLLException e) { log.warnFormat("Failed to update VM '{0}' with the new volume size due to error: {1}." + "VM should be restarted to detect the new size.", vm.getName(), ExceptionUtils.getMessage(e)); updateAuditLogFailedToUpdateVM(vm.getName()); } } }