auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public RegexFilter( String dimension, final String pattern, final ExtractionFn extractionFn ) { super( dimension, extractionFn == null ? new Predicate<String>() { Pattern compiled = Pattern.compile(pattern); @Override public boolean apply(String input) { return (input != null) && compiled.matcher(input).find(); } } : new Predicate<String>() { Pattern compiled = Pattern.compile(pattern); @Override public boolean apply(String input) { return (input != null) && compiled.matcher(extractionFn.apply(input)).find(); } } ); }

Target:
public RegexFilter( String dimension, final String pattern, final ExtractionFn extractionFn ) { super( dimension, new Predicate<String>() { Pattern compiled = Pattern.compile(pattern); @Override public boolean apply(String input) { return (input != null) && compiled.matcher(input).find(); } }, extractionFn ); }
Source:
public static ArrayList<Vector2> readV2List(JSONObject parentNode, String name) { ArrayList<Vector2> res = new ArrayList<>(); JSONArray listNode = parentNode.has(name) ? parentNode.getJSONArray(name) : null; if (listNode == null) { return res; } for (int i = 0; i < listNode.length(); i++) { Vector2 vec = readV2(listNode.getString(i)); res.add(vec); } return res; }

Target:
public static ArrayList<Vector2> readV2List(JSONObject parentNode, String name) { ArrayList<Vector2> res = new ArrayList<>(); JSONArray listNode = parentNode.has(name) ? parentNode.getJSONArray(name) : null; if (listNode == null) { return res; } for (Object val : listNode) { if(val instanceof String) { Vector2 vec = readV2((String) val); res.add(vec); } } return res; }
Source:
private static List<String> getCompileFilePathsDefault(@NotNull JpsModule module, @NotNull ElixirTarget target){ CommonProcessors.CollectProcessor<File> exFilesCollector = new CommonProcessors.CollectProcessor<File>(){ @Override protected boolean accept(File file) { return !file.isDirectory() && FileUtilRt.extensionEquals(file.getName(), "ex"); } }; List<JpsModuleSourceRoot> sourceRoots = new ArrayList<JpsModuleSourceRoot>(); ContainerUtil.addAll(sourceRoots, module.getSourceRoots(JavaSourceRootType.SOURCE)); if(target.isTests()){ ContainerUtil.addAll(sourceRoots, module.getSourceRoots(JavaSourceRootType.TEST_SOURCE)); } for (JpsModuleSourceRoot root : sourceRoots){ FileUtil.processFilesRecursively(root.getFile(), exFilesCollector); } return ContainerUtil.map(exFilesCollector.getResults(), new Function<File, String>() { @NotNull @Override public String fun(@NotNull File file) { return file.getAbsolutePath(); } }); }

Target:
private static List<String> getCompileFilePathsDefault(@NotNull JpsModule module, @NotNull ElixirTarget target){ CommonProcessors.CollectProcessor<File> exFilesCollector = new CommonProcessors.CollectProcessor<File>(){ @Override protected boolean accept(File file) { return !file.isDirectory() && FileUtilRt.extensionEquals(file.getName(), ELIXIR_SOURCE_EXTENSION); } }; List<JpsModuleSourceRoot> sourceRoots = new ArrayList<JpsModuleSourceRoot>(); ContainerUtil.addAll(sourceRoots, module.getSourceRoots(JavaSourceRootType.SOURCE)); if(target.isTests()){ ContainerUtil.addAll(sourceRoots, module.getSourceRoots(JavaSourceRootType.TEST_SOURCE)); } for (JpsModuleSourceRoot root : sourceRoots){ FileUtil.processFilesRecursively(root.getFile(), exFilesCollector); } return ContainerUtil.map(exFilesCollector.getResults(), new Function<File, String>() { @NotNull @Override public String fun(@NotNull File file) { return file.getAbsolutePath(); } }); }
Source:
private synchronized void newUpdateThread(@NonNull FlowScopeLog fScope) { cancelUpdate(); if (getSwtChart().isDisposed()) { return; } int numRequests = fOverrideNbPoints != 0 ? fOverrideNbPoints : (int) Math.min(getWindowEndTime() - getWindowStartTime() + 1, (long) (getSwtChart().getPlotArea().getBounds().width * fResolution)); fUpdateThread = new UpdateThread(numRequests, fScope); fUpdateThread.start(); }

Target:
private synchronized void newUpdateThread(@NonNull FlowScopeLog fScope) { if (getSwtChart().isDisposed()) { return; } int numRequests = fOverrideNbPoints != 0 ? fOverrideNbPoints : (int) Math.min(getWindowEndTime() - getWindowStartTime() + 1, (long) (getSwtChart().getPlotArea().getBounds().width * fResolution)); fUpdateThread = new UpdateThread(numRequests, fScope); fUpdateThread.start(); }
Source:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Query query = RemoteAccess.evaluate(request); if (query.isDoS_blackout()) {response.sendError(503, "your request frequency is too high"); return;} String callback = query.get("callback", ""); boolean jsonp = callback != null && callback.length() > 0; boolean minified = query.get("minified", false); String tweetQuery = query.get("tweet", ""); String userQuery = query.get("user", ""); response.setCharacterEncoding("UTF-8"); PrintWriter sos = response.getWriter(); JSONObject result = new JSONObject(true); if(tweetQuery != null) { String tweetId = parseTweetId(tweetQuery); boolean exists = DAO.existMessage(tweetId); if(exists) { JSONObject post = DAO.searchLocalTweetById(tweetId); result.put("tweet", post); } } query.setResponse(response, jsonp ? "application/javascript" : "application/json"); if (jsonp) sos.print(callback + "("); sos.print(result.toString(minified ? 0 : 2)); if (jsonp) sos.println(");"); sos.println(); sos.flush(); sos.close(); query.finalize(); }

Target:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Query query = RemoteAccess.evaluate(request); if (query.isDoS_blackout()) {response.sendError(503, "your request frequency is too high"); return;} String callback = query.get("callback", ""); boolean jsonp = callback != null && callback.length() > 0; boolean minified = query.get("minified", false); String tweetQuery = query.get("tweet", ""); response.setCharacterEncoding("UTF-8"); PrintWriter sos = response.getWriter(); JSONObject result = new JSONObject(true); if (tweetQuery != null) { String tweetId = parseTweetId(tweetQuery); boolean exists = DAO.existMessage(tweetId); if (exists) { JSONObject post = DAO.searchLocalTweetById(tweetId); result.put("tweet", post); } } query.setResponse(response, jsonp ? "application/javascript" : "application/json"); if (jsonp) sos.print(callback + "("); sos.print(result.toString(minified ? 0 : 2)); if (jsonp) sos.println(");"); sos.println(); sos.flush(); sos.close(); }
Source:
String formatStepText(String keyword, String stepText, Format textFormat, Format argFormat, List<Argument> arguments) { int beginIndex = 0; StringBuilder result = new StringBuilder(textFormat.text(keyword)); for (Argument argument : arguments) { if (argument.getOffset() != null) { int argumentOffset = argument.getOffset(); if (argumentOffset < beginIndex ) { continue; } String text = stepText.substring(beginIndex, argumentOffset); result.append(textFormat.text(text)); } if (argument.getVal() != null) { result.append(argFormat.text(argument.getVal())); int argumentEnd = argument.getOffset() + argument.getVal().length(); beginIndex = argumentEnd; } } if (beginIndex != stepText.length() && beginIndex >= 0) { String text = stepText.substring(beginIndex, stepText.length()); result.append(textFormat.text(text)); } return result.toString(); }

Target:
String formatStepText(String keyword, String stepText, Format textFormat, Format argFormat, List<Argument> arguments) { int beginIndex = 0; StringBuilder result = new StringBuilder(textFormat.text(keyword)); for (Argument argument : arguments) { if (argument.getOffset() != null) { int argumentOffset = argument.getOffset(); if (argumentOffset < beginIndex ) { continue; } String text = stepText.substring(beginIndex, argumentOffset); result.append(textFormat.text(text)); } if (argument.getVal() != null) { result.append(argFormat.text(argument.getVal())); beginIndex = argument.getOffset() + argument.getVal().length(); } } if (beginIndex != stepText.length()) { String text = stepText.substring(beginIndex, stepText.length()); result.append(textFormat.text(text)); } return result.toString(); }
Source:
getMrrtReportTemplates_shouldReturnAllMrrtReportTemplatesThatMatchGivenPublisherAnywhereInDctermsPublisherInsensitiveToCase() throws Exception { MrrtReportTemplateSearchCriteria searchCriteria = new MrrtReportTemplateSearchCriteria.Builder().withPublisher("IHE CAT publisher") .build(); List<MrrtReportTemplate> templates = mrrtReportTemplateService.getMrrtReportTemplates(searchCriteria); assertNotNull(templates); assertThat(templates.size(), is(2)); }

Target:
getMrrtReportTemplates_shouldReturnAllMrrtReportTemplatesThatMatchGivenPublisherAnywhereInDctermsPublisherInsensitiveToCase() throws Exception { MrrtReportTemplateSearchCriteria searchCriteria = new MrrtReportTemplateSearchCriteria.Builder().withPublisher("cat") .build(); List<MrrtReportTemplate> templates = mrrtReportTemplateService.getMrrtReportTemplates(searchCriteria); List<String> uuids = new ArrayList<>(); for (MrrtReportTemplate template : templates) { uuids.add(template.getUuid()); } assertNotNull(templates); assertThat(templates.size(), is(2)); assertThat(uuids.contains(UUID_FOR_TEMPLATE_ONE), is(true)); assertThat(uuids.contains(UUID_FOR_TEMPLATE_TWO), is(true)); searchCriteria = new MrrtReportTemplateSearchCriteria.Builder().withPublisher("IHE CAT Publisher") .build(); templates = mrrtReportTemplateService.getMrrtReportTemplates(searchCriteria); uuids = new ArrayList<>(); for (MrrtReportTemplate template : templates) { uuids.add(template.getUuid()); } assertNotNull(templates); assertThat(templates.size(), is(1)); assertThat(uuids.contains(UUID_FOR_TEMPLATE_ONE), is(true)); }
Source:
public void write(final InputStream input) throws IOException { this.decorated.write( new ThresholdInputStream( input, this.mlength, new Runnable() { @Override public void run() { throw new IllegalArgumentException( String.format( "Now you can't upload a file that is larger than %s bytes", SmallDoc.this.mlength ) ); } } ) ); }

Target:
public void write(final InputStream input) throws IOException { try { this.decorated.write( new ThresholdInputStream(input, this.mlength) ); } catch (final ThresholdInputStream.LimitReachedException exc) { throw new IllegalArgumentException( String.format( "Now you can't upload a file that is larger than %s bytes", this.mlength ), exc ); } }
Source:
public boolean isVmManaged() { VM vm = getVm(); return vm != null && vm.isManagedVm(); }

Target:
public boolean isVmManaged() { return hostedEngineVm != null && hostedEngineVm.isManagedVm(); }
Source:
public String toString() { String builder = "FSFPair [featureStructure=" + featureStructure + ", affectedFeature=" + affectedFeature + "]"; return builder; }

Target:
public String toString() { return "FSFPair [featureStructure=" + featureStructure + ", affectedFeature=" + affectedFeature + "]"; }
Source:
private static byte[] sign(byte[] key, byte[] value) { try { String algorithm = "HmacSHA256"; Mac mac = Mac.getInstance(algorithm); mac.init(new SecretKeySpec(key, algorithm)); return mac.doFinal(value); } catch (NoSuchAlgorithmException | InvalidKeyException ex) { throw new IllegalStateException("Failed to calculate the AWS V4 Signature.", ex); } }

Target:
private static byte[] sign(byte[] key, byte[] value) { try { String algorithm = "HmacSHA256"; Mac mac = Mac.getInstance(algorithm); mac.init(new SecretKeySpec(key, algorithm)); return mac.doFinal(value); } catch (NoSuchAlgorithmException e) { throw new RuntimeException( "Invalid algorithm used when calculating the AWS V4 Signature.", e); } catch (InvalidKeyException e) { throw new SigningException("Invalid key used when calculating the AWS V4 Signature", e); } }
Source:
protected IDialogSettings getDialogBoundsSettings() { IDialogSettings settings = Activator.getDefault().getDialogSettings(); IDialogSettings section = settings .getSection(DIALOG_SETTINGS_SECTION_NAME); if (section == null) { section = settings.addNewSection(DIALOG_SETTINGS_SECTION_NAME); } return section; }

Target:
protected IDialogSettings getDialogBoundsSettings() { IDialogSettings settings = Activator.getDefault().getDialogSettings(); IDialogSettings section = settings .getSection(DIALOG_SETTINGS_SECTION_NAME); if (section == null) section = settings.addNewSection(DIALOG_SETTINGS_SECTION_NAME); return section; }
Source:
private static Map<String, Object> buildDataModel(RunConfiguration runConfiguration) { Map<String, Object> data = new HashMap<String, Object>(); data.put("run", runConfiguration.getRunName()); data.put("dry_run", runConfiguration.getExecutionConfig().getDryRunFlag()); data.put("max_cpu", runConfiguration.getExecutionConfig().getMaxCPUs()); data.put("verbose", runConfiguration.getExecutionConfig().getVerboseFlag()); data.put("model_version", runConfiguration.getCodeConfig().getModelVersion()); data.put("occurrence_file", "data/occurrence.csv"); data.put("extent_file", "data/extent.asc"); data.put("admin1_file", escapeFilePathForR(runConfiguration.getAdminUnitConfig().getAdmin1RasterFile())); data.put("admin2_file", escapeFilePathForR(runConfiguration.getAdminUnitConfig().getAdmin2RasterFile())); final String covariatePathPrefix = runConfiguration.getCovariateConfig().getCovariateDirectory(); Collection<String> covariatePaths = convert(runConfiguration.getCovariateConfig().getCovariateFilePaths(), new Converter<String, String>() { public String convert(String subpath) { return escapeFilePathForR(Paths.get(covariatePathPrefix, subpath).toString()); } }); data.put("covariate_files", covariatePaths); return data; }

Target:
private static Map<String, Object> buildDataModel(RunConfiguration runConfiguration) { Map<String, Object> data = new HashMap<String, Object>(); data.put("run", runConfiguration.getRunName()); data.put("dry_run", runConfiguration.getExecutionConfig().getDryRunFlag()); data.put("max_cpu", runConfiguration.getExecutionConfig().getMaxCPUs()); data.put("verbose", runConfiguration.getExecutionConfig().getVerboseFlag()); data.put("model_version", runConfiguration.getCodeConfig().getModelVersion()); data.put("occurrence_file", "data/occurrences.csv"); data.put("extent_file", "data/extent.asc"); data.put("admin1_file", escapeFilePathForR(runConfiguration.getAdminUnitConfig().getAdmin1RasterFile())); data.put("admin2_file", escapeFilePathForR(runConfiguration.getAdminUnitConfig().getAdmin2RasterFile())); final String covariatePathPrefix = runConfiguration.getCovariateConfig().getCovariateDirectory(); Collection<String> covariatePaths = convert(runConfiguration.getCovariateConfig().getCovariateFilePaths(), new Converter<String, String>() { public String convert(String subpath) { return escapeFilePathForR(Paths.get(covariatePathPrefix, subpath).toString()); } }); data.put("covariate_files", covariatePaths); return data; }
Source:
public ByteBuf getCommandLineBytes() { final StringBuilder sb = new StringBuilder(); sb.append(msgNumbers); sb.append(ImapClientConstants.SPACE); if (dataItems != null) { sb.append(ImapClientConstants.L_PAREN); sb.append(dataItems); sb.append(ImapClientConstants.R_PAREN); } else { sb.append(macro.name()); } if (changedSince != null) { sb.append(ImapClientConstants.SPACE); sb.append(ImapClientConstants.L_PAREN); sb.append(CHANGEDSINCE_SP); sb.append(changedSince); if (vanished) { sb.append(SP_VANISHED); } sb.append(ImapClientConstants.R_PAREN); } final String fetchCmdStr = sb.toString(); final int len = ImapClientConstants.PAD_LEN + fetchCmdStr.length(); final ByteBuf byteBuf = Unpooled.buffer(len); byteBuf.writeBytes(isUid ? UID_FETCH_SP_B : FETCH_SP_B); byteBuf.writeBytes(fetchCmdStr.getBytes(StandardCharsets.US_ASCII)); byteBuf.writeBytes(CRLF_B); return byteBuf; }

Target:
public ByteBuf getCommandLineBytes() { final int dataItemsSize = dataItems == null ? macro.name().length() : dataItems.length(); final String changedSinceStr = changedSince == null ? "" : changedSince.toString(); final int vanishedSize = isVanished ? SP_VANISHED.length() : 0; final int len = ImapClientConstants.PAD_LEN + changedSinceStr.length() + dataItemsSize + msgNumbers.length() + vanishedSize; final ByteBuf sb = Unpooled.buffer(len); sb.writeBytes(isUid ? UID_FETCH_SP_B : FETCH_SP_B); sb.writeBytes(msgNumbers.getBytes(StandardCharsets.US_ASCII)); sb.writeByte(ImapClientConstants.SPACE); if (dataItems != null) { sb.writeByte(ImapClientConstants.L_PAREN); sb.writeBytes(dataItems.getBytes(StandardCharsets.US_ASCII)); sb.writeByte(ImapClientConstants.R_PAREN); } else { sb.writeBytes(macro.name().getBytes(StandardCharsets.US_ASCII)); } if (changedSince != null) { sb.writeByte(ImapClientConstants.SPACE); sb.writeByte(ImapClientConstants.L_PAREN); sb.writeBytes(CHANGEDSINCE_SP_B); sb.writeBytes(changedSinceStr.getBytes(StandardCharsets.US_ASCII)); if (isVanished) { sb.writeBytes(SP_VANISHED_B); } sb.writeByte(ImapClientConstants.R_PAREN); } sb.writeBytes(CRLF_B); return sb; }
Source:
public void runBrowserStackLocal(String accessKey, String additionalArgs, String localBinary) { if (process != null) { return; } if (isEmpty(localBinary)) { if (!browserStackLocalFile.exists()) { prepareBrowserStackLocal(); } runTheBinary(browserStackLocalFile, accessKey, additionalArgs); } else { runTheBinary(new File(localBinary), accessKey, additionalArgs); } }

Target:
public void runBrowserStackLocal(String accessKey, String additionalArgs, String localBinary) throws BrowserStackLocalException { if (browserStackLocalBinary != null) { log.fine("One BrowserStackLocal binary has been already started."); return; } if (Utils.isNullOrEmpty(localBinary)) { if (!browserStackLocalFile.exists()) { prepareBrowserStackLocal(); } runBrowserStackLocal(browserStackLocalFile, accessKey, additionalArgs); } else { runBrowserStackLocal(new File(localBinary), accessKey, additionalArgs); } }
Source:
protected Iterable<IAnalysisModule> getDependentAnalyses() { ITmfTrace trace = getTrace(); if (trace == null) { throw new IllegalStateException(); } IAnalysisModule module = trace.getAnalysisModule(KernelAnalysisModule.ID); if (module == null) { return Collections.EMPTY_SET; } return ImmutableSet.of(module); }

Target:
protected Iterable<IAnalysisModule> getDependentAnalyses() { ITmfTrace trace = getTrace(); if (trace == null) { throw new IllegalStateException(); } IAnalysisModule module = trace.getAnalysisModule(TidAnalysisModule.ID); if (module == null) { return Collections.EMPTY_SET; } return ImmutableSet.of(module); }
Source:
private Plan generatePlan(final List<OptimizedComputeTask> optimizedComputeTasks) { final PlanImpl.Builder builder = PlanImpl.newBuilder(); final PriorityQueue<OptimizedComputeTask> senderPriorityQueue = new PriorityQueue<>(optimizedComputeTasks.size(), ascendingComparator); final PriorityQueue<OptimizedComputeTask> receiverPriorityQueue = new PriorityQueue<>(optimizedComputeTasks.size(), descendingComparator); for (final OptimizedComputeTask cmpTask : optimizedComputeTasks) { final int dataUnitToMove = getDataUnitsToMove(cmpTask); if (dataUnitToMove < 0) { senderPriorityQueue.add(cmpTask); } else if (dataUnitToMove > 0) { receiverPriorityQueue.add(cmpTask); } else { continue; } if (cmpTask.getParticipateValue() && cmpTask.getId().startsWith(TEMP_COMPUTE_TASK_ID_PREFIX)) { cmpTask.setId(getNewComputeTaskId()); builder.addEvaluatorToAdd(cmpTask.getId()); } else if (!cmpTask.getParticipateValue() && !cmpTask.getId().startsWith(TEMP_COMPUTE_TASK_ID_PREFIX)) { builder.addEvaluatorToDelete(cmpTask.getId()); } } while (senderPriorityQueue.size() > 0) { final OptimizedComputeTask sender = senderPriorityQueue.poll(); while (getDataUnitsToMove(sender) < 0) { final OptimizedComputeTask receiver = receiverPriorityQueue.poll(); builder.addTransferSteps(generateTransferStep(sender, receiver)); if (getDataUnitsToMove(receiver) > 0) { receiverPriorityQueue.add(receiver); } } } return builder.build(); }

Target:
private Plan generatePlan(final List<OptimizedComputeTask> optimizedComputeTasks) { final PlanImpl.Builder builder = PlanImpl.newBuilder(); final PriorityQueue<OptimizedComputeTask> senderPriorityQueue = new PriorityQueue<>(optimizedComputeTasks.size(), ascendingComparator); final PriorityQueue<OptimizedComputeTask> receiverPriorityQueue = new PriorityQueue<>(optimizedComputeTasks.size(), descendingComparator); for (final OptimizedComputeTask cmpTask : optimizedComputeTasks) { final int dataUnitToMove = getDataUnitsToMove(cmpTask); if (dataUnitToMove < 0) { senderPriorityQueue.add(cmpTask); } else if (dataUnitToMove > 0) { receiverPriorityQueue.add(cmpTask); } else { continue; } if (cmpTask.getParticipateValue() && cmpTask.isNewComputeTask()) { cmpTask.setId(getNewComputeTaskId()); builder.addEvaluatorToAdd(cmpTask.getId()); } else if (!cmpTask.getParticipateValue() && !cmpTask.isNewComputeTask()) { builder.addEvaluatorToDelete(cmpTask.getId()); } } while (senderPriorityQueue.size() > 0) { final OptimizedComputeTask sender = senderPriorityQueue.poll(); while (getDataUnitsToMove(sender) < 0) { final OptimizedComputeTask receiver = receiverPriorityQueue.poll(); builder.addTransferSteps(generateTransferStep(sender, receiver)); if (getDataUnitsToMove(receiver) > 0) { receiverPriorityQueue.add(receiver); break; } } } return builder.build(); }
Source:
protected Screen createScreen() { switch (status) { case ABANDONED: return new ByProjectAbandonedChangesScreen(project, "n,z"); case MERGED: return new ByProjectMergedChangesScreen(project, "n,z"); default: return new ByProjectOpenChangesScreen(project, "n,z"); } }

Target:
protected Screen createScreen() { switch (status) { case ABANDONED: return new ByProjectAbandonedChangesScreen(project, "n,z"); case MERGED: return new ByProjectMergedChangesScreen(project, "n,z"); case NEW: case SUBMITTED: default: return new ByProjectOpenChangesScreen(project, "n,z"); } }
Source:
public void onMessage(ClientMessage msg) { String body = ""; try { msg.acknowledge(); log.debug("ActiveMQ message acknowledged for listener: {}", msg.getMessageID(), listener); body = msg.getBodyBuffer().readString(); log.debug("Got event: {}", body); Event event = mapper.readValue(body, Event.class); listener.onEvent(event); session.commit(); } catch (Exception e) { String messageId = msg == null ? "" : Long.toString(msg.getMessageID()); String reason = e.getCause() == null ? e.getMessage() : e.getCause().getMessage(); log.error("Unable to process message {}: {}", messageId, reason); log.debug("Unable to process message. Rolling back client session.\n" + body, e); try { session.rollback(); } catch (ActiveMQException amqe) { log.error("Unable to roll back client session.", amqe); } } }

Target:
public void onMessage(ClientMessage msg) { String body = ""; try { msg.acknowledge(); log.debug("ActiveMQ message acknowledged for listener: {}", msg.getMessageID(), listener); body = msg.getBodyBuffer().readString(); log.debug("Got event: {}", body); Event event = mapper.readValue(body, Event.class); listener.onEvent(event); session.commit(); } catch (Exception e) { String messageId = (msg == null) ? "" : Long.toString(msg.getMessageID()); String reason = (e.getCause() == null) ? e.getMessage() : e.getCause().getMessage(); log.error("Unable to process message {}: {}", messageId, reason); log.debug("Unable to process message. Rolling back client session.\n{}", body, e); try { session.rollback(); } catch (ActiveMQException amqe) { log.error("Unable to roll back client session.", amqe); } } }
Source:
public void testFetchFromBundle() { try { File remoteWorkDir = tempFolder.newFolder("TempDir2"); JGitFacade.cloneFromRepo(localWorkDir, remoteWorkDir); writeCommitToRepo(localWorkDir, 3); File bundle = JGitFacade.createBundle(localWorkDir, "refs/heads/master", "CheckoutAtCommit2"); assertNotEquals( getObjectIdByRevisionString(localWorkDir, "HEAD"), getObjectIdByRevisionString(remoteWorkDir, "FETCH_HEAD")); JGitFacade.fetchFromBundle(bundle, remoteWorkDir); assertEquals( getObjectIdByRevisionString(localWorkDir, "HEAD"), getObjectIdByRevisionString(remoteWorkDir, "FETCH_HEAD")); } catch (IOException e) { fail("IO"); } catch (GitAPIException e) { fail("Git"); } }

Target:
public void testFetchFromBundle() throws IllegalArgumentException, Exception { File remoteWorkDir = tempFolder.newFolder("TempDir2"); JGitFacade.cloneFromRepo(localWorkDir, remoteWorkDir); writeCommitToRepo(localWorkDir, 3); String basis = JGitFacade.getSHA1HashByRevisionString(remoteWorkDir, "HEAD"); File bundle = JGitFacade.createBundle(localWorkDir, "HEAD", basis); assertNotEquals( getObjectIdByRevisionString(localWorkDir, "HEAD"), getObjectIdByRevisionString(remoteWorkDir, "FETCH_HEAD")); JGitFacade.fetchFromBundle(remoteWorkDir, bundle); assertEquals( getObjectIdByRevisionString(localWorkDir, "HEAD"), getObjectIdByRevisionString(remoteWorkDir, "FETCH_HEAD")); }
Source:
public RocksBlockStore(String baseDir) { RocksDB.loadLibrary(); mDisableWAL = new WriteOptions().setDisableWAL(true); mIteratorOption = new ReadOptions().setReadaheadSize( ServerConfiguration.getInt(PropertyKey.MASTER_METASTORE_BLOCK_ITERATOR_READAHEAD_SIZE)); ColumnFamilyOptions cfOpts = new ColumnFamilyOptions() .setMemTableConfig(new HashLinkedListMemTableConfig()) .setCompressionType(CompressionType.NO_COMPRESSION); List<ColumnFamilyDescriptor> columns = Arrays.asList(new ColumnFamilyDescriptor(BLOCK_META_COLUMN.getBytes(), cfOpts), new ColumnFamilyDescriptor(BLOCK_LOCATIONS_COLUMN.getBytes(), cfOpts)); DBOptions dbOpts = new DBOptions() .setAllowConcurrentMemtableWrite(false) .setMaxOpenFiles(-1) .setCreateIfMissing(true) .setCreateMissingColumnFamilies(true); String dbPath = PathUtils.concatPath(baseDir, BLOCKS_DB_NAME); String backupPath = PathUtils.concatPath(baseDir, BLOCKS_DB_NAME + "-backups"); if (!FileUtils.exists(dbPath)) { try { FileUtils.createDir(dbPath); } catch (IOException e) { LOG.warn("Failed to create nonexistent db path at: {}. Error:{}", dbPath, e); } } mRocksStore = new RocksStore(dbPath, backupPath, columns, dbOpts, Arrays.asList(mBlockMetaColumn, mBlockLocationsColumn)); }

Target:
public RocksBlockStore(String baseDir) { RocksDB.loadLibrary(); mDisableWAL = new WriteOptions().setDisableWAL(true); mIteratorOption = new ReadOptions().setReadaheadSize( ServerConfiguration.getBytes(PropertyKey.MASTER_METASTORE_ITERATOR_READAHEAD_SIZE)); ColumnFamilyOptions cfOpts = new ColumnFamilyOptions() .setMemTableConfig(new HashLinkedListMemTableConfig()) .setCompressionType(CompressionType.NO_COMPRESSION); List<ColumnFamilyDescriptor> columns = Arrays.asList(new ColumnFamilyDescriptor(BLOCK_META_COLUMN.getBytes(), cfOpts), new ColumnFamilyDescriptor(BLOCK_LOCATIONS_COLUMN.getBytes(), cfOpts)); DBOptions dbOpts = new DBOptions() .setAllowConcurrentMemtableWrite(false) .setMaxOpenFiles(-1) .setCreateIfMissing(true) .setCreateMissingColumnFamilies(true); String dbPath = PathUtils.concatPath(baseDir, BLOCKS_DB_NAME); String backupPath = PathUtils.concatPath(baseDir, BLOCKS_DB_NAME + "-backups"); if (!FileUtils.exists(dbPath)) { try { FileUtils.createDir(dbPath); } catch (IOException e) { LOG.warn("Failed to create nonexistent db path at: {}. Error:{}", dbPath, e); } } mRocksStore = new RocksStore(dbPath, backupPath, columns, dbOpts, Arrays.asList(mBlockMetaColumn, mBlockLocationsColumn)); }
Source:
public static boolean isAllowedTime(byte[] signedTime, int durationSeconds, ContentAddressedStorage ipfs, PublicKeyHash owner) { try { Optional<PublicSigningKey> ownerOpt = ipfs.getSigningKey(owner).get(); if (! ownerOpt.isPresent()) throw new IllegalStateException("Couldn't retrieve owner key during getFollowRequests() call!"); byte[] raw = ownerOpt.get().unsignMessage(signedTime); CborObject cbor = CborObject.fromByteArray(raw); if (! (cbor instanceof CborObject.CborLong)) throw new IllegalStateException("Invalid cbor for getFollowRequests authorisation!"); long utcMillis = ((CborObject.CborLong) cbor).value; long now = System.currentTimeMillis(); if (Math.abs(now - utcMillis) > durationSeconds * 1_000) throw new IllegalStateException("Stale auth time, is your clock accurate?"); } catch (Exception e) { throw new RuntimeException(e); } return true; }

Target:
public static boolean isAllowedTime(byte[] signedTime, int durationSeconds, ContentAddressedStorage ipfs, PublicKeyHash owner) { try { Optional<PublicSigningKey> ownerOpt = ipfs.getSigningKey(owner).get(); if (! ownerOpt.isPresent()) throw new IllegalStateException("Couldn't retrieve owner key!"); byte[] raw = ownerOpt.get().unsignMessage(signedTime); CborObject cbor = CborObject.fromByteArray(raw); if (! (cbor instanceof CborObject.CborLong)) throw new IllegalStateException("Invalid cbor for time in authorisation!"); long utcMillis = ((CborObject.CborLong) cbor).value; long now = System.currentTimeMillis(); if (Math.abs(now - utcMillis) > durationSeconds * 1_000) throw new IllegalStateException("Stale auth time, is your clock accurate?"); } catch (Exception e) { throw new RuntimeException(e); } return true; }
Source:
public Declarables(Collection<Declarable> declarables) { this.declarables.addAll(declarables); }

Target:
public Declarables(Collection<Declarable> declarables) { Assert.notNull(declarables, "declarables cannot be null"); this.declarables.addAll(declarables); }
Source:
public BatchDataSegmentAnnouncer( DruidServerMetadata server, final BatchDataSegmentAnnouncerConfig config, ZkPathsConfig zkPaths, Announcer announcer, ObjectMapper jsonMapper ) { super(server, zkPaths, announcer, jsonMapper); this.config = config; this.announcer = announcer; this.jsonMapper = jsonMapper; this.server = server; this.liveSegmentLocation = ZKPaths.makePath(zkPaths.getLiveSegmentsPath(), server.getName()); segmentTransformer = new Function<DataSegment, DataSegment>() { @Override public DataSegment apply(DataSegment input) { DataSegment rv = input; if (config.isSkipDimensionsAndMetrics()) { rv = rv.withDimensions(null).withMetrics(null); } if (config.isSkipLoadSpec()) { rv = rv.withLoadSpec(null); } return rv; } }; if (this.config.isSkipSegmentAnnouncementOnZk()) { dummyZnode = new SegmentZNode("PLACE_HOLDER_ONLY"); } else { dummyZnode = null; } }

Target:
public BatchDataSegmentAnnouncer( DruidServerMetadata server, final BatchDataSegmentAnnouncerConfig config, ZkPathsConfig zkPaths, Announcer announcer, ObjectMapper jsonMapper ) { this.config = config; this.announcer = announcer; this.jsonMapper = jsonMapper; this.server = server; this.liveSegmentLocation = ZKPaths.makePath(zkPaths.getLiveSegmentsPath(), server.getName()); segmentTransformer = new Function<DataSegment, DataSegment>() { @Override public DataSegment apply(DataSegment input) { DataSegment rv = input; if (config.isSkipDimensionsAndMetrics()) { rv = rv.withDimensions(null).withMetrics(null); } if (config.isSkipLoadSpec()) { rv = rv.withLoadSpec(null); } return rv; } }; if (this.config.isSkipSegmentAnnouncementOnZk()) { dummyZnode = new SegmentZNode("PLACE_HOLDER_ONLY"); } else { dummyZnode = null; } }
Source:
public OauthAuthenticationResult authenticate(HttpServletRequest httpRequest) { Assert.notNull(httpRequest, "httpRequest cannot be null."); Class httpRequestClass = httpRequest.getClass(); if (HttpServletRequest.class.isAssignableFrom(httpRequestClass)) { this.httpServletRequest = (HttpServletRequest) httpRequest; } else { throw new IllegalArgumentException(String.format(HTTP_REQUEST_NOT_SUPPORTED_MSG, httpRequest.getClass(), HttpServletRequest.class.getName())); } OauthAuthenticationRequestFactory factory = new OauthAuthenticationRequestFactory(); AuthenticationRequest request = factory.createFrom(httpServletRequest); AuthenticationResult result = application.authenticateAccount(request); Assert.isInstanceOf(OauthAuthenticationResult.class, result); return (OauthAuthenticationResult) result; }

Target:
public OauthAuthenticationResult authenticate(HttpServletRequest httpRequest) { Assert.notNull(httpRequest, "httpRequest cannot be null."); Class httpRequestClass = httpRequest.getClass(); if (HttpServletRequest.class.isAssignableFrom(httpRequestClass)) { this.httpServletRequest = httpRequest; } else { throw new IllegalArgumentException(String.format(HTTP_REQUEST_NOT_SUPPORTED_MSG, httpRequest.getClass(), HttpServletRequest.class.getName())); } OauthAuthenticationRequestFactory factory = new OauthAuthenticationRequestFactory(); AuthenticationRequest request = factory.createFrom(httpServletRequest); AuthenticationResult result = application.authenticateAccount(request); Assert.isInstanceOf(OauthAuthenticationResult.class, result); return (OauthAuthenticationResult) result; }
Source:
private List<RepoProject> getBareProjects(List<RepoProject> projects) { assert (repo.isBare()); Map<String, List<RepoProject>> m = new HashMap<>(); for (RepoProject proj : projects) { if (m.containsKey(proj.getName())) { m.get(proj.getName()).add(proj); } else { List<RepoProject> l = new ArrayList<>(); l.add(proj); m.put(proj.getName(), l); } } List<RepoProject> ret = new ArrayList<>(); for (Entry<String, List<RepoProject>> e : m.entrySet()) { boolean suffixWithPath = e.getValue().size() != 1; for (RepoProject proj : e.getValue()) { String name = proj.getName(); if (suffixWithPath) { name += SLASH + proj.getPath(); } RepoProject bareProj = new RepoProject(name, proj.getPath(), proj.getRevision(), null, proj.getGroups(), proj.getRecommendShallow()); bareProj.setUrl(proj.getUrl()); bareProj.addCopyFiles(proj.getCopyFiles()); bareProj.addLinkFiles(proj.getLinkFiles()); ret.add(bareProj); } } return ret; }

Target:
private List<RepoProject> getBareProjects(List<RepoProject> projects) { assert (repo.isBare()); Map<String, List<RepoProject>> m = new HashMap<>(); for (RepoProject proj : projects) { List<RepoProject> l = m.get(proj.getName()); if (l == null) { l = new ArrayList<>(); m.put(proj.getName(), l); } l.add(proj); } List<RepoProject> ret = new ArrayList<>(); for (List<RepoProject> ps : m.values()) { boolean nameConflict = ps.size() != 1; for (RepoProject proj : ps) { String name = proj.getName(); if (nameConflict) { name += SLASH + proj.getPath(); } RepoProject bareProj = new RepoProject(name, proj.getPath(), proj.getRevision(), null, proj.getGroups(), proj.getRecommendShallow()); bareProj.setUrl(proj.getUrl()); bareProj.addCopyFiles(proj.getCopyFiles()); bareProj.addLinkFiles(proj.getLinkFiles()); ret.add(bareProj); } } return ret; }
Source:
public Tuple2<Integer, String> cross( Tuple5<Integer, Long, Integer, String, Long> first, Tuple5<Integer, Long, Integer, String, Long> second) throws Exception { if(first.f0 < 3 && second.f0 < 3) return new Tuple2<Integer, String>(first.f2+second.f2, first.f3+second.f3); return new Tuple2<Integer, String>(1,"test"); }

Target:
public Tuple2<Integer, String> cross( Tuple5<Integer, Long, Integer, String, Long> first, Tuple5<Integer, Long, Integer, String, Long> second) throws Exception { return new Tuple2<Integer, String>(first.f2+second.f2, first.f3+second.f3); }
Source:
public Date getStartDate() { return new Date(startDate.getTime()); }

Target:
public Date getStartDate() { return return (Date) endDate.clone(); }
Source:
public static boolean isDescendant(File forParent, File potentialChild) throws IOException { Path child = potentialChild.getAbsoluteFile().toPath(); Path parent = forParent.getAbsoluteFile().toPath(); return child.startsWith(parent); }

Target:
public static boolean isDescendant(File forParent, File potentialChild) throws IOException { try { Path child = potentialChild.getAbsoluteFile().toPath().normalize(); Path parent = forParent.getAbsoluteFile().toPath().normalize(); return child.startsWith(parent); } catch (InvalidPathException e) { throw new IOException(e); } }
Source:
public Class<?> defineClass(String name, byte[] bytes) { Class<?> ret = defined.get(name.replace('/', '.')); if (ret != null) { return ret; } if (name.endsWith("package-info")) { Package p = super.getPackage(name.substring(0, name.length() - 13)); if (p == null) { definePackage(name.substring(0, name.length() - 13).replace('/', '.'), null, null, null, null, null, null, null); } } ret = super.defineClass(name.replace('/', '.'), bytes, 0, bytes.length); Class<?> tmpRet = defined.putIfAbsent(name.replace('/', '.'), ret); if (tmpRet != null) { ret = tmpRet; } return ret; }

Target:
public Class<?> defineClass(String name, byte[] bytes) { Class<?> ret = defined.get(StringUtils.slashesToPeriod(name)); if (ret != null) { return ret; } if (name.endsWith("package-info")) { String s = name.substring(0, name.length() - 13); Package p = super.getPackage(s); if (p == null) { definePackage(StringUtils.slashesToPeriod(s), null, null, null, null, null, null, null); } } ret = defined.computeIfAbsent(StringUtils.slashesToPeriod(name), key -> TypeHelperClassLoader.super.defineClass(key, bytes, 0, bytes.length)); return ret; }
Source:
public void execute() { SaveDatabaseAction saveDatabaseAction = SaveDatabaseAction.create(frame.getCurrentBasePanel(), Globals.prefs, Globals.entryTypesManager); switch (saveMethod) { case SAVE: saveDatabaseAction.save(); break; case SAVE_AS: saveDatabaseAction.saveAs(); break; case SAVE_SELECTED: saveDatabaseAction.saveSelectedAsPlain(); break; default: } }

Target:
public void execute() { SaveDatabaseAction saveDatabaseAction = new SaveDatabaseAction( frame.getCurrentLibraryTab(), Globals.prefs, Globals.entryTypesManager); switch (saveMethod) { case SAVE -> saveDatabaseAction.save(); case SAVE_AS -> saveDatabaseAction.saveAs(); case SAVE_SELECTED -> saveDatabaseAction.saveSelectedAsPlain(); } }
Source:
public FileInfo[] listDir() { if( !exists() ) return new FileInfo[] {}; if( !isDirectory() ) return new FileInfo[] { this }; ArrayList<FileInfo> res = new ArrayList<>(); try { RemoteIterator<LocatedFileStatus> iterator = fs.listLocatedStatus(path); while (iterator.hasNext()) { res.add( new HFileInfo(iterator.next()) ); } } catch (IOException e) { return new FileInfo[0]; } return res.toArray(new FileInfo[res.size()]); }

Target:
public FileInfo[] listDir() throws IOException { if( !exists() ) return new FileInfo[] {}; if( !isDirectory() ) return new FileInfo[] { this }; List<FileInfo> res = new ArrayList<>(); RemoteIterator<LocatedFileStatus> iterator = fs.listLocatedStatus(path); while (iterator.hasNext()) { res.add( new HFileInfo(iterator.next()) ); } return res.toArray(new FileInfo[res.size()]); }
Source:
public RequestStats() { allResponse = new CounterStat(); informationalResponse = new CounterStat(); successfulResponse = new CounterStat(); redirectionResponse = new CounterStat(); clientErrorResponse = new CounterStat(); serverErrorResponse = new CounterStat(); requestFailed = new CounterStat(); requestCanceled = new CounterStat(); requestTime = new TimeStat(); responseTime = new TimeStat(); readBytes = new DistributionStat(); writtenBytes = new DistributionStat(); }

Target:
public RequestStats() { }
Source:
public int countDownBricks(GlusterVolumeEntity volume) { int downCount = 0; int upCount = 0; for (int i = 0 ; i < volume.getBricks().size(); i++) { GlusterBrickEntity brick = volume.getBricks().get(i); if(brick.getStatus() == GlusterStatus.UP) { upCount++; }else { downCount++; } if(upCount > 0 && downCount > 0) { return downCount; } } return downCount; }

Target:
public int countDownBricks(GlusterVolumeEntity volume) { int downCount = 0; int upCount = 0; for (GlusterBrickEntity brick : volume.getBricks()) { if (brick.getStatus() == GlusterStatus.UP) { upCount++; } else { downCount++; } if (upCount > 0 && downCount > 0) { return downCount; } } return downCount; }
Source:
public static ArgumentBuilder<CommandSource, ?> register(String name, ITreeSpawner treeSpawner) { return Commands.literal(name).requires(PermLevel.ADMIN) .then(Commands.argument("type", EnumArgument.enumArgument(TreeDefinition.class)) .executes(a -> run(treeSpawner, a.getSource(), a.getArgument("type", TreeDefinition.class)))) .executes(a -> run(treeSpawner, a.getSource(), TreeDefinition.Oak)); }

Target:
public static ArgumentBuilder<CommandSource, ?> register(String name, ITreeSpawner treeSpawner) { return Commands.literal(name).requires(PermLevel.ADMIN) .then(Commands.argument("type", TreeArugment.treeArgument()) .executes(a -> run(treeSpawner, a.getSource(), a.getArgument("type", ITree.class)))) .executes(a -> run(treeSpawner, a.getSource(), TreeDefinition.Oak.createIndividual())); }
Source:
protected Result check() throws Exception { String entity = "test"; String version = "1.0.0"; String request = getFindTestRequest(entity, version); RequestMetrics metrics = new DropwizardRequestMetrics(MetricRegistryFactory.getJmxMetricRegistry()); CallStatus callStatus = new FindCommand(entity, version, request, metrics).run(); if(callStatus.hasErrors()){ return Result.unhealthy("Reads are not healthy: " + callStatus.getErrors()); } return Result.healthy(); }

Target:
protected Result check() throws Exception { String entity = "test"; String version = "1.0.0"; String request = getFindTestRequest(entity, version); RequestMetrics metrics = new DropwizardRequestMetrics(MetricRegistryFactory.getJmxMetricRegistry()); CallStatus callStatus = new FindCommand(entity, version, request, metrics).run(); ResultBuilder resultBuilder; if (Response.Status.OK.equals(callStatus.getHttpStatus())) { resultBuilder = Result.builder().healthy(); } else { resultBuilder = Result.builder().unhealthy().withMessage("Reads are not healthy"); } resultBuilder.withDetail("readResponse", callStatus.getReturnValue().toJson()); return resultBuilder.build(); }
Source:
private void overrideBlobName(Exchange exchange) { String blobName = exchange.getIn().getHeader(OVERRIDE_BLOB_NAME, String.class); if (StringUtils.isNotEmpty(blobName)) { getEndpoint().getConfiguration().setBlobName(blobName); } }

Target:
private void overrideBlobName(Exchange exchange) { String blobName = exchange.getIn().getHeader(OVERRIDE_BLOB_NAME, String.class); if (ObjectHelper.isNotEmpty(blobName)) { getEndpoint().getConfiguration().setBlobName(blobName); } }
Source:
private boolean isQuarriableBlock(int bx, int by, int bz) { Block block = worldObj.getBlock(bx, by, bz); return !BlockUtil.canChangeBlock(block, worldObj, bx, by, bz) || BuildCraftAPI.isSoftBlock(block, worldObj, bx, by, bz) || (block.getBlockHardness(worldObj, bx, by, bz) > MAX_BREAK_HARDNESS); }

Target:
private boolean isQuarriableBlock(int bx, int by, int bz) { Block block = worldObj.getBlock(bx, by, bz); return BlockUtil.canChangeBlock(block, worldObj, bx, by, bz) && !BuildCraftAPI.isSoftBlock(block, worldObj, bx, by, bz) && (block.getBlockHardness(worldObj, bx, by, bz) < MAX_BREAK_HARDNESS); }
Source:
public static TransactionManager getTransactionManager() throws Exception { long key = Thread.currentThread().getId(); try { if (log.isDebugEnabled()) { log.debug("beginTransaction()"); } TransactionManager txMgr = txManagers.get().get(key); return txMgr; } catch (Exception ex) { log.debug(" BEGIN ERROR : " + txManagers.get().get(key).getStatus()); throw ex; } }

Target:
public static TransactionManager getTransactionManager() throws Exception { long key = Thread.currentThread().getId(); try { if (log.isDebugEnabled()) { log.debug("getTransactionManager Called"); } TransactionManager txMgr = txManagers.get().get(key); return txMgr; } catch (Exception ex) { log.error(" BEGIN ERROR : " + txManagers.get().get(key).getStatus()); throw ex; } }
Source:
private static QueryStatusEncoding queryStatusHelper(final SQLiteStatement statement) throws SQLiteException { final QueryStatusEncoding queryStatus = new QueryStatusEncoding(statement.columnLong(0)); queryStatus.rawQuery = statement.columnString(1); queryStatus.logicalRa = statement.columnString(2); String physicalString = statement.columnString(3); try { queryStatus.physicalPlan = MyriaJsonMapperProvider.getMapper().readValue(physicalString, QueryEncoding.class); } catch (IOException e) { queryStatus.physicalPlan = physicalString; System.out.println(e); } queryStatus.submitTime = statement.columnString(4); queryStatus.startTime = statement.columnString(5); queryStatus.finishTime = statement.columnString(6); if (!statement.columnNull(7)) { queryStatus.elapsedNanos = statement.columnLong(7); } queryStatus.status = QueryStatusEncoding.Status.valueOf(statement.columnString(8)); return queryStatus; }

Target:
private static QueryStatusEncoding queryStatusHelper(final SQLiteStatement statement) throws SQLiteException { final QueryStatusEncoding queryStatus = new QueryStatusEncoding(statement.columnLong(0)); queryStatus.rawQuery = statement.columnString(1); queryStatus.logicalRa = statement.columnString(2); String physicalString = statement.columnString(3); try { queryStatus.physicalPlan = MyriaJsonMapperProvider.getMapper().readValue(physicalString, QueryEncoding.class); } catch (IOException e) { queryStatus.physicalPlan = physicalString; } queryStatus.submitTime = statement.columnString(4); queryStatus.startTime = statement.columnString(5); queryStatus.finishTime = statement.columnString(6); if (!statement.columnNull(7)) { queryStatus.elapsedNanos = statement.columnLong(7); } queryStatus.status = QueryStatusEncoding.Status.valueOf(statement.columnString(8)); return queryStatus; }
Source:
public static NovaTemplateOptions availabilityZone(String availabilityZone) { return new NovaTemplateOptions().availabilityZone(availabilityZone); }

Target:
public static NovaTemplateOptions availabilityZone(String availabilityZone) { NovaTemplateOptions options = new NovaTemplateOptions(); return options.availabilityZone(availabilityZone); }
Source:
public String[] optimize(String appModel, String suitableCloudOffer) { String[] outputPlans = new String[NUMBER_OF_PLANS_GENERATED]; outputPlans[0] = "Plan generation was not possible"; if (previousPlans == null) { OptimizerInitialDeployment initialOptimizer = new OptimizerInitialDeployment(searchName); try { outputPlans = initialOptimizer.optimize(appModel, suitableCloudOffer, NUMBER_OF_PLANS_GENERATED); previousPlans = outputPlans; } catch (Error E) { log.error("Error optimizing the initial deployment"); } } else { Reoptimizer optimizerReplanning = new Reoptimizer(searchName); try { log.error("Calling a Replanning. The previously generated Plan will be used as a base"); outputPlans = optimizerReplanning.optimize(appModel, suitableCloudOffer, NUMBER_OF_PLANS_GENERATED); previousPlans = outputPlans; } catch (Error E) { log.error("Error optimizing the Replanning"); } } return outputPlans; }

Target:
public String[] optimize(String appModel, String suitableCloudOffer) { String[] outputPlans = new String[NUMBER_OF_PLANS_GENERATED]; outputPlans[0] = "Plan generation was not possible"; if (previousPlans == null) { OptimizerInitialDeployment initialOptimizer = new OptimizerInitialDeployment(searchName); try { outputPlans = initialOptimizer.optimize(appModel, suitableCloudOffer, NUMBER_OF_PLANS_GENERATED); previousPlans = outputPlans; } catch (Error E) { log.error("Error optimizing the initial deployment"); } } else { Reoptimizer optimizerReplanning = new Reoptimizer(searchName); try{ log.error("Calling a Replanning. The previously generated Plan will be used as a base"); outputPlans = optimizerReplanning.optimize(appModel, suitableCloudOffer, NUMBER_OF_PLANS_GENERATED); previousPlans = outputPlans; } catch (Error E) { log.error("Error optimizing the Replanning"); throw E; } } return outputPlans; }
Source:
public void batchesConcurrentRequests() throws InterruptedException { freezableDelegate.freeze(); AsyncTasks tasks = getConcurrently(5); freezableDelegate.unfreeze(); tasks.await(); verify(delegate, times(2)).get(); }

Target:
public void batchesConcurrentRequests() throws InterruptedException { freezableDelegate.freeze(); AsyncTasks initialTask = getConcurrently(1); AsyncTasks batch = getConcurrently(5); freezableDelegate.unfreeze(); batch.await(); verify(delegate, times(2)).get(); }
Source:
public void lock() { try { this.mutex.acquire(); } catch (Exception e) { throw new MessagingException("Failed to aquire mutex at " + this.path, e); } }

Target:
public void lock() { try { this.mutex.acquire(); } catch (Exception e) { throw new RuntimeException("Failed to aquire mutex at " + this.path, e); } }
Source:
private void pullModels() { oldModel = vectorFactory.createDenseZeros(numFeatures); for (int modelIndex = 0; modelIndex < numFeatures; modelIndex++) { oldModel.set(modelIndex, parameterWorker.pull(modelIndex)); } newModel = oldModel.copy(); }

Target:
private void pullModels() { for (int modelIndex = 0; modelIndex < numFeatures; modelIndex++) { oldModel.set(modelIndex, parameterWorker.pull(modelIndex)); } newModel = oldModel.copy(); }