auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void moduleCreated(IAnalysisModule module) { IPath pathToFiles = XmlUtils.getXmlFilesPath(); File fFolder = pathToFiles.toFile(); if (!(fFolder.isDirectory() && fFolder.exists())) { return; } Map<String, File> files = XmlUtils.listFiles(); for (File xmlFile : files.values()) { if (!XmlUtils.xmlValidate(xmlFile).isOK()) { continue; } try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(xmlFile); doc.getDocumentElement().normalize(); if (module instanceof TmfStateSystemAnalysisModule) { for (ViewType viewType : ViewType.values()) { NodeList ssViewNodes = doc.getElementsByTagName(viewType.getXmlElem()); for (int i = 0; i < ssViewNodes.getLength(); i++) { Element node = (Element) ssViewNodes.item(i); List<Element> headNodes = XmlUtils.getChildElements(node, TmfXmlStrings.HEAD); if (headNodes.size() != 1) { continue; } List<Element> analysisNodes = XmlUtils.getChildElements(headNodes.get(0), TmfXmlStrings.ANALYSIS); for (Element analysis : analysisNodes) { String analysisId = analysis.getAttribute(TmfXmlStrings.ID); if (analysisId.equals(module.getId())) { String viewId = viewType.getViewId(); IAnalysisOutput output = new TmfXmlViewOutput(viewId, viewType); output.setOutputProperty(TmfXmlUiStrings.XML_OUTPUT_DATA, node.getAttribute(TmfXmlStrings.ID) + DATA_SEPARATOR + xmlFile.getAbsolutePath(), false); module.registerOutput(output); } } } } } } catch (ParserConfigurationException | SAXException | IOException e) { Activator.logError("Error opening XML file", e); } } }

Target:
public void moduleCreated(IAnalysisModule module) { Map<String, File> files = XmlUtils.listFiles(); for (File xmlFile : files.values()) { if (!XmlUtils.xmlValidate(xmlFile).isOK()) { continue; } try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(xmlFile); doc.getDocumentElement().normalize(); if (module instanceof TmfStateSystemAnalysisModule) { for (ViewType viewType : ViewType.values()) { NodeList ssViewNodes = doc.getElementsByTagName(viewType.getXmlElem()); for (int i = 0; i < ssViewNodes.getLength(); i++) { Element node = (Element) ssViewNodes.item(i); List<Element> headNodes = XmlUtils.getChildElements(node, TmfXmlStrings.HEAD); if (headNodes.size() != 1) { continue; } List<Element> analysisNodes = XmlUtils.getChildElements(headNodes.get(0), TmfXmlStrings.ANALYSIS); for (Element analysis : analysisNodes) { String analysisId = analysis.getAttribute(TmfXmlStrings.ID); if (analysisId.equals(module.getId())) { String viewId = viewType.getViewId(); IAnalysisOutput output = new TmfXmlViewOutput(viewId, viewType); output.setOutputProperty(TmfXmlUiStrings.XML_OUTPUT_DATA, node.getAttribute(TmfXmlStrings.ID) + DATA_SEPARATOR + xmlFile.getAbsolutePath(), false); module.registerOutput(output); } } } } } } catch (ParserConfigurationException | SAXException | IOException e) { Activator.logError("Error opening XML file", e); } } }
Source:
public void getSelectTest() throws Exception { iface.go("<LINK_0>"); WebDriverElement formElement = iface.getWebDriverElement(Strategy.ID, "search"); WebDriverElement actualSelectElement = (WebDriverElement)formElement.getSelect(new Hook(Strategy.TAG, "select")); Assert.assertNotNull(actualSelectElement); }

Target:
public void getSelectTest() throws Exception { iface.go("<LINK_0>"); WebDriverElement formElement = iface.getWebDriverElement(Strategy.ID, "search"); WebDriverSelector actualSelectElement = (WebDriverSelector) formElement.getSelect(new Hook(Strategy.TAG, "select"), 0); Assert.assertEquals("for sale", actualSelectElement.getFirstSelectedOption()); }
Source:
public ModelResolverManager(Preferences preferenceStore) { super(); this.preferenceStore = preferenceStore; }

Target:
public ModelResolverManager(Preferences preferenceStore) { this.preferenceStore = preferenceStore; }
Source:
public Set<String> getSubscribedCategories(Installation installation) { String url = IIDURL + "info/" + installation.getDeviceToken() + "?details=true"; String deviceInfo; try { deviceInfo = get(url); } catch (IOException e) { logger.debug("Couldn't get list of subscribed topics from Instance ID service."); return new HashSet<String>(0); } JSONParser parser = new JSONParser(); JSONObject info; try { info = (JSONObject) parser.parse(deviceInfo); } catch (ParseException e) { logger.debug("Couldn't parse list of subscribed topics from Instance ID service."); return new HashSet<String>(0); } JSONObject rel = (JSONObject) info.get("rel"); if (rel == null){ logger.debug("Couldn't parse rel object Instance ID service."); return new HashSet<String>(0); } JSONObject topics = (JSONObject) rel.get("topics"); return topics.keySet(); }

Target:
public Set<String> getSubscribedCategories(Installation installation) { String url = IIDURL + "info/" + installation.getDeviceToken() + "?details=true"; String deviceInfo; try { deviceInfo = get(url); } catch (IOException e) { logger.debug("Couldn't get list of subscribed topics from Instance ID service."); return Collections.emptySet(); } JSONParser parser = new JSONParser(); JSONObject info; try { info = (JSONObject) parser.parse(deviceInfo); } catch (ParseException e) { logger.debug("Couldn't parse list of subscribed topics from Instance ID service."); return Collections.emptySet(); } JSONObject rel = (JSONObject) info.get("rel"); if (rel == null){ logger.debug("Couldn't parse rel object Instance ID service."); return Collections.emptySet(); } JSONObject topics = (JSONObject) rel.get("topics"); return topics.keySet(); }
Source:
private void selectItem(int position) { String long_name = MITModuleActivity.navigationTitles.get(position).getLong_name(); currentModule = long_name; mNavItem = MITModuleActivity.navMap.get(long_name); String intentString = mNavItem.getIntent(); String title = navigationTitles.get(position).getLong_name(); mDrawerLayout.closeDrawer(mDrawerList); swapInFragment(intentString, title); }

Target:
private void selectItem(int position) { String longName = MITModuleActivity.navigationTitles.get(position).getLongName(); currentModule = longName; mNavItem = MITModuleActivity.navMap.get(longName); String intentString = mNavItem.getIntent(); String title = navigationTitles.get(position).getLongName(); mDrawerLayout.closeDrawer(mDrawerList); swapInFragment(intentString, title); }
Source:
public void testStopConsumingChunksWhenFailed() { final ByteBuf buffer = Unpooled.copiedBuffer("Test", CharsetUtil.ISO_8859_1); final AtomicInteger chunks = new AtomicInteger(0); ChunkedInput<ByteBuf> nonClosableInput = new ChunkedInput<ByteBuf>() { @Override public boolean isEndOfInput() throws Exception { return chunks.get() >= 5; } @Override public void close() throws Exception { } @Deprecated @Override public ByteBuf readChunk(ChannelHandlerContext ctx) throws Exception { return readChunk(ctx.alloc()); } @Override public ByteBuf readChunk(ByteBufAllocator allocator) throws Exception { chunks.incrementAndGet(); return buffer.retainedDuplicate(); } @Override public long length() { return -1; } @Override public long progress() { return 1; } }; ChannelOutboundHandlerAdapter noOpWrites = new ChannelOutboundHandlerAdapter() { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { promise.tryFailure(new RuntimeException()); } }; EmbeddedChannel ch = new EmbeddedChannel(noOpWrites, new ChunkedWriteHandler()); ch.writeAndFlush(nonClosableInput).awaitUninterruptibly(); ch.close(); buffer.release(); assertEquals(1, chunks.get()); }

Target:
public void testStopConsumingChunksWhenFailed() { final ByteBuf buffer = Unpooled.copiedBuffer("Test", CharsetUtil.ISO_8859_1); final AtomicInteger chunks = new AtomicInteger(0); ChunkedInput<ByteBuf> nonClosableInput = new ChunkedInput<ByteBuf>() { @Override public boolean isEndOfInput() throws Exception { return chunks.get() >= 5; } @Override public void close() throws Exception { } @Deprecated @Override public ByteBuf readChunk(ChannelHandlerContext ctx) throws Exception { return readChunk(ctx.alloc()); } @Override public ByteBuf readChunk(ByteBufAllocator allocator) throws Exception { chunks.incrementAndGet(); return buffer.retainedDuplicate(); } @Override public long length() { return -1; } @Override public long progress() { return 1; } }; ChannelOutboundHandlerAdapter noOpWrites = new ChannelOutboundHandlerAdapter() { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { ReferenceCountUtil.release(msg); promise.tryFailure(new RuntimeException()); } }; EmbeddedChannel ch = new EmbeddedChannel(noOpWrites, new ChunkedWriteHandler()); ch.writeAndFlush(nonClosableInput).awaitUninterruptibly(); assertFalse(ch.finish()); buffer.release(); assertEquals(1, chunks.get()); }
Source:
public DiskImage getImageAsDiskImage(String id) { DiskImage diskImage = new DiskImage(); Image glanceImage; try { glanceImage = getClient().images().show(id).execute(); } catch (OpenStackResponseException e) { log.error("Exception:", e); throw new OpenStackImageException( OpenStackImageException.ErrorType.UNABLE_TO_ACCESS_IMAGE_REPOSITORY, "Cannot access the image repository. Please make sure it's accessible."); } catch (RuntimeException rte) { log.error("Exception:", rte); throw new RuntimeException("Failed importing image from repository."); } validateContainerFormat(glanceImage); String shortHash = glanceImage.getId().substring(0, 7); if (glanceImage.getName() != null) { diskImage.setDiskDescription(glanceImage.getName() + " (" + shortHash + ")"); } else { diskImage.setDiskDescription("Glance disk: " + shortHash); } setDiskAttributes(diskImage, glanceImage); if (glanceImage.getDiskFormat().equals(GlanceImageFormat.RAW.getValue())) { diskImage.setVolumeFormat(VolumeFormat.RAW); } else if (glanceImage.getDiskFormat().equals(GlanceImageFormat.COW.getValue())) { diskImage.setVolumeFormat(VolumeFormat.COW); } else { throw new OpenStackImageException( OpenStackImageException.ErrorType.UNSUPPORTED_DISK_FORMAT, "Unknown disk format: " + glanceImage.getDiskFormat()); } return diskImage; }

Target:
public DiskImage getImageAsDiskImage(String id) { DiskImage diskImage = new DiskImage(); Image glanceImage; try { glanceImage = getClient().images().show(id).execute(); } catch (OpenStackResponseException e) { log.debug("Exception:", e); throw new OpenStackImageException( OpenStackImageException.ErrorType.IMAGE_NOT_FOUND, "Cannot find the specified image."); } catch (RuntimeException rte) { log.error("Exception:", rte); throw new RuntimeException("Failed to import from the repository."); } validateContainerFormat(glanceImage); String shortHash = glanceImage.getId().substring(0, 7); if (glanceImage.getName() != null) { diskImage.setDiskDescription(glanceImage.getName() + " (" + shortHash + ")"); } else { diskImage.setDiskDescription("Glance disk: " + shortHash); } setDiskAttributes(diskImage, glanceImage); if (glanceImage.getDiskFormat().equals(GlanceImageFormat.RAW.getValue())) { diskImage.setVolumeFormat(VolumeFormat.RAW); } else if (glanceImage.getDiskFormat().equals(GlanceImageFormat.COW.getValue())) { diskImage.setVolumeFormat(VolumeFormat.COW); } else { throw new OpenStackImageException( OpenStackImageException.ErrorType.UNSUPPORTED_DISK_FORMAT, "Unknown disk format: " + glanceImage.getDiskFormat()); } return diskImage; }
Source:
private String[] splitToFileNameAndOvf(String str) { int delimiter = str.indexOf('='); return new String[] { str.substring(0, delimiter), str.substring(delimiter+1) }; }

Target:
private String[] splitToFileNameAndOvf(String str) { return str.split("=", 2); }
Source:
public void refreshVdsStats() { if (Config.<Boolean> getValue(ConfigValues.DebugTimerLogging)) { log.debug("vdsManager::refreshVdsStats entered, vds='{}'({})", _vds.getName(), _vds.getId()); } fetchHostInterfaces(); VDSReturnValue statsReturnValue = getResourceManager().runVdsCommand(VDSCommandType.GetStats, new VdsIdAndVdsVDSCommandParametersBase(_vds)); getResourceManager().getEventListener().updateSchedulingStats(_vds); if (!statsReturnValue.getSucceeded() && statsReturnValue.getExceptionObject() != null) { VDSNetworkException ex = (VDSNetworkException) ((statsReturnValue.getExceptionObject() instanceof VDSNetworkException) ? statsReturnValue.getExceptionObject() : null); if (ex != null) { if (_vdsManager.handleNetworkException(ex, _vds)) { _saveVdsDynamic = true; } log.error("vds::refreshVdsStats Failed getVdsStats, vds='{}'({}): {}", _vds.getName(), _vds.getId(), ex.getMessage()); } else { log.error("vds::refreshVdsStats Failed getVdsStats, vds='{}'({}): {}", _vds.getName(), _vds.getId(), statsReturnValue.getExceptionString()); } throw statsReturnValue.getExceptionObject(); } _saveVdsDynamic = true; _saveVdsStatistics = true; alertIfLowDiskSpaceOnHost(); checkVdsInterfaces(); if (Config.<Boolean> getValue(ConfigValues.DebugTimerLogging)) { log.debug("vds::refreshVdsStats\n{0}", this); } }

Target:
public void refreshVdsStats() { if (Config.<Boolean> getValue(ConfigValues.DebugTimerLogging)) { log.debug("vdsManager::refreshVdsStats entered, vds='{}'({})", _vds.getName(), _vds.getId()); } fetchHostInterfaces(); VDSReturnValue statsReturnValue = getResourceManager().runVdsCommand(VDSCommandType.GetStats, new VdsIdAndVdsVDSCommandParametersBase(_vds)); getVdsEventListener().updateSchedulingStats(_vds); if (!statsReturnValue.getSucceeded() && statsReturnValue.getExceptionObject() != null) { VDSNetworkException ex = (VDSNetworkException) ((statsReturnValue.getExceptionObject() instanceof VDSNetworkException) ? statsReturnValue.getExceptionObject() : null); if (ex != null) { if (_vdsManager.handleNetworkException(ex, _vds)) { _saveVdsDynamic = true; } log.error("vds::refreshVdsStats Failed getVdsStats, vds='{}'({}): {}", _vds.getName(), _vds.getId(), ex.getMessage()); } else { log.error("vds::refreshVdsStats Failed getVdsStats, vds='{}'({}): {}", _vds.getName(), _vds.getId(), statsReturnValue.getExceptionString()); } throw statsReturnValue.getExceptionObject(); } _saveVdsDynamic = true; _saveVdsStatistics = true; alertIfLowDiskSpaceOnHost(); checkVdsInterfaces(); if (Config.<Boolean> getValue(ConfigValues.DebugTimerLogging)) { log.debug("vds::refreshVdsStats\n{0}", this); } }
Source:
public void writeEntityToNBT(NBTTagCompound n) { n.setInteger("frogType", (byte)getType().ordinal()); super.writeEntityToNBT(n); }

Target:
public void writeEntityToNBT(NBTTagCompound n) { n.setInteger("frogType", getType().ordinal()); super.writeEntityToNBT(n); }
Source:
public @Nullable URL getResource(final String inputPath, final String inputPath2) { final String path = resourceLocationTracker.getMapPrefix() + inputPath; final String path2 = resourceLocationTracker.getMapPrefix() + inputPath2; return getMatchingResources(path).stream() .findFirst() .orElse( getMatchingResources(path2).stream() .findFirst() .orElse( getMatchingResources(inputPath).stream() .findFirst() .orElse( getMatchingResources(inputPath2).stream().findFirst().orElse(null)))); }

Target:
public @Nullable URL getResource(final String inputPath, final String inputPath2) { final String path = resourceLocationTracker.getMapPrefix() + inputPath; final String path2 = resourceLocationTracker.getMapPrefix() + inputPath2; return findResource(path) .or(() -> findResource(path2)) .or(() -> findResource(inputPath)) .or(() -> findResource(inputPath2)) .orElse(null); }
Source:
protected void updateData(double[] x, @NonNull AnalysisBaseQueryFilter filters, IProgressMonitor monitor) { if (fXYDataProvider == null) { return; } ICommonXAxisResponse response = null; ICommonXAxisModel model = null; boolean isComplete = false; long currentEnd = 0; while (!isComplete && currentEnd < filters.getQueryInterval().getEndTime().toNanos()) { response = fXYDataProvider.fetch(x, filters, monitor); model = response.getModel(); if (model != null) { updateDisplay(model); } isComplete = response.getStatus() == ICommonXAxisResponse.Status.COMPLETED; if(isComplete) { return; } try { finishedLatch.await(BUILD_UPDATE_TIMEOUT, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); return; } } }

Target:
protected void updateData(double[] x, @NonNull AnalysisBaseQueryFilter filters, IProgressMonitor monitor) { if (fXYDataProvider == null) { return; } ICommonXAxisResponse response = null; ICommonXAxisModel model = null; ICommonXAxisResponse.Status status; long currentEnd = 0; while (currentEnd < filters.getQueryInterval().getEndTime().toNanos()) { response = fXYDataProvider.fetch(x, filters, monitor); model = response.getModel(); if (model != null) { updateDisplay(model); } status = response.getStatus(); if (status == ICommonXAxisResponse.Status.COMPLETED) { return; } else if(status == ICommonXAxisResponse.Status.FAILED || status == ICommonXAxisResponse.Status.CANCELLED) { LOGGER.log(Level.WARNING, response.getStatusMessage()); return; } else { try { finishedLatch.await(BUILD_UPDATE_TIMEOUT, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { LOGGER.log(Level.INFO, e.getMessage()); return; } } } }
Source:
public RsWithHeader(final Response res, final CharSequence header) { super( new RsOf( () -> RsWithHeader.extend(res.head(), header.toString()), res::body ) ); }

Target:
public RsWithHeader(final Response res, final CharSequence header) { super( new ResponseOf( () -> RsWithHeader.extend(res.head(), header.toString()), res::body ) ); }
Source:
public Response act(final Request req) throws IOException { final Request file = new RqMultipart.Smart( new RqMultipart.Base(req) ).single("file"); final String name = name(file); final File temp = File.createTempFile("netbout", "bin"); IOUtils.copy(file.body(), new FileOutputStream(temp)); final Bout bout = new RqBout(this.base, req).bout(); final StringBuilder msg = new StringBuilder(Tv.HUNDRED); if (new Attachments.Search(bout.attachments()).exists(name)) { msg.append(String.format("attachment \"%s\" overwritten", name)); } else { try { bout.attachments().create(name); } catch (final Attachments.InvalidNameException ex) { throw new RsFailure(ex); } msg.append(String.format("attachment \"%s\" uploaded", name)); } final String ctype = TkAttach.ctype(temp); msg.append(" (").append(temp.length()) .append(" bytes, ").append(ctype).append(')'); try { bout.attachments().get(name).write( new FileInputStream(temp), ctype, Long.toString(System.currentTimeMillis()) ); } catch (final Attachment.TooBigException | Attachment.BrokenContentException ex) { throw new RsFailure(ex); } FileUtils.forceDelete(temp); bout.messages().post(msg.toString()); throw new RsForward(new RsFlash(msg.toString())); }

Target:
public Response act(final Request req) throws IOException { final Request file = new RqMultipart.Smart( new RqMultipart.Base(req) ).single("file"); final String name = this.name(file); final File temp = File.createTempFile("netbout", "bin"); IOUtils.copy(file.body(), new FileOutputStream(temp)); final Bout bout = new RqBout(this.base, req).bout(); final StringBuilder msg = new StringBuilder(Tv.HUNDRED); if (new Attachments.Search(bout.attachments()).exists(name)) { msg.append(String.format("attachment \"%s\" overwritten", name)); } else { try { bout.attachments().create(name); } catch (final Attachments.InvalidNameException ex) { throw new RsFailure(ex); } msg.append(String.format("attachment \"%s\" uploaded", name)); } final String ctype = TkAttach.ctype(temp); msg.append(" (").append(temp.length()) .append(" bytes, ").append(ctype).append(')'); try { bout.attachments().get(name).write( new FileInputStream(temp), ctype, Long.toString(System.currentTimeMillis()) ); } catch (final Attachment.TooBigException | Attachment.BrokenContentException ex) { throw new RsFailure(ex); } FileUtils.forceDelete(temp); bout.messages().post(msg.toString()); throw new RsForward(new RsFlash(msg.toString())); }
Source:
public List<LogEntry> getCurrentPage() { long t0 = System.currentTimeMillis(); Bson filter = buildAuditFilter(); List<SortInfo> sortInfos = getSortInfos(); List<Bson> sorts = new ArrayList<>(sortInfos.size()); for (SortInfo sortInfo : sortInfos) { String sortColumn = sortInfo.getSortColumn(); if ("id".equals(sortColumn)) { sortColumn = MongoDBSerializationHelper.MONGODB_ID; } if (sortInfo.getSortAscending()) { sorts.add(Sorts.ascending(sortColumn)); } else { sorts.add(Sorts.descending(sortColumn)); } } MongoCollection<Document> auditCollection = getMongoDBBackend().getAuditCollection(); FindIterable<Document> response = auditCollection.find(filter) .sort(Sorts.orderBy(sorts)) .skip((int) (getCurrentPageIndex() * pageSize)) .limit((int) getMinMaxPageSize()); List<LogEntry> entries = new ArrayList<>(); MongoDatabase database = Framework.getService(MongoDBConnectionService.class).getDatabase(AUDIT_DATABASE_ID); setResultsCount(countDocuments(database, auditCollection, filter)); for (Document document : response) { entries.add(MongoDBAuditEntryReader.read(document)); } preprocessCommentsIfNeeded(entries); CoreSession session = getCoreSession(); if (session != null) { fireSearchEvent(session.getPrincipal(), filter.toString(), entries, System.currentTimeMillis() - t0); } return entries; }

Target:
public List<LogEntry> getCurrentPage() { long t0 = System.currentTimeMillis(); Bson filter = buildAuditFilter(); List<SortInfo> sortInfos = getSortInfos(); List<Bson> sorts = new ArrayList<>(sortInfos.size()); for (SortInfo sortInfo : sortInfos) { String sortColumn = sortInfo.getSortColumn(); if ("id".equals(sortColumn)) { sortColumn = MongoDBSerializationHelper.MONGODB_ID; } if (sortInfo.getSortAscending()) { sorts.add(Sorts.ascending(sortColumn)); } else { sorts.add(Sorts.descending(sortColumn)); } } MongoCollection<Document> auditCollection = getMongoDBBackend().getAuditCollection(); FindIterable<Document> response = auditCollection.find(filter) .sort(Sorts.orderBy(sorts)) .skip((int) (getCurrentPageIndex() * pageSize)) .limit((int) getMinMaxPageSize()); List<LogEntry> entries = new ArrayList<>(); setResultsCount(countDocuments(AUDIT_DATABASE_ID, auditCollection, filter)); for (Document document : response) { entries.add(MongoDBAuditEntryReader.read(document)); } preprocessCommentsIfNeeded(entries); CoreSession session = getCoreSession(); if (session != null) { fireSearchEvent(session.getPrincipal(), filter.toString(), entries, System.currentTimeMillis() - t0); } return entries; }
Source:
public void testGetHTMLNullInput() { DoorsTableRowCollector dtc = new DoorsTableRowCollector(extractor); dtc.getHTML(null, DoorsColumnType.OBJECT_TEXT); Assert.fail(); }

Target:
public void testGetHTMLNullInput() { DoorsTableRowCollector dtc = new DoorsTableRowCollector(extractor); dtc.getHTML(null, DoorsColumnType.OBJECT_TEXT); }
Source:
Entries(Object[] pairs) { Objects.requireNonNull(pairs, "pairs is null"); if ((pairs.length & 1) != 0) { throw new IllegalArgumentException("Odd length of key-value pairs"); } this.pairs = pairs; }

Target:
Entries(Object[] pairs) { Objects.requireNonNull(pairs, "pairs is null"); if (!hasEvenSize(pairs)) { throw new IllegalArgumentException("Odd length of key-value pairs"); } this.pairs = pairs; }
Source:
private static Date getUsableDate(Order order) { return order.getDateStopped() != null ? order.getDateStopped() : order.getAutoExpireDate(); }

Target:
private static Date getUsableDate(Order order) { return order.getDateStopped() != null ? order.getDateStopped() : (order.getAutoExpireDate() != null ? order.getAutoExpireDate() : order.getDateCreated()); }
Source:
private BuildCommand isRepoUrlChanged(String workDir) { return test("-neq", material.getUrlArgument().rawUrl(), exec("git", "config", "remote.origin.url").setWorkingDirectory(workDir)); }

Target:
private BuildCommand isRepoUrlChanged(String workDir) { return test("-neq", material.getUrlArgument().forCommandLine(), exec("git", "config", "remote.origin.url").setWorkingDirectory(workDir)); }
Source:
public void processRequest(RequestEvent requestReceivedEvent) { Request request = requestReceivedEvent.getRequest(); ServerTransaction serverTransactionId = requestReceivedEvent .getServerTransaction(); LOG.info("\n\nRequest " + request.getMethod() + " received at " + ProtocolObjects.sipStack.getStackName() + " with server transaction id " + serverTransactionId); SipProvider provider = (SipProvider) requestReceivedEvent.getSource(); if (request.getMethod().equals(Request.BYE)) processBye(provider, request, serverTransactionId); }

Target:
public void processRequest(RequestEvent requestReceivedEvent) { Request request = requestReceivedEvent.getRequest(); ServerTransaction serverTransactionId = requestReceivedEvent .getServerTransaction(); logger.info("\n\nRequest " + request.getMethod() + " received at " + ProtocolObjects.sipStack.getStackName() + " with server transaction id " + serverTransactionId); SipProvider provider = (SipProvider) requestReceivedEvent.getSource(); if (request.getMethod().equals(Request.BYE)) processBye(provider, request, serverTransactionId); }
Source:
public void testEntitiesOnSameNodeBecomeSameServerEntities() { String templateUrl = "classpath://templates EntitySpec<? extends Application> spec = transformer.createApplicationSpec( new ResourceUtils(mgmt).getResourceAsString(templateUrl)); assertNotNull(spec); Application app = this.mgmt.getEntityManager().createEntity(spec); assertEquals(app.getChildren().size(), 1); Entity appChild = Iterables.getOnlyElement(app.getChildren()); assertTrue(appChild instanceof SameServerEntity, "Expected " + SameServerEntity.class.getName() + ", got " + appChild); assertEquals(appChild.getChildren().size(), 2); assertEquals(Iterables.size(Entities.descendants(appChild, MySqlNode.class)), 1, "expected " + MySqlNode.class.getName() + " in " + appChild.getChildren()); assertEquals(Iterables.size(Entities.descendants(appChild, TomcatServer.class)), 1, "expected " + TomcatServer.class.getName() + " in " + appChild.getChildren()); }

Target:
public void testEntitiesOnSameNodeBecomeSameServerEntities() { String templateUrl = "classpath://templates/tomcat-mysql-on-one-compute.yaml"; EntitySpec<? extends Application> spec = transformer.createApplicationSpec( new ResourceUtils(mgmt).getResourceAsString(templateUrl)); assertNotNull(spec); Application app = this.mgmt.getEntityManager().createEntity(spec); assertEquals(app.getChildren().size(), 1); Entity appChild = Iterables.getOnlyElement(app.getChildren()); assertTrue(appChild instanceof SameServerEntity, "Expected " + SameServerEntity.class.getName() + ", got " + appChild); assertEquals(appChild.getChildren().size(), 2); assertEquals(Iterables.size(Entities.descendants(appChild, MySqlNode.class)), 1, "expected " + MySqlNode.class.getName() + " in " + appChild.getChildren()); assertEquals(Iterables.size(Entities.descendants(appChild, TomcatServer.class)), 1, "expected " + TomcatServer.class.getName() + " in " + appChild.getChildren()); }
Source:
void afterChannelIsSet() { this.messages = new ArrayBlockingQueue<>(1000); this.getChannel().subscribe(new MessageHandler() { @Override public void handleMessage(Message<?> message) throws MessagingException { messages.offer(message); } }); }

Target:
void afterChannelIsSet() { this.messages = new LinkedTransferQueue<>(); this.getChannel().subscribe(message -> messages.offer(message)); }
Source:
private DbUser getUserByUserId(Guid userId) throws SQLException { Connection connection = null; Statement ps = null; ResultSet rs = null; DbUser dbUser = null; try { connection = ds.getConnection(); ps = connection.createStatement(); rs = ps.executeQuery(String.format("SELECT email FROM users WHERE user_id = '%s'", userId.toString())); if (rs.next()) { dbUser = new DbUser(); dbUser.setuser_id(userId); dbUser.setemail(rs.getString("email")); } } finally { DbUtils.closeQuietly(rs,connection); } return dbUser; }

Target:
private DbUser getUserByUserId(Guid userId) throws SQLException { Connection connection = null; Statement ps = null; ResultSet rs = null; DbUser dbUser = null; try { connection = ds.getConnection(); ps = connection.createStatement(); rs = ps.executeQuery(String.format("SELECT email FROM users WHERE user_id = '%s'", userId.toString())); if (rs.next()) { dbUser = new DbUser(); dbUser.setuser_id(userId); dbUser.setemail(rs.getString("email")); } } finally { DbUtils.closeQuietly(rs,ps,connection); } return dbUser; }
Source:
private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints, boolean failOnRequired, boolean headless) { boolean success = true; if (isEventQuestionOrListGroup()) { HashMap<FormIndex, IAnswerData> answers = uiController.questionsView.getAnswers(); List<FormIndex> indexKeys = new ArrayList<>(); indexKeys.addAll(answers.keySet()); Collections.sort(indexKeys, FormIndex::compareTo); try { for (FormIndex index : indexKeys) { if (mFormController.getEvent(index) == FormEntryController.EVENT_QUESTION) { int saveStatus = saveAnswer(answers.get(index), index, evaluateConstraints); if (evaluateConstraints && ((saveStatus != FormEntryController.ANSWER_OK) && (failOnRequired || saveStatus != FormEntryController.ANSWER_REQUIRED_BUT_EMPTY))) { if (!headless) { uiController.showConstraintWarning(index, mFormController.getQuestionPrompt(index).getConstraintText(), saveStatus, success); } success = false; } } else { Log.w(TAG, "Attempted to save an index referencing something other than a question: " + index.getReference()); } } } catch (XPathException e) { UserfacingErrorHandling.createErrorDialog(this, e.getLocalizedMessage(), true); } catch (Exception e) { Log.d(TAG, e.getLocalizedMessage()); e.printStackTrace(); } } return success; }

Target:
private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints, boolean failOnRequired, boolean headless) { boolean success = true; if (isEventQuestionOrListGroup()) { HashMap<FormIndex, IAnswerData> answers = uiController.questionsView.getAnswers(); List<FormIndex> indexKeys = new ArrayList<>(); indexKeys.addAll(answers.keySet()); Collections.sort(indexKeys, FormIndex::compareTo); try { for (FormIndex index : indexKeys) { if (mFormController.getEvent(index) == FormEntryController.EVENT_QUESTION) { int saveStatus = saveAnswer(answers.get(index), index, evaluateConstraints); if (evaluateConstraints && ((saveStatus != FormEntryController.ANSWER_OK) && (failOnRequired || saveStatus != FormEntryController.ANSWER_REQUIRED_BUT_EMPTY))) { if (!headless) { uiController.showConstraintWarning(index, mFormController.getQuestionPrompt(index).getConstraintText(), saveStatus, success); } success = false; } } else { Log.w(TAG, "Attempted to save an index referencing something other than a question: " + index.getReference()); } } } catch (XPathException e) { UserfacingErrorHandling.createErrorDialog(this, e.getLocalizedMessage(), true); } } return success; }
Source:
public void testAssetReportGetSuccess() throws Exception { List<String> accessTokens = Arrays.asList(getItemCreateResponse().getAccessToken()); Response<AssetReportCreateResponse> createResponse = AssetReportCreateTest.createAssetReport(client(), accessTokens); String assetReportToken = createResponse.body().getAssetReportToken(); Response<AssetReportGetResponse> response = waitTillReady(client(), assetReportToken); AssetReportGetResponse respBody = response.body(); assertSuccessResponse(response); assertNotNull(respBody.getReport()); assertNotNull(respBody.getReport().getUser()); assertFalse(respBody.getReport().getItems().isEmpty()); assertNotNull(respBody.getReport().getAssetReportId()); assertEquals(new Integer(365), respBody.getReport().getDaysRequested()); assertEquals("Alberta", respBody.getReport().getUser().getFirstName()); assertEquals("Charleson", respBody.getReport().getUser().getLastName()); assertEquals(1, respBody.getReport().getItems().size()); AssetReportGetResponse.Item assetItem = respBody.getReport().getItems().get(0); assertEquals(4, assetItem.getAccounts().size()); assertEquals("ins_109511", assetItem.getInstitutionId()); assertEquals("Tartan Bank", assetItem.getInstitutionName()); }

Target:
public void testAssetReportGetSuccess() throws Exception { List<String> accessTokens = Arrays.asList(getItemCreateResponse().getAccessToken()); Response<AssetReportCreateResponse> createResponse = AssetReportCreateTest.createAssetReport(client(), accessTokens); String assetReportToken = createResponse.body().getAssetReportToken(); Response<AssetReportGetResponse> response = waitTillReady(client(), assetReportToken); AssetReportGetResponse respBody = response.body(); assertSuccessResponse(response); assertNotNull(respBody.getReport()); assertNotNull(respBody.getReport().getUser()); assertFalse(respBody.getReport().getItems().isEmpty()); assertNotNull(respBody.getReport().getAssetReportId()); }
Source:
public byte[] getBody() { byte[] body = null; switch(amqpAnnotatedMessage.getBody().getBodyType()) { case DATA: List<BinaryData> binaryData = ((AmqpDataBody)amqpAnnotatedMessage.getBody()).getData().stream() .collect(Collectors.toList()); if (binaryData != null && binaryData.size() > 0) { byte[] firstData = binaryData.get(0).getData(); body = Arrays.copyOf(firstData, firstData.length); } break; case SEQUENCE: case VALUE: throw logger.logThrowableAsError(new UnsupportedOperationException("Not supported AmqpBodyType: " + amqpAnnotatedMessage.getBody().getBodyType())); default: throw logger.logThrowableAsError(new IllegalArgumentException("Unknown AmqpBodyType: " + amqpAnnotatedMessage.getBody().getBodyType())); } return body; }

Target:
public byte[] getBody() { final AmqpBodyType type = amqpAnnotatedMessage.getBody().getBodyType(); switch (type) { case DATA: return Arrays.copyOf(binaryData, binaryData.length); case SEQUENCE: case VALUE: throw logger.logExceptionAsError(new UnsupportedOperationException("Not supported AmqpBodyType: " + type.toString())); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: " + type.toString())); } }
Source:
private static Object castIntegerToObect(int value, Type type) { if (type == INTEGER || type == TINYINT || type == BIGINT) { return (long) value; } if (type == VARCHAR) { return value + ""; } if (type == DOUBLE) { return (double) value; } throw new UnsupportedOperationException(); }

Target:
private static Object castIntegerToObect(int value, Type type) { if (type == INTEGER || type == TINYINT || type == BIGINT) { return (long) value; } if (type == VARCHAR) { return String.valueOf(value); } if (type == DOUBLE) { return (double) value; } throw new UnsupportedOperationException(); }
Source:
private IndexEntry(final long compressedOffset, final long uncompressedOffset) { if (Long.signum(compressedOffset) == -1) { throw new IllegalArgumentException("negative compressed offset: " + compressedOffset); } if (Long.signum(uncompressedOffset) == -1) { throw new IllegalArgumentException("negative uncompressed offset: " + uncompressedOffset); } this.compressedOffset = compressedOffset; this.uncompressedOffset = uncompressedOffset; }

Target:
private IndexEntry(final long compressedOffset, final long uncompressedOffset) { if (compressedOffset < 0) { throw new IllegalArgumentException("negative compressed offset: " + compressedOffset); } if (uncompressedOffset < 0) { throw new IllegalArgumentException("negative uncompressed offset: " + uncompressedOffset); } this.compressedOffset = compressedOffset; this.uncompressedOffset = uncompressedOffset; }
Source:
public void testPut(BaseThreadState state) { long key = state.randomInt(keyCount); try { map.put(key, 0L); } catch (QuorumException qe) { qe.printStackTrace(); } }

Target:
public void testPut(BaseThreadState state) { final long key = state.randomInt(keyCount); LastClusterSizeChange lastChange = lastClusterSizeChange; if (lastChange.timestamp + gracePeriodMillis > System.currentTimeMillis()) { doProtectedOperation(key, 0L); return; } try { map.put(key, 0L); checkGracePeriod(lastChange, true); } catch (QuorumException qe) { checkGracePeriod(lastChange, false); } }
Source:
public EEFTextLifecycleManager(EEFTextDescription description, IVariableManager variableManager, IInterpreter interpreter, TransactionalEditingDomain editingDomain) { super(description, variableManager, interpreter, editingDomain); this.description = description; }

Target:
public EEFTextLifecycleManager(EEFTextDescription description, IVariableManager variableManager, IInterpreter interpreter, TransactionalEditingDomain editingDomain) { super(variableManager, interpreter, editingDomain); this.description = description; }
Source:
public ViewPreferencesPanel(boolean immediateUpdates) { initComponents(); this.immediateUpdates = immediateUpdates; TextTranslationService tts = TextTranslationService.getInstance(); if(!tts.hasProvider()) { translatedNamesButton.setVisible(false); fileDisplayLabel.setVisible(false); } }

Target:
public ViewPreferencesPanel(boolean immediateUpdates) { initComponents(); this.immediateUpdates = immediateUpdates; this.timeZoneList.setListData(TimeZoneUtils.createTimeZoneList().stream().toArray(String[]::new)); }
Source:
protected void writeBlobProperty(JsonGenerator jg, Property prop, PropertyConsumer fieldNameWriter) throws PropertyException, JsonGenerationException, IOException { Blob blob = (Blob) prop.getValue(); if (blob == null) { if (writeNull) { fieldNameWriter.accept(jg, prop); jg.writeNull(); } } else { fieldNameWriter.accept(jg, prop); jg.writeStartObject(); String v = blob.getFilename(); if (v == null) { if (writeNull) { jg.writeNullField("name"); } } else { if (writeNull) { jg.writeStringField("name", v); } } v = blob.getMimeType(); if (v == null) { if (writeNull) { jg.writeNullField("mime-type"); } } else { jg.writeStringField("mime-type", v); } v = blob.getEncoding(); if (v == null) { if (writeNull) { jg.writeNullField("encoding"); } } else { jg.writeStringField("encoding", v); } v = blob.getDigest(); if (v == null) { if (writeNull) { jg.writeNullField("digest"); } } else { jg.writeStringField("digest", v); } jg.writeNumberField("length", blob.getLength()); if (filesBaseUrl != null) { jg.writeStringField("data", getBlobUrl(prop, filesBaseUrl)); } jg.writeEndObject(); } }

Target:
protected void writeBlobProperty(JsonGenerator jg, Property prop, PropertyConsumer fieldNameWriter) throws PropertyException, JsonGenerationException, IOException { Blob blob = (Blob) prop.getValue(); if (blob == null) { if (writeNull) { fieldNameWriter.accept(jg, prop); jg.writeNull(); } } else { fieldNameWriter.accept(jg, prop); jg.writeStartObject(); String v = blob.getFilename(); if (v == null) { if (writeNull) { jg.writeNullField("name"); } } else { jg.writeStringField("name", v); } v = blob.getMimeType(); if (v == null) { if (writeNull) { jg.writeNullField("mime-type"); } } else { jg.writeStringField("mime-type", v); } v = blob.getEncoding(); if (v == null) { if (writeNull) { jg.writeNullField("encoding"); } } else { jg.writeStringField("encoding", v); } v = blob.getDigest(); if (v == null) { if (writeNull) { jg.writeNullField("digest"); } } else { jg.writeStringField("digest", v); } jg.writeNumberField("length", blob.getLength()); if (filesBaseUrl != null) { jg.writeStringField("data", getBlobUrl(prop, filesBaseUrl)); } jg.writeEndObject(); } }
Source:
public Set<String> getAllNodesUrls() { HashSet<String> nodesUrls = new HashSet<>(size() + (extraNodes != null ? extraNodes.size() : 0)); for (Node node : this) { nodesUrls.add(node.getNodeInformation().getURL()); } if (extraNodes != null) { for (Node node : extraNodes) { nodesUrls.add(node.getNodeInformation().getURL()); } } return nodesUrls; }

Target:
public Set<String> getAllNodesUrls() { HashSet<String> nodesUrls = new HashSet<>(size() + (extraNodes != null ? extraNodes.size() : 0)); addNodesToUrlsSet(nodesUrls, this); if (extraNodes != null) { addNodesToUrlsSet(nodesUrls, extraNodes); } return nodesUrls; }
Source:
private Ports() { super(); }

Target:
private Ports() { }
Source:
private static QualityProfile buildProfile(String key, String name, @Nullable String parentKey, Statistics statistics) { return QualityProfile.newBuilder() .setKey(key) .setName(name) .setParent(parentKey == null ? "" : parentKey) .setActiveRuleCount(statistics.getActiveRuleCount(key)) .setOverridingRuleCount(statistics.getOverridingRuleCount(key)) .build(); }

Target:
private static QualityProfile buildProfile(String key, String name, @Nullable String parentKey, Statistics statistics) { QualityProfile.Builder builder = QualityProfile.newBuilder() .setKey(key) .setName(name) .setActiveRuleCount(statistics.countRulesByProfileKey.getOrDefault(key, 0L)) .setOverridingRuleCount(statistics.countOverridingRulesByProfileKey.getOrDefault(key, 0L)); Protobuf.setNullable(parentKey, builder::setParent); return builder.build(); }
Source:
public String getSeqResSequence(){ StringBuilder str = new StringBuilder(); for (Group g : seqResGroups) { ChemComp cc = g.getChemComp(); if ( cc == null) { logger.warn("Could not load ChemComp for group: ", g); str.append(StructureTools.UNKNOWN_GROUP_LABEL); } else if ( PolymerType.PROTEIN_ONLY.contains(cc.getPolymerType()) || PolymerType.POLYNUCLEOTIDE_ONLY.contains(cc.getPolymerType())){ String oneLetter= ChemCompGroupFactory.getOneLetterCode(cc); if ( oneLetter == null || oneLetter.isEmpty() || oneLetter.equals("?") || oneLetter.length()!=1) { oneLetter = Character.toString(StructureTools.UNKNOWN_GROUP_LABEL); } str.append(oneLetter); } else { str.append(StructureTools.UNKNOWN_GROUP_LABEL); } } return str.toString(); }

Target:
public String getSeqResSequence(){ StringBuilder str = new StringBuilder(); for (Group g : seqResGroups) { ChemComp cc = g.getChemComp(); if ( cc == null) { logger.warn("Could not load ChemComp for group: ", g); str.append(StructureTools.UNKNOWN_GROUP_LABEL); } else if ( PolymerType.PROTEIN_ONLY.contains(cc.getPolymerType()) || PolymerType.POLYNUCLEOTIDE_ONLY.contains(cc.getPolymerType())){ String oneLetter= ChemCompGroupFactory.getOneLetterCode(cc); if ( oneLetter == null || oneLetter.isEmpty() || oneLetter.equals("?")) { oneLetter = Character.toString(StructureTools.UNKNOWN_GROUP_LABEL); } str.append(oneLetter); } else { str.append(StructureTools.UNKNOWN_GROUP_LABEL); } } return str.toString(); }
Source:
private void handleSuccess(IndexedRecord input, String id, String status) { successCount++; Schema outSchema = sprops.schemaFlow.schema.getValue(); if (outSchema == null || outSchema.getFields().size() == 0) { return; } if (input.getSchema().equals(outSchema)) { successfulWrites.add(input); } else { IndexedRecord successful = new GenericData.Record(outSchema); for (Schema.Field outField : successful.getSchema().getFields()) { Object outValue = null; Schema.Field inField = input.getSchema().getField(outField.name()); if (inField != null) { outValue = input.get(inField.pos()); } else if (TSalesforceOutputProperties.FIELD_SALESFORCE_ID.equals(outField.name())) { outValue = id; } else if (TSalesforceOutputProperties.FIELD_STATUS.equals(outField.name())) { outValue = status; } successful.put(outField.pos(), outValue); } successfulWrites.add(successful); } LOGGER.info("Has record successfully.", getPastForm(sprops.outputAction.getValue()), dataCount); }

Target:
private void handleSuccess(IndexedRecord input, String id, String status) { successCount++; Schema outSchema = sprops.schemaFlow.schema.getValue(); if (outSchema == null || outSchema.getFields().size() == 0) { return; } if (input.getSchema().equals(outSchema)) { successfulWrites.add(input); } else { IndexedRecord successful = new GenericData.Record(outSchema); for (Schema.Field outField : successful.getSchema().getFields()) { Object outValue = null; Schema.Field inField = input.getSchema().getField(outField.name()); if (inField != null) { outValue = input.get(inField.pos()); } else if (TSalesforceOutputProperties.FIELD_SALESFORCE_ID.equals(outField.name())) { outValue = id; } else if (TSalesforceOutputProperties.FIELD_STATUS.equals(outField.name())) { outValue = status; } successful.put(outField.pos(), outValue); } successfulWrites.add(successful); } LOGGER.info(MESSAGES.getMessage("info.successfulRecord", getPastForm(sprops.outputAction.getValue()), dataCount)); }
Source:
public void setGuideItem(GuideInfo guide) { ImageSizes imageSizes = MainApplication.get().getImageSizes(); mTitleView.setText(mShortTitle && guide.hasSubject() ? guide.mSubject : Html.fromHtml(guide.mTitle)); Transformation transform = new RoundedTransformation(4, 0); if (guide.hasImage()) { Utils.safeStripImageView(mThumbnail); mPicasso.cancelRequest(mThumbnail); String url = guide.getImagePath(imageSizes.getGrid()); Log.d("GuideItemView", "Loading image " + url); mPicasso .load(url) .transform(transform) .error(R.drawable.no_image) .into(mThumbnail); } else { mPicasso .load(R.drawable.no_image) .fit() .transform(transform) .into(mThumbnail); } }

Target:
public void setGuideItem(GuideInfo guide) { ImageSizes imageSizes = MainApplication.get().getImageSizes(); mTitleView.setText(mShortTitle && guide.hasSubject() ? guide.mSubject : Html.fromHtml(guide.mTitle)); Transformation transform = new RoundedTransformation(4, 0); if (guide.hasImage()) { Utils.safeStripImageView(mThumbnail); mPicasso.cancelRequest(mThumbnail); String url = guide.getImagePath(imageSizes.getGrid()); mPicasso .load(url) .transform(transform) .error(R.drawable.no_image) .into(mThumbnail); } else { mPicasso .load(R.drawable.no_image) .fit() .transform(transform) .into(mThumbnail); } }
Source:
public LeaderInitiatorFactoryBean setRole(String role) { this.candidate = newCandidate(role); return this; }

Target:
public LeaderInitiatorFactoryBean setRole(String role) { this.candidate = this.candidateProvider.generate(role); Assert.state(this.candidate != null, String.format("The %s requires a candidate; newCandidate(role) returned none.", getClass().getName())); return this; }
Source:
public void init(InstructorAttributes currentInstructor, CourseDetailsBundle courseDetails, List<InstructorAttributes> instructors, List<StudentAttributes> students) { this.currentInstructor = currentInstructor; this.courseDetails = courseDetails; this.instructors = instructors; boolean isDisabled = !currentInstructor.isAllowedForPrivilege( Const.ParamsNames.INSTRUCTOR_PERMISSION_GIVE_COMMENT_IN_SECTIONS); String content = "<span class=\"glyphicon glyphicon-comment glyphicon-primary\"></span>"; giveCommentButton = createButton(content, "btn btn-default btn-xs icon-button pull-right", "button_add_comment", null, "", "tooltip", null, isDisabled); isDisabled = !currentInstructor.isAllowedForPrivilege(Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_STUDENT); String onClick = "if(toggleSendRegistrationKeysConfirmation('" + Sanitizer.sanitizeForJs(courseDetails.course.id) + "')) " + "window.location.href='" + Sanitizer.sanitizeForJs(getInstructorCourseRemindLink()) + "';"; courseRemindButton = createButton(null, "btn btn-primary", "button_remind", null, Const.Tooltips.COURSE_REMIND, "tooltip", onClick, isDisabled); studentsTable = new CourseDetailsStudentsTable(); int studentIndex = 0; for (StudentAttributes student : students) { CourseDetailsStudentsTableRow row = createStudentsTableRow(studentIndex, student); studentsTable.getRows().add(row); studentIndex++; } }

Target:
public void init(InstructorAttributes currentInstructor, CourseDetailsBundle courseDetails, List<InstructorAttributes> instructors, List<StudentAttributes> students) { this.currentInstructor = currentInstructor; this.courseDetails = courseDetails; this.instructors = instructors; boolean isDisabled = !currentInstructor.isAllowedForPrivilege( Const.ParamsNames.INSTRUCTOR_PERMISSION_GIVE_COMMENT_IN_SECTIONS); String content = "<span class=\"glyphicon glyphicon-comment glyphicon-primary\"></span>"; giveCommentButton = createButton(content, "btn btn-default btn-xs icon-button pull-right", "button_add_comment", null, "", "tooltip", null, isDisabled); isDisabled = !currentInstructor.isAllowedForPrivilege(Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_STUDENT); String onClick = "if(toggleSendRegistrationKeysConfirmation('" + sanitizeForJs(courseDetails.course.id) + "')) " + "window.location.href='" + sanitizeForJs(getInstructorCourseRemindLink()) + "';"; courseRemindButton = createButton(null, "btn btn-primary", "button_remind", null, Const.Tooltips.COURSE_REMIND, "tooltip", onClick, isDisabled); studentsTable = new CourseDetailsStudentsTable(); int studentIndex = 0; List<CourseDetailsStudentsTableRow> studentTableRows = new ArrayList<CourseDetailsStudentsTableRow>(); for (StudentAttributes student : students) { CourseDetailsStudentsTableRow row = createStudentsTableRow(studentIndex, student); studentTableRows.add(row); studentIndex++; } studentsTable.setRows(studentTableRows); }