auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void writeData(GeoJsonDiseaseOccurrenceFeatureCollection occurrenceData, File dataDirectory) throws IOException { if (!occurrenceData.getCrs().equals(GeoJsonNamedCrs.createEPSG4326())) { throw new IllegalArgumentException("Only EPSG4326 is supported."); } File outbreakFile = Paths.get(dataDirectory.toString(), OUTBREAK_CSV).toFile(); BufferedWriter writer = null; try { writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(outbreakFile.getAbsoluteFile()), UTF_8)); for (GeoJsonDiseaseOccurrenceFeature occurrence : occurrenceData.getFeatures()) { if (occurrence.getCrs() != null) { throw new IllegalArgumentException("Feature level CRS are not supported."); } writer.write(StringUtils.join(new String[]{ occurrence.getGeometry().getCoordinates().get(0).toString(), occurrence.getGeometry().getCoordinates().get(1).toString(), occurrence.getProperties().getLocationPrecision().toString(), occurrence.getProperties().getWeighting().toString() }, ',')); writer.newLine(); } } finally { if (writer != null) { writer.close(); } } }

Target:
public void writeData(GeoJsonDiseaseOccurrenceFeatureCollection occurrenceData, File dataDirectory) throws IOException { if (!occurrenceData.getCrs().equals(GeoJsonNamedCrs.createEPSG4326())) { throw new IllegalArgumentException("Only EPSG:4326 is supported."); } File outbreakFile = Paths.get(dataDirectory.toString(), OUTBREAK_CSV).toFile(); BufferedWriter writer = null; try { writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(outbreakFile.getAbsoluteFile()), UTF_8)); for (GeoJsonDiseaseOccurrenceFeature occurrence : occurrenceData.getFeatures()) { if (occurrence.getCrs() != null) { throw new IllegalArgumentException("Feature level CRS are not supported."); } writer.write(extractCsvLine(occurrence)); writer.newLine(); } } finally { if (writer != null) { writer.close(); } } }
Source:
public void testExecuteNullTable() throws Exception { GroupRequest groupRequest = new GroupRequest(); groupRequest.setTable(null); groupRequest.setNesting(Arrays.asList("os", "device", "version")); queryExecutor.execute(groupRequest); }

Target:
public void testExecuteNullTable() throws Exception { GroupRequest groupRequest = new GroupRequest(); groupRequest.setTable(null); groupRequest.setNesting(Arrays.asList("os", "device", "version")); try { queryExecutor.execute(groupRequest); } catch (QueryStoreException e) { assertEquals(QueryStoreException.ErrorCode.INVALID_REQUEST, e.getErrorCode()); throw e; } }
Source:
public boolean apply(Game game, Ability source) { Player player = game.getPlayer(source.getControllerId()); Player targetPlayer = game.getPlayer(source.getFirstTarget()); if (player == null || targetPlayer == null) { return false; } targetPlayer.revealCards(source, targetPlayer.getHand(), game); if (targetPlayer.getHand().size() <= 2) { targetPlayer.discard(2, false, source, game); } TargetCard target = new TargetCardInHand(2, StaticFilters.FILTER_CARD_CARDS); player.choose(Outcome.Benefit, targetPlayer.getHand(), target, game); targetPlayer.discard(new CardsImpl(target.getTargets()), source, game); return true; }

Target:
public boolean apply(Game game, Ability source) { Player player = game.getPlayer(source.getControllerId()); Player targetPlayer = game.getPlayer(source.getFirstTarget()); if (player == null || targetPlayer == null) { return false; } targetPlayer.revealCards(source, targetPlayer.getHand(), game); if (targetPlayer.getHand().size() <= 2) { targetPlayer.discard(2, false, source, game); } TargetCard target = new TargetCardInHand(2, StaticFilters.FILTER_CARD_CARDS); player.choose(Outcome.Discard, targetPlayer.getHand(), target, game); targetPlayer.discard(new CardsImpl(target.getTargets()), source, game); return true; }
Source:
public T call() throws Exception { try (CloseableHttpResponse response = FastTextClient.getInstance().execute(this.getRequestBase())) { String jsonResponse = EntityUtils.toString(response.getEntity()); int code = response.getStatusLine().getStatusCode(); if (code != HttpStatus.SC_OK) { System.out.println("External search service returned non 200 response"); throw new FastTextServerError(jsonResponse, code, this.getRequestId()); } if (this.typeReference != null) { return MAPPER.readValue(jsonResponse, this.typeReference); } return MAPPER.readValue(jsonResponse, this.returnClass); } }

Target:
public T call() throws Exception { HttpRequestBase requestBase = this.getRequestBase(); logInfo("Executing fastText request") .addParameter("method", requestBase.getMethod()) .addParameter("requestId", this.requestIdHeader.getRequestId()) .addParameter("uri", requestBase.getURI().toString()) .log(); try (CloseableHttpResponse response = FastTextClient.getInstance().execute(requestBase)) { String jsonResponse = EntityUtils.toString(response.getEntity()); int code = response.getStatusLine().getStatusCode(); if (code != HttpStatus.SC_OK) { FastTextServerError e = new FastTextServerError(jsonResponse, code, this.getRequestId()); logError(e) .addMessage("dp-fasttext returned non-200 response") .addParameter("status", code) .log(); throw e; } if (this.typeReference != null) { return MAPPER.readValue(jsonResponse, this.typeReference); } return MAPPER.readValue(jsonResponse, this.returnClass); } }
Source:
public CollisionMap defaultCollisions() { final CollisionMap collisionMap = new CollisionMap(); collisionMap.onCollision(Player.class, AbstractObstacle.class, (collider, collidee) -> { if (!AbstractPowerup.isActive(PowerupInvulnerable.class)) { collider.die(); notifyCollide(AbstractObstacle.class); } }); collisionMap.onCollision(Player.class, Log.class, (collider, collidee) -> { if (AbstractPowerup.isActive(PowerupDestroy.class)) { collidee.selfDestruct(); notifyCollide(Log.class); State.addScore(Log.VALUE); return; } if (!AbstractPowerup.isActive(PowerupInvulnerable.class)) { collider.die(); notifyCollide(AbstractObstacle.class); } }); collisionMap.onCollision(Player.class, AbstractPickup.class, (collider, collidee) -> { collidee.doAction(); collidee.selfDestruct(); notifyCollide(collidee.getClass()); }); return collisionMap; }

Target:
public CollisionMap defaultCollisions() { final CollisionMap collisionMap = new CollisionMap(); collisionMap.onCollision(Player.class, AbstractObstacle.class, (collider, collidee) -> { if (!AbstractPowerup.isActive(PowerupInvulnerable.class)) { collider.die(); notifyCollide(AbstractObstacle.class); } }); collisionMap.onCollision(Player.class, Log.class, (collider, collidee) -> { if (AbstractPowerup.isActive(PowerupDestroy.class)) { collidee.selfDestruct(); notifyCollide(Log.class); State.addScore(Log.VALUE); } else if (!AbstractPowerup.isActive( PowerupInvulnerable.class)) { collider.die(); notifyCollide(AbstractObstacle.class); } }); collisionMap.onCollision(Player.class, AbstractPickup.class, (collider, collidee) -> { collidee.doAction(); collidee.selfDestruct(); notifyCollide(collidee.getClass()); }); return collisionMap; }
Source:
public void setDebugACRAConfig(SharedPreferences prefs) { setAcraReportingMode(FEEDBACK_REPORT_NEVER); prefs.edit().putString(FEEDBACK_REPORT_KEY, FEEDBACK_REPORT_NEVER).apply(); String logcatArgs = { "-t", "300", "-v", "long", "ACRA:S"}; setAcraConfigBuilder(getAcraCoreConfigBuilder().setLogcatArguments(logcatArgs)); }

Target:
private void setDebugACRAConfig(SharedPreferences prefs) { setAcraReportingMode(FEEDBACK_REPORT_NEVER); prefs.edit().putString(FEEDBACK_REPORT_KEY, FEEDBACK_REPORT_NEVER).apply(); String logcatArgs = { "-t", "300", "-v", "long", "ACRA:S"}; setAcraConfigBuilder(getAcraCoreConfigBuilder().setLogcatArguments(logcatArgs)); }
Source:
private void addSmallCategory(List<SmallCategory> categories, Category parentCat, String langCode, boolean completeTitle) { String[] childrenCodes = parentCat.getChildrenCodes(); for (int i = 0; i < childrenCodes.length; i++) { Category cat = this.getCategory(childrenCodes[i]); if (null == cat.getChildrenCodes() || cat.getChildrenCodes().length == 0) { SmallCategory catSmall = new SmallCategory(); catSmall.setCode(cat.getCode()); if (!completeTitle) { catSmall.setTitle(cat.getTitles().getProperty(langCode)); } else { catSmall.setTitle(cat.getFullTitle(langCode)); } categories.add(catSmall); } this.addSmallCategory(categories, cat, langCode, completeTitle); } }

Target:
private void addSmallCategory(List<SmallCategory> categories, Category parentCat, String langCode, boolean completeTitle) { String[] childrenCodes = parentCat.getChildrenCodes(); if (null == childrenCodes) { return; } for (int i = 0; i < childrenCodes.length; i++) { Category cat = this.getCategory(childrenCodes[i]); if (null == cat.getChildrenCodes() || cat.getChildrenCodes().length == 0) { SmallCategory catSmall = new SmallCategory(); catSmall.setCode(cat.getCode()); if (!completeTitle) { catSmall.setTitle(cat.getTitles().getProperty(langCode)); } else { catSmall.setTitle(cat.getFullTitle(langCode)); } categories.add(catSmall); } this.addSmallCategory(categories, cat, langCode, completeTitle); } }
Source:
private File handleStringMessage(final String content, File originalFile, File tempFile, final File resultFile, final Message<?> requestMessage) throws IOException { final File fileToWriteTo = this.determineFileToWrite(resultFile, tempFile); final boolean append = FileExistsMode.APPEND.equals(this.fileExistsMode); WhileLockedProcessor whileLockedProcessor = new WhileLockedProcessor(this.lockRegistry, fileToWriteTo.getAbsolutePath()) { @Override protected void whileLocked() throws IOException { if (newFileCallback != null && !fileToWriteTo.exists() && (FileExistsMode.APPEND.equals(fileExistsMode) || FileExistsMode.APPEND_NO_FLUSH.equals(fileExistsMode))) { newFileCallback.accept(fileToWriteTo, requestMessage); } FileState state = getFileState(fileToWriteTo, true); BufferedWriter writer = null; try { writer = state != null ? state.writer : createWriter(fileToWriteTo, append); writer.write(content); if (FileWritingMessageHandler.this.appendNewLine) { writer.newLine(); } } finally { try { if (state == null || FileWritingMessageHandler.this.flushTask == null) { if (writer != null) { writer.close(); } clearState(fileToWriteTo, state); } else { state.lastWrite = System.currentTimeMillis(); } } catch (IOException ex) { } } } }; whileLockedProcessor.doWhileLocked(); this.cleanUpAfterCopy(fileToWriteTo, resultFile, originalFile); return resultFile; }

Target:
private File handleStringMessage(final String content, File originalFile, File tempFile, final File resultFile, final Message<?> requestMessage) throws IOException { final File fileToWriteTo = this.determineFileToWrite(resultFile, tempFile); final boolean append = FileExistsMode.APPEND.equals(this.fileExistsMode); WhileLockedProcessor whileLockedProcessor = new WhileLockedProcessor(this.lockRegistry, fileToWriteTo.getAbsolutePath()) { @Override protected void whileLocked() throws IOException { if (FileWritingMessageHandler.this.newFileCallback != null && !fileToWriteTo.exists() && (FileExistsMode.APPEND.equals(FileWritingMessageHandler.this.fileExistsMode) || FileExistsMode.APPEND_NO_FLUSH.equals(FileWritingMessageHandler.this.fileExistsMode))) { FileWritingMessageHandler.this.newFileCallback.accept(fileToWriteTo, requestMessage); } FileState state = getFileState(fileToWriteTo, true); BufferedWriter writer = null; try { writer = state != null ? state.writer : createWriter(fileToWriteTo, append); writer.write(content); if (FileWritingMessageHandler.this.appendNewLine) { writer.newLine(); } } finally { try { if (state == null || FileWritingMessageHandler.this.flushTask == null) { if (writer != null) { writer.close(); } clearState(fileToWriteTo, state); } else { state.lastWrite = System.currentTimeMillis(); } } catch (IOException ex) { } } } }; whileLockedProcessor.doWhileLocked(); this.cleanUpAfterCopy(fileToWriteTo, resultFile, originalFile); return resultFile; }
Source:
public ResourceResponse retrieveResource(URI resourceURI, Map<String, Serializable> properties) throws IOException, ResourceNotFoundException { logger.entry(); String bytesToSkip = null; if (resourceURI == null) { logger.warn("Resource URI was null"); throw new ResourceNotFoundException("Unable to find resource"); } if (properties.containsKey(BYTES_TO_SKIP)) { bytesToSkip = properties.get(BYTES_TO_SKIP).toString(); } if (resourceURI.getScheme().equals(URL_HTTP_SCHEME) || resourceURI.getScheme().equals(URL_HTTPS_SCHEME)) { logger.debug("Resource URI is HTTP or HTTPS"); String fileAddress = resourceURI.toURL().getFile(); logger.debug("resource name: {}", fileAddress); return doRetrieveProduct(resourceURI, fileAddress, bytesToSkip); } else if (resourceURI.getScheme().equals(URL_FILE_SCHEME)) { logger.debug("Resource URI is a File"); File filePathName = new File(resourceURI); String fileName = filePathName.getName(); logger.debug("resource name: {}", fileName); return doRetrieveProduct(resourceURI, fileName, bytesToSkip); } else { ResourceNotFoundException ce = new ResourceNotFoundException("Resource qualifier ( " + resourceURI.getScheme() + " ) not valid. " + URLResourceReader.TITLE + " requires a qualifier of " + URL_HTTP_SCHEME + " or " + URL_HTTPS_SCHEME + " or " + URL_FILE_SCHEME); logger.throwing(XLogger.Level.DEBUG, ce); logger.exit(); throw ce; } }

Target:
public ResourceResponse retrieveResource(URI resourceURI, Map<String, Serializable> properties) throws IOException, ResourceNotFoundException { logger.entry(); String bytesToSkip = null; if (resourceURI == null) { logger.warn("Resource URI was null"); throw new ResourceNotFoundException("Unable to find resource"); } if (properties.containsKey(BYTES_TO_SKIP)) { bytesToSkip = properties.get(BYTES_TO_SKIP).toString(); logger.debug("bytesToSkip: {}", bytesToSkip); } if (resourceURI.getScheme().equals(URL_HTTP_SCHEME) || resourceURI.getScheme().equals(URL_HTTPS_SCHEME)) { logger.debug("Resource URI is HTTP or HTTPS"); String fileAddress = resourceURI.toURL().getFile(); logger.debug("resource name: {}", fileAddress); return doRetrieveProduct(resourceURI, fileAddress, bytesToSkip); } else if (resourceURI.getScheme().equals(URL_FILE_SCHEME)) { logger.debug("Resource URI is a File"); File filePathName = new File(resourceURI); String fileName = filePathName.getName(); logger.debug("resource name: {}", fileName); return doRetrieveProduct(resourceURI, fileName, bytesToSkip); } else { ResourceNotFoundException ce = new ResourceNotFoundException("Resource qualifier ( " + resourceURI.getScheme() + " ) not valid. " + URLResourceReader.TITLE + " requires a qualifier of " + URL_HTTP_SCHEME + " or " + URL_HTTPS_SCHEME + " or " + URL_FILE_SCHEME); logger.throwing(XLogger.Level.DEBUG, ce); logger.exit(); throw ce; } }
Source:
private List<List<Scan>> getParallelScans() throws SQLException { if (scan == null || (ScanUtil.isLocalIndex(scan) && Bytes.compareTo(context.getScan().getStartRow(), scan.getStartRow()) == 0 && Bytes .compareTo(context.getScan().getStopRow(), scan.getStopRow()) == 0)) { return getParallelScans(EMPTY_BYTE_ARRAY, EMPTY_BYTE_ARRAY); } else { return getParallelScans(scan.getStartRow(), scan.getStopRow()); } }

Target:
private List<List<Scan>> getParallelScans() throws SQLException { if (!ScanUtil.isConextScan(scan, context)) { return getParallelScans(scan); } return getParallelScans(EMPTY_BYTE_ARRAY, EMPTY_BYTE_ARRAY); }
Source:
public void updateSubscription(Subscription newSubscription) { rateLimiter.updateSubscription(newSubscription); sender.updateSubscription(newSubscription); if (messageReceiver != null) { messageReceiver.update(newSubscription); } this.subscription = newSubscription; }

Target:
public void updateSubscription(Subscription newSubscription) { rateLimiter.updateSubscription(newSubscription); sender.updateSubscription(newSubscription); messageReceiver.update(newSubscription); this.subscription = newSubscription; }
Source:
public SERVICE_FAILURE_ACTIONS getFailureActions() { Pointer buffer = queryServiceConfig2(Winsvc.SERVICE_CONFIG_FAILURE_ACTIONS); SERVICE_FAILURE_ACTIONS result = new SERVICE_FAILURE_ACTIONS(buffer); result.read(); return result; }

Target:
public SERVICE_FAILURE_ACTIONS getFailureActions() { Pointer buffer = queryServiceConfig2(Winsvc.SERVICE_CONFIG_FAILURE_ACTIONS); SERVICE_FAILURE_ACTIONS result = new SERVICE_FAILURE_ACTIONS(buffer); return result; }
Source:
public String getPath(@Assisted("workspace") String workspaceId) throws IOException { if (projectsFolder != null) { return projectsFolder; } else { Path folder = Paths.get(workspacesFolder + "/" + workspaceId); if (Files.notExists(folder)) { Files.createDirectory(folder).toString(); } return folder.toString(); } }

Target:
public String getPath(@Assisted("workspace") String workspaceId) throws IOException { if (hostProjectsFolder != null) { return hostProjectsFolder; } else { Path folder = Paths.get(workspacesMountPoint).resolve(workspaceId); if (Files.notExists(folder)) { Files.createDirectory(folder); } return folder.toString(); } }
Source:
public void init(HelixManager helixManager, TableConfig tableConfig) { _helixManager = helixManager; _offlineTableName = tableConfig.getTableName(); _tenantConfig = tableConfig.getTenantConfig(); Preconditions.checkState(tableConfig.isDimTable(), "Not a dimension table: %s" + _offlineTableName); }

Target:
public void init(HelixManager helixManager, TableConfig tableConfig) { Preconditions.checkState(tableConfig.isDimTable(), "Not a dimension table: %s" + _offlineTableName); _helixManager = helixManager; _offlineTableName = tableConfig.getTableName(); _tenantConfig = tableConfig.getTenantConfig(); }
Source:
DigestSaslClient(String mechanism, String protocol, String serverName, CallbackHandler callbackHandler, String authorizationId, boolean hasInitialResponse, Charset charset, String[] qops, String[] ciphers) throws SaslException { super(mechanism, protocol, serverName, callbackHandler, FORMAT.CLIENT, charset, ciphers); this.hasInitialResponse = hasInitialResponse; this.authorizationId = authorizationId; this.clientQops = qops == null ? new String[] {DigestUtils.QOP_AUTH} : qops; this.demandedCiphers = ciphers == null ? new String[] : ciphers; try { this.messageDigest = MessageDigest.getInstance(DigestUtils.messageDigestAlgorithm(mechanism)); } catch (NoSuchAlgorithmException e) { throw new SaslException(getMechanismName() + ": Expected message digest algorithm is not available", e); } }

Target:
DigestSaslClient(String mechanism, String protocol, String serverName, CallbackHandler callbackHandler, String authorizationId, boolean hasInitialResponse, Charset charset, String[] qops, String[] ciphers) throws SaslException { super(mechanism, protocol, serverName, callbackHandler, FORMAT.CLIENT, charset, ciphers); this.hasInitialResponse = hasInitialResponse; this.authorizationId = authorizationId; this.clientQops = qops == null ? new String[] {QOP_AUTH} : qops; this.demandedCiphers = ciphers == null ? new String[] : ciphers; try { this.messageDigest = MessageDigest.getInstance(messageDigestAlgorithm(mechanism)); } catch (NoSuchAlgorithmException e) { throw new SaslException(getMechanismName() + ": Expected message digest algorithm is not available", e); } }
Source:
public static void savePrivateMessageAsDraft(PrivateMessage pm) throws NoSuchElementException, ValidationException { composeMessage(pm); if (pmPage.isSaveButtonEnabled()) { info("Clicking Save PM button"); try { pmPage.clickSaveButton(); } catch (NoSuchElementException e) { info("No such button found!"); throw new NoSuchElementException("Couldn't find Save button."); } } assertFormValid(); info("Draft had to be saved"); }

Target:
public static void savePrivateMessageAsDraft(PrivateMessage pm) throws NoSuchElementException, ValidationException { composeMessage(pm); if (pmPage.isSaveButtonEnabled()) { try { pmPage.clickSaveButton(); } catch (NoSuchElementException e) { throw new NoSuchElementException("Couldn't find Save button.", e); } } assertFormValid(); info("Draft had to be saved"); }
Source:
public void loadNodesFromModels(final List<DMNIncludedModel> includedModels, final ServiceCallback<List<DMNIncludedNode>> callback) { final List<DMNIncludedNode> result = new Vector<>(); final List<Promise> fileLoadPromises = new ArrayList<>(); for (final DMNIncludedModel model : includedModels) { final String path = model.getPath(); final Promise promise = contentService.loadFile(path).then(content -> { diagramService.transform(content, new ServiceCallback<Diagram>() { @Override public void onSuccess(final Diagram item) { final Optional<DMNIncludedModel> diagramImport = getDiagramImport(item, includedModels); final List<DMNIncludedNode> nodes = diagramImport .map(dmn -> diagramUtils .getDRGElements(item) .stream() .map(node -> includedModelFactory.makeDMNIncludeNode(path, dmn, node)) .collect(Collectors.toList())) .orElse(new ArrayList<>()); result.addAll(nodes); } @Override public void onError(final ClientRuntimeError error) { LOGGER.log(Level.SEVERE, error.getMessage()); } }); return promises.resolve(); } ); fileLoadPromises.add(promise); } promises.all(fileLoadPromises.toArray(new Promise[]{})).then(p -> { callback.onSuccess(result); return promises.resolve(); }); }

Target:
public void loadNodesFromModels(final List<DMNIncludedModel> includedModels, final ServiceCallback<List<DMNIncludedNode>> callback) { final List<DMNIncludedNode> result = new Vector<>(); if (includedModels.isEmpty()) { callback.onSuccess(result); } else { loadDMNDefinitions() .then(existingDefinitions -> promises.all(includedModels, model -> loadNodes(existingDefinitions, model, result)) .then(p -> { callback.onSuccess(result); return promises.resolve(); })); } }
Source:
public void setSessionLocaleFieldId() { String key = ""; if (Objects.isNull(serviceManager.getUserService().getAuthenticatedUser())) { key = ConfigCore.getParameter("language.force-default", "de"); } else { try { User user = serviceManager.getUserService().getById(serviceManager.getUserService().getAuthenticatedUser().getId()); key = ConfigCore.getParameter("language.force-default", user.getLanguage()); } catch (DAOException e) { logger.error("Error in retrieving user : " + e.getMessage()); } } Locale locale = new Locale.Builder().setLanguageTag(key).build(); if (LocaleUtils.isAvailableLocale(locale)) { FacesContext context = FacesContext.getCurrentInstance(); if (Objects.nonNull(context.getViewRoot())) { context.getViewRoot().setLocale(locale); context.getExternalContext().getSessionMap().put(SESSION_LOCALE_FIELD_ID, locale); } } }

Target:
private void setSessionLocaleFieldId() { String key = ""; if (Objects.isNull(serviceManager.getUserService().getAuthenticatedUser())) { key = ConfigCore.getParameter(Parameters.LANGUAGE_DEFAULT, DefaultValues.LANGUAGE_DEFAULT); } else { try { User user = serviceManager.getUserService().getById(serviceManager.getUserService().getAuthenticatedUser().getId()); key = user.getLanguage(); } catch (DAOException e) { Helper.setErrorMessage("Error in retrieving user ", logger, e); } } Locale locale = new Locale.Builder().setLanguageTag(key).build(); if (LocaleUtils.isAvailableLocale(locale)) { FacesContext context = FacesContext.getCurrentInstance(); if (Objects.nonNull(context.getViewRoot())) { context.getViewRoot().setLocale(locale); context.getExternalContext().getSessionMap().put(SESSION_LOCALE_FIELD_ID, locale); } } }
Source:
public void onLanguageTabSelected(String selectedLanguageCode) { Log.e("####", "HERE"); searchLanguageCode = selectedLanguageCode; startSearch(query, query != null && query.length() > 1); }

Target:
public void onLanguageTabSelected(String selectedLanguageCode) { searchLanguageCode = selectedLanguageCode; startSearch(query, query != null && query.length() > 1); }
Source:
private Collection<ControlModel> convertBannerButtons(Collection<BannerButton> buttons) { Collection<ControlModel> convertedItems = new ArrayList<ControlModel>(); if (!(buttons == null)) { for (BannerButton button : buttons) { convertedItems.add(new CustomControlModel(button)); } } return convertedItems; }

Target:
private Collection<CustomControlModel> convertBannerButtons(Collection<BannerButton> buttons) { if (buttons != null) { return buttons.stream().map(CustomControlModel::new).collect(Collectors.toList()); } else { return new ArrayList<CustomControlModel>(); } }
Source:
private static void saveToFile(Mets mets, URI xmlFile) throws JAXBException, IOException { FileManagementInterface fileManagementModule = new KitodoServiceLoader<FileManagementInterface>( FileManagementInterface.class).loadModule(); OutputStream out = fileManagementModule.write(fileManagementModule.getFile(xmlFile).toURI()); JAXBContext context = JAXBContext.newInstance(Mets.class); Marshaller marshal = context.createMarshaller(); marshal.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshal.marshal(mets, out); }

Target:
private static void saveToFile(Mets mets, URI xmlFile) throws JAXBException, IOException { URI metsFileUri = fileManagementModule.getFile(xmlFile).toURI(); try (OutputStream outputStream = fileManagementModule.write(metsFileUri)) { JAXBContext context = JAXBContext.newInstance(Mets.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(mets, outputStream); } }
Source:
public StreamLogFiles(ServerContext serverContext, boolean noVerify) { logDir = Paths.get(serverContext.getServerConfig().get("--log-path").toString(), "log"); writeChannels = new ConcurrentHashMap<>(); channelsToSync = new HashSet<>(); this.verify = !noVerify; this.dataStore = StreamLogDataStore.builder().dataStore(serverContext.getDataStore()).build(); String logSizeLimitPercParam = (String) serverContext.getServerConfig().get("--log-size-quota-percentage"); logSizeLimitPercentage = Double.parseDouble(logSizeLimitPercParam); initStreamLogDirectory(); long initialLogSize = estimateSize(logDir); log.info("StreamLogFiles: size is bytes, limit {}", logDir, initialLogSize, logSizeLimit); logSizeQuota = new ResourceQuota("LogSizeQuota", logSizeLimit); logSizeQuota.consume(initialLogSize); verifyLogs(); logMetadata = new LogMetadata(); initializeLogMetadata(); if (Math.max(logMetadata.getGlobalTail(), 0L) < getTrimMark()) { syncTailSegment(getTrimMark() - 1); } }

Target:
public StreamLogFiles(ServerContext serverContext, boolean noVerify) { logDir = Paths.get(serverContext.getServerConfig().get("--log-path").toString(), "log"); writeChannels = new ConcurrentHashMap<>(); channelsToSync = new HashSet<>(); this.verify = !noVerify; this.dataStore = StreamLogDataStore.builder().dataStore(serverContext.getDataStore()).build(); String logSizeLimitPercentageParam = (String)serverContext.getServerConfig().get("--log-size-quota-percentage"); final double logSizeLimitPercentage = Double.parseDouble(logSizeLimitPercentageParam); if (logSizeLimitPercentage < 0.0 || 100.0 < logSizeLimitPercentage) { String msg = String.format("Invalid quota: quota(%d)% must be between 0-100%", logSizeLimitPercentage); throw new LogUnitException(msg); } long fileSystemCapacity = initStreamLogDirectory(); logSizeLimit = (long)(fileSystemCapacity * logSizeLimitPercentage / 100.0); long initialLogSize = estimateSize(logDir); log.info("StreamLogFiles: size is bytes, limit {}", logDir, initialLogSize, logSizeLimit); logSizeQuota = new ResourceQuota("LogSizeQuota", logSizeLimit); logSizeQuota.consume(initialLogSize); verifyLogs(); logMetadata = new LogMetadata(); initializeLogMetadata(); if (Math.max(logMetadata.getGlobalTail(), 0L) < getTrimMark()) { syncTailSegment(getTrimMark() - 1); } }
Source:
private Point getPointForTime(long time) { return UIThreadRunnable.syncExec((Result<Point>) () -> { ITimeDataProvider timeDataProvider = widget.getTimeDataProvider(); if (timeDataProvider.getTime0() >= time || timeDataProvider.getTime1() <= time) { return null; } int x = widget.getXForTime(time); Rectangle bounds = widget.getItemBounds(fEntry); int y = bounds.y + bounds.height / 2; return new Point(x, y); }); }

Target:
private Point getPointForTime(long time) { return UIThreadRunnable.syncExec((Result<Point>) () -> { ITimeDataProvider timeDataProvider = widget.getTimeDataProvider(); if (timeDataProvider.getTime0() > time || timeDataProvider.getTime1() < time) { return null; } int x = widget.getXForTime(time); Rectangle bounds = widget.getItemBounds(fEntry); int y = bounds.y + bounds.height / 2; return new Point(x, y); }); }
Source:
private Guid findAvailableStorageDomain( Map<Guid, Long> targetDomainsSize, long diskSize, List<Guid> storageIds) { Guid dest = storageIds.stream() .min(Comparator.comparingLong(targetDomainsSize::get)) .orElse(storageIds.get(0)); long destSize = targetDomainsSize.get(dest); targetDomainsSize.put(dest, destSize - diskSize); return dest; }

Target:
private Guid findAvailableStorageDomain( Map<Guid, Long> targetDomainsSize, long diskSize, List<Guid> storageIds) { Guid dest = storageIds.stream() .max(Comparator.comparingLong(targetDomainsSize::get)) .orElse(storageIds.get(0)); long destSize = targetDomainsSize.get(dest); targetDomainsSize.put(dest, destSize - diskSize); return dest; }
Source:
public static <T extends Cborable> PaddedCipherText build(SymmetricKey from, T secret, int paddingBlockSize) { byte[] nonce = from.createNonce(); byte[] cipherText = from.encrypt(pad(secret.serialize(), paddingBlockSize), nonce); return new PaddedCipherText(new CipherText(nonce, cipherText)); }

Target:
public static <T extends Cborable> PaddedCipherText build(SymmetricKey from, T secret, int paddingBlockSize) { if (paddingBlockSize < 1) throw new IllegalStateException("Invalid padding block size: " + paddingBlockSize); byte[] nonce = from.createNonce(); byte[] cipherText = from.encrypt(pad(secret.serialize(), paddingBlockSize), nonce); return new PaddedCipherText(new CipherText(nonce, cipherText)); }
Source:
public void doVisitRandomArticle() { final Bus bus = app.getBus(); Handler randomHandler = new Handler(new Handler.Callback(){ @Override public boolean handleMessage(Message msg) { RandomArticleIdTask randomTask = new RandomArticleIdTask(app.getAPIForSite(app.getPrimarySite()), app.getPrimarySite(), app) { private ProgressDialog progressDialog; @Override public void onBeforeExecute() { setState(true); } @Override public void onFinish(PageTitle title) { if (activityStopped) { return; } setState(false); Log.d("Wikipedia", "Random article title pulled: " + title); if (title != null) { HistoryEntry historyEntry = new HistoryEntry(title, HistoryEntry.SOURCE_RANDOM); bus.post(new NewWikiPageNavigationEvent(title, historyEntry)); } else { Toast.makeText(app, app.getString(R.string.error_network_error), Toast.LENGTH_LONG).show(); } } @Override public void onCatch(Throwable caught) { if (activityStopped) { return; } setState(false); Log.d("Wikipedia", "Random article ID retrieval failed"); curRandomArticleIdTask = null; Toast.makeText(app, app.getString(R.string.error_network_error), Toast.LENGTH_LONG).show(); } }; if (curRandomArticleIdTask != null) { curRandomArticleIdTask.cancel(); } curRandomArticleIdTask = randomTask; curRandomArticleIdTask.execute(); return true; } }); randomHandler.removeMessages(MESSAGE_RND); Message randomMessage = Message.obtain(); randomMessage.what = MESSAGE_RND; randomMessage.obj = "random"; randomHandler.sendMessage(randomMessage); }

Target:
public void doVisitRandomArticle() { final Bus bus = app.getBus(); Handler randomHandler = new Handler(new Handler.Callback(){ @Override public boolean handleMessage(Message msg) { RandomArticleIdTask randomTask = new RandomArticleIdTask(app.getAPIForSite(app.getPrimarySite()), app.getPrimarySite(), app) { private ProgressDialog progressDialog; @Override public void onBeforeExecute() { setState(true); } @Override public void onFinish(PageTitle title) { if (isClosed) { return; } setState(false); Log.d("Wikipedia", "Random article title pulled: " + title); if (title != null) { HistoryEntry historyEntry = new HistoryEntry(title, HistoryEntry.SOURCE_RANDOM); bus.post(new NewWikiPageNavigationEvent(title, historyEntry)); } else { Toast.makeText(app, app.getString(R.string.error_network_error), Toast.LENGTH_LONG).show(); } } @Override public void onCatch(Throwable caught) { if (isClosed) { return; } setState(false); Log.d("Wikipedia", "Random article ID retrieval failed"); curRandomArticleIdTask = null; Toast.makeText(app, app.getString(R.string.error_network_error), Toast.LENGTH_LONG).show(); } }; if (curRandomArticleIdTask != null) { curRandomArticleIdTask.cancel(); } curRandomArticleIdTask = randomTask; curRandomArticleIdTask.execute(); return true; } }); randomHandler.removeMessages(MESSAGE_RND); Message randomMessage = Message.obtain(); randomMessage.what = MESSAGE_RND; randomMessage.obj = "random"; randomHandler.sendMessage(randomMessage); }
Source:
public void updateModel(final OperationContext context, ModelNode model, ListAttributeDefinition attributeDefinition, ModelNode listAttribute) throws OperationFailedException { ModelNode value = VALUE.resolveModelAttribute(context, model); ModelNode index = INDEX.resolveModelAttribute(context, model); List<ModelNode> res = new LinkedList<>(listAttribute.asList()); if (index.isDefined()) { res.remove(index.asInt()); } else { res.remove(value); } listAttribute.set(res); }

Target:
void updateModel(final OperationContext context, ModelNode model, ListAttributeDefinition attributeDefinition, ModelNode listAttribute) throws OperationFailedException { ModelNode value = VALUE.resolveModelAttribute(context, model); ModelNode index = INDEX.resolveModelAttribute(context, model); List<ModelNode> res = new ArrayList<>(listAttribute.asList()); if (index.isDefined()) { res.remove(index.asInt()); } else { res.remove(value); } listAttribute.set(res); }
Source:
private static JavaRDD<Vector> parsedToVectorRDD(JavaRDD<String[]> parsedRDD) { return parsedRDD.map(new Function<String[], Vector>() { @Override public Vector call(String[] tokens) { int numTokens = tokens.length; double[] values = new double[numTokens]; for (int i = 0; i < numTokens; i++) { values[i] = Double.parseDouble(tokens[i]); } return Vectors.dense(values); } }); }

Target:
private static JavaRDD<Vector> parsedToVectorRDD(JavaRDD<String[]> parsedRDD) { return parsedRDD.map(new Function<String[],Vector>() { @Override public Vector call(String[] tokens) { int numTokens = tokens.length; int i = 0; double[] values = new double[numTokens]; for (String token : tokens) { values[i] = Double.parseDouble(token); i++; } return Vectors.dense(values); } }); }
Source:
public SourceFile testParameterPath(@ApiParam(value = "Tool id", required = true) @PathParam("containerId") Long containerId, @QueryParam("tag") String tag, @QueryParam("type") String type){ if (type.toLowerCase().equals("cwl")) { return entryVersionHelper.getSourceFile(containerId, tag, FileType.CWL_TEST_JSON); } else { return entryVersionHelper.getSourceFile(containerId, tag, FileType.WDL_TEST_JSON); } }

Target:
public SourceFile testParameterPath(@ApiParam(value = "Tool id", required = true) @PathParam("containerId") Long containerId, @QueryParam("tag") String tag, @QueryParam("type") String type){ if (type.toLowerCase().equals(DescriptorType.CWL.toString())) { return entryVersionHelper.getSourceFile(containerId, tag, FileType.CWL_TEST_JSON); } else { return entryVersionHelper.getSourceFile(containerId, tag, FileType.WDL_TEST_JSON); } }
Source:
public void testDateConvertUtils() throws Exception { Constructor<DateConvertUtils> constructor = DateConvertUtils.class.getDeclaredConstructor(); assertThat(constructor.isAccessible(), is(false)); constructor.setAccessible(true); assertNotNull(constructor.newInstance()); constructor.setAccessible(false); }

Target:
public void testDateConvertUtils() throws Exception { Constructor<DateConvertUtils> constructor = DateConvertUtils.class.getDeclaredConstructor(); assertThat(constructor.isAccessible(), is(false)); constructor.setAccessible(true); assertThat(constructor.newInstance(), notNullValue()); constructor.setAccessible(false); }
Source:
public void multipleQueriesTest() { createAndExecuteVDB(VDB_NAME_MULTIPLE, PROJECT_NAME, NAME_ORACLE_MODEL); setTextToScrapbookAndExecute(QUERY_MULTIPLE); SQLResult result = DatabaseDevelopmentPerspective.getInstance().getSqlResultsView().getByOperation("Group Execution"); if(result.getStatus().equals("Succeeded")) { }else{ new NoButton(new DefaultShell("Continue Execution") ).click(); setTextToScrapbookAndExecute("delete from status where status_id = 97 or status_id = 98 or status_id = 99;"); fail("Queries status is not Succeeded, something is wrong!!"); } }

Target:
public void multipleQueriesTest() { createAndExecuteVDB(VDB_NAME_MULTIPLE, PROJECT_NAME, NAME_ORACLE_MODEL); setTextToScrapbookAndExecute(QUERY_MULTIPLE); SQLResult result = DatabaseDevelopmentPerspective.getInstance().getSqlResultsView().getByOperation("Group Execution"); if (new ShellIsAvailable("Continue Execution").test()) { new NoButton(new DefaultShell("Continue Execution")).click(); } assertEquals("Succeeded", result.getStatus()); }
Source:
private void addOperation(final VdcOperation<?, ?> operation, final boolean isPublic) { if ((loggedIn || isPublic) && (!operationQueue.contains(operation) || operation.allowDuplicates()) && operationQueue.add(operation)) { processor.processOperation(this); } }

Target:
private boolean addOperation(final VdcOperation<?, ?> operation, final boolean isPublic) { final boolean isAllowedToExecute = loggedIn || isPublic; final boolean operationCanBeAdded = !operationQueue.contains(operation) || operation.allowDuplicates(); if (isAllowedToExecute) { if (operationCanBeAdded && operationQueue.add(operation)) { processor.processOperation(this); } } return isAllowedToExecute; }
Source:
private <T> void notifyListeners(T t, List<Consumer<T>> lsnrs) { for (Consumer<T> lsnr : lsnrs) { try { lsnr.accept(t); } catch (Exception e) { log.warning("Metric listener error", e); } } }

Target:
private <T> void notifyListeners(T t, List<Consumer<T>> lsnrs) { for (Consumer<T> lsnr : lsnrs) { try { lsnr.accept(t); } catch (Exception e) { U.warn(log, "Metric listener error", e); } } }
Source:
private Request buildRequest(Message message) throws EndpointAddressResolutionException { Request request = client.newRequest(endpoint.resolveFor(message)) .method(HttpMethod.POST) .header(HttpHeader.KEEP_ALIVE.toString(), "true") .header(MESSAGE_ID.getName(), message.getId()) .header(HttpHeader.CONTENT_TYPE.toString(), MediaType.APPLICATION_JSON) .timeout(timeout, TimeUnit.MILLISECONDS) .content(new BytesContentProvider(message.getData())); return appendTraceInfo(request, message); }

Target:
private Request buildRequest(Message message) throws EndpointAddressResolutionException { Request request = client.newRequest(endpoint.resolveFor(message)) .method(HttpMethod.POST) .header(HttpHeader.KEEP_ALIVE.toString(), "true") .header(MESSAGE_ID.getName(), message.getId()) .header(HttpHeader.CONTENT_TYPE.toString(), contentTypeToMediaType.apply(message.getContentType())) .timeout(timeout, TimeUnit.MILLISECONDS) .content(new BytesContentProvider(message.getData())); return appendTraceInfo(request, message); }
Source:
private void finishCommon() throws ContainedException { if (!unknownSubjects.isEmpty()) { if(statements.isEmpty() && restoredStatements.isEmpty()) { throw new BadSubjectException(unknownSubjects.keySet(), uris); } else { log.debug(String.format(Locale.ROOT, "Unrecognized subjects: %s. Expected only sitelinks and subjects starting with %s and %s", unknownSubjects.keySet(), uris.entityData(), uris.entity())); } } if (revisionId == null) { throw new ContainedException("Didn't get a revision id for " + statements); } if (lastModified == null) { throw new ContainedException("Didn't get a last modified date for " + statements); } statements.add(new StatementImpl(entityUriImpl, new URIImpl(SchemaDotOrg.VERSION), revisionId)); statements.add(new StatementImpl(entityUriImpl, new URIImpl(SchemaDotOrg.DATE_MODIFIED), lastModified)); statements.addAll(restoredStatements); }

Target:
private void finishCommon() throws ContainedException { if (!unknownSubjects.isEmpty()) { if(statements.isEmpty() && restoredStatements.isEmpty()) { throw new BadSubjectException(unknownSubjects.keySet(), uris); } else { log.debug("Unrecognized subjects: {}. Expected only sitelinks and subjects starting with and {}", unknownSubjects.keySet(), uris.entityData(), uris.entity()); } } if (revisionId == null) { throw new ContainedException("Didn't get a revision id for " + statements); } if (lastModified == null) { throw new ContainedException("Didn't get a last modified date for " + statements); } statements.add(new StatementImpl(entityUriImpl, new URIImpl(SchemaDotOrg.VERSION), revisionId)); statements.add(new StatementImpl(entityUriImpl, new URIImpl(SchemaDotOrg.DATE_MODIFIED), lastModified)); statements.addAll(restoredStatements); }
Source:
public FilterPanel(UI ui, IModel model, PanelControl parentPanelControl, int panelIndex) { super(model, parentPanelControl, panelIndex); this.ui = ui; getChildren().addAll(createPanelMenuBar(), createFilterBox()); this.setOnMouseClicked(e-> { ui.triggerEvent(new PanelClickedEvent(this.panelIndex)); requestFocus(); }); focusedProperty().addListener((unused, wasFocused, isFocused) -> { if (isFocused) { getStyleClass().add("panel-focused"); } else { getStyleClass().remove("panel-focused"); } }); }

Target:
public FilterPanel(UI ui, IModel model, PanelControl parentPanelControl, int panelIndex) { super(model, parentPanelControl, panelIndex); this.ui = ui; getChildren().addAll(createPanelMenuBar(), createFilterBox()); setUpEventHandler(); focusedProperty().addListener((unused, wasFocused, isFocused) -> { if (isFocused) { getStyleClass().add("panel-focused"); } else { getStyleClass().remove("panel-focused"); } }); }
Source:
public void removeTable(Table tableInstance) { getResource().getContents().remove(tableInstance); }

Target:
public void removeTable(Table tableInstance) { if (getResource() != null) { getResource().getContents().remove(tableInstance); } }
Source:
private String token(final String home, final String code) throws IOException { final String uri = new Href(this.github) .path("login").path("oauth").path("access_token") .toString(); final XmlResponse xmlres = new JdkRequest(uri) .method("POST") .header("Accept", "application/xml") .body() .formParam("client_id", this.app) .formParam("redirect_uri", home) .formParam("client_secret", this.key) .formParam("code", code) .back() .fetch().as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(XmlResponse.class); String tokenString = null; try { tokenString = xmlres.xml() .xpath("/OAuth/access_token/text()").get(0); } catch (final IndexOutOfBoundsException exce) { throw new HttpException( HttpURLConnection.HTTP_BAD_REQUEST,"Invalid XML",exce); } return tokenString; }

Target:
private String token(final String home, final String code) throws IOException { final String uri = new Href(this.github) .path("login").path("oauth").path("access_token") .toString(); final List<String> tokens = new JdkRequest(uri) .method("POST") .header("Accept", "application/xml") .body() .formParam("client_id", this.app) .formParam("redirect_uri", home) .formParam("client_secret", this.key) .formParam("code", code) .back() .fetch().as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(XmlResponse.class) .xml().xpath("/OAuth/access_token/text()"); if (tokens.isEmpty()) { throw new HttpException( HttpURLConnection.HTTP_BAD_REQUEST, "No access token" ); } return tokens.get(0); }
Source:
public Iterable<Organization> iterate( @NotNull(message = "login is never NULL") final String login ) { return new MkIterable<Organization>( this.storage, "/github/orgs/org/login", new MkIterable.Mapping<Organization>() { @Override public Organization map(final XML xml) { return MkOrganizations.this.get( xml.xpath("login/text()").get(0) ); } } ); }

Target:
public Iterable<Organization> iterate( @NotNull(message = "login is never NULL") final String login ) { return new MkIterable<Organization>( this.storage, String.format("%s/org/login", this.xpath()), new MkIterable.Mapping<Organization>() { @Override public Organization map(final XML xml) { return MkOrganizations.this.get( xml.xpath("login/text()").get(0) ); } } ); }
Source:
public static AmazonS3 createS3ClientForRadosGW(String endpoint) { ClientConfiguration clientConfiguration = new ClientConfiguration(); SignerFactory.registerSigner("S3Signer", S3Signer.class); clientConfiguration.setSignerOverride("S3SignerType"); clientConfiguration.setProtocol(Protocol.HTTPS); AmazonS3 s3Client = new AmazonS3Client(new BasicAWSCredentials("accesskey", "secret"), clientConfiguration); s3Client.setEndpoint(endpoint); s3Client.setS3ClientOptions(new S3ClientOptions().withPathStyleAccess(true)); return s3Client; }

Target:
public static AmazonS3 createS3ClientForRadosGW(String endpoint) { val clientConfiguration = new ClientConfiguration(); SignerFactory.registerSigner("S3Signer", S3Signer.class); clientConfiguration.setSignerOverride("S3SignerType"); clientConfiguration.setProtocol(Protocol.HTTPS); val s3Client = new AmazonS3Client(new BasicAWSCredentials("accesskey", "secret"), clientConfiguration); s3Client.setEndpoint(endpoint); s3Client.setS3ClientOptions(new S3ClientOptions().withPathStyleAccess(true)); return s3Client; }
Source:
public void purgeDeletedKeySnippets() { KeyAsyncClient keyAsyncClient = createAsyncClient(); keyAsyncClient.purgeDeletedKey("deletedKeyName") .subscribe(purgeResponse -> System.out.println("Successfully Purged deleted Key \n")); END: com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKey#string }

Target:
public void purgeDeletedKeySnippets() { KeyAsyncClient keyAsyncClient = createAsyncClient(); keyAsyncClient.purgeDeletedKey("deletedKeyName") .subscribe(purgeResponse -> System.out.println("Successfully Purged deleted Key")); END: com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKey#string }
Source:
public void containsConversion(Class<?> from, Class<?> to) { isNotNull(); boolean foundMatchingConversion = false; for ( GroupConversionDescriptor groupConversionDescriptor : actual ) { if ( groupConversionDescriptor.getFrom().equals( from ) && groupConversionDescriptor.getTo().equals( to ) ) { foundMatchingConversion = true; break; } } if ( !foundMatchingConversion ) { fail( String.format( Locale.getDefault(), "<%s> does not contain a conversion from <%s> to <%s>.", actual, from, to ) ); } }

Target:
public void containsConversion(Class<?> from, Class<?> to) { isNotNull(); boolean foundMatchingConversion = false; for ( GroupConversionDescriptor groupConversionDescriptor : actual ) { if ( groupConversionDescriptor.getFrom().equals( from ) && groupConversionDescriptor.getTo().equals( to ) ) { foundMatchingConversion = true; break; } } if ( !foundMatchingConversion ) { fail( String.format( "<%s> does not contain a conversion from <%s> to <%s>.", actual, from, to ) ); } }
Source:
public void reboot() { String cmd = ""; if (OS_LINUX.equals(getOsName()) || OS_MAC_OSX.equals(getOsName())) { cmd = "reboot"; } else if (getOsName().toLowerCase().startsWith(OS_WINDOWS)) { cmd = "shutdown -r"; } else { logger.error("Unsupported OS for reboot()"); return; } Command command = new Command(cmd); command.setTimeout(60); CommandStatus status = this.executorService.execute(command); if ((Integer) status.getExitStatus().getExitValue() != 0) { logger.error("failed to issue reboot"); } }

Target:
public void reboot() { if (OS_LINUX.equals(getOsName()) || OS_MAC_OSX.equals(getOsName())) { executeCommand(new String[] { "reboot" }); } else if (getOsName().toLowerCase().startsWith(OS_WINDOWS)) { executeCommand(new String[] { "shutdown", "-r" }); } else { logger.error("Unsupported OS for reboot()"); } }
Source:
private int getNextPosition() throws CoreException { if (nextMemberPosition == -1) { nextMemberPosition = 0; while (nextMemberPosition < MAX_MEMBER_COUNT && getMemberRecord(nextMemberPosition) != 0) { nextMemberPosition++; } } return nextMemberPosition; }

Target:
private int getNextPosition() throws CoreException { if (nextMemberPosition < 0) { nextMemberPosition = 0; while (nextMemberPosition < MAX_MEMBER_COUNT && getMemberRecord(nextMemberPosition) != 0) { nextMemberPosition++; } } return nextMemberPosition; }