auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public String whichCommand(String command, IProject project) throws IOException { if (project != null) { String[] envp = updateEnvironment(null, project); try { IRemoteFileProxy proxy = RemoteProxyManager.getInstance().getFileProxy(project); URI whichUri = URI.create(WHICH_CMD); IPath whichPath = new Path(proxy.toPath(whichUri)); IRemoteCommandLauncher launcher = RemoteProxyManager.getInstance().getLauncher(project); Process pProxy = launcher.execute(whichPath, new String[]{command}, envp, null, new NullProgressMonitor()); if (pProxy != null){ BufferedReader error = new BufferedReader(new InputStreamReader(pProxy.getErrorStream())); BufferedReader reader = new BufferedReader(new InputStreamReader(pProxy.getInputStream())); String errorLine; if((errorLine = error.readLine()) != null){ throw new IOException(errorLine); } error.close(); String readLine = reader.readLine(); ArrayList<String> lines = new ArrayList<String>(); while (readLine != null) { lines.add(readLine); readLine = reader.readLine(); } reader.close(); if (project.getLocationURI() != null && !lines.isEmpty()) { if(project.getLocationURI().toString().startsWith("rse:") && lines.size() > 1) { command = lines.get(lines.size()-2); } else { command = lines.get(0); } } else { <START> command = lines.get(0); <END> } } } catch (CoreException e) { } } return command; }</code><technical_language>This line throws IndexOutOfBoundsException</technical_language>

Target:
public String whichCommand(String command, IProject project) throws IOException { if (project != null) { String[] envp = updateEnvironment(null, project); try { IRemoteFileProxy proxy = RemoteProxyManager.getInstance().getFileProxy(project); URI whichUri = URI.create(WHICH_CMD); IPath whichPath = new Path(proxy.toPath(whichUri)); IRemoteCommandLauncher launcher = RemoteProxyManager.getInstance().getLauncher(project); Process pProxy = launcher.execute(whichPath, new String[]{command}, envp, null, new NullProgressMonitor()); if (pProxy != null){ BufferedReader error = new BufferedReader(new InputStreamReader(pProxy.getErrorStream())); BufferedReader reader = new BufferedReader(new InputStreamReader(pProxy.getInputStream())); String errorLine; if((errorLine = error.readLine()) != null){ throw new IOException(errorLine); } error.close(); String readLine = reader.readLine(); ArrayList<String> lines = new ArrayList<String>(); while (readLine != null) { lines.add(readLine); readLine = reader.readLine(); } reader.close(); if (!lines.isEmpty()) { if (project.getLocationURI() != null) { if (project.getLocationURI().toString().startsWith("rse:")) { if (lines.size() > 1) { command = lines.get(lines.size() - 2); } } else { command = lines.get(0); } } else { command = lines.get(0); } } } } catch (CoreException e) { } } return command; }
Source:
<code>public List<String> resolveArtifacts(List<Dependency> dependencies) throws MojoExecutionException { List<String> files = new ArrayList<String>(); if (dependencies == null || dependencies.isEmpty()) { return files; } MavenSession session = legacySupport.getSession(); MavenProject project = session.getCurrentProject(); for (Dependency dependency : dependencies) { Artifact artifact = repositorySystem.createDependencyArtifact(dependency); ArtifactResolutionRequest request = new ArtifactResolutionRequest(); request.setArtifact(artifact); request.setResolveRoot(true).setResolveTransitively(false); request.setLocalRepository(session.getLocalRepository()); <START> request.setRemoteRepositories(project.getRemoteArtifactRepositories()); <END> request.setOffline(session.isOffline()); request.setForceUpdate(session.getRequest().isUpdateSnapshots()); ArtifactResolutionResult result = repositorySystem.resolve(request); try { resolutionErrorHandler.throwErrors(request, result); } catch (ArtifactResolutionException e) { throw new MojoExecutionException("Failed to resolve doclet artifact " + dependency.getManagementKey(), e); } files.add(artifact.getFile().getAbsolutePath()); } return files; }</code><technical_language>generally, is considered a practice separate project dependencies development tools. organizations license policies for dependencies tools, for example, tools dependencies in repositories. MavenProject#getPluginArtifactRepositories() returns right repository type ArtifactResolutionRequest</technical_language>

Target:
public List<String> resolveArtifacts(List<Dependency> dependencies) throws MojoExecutionException { List<String> files = new ArrayList<String>(); if (dependencies == null || dependencies.isEmpty()) { return files; } MavenSession session = legacySupport.getSession(); MavenProject project = session.getCurrentProject(); for (Dependency dependency : dependencies) { Artifact artifact = repositorySystem.createDependencyArtifact(dependency); ArtifactResolutionRequest request = new ArtifactResolutionRequest(); request.setArtifact(artifact); request.setResolveRoot(true).setResolveTransitively(false); request.setLocalRepository(session.getLocalRepository()); request.setRemoteRepositories(project.getPluginArtifactRepositories()); request.setOffline(session.isOffline()); request.setForceUpdate(session.getRequest().isUpdateSnapshots()); ArtifactResolutionResult result = repositorySystem.resolve(request); try { resolutionErrorHandler.throwErrors(request, result); } catch (ArtifactResolutionException e) { throw new MojoExecutionException("Failed to resolve doclet artifact " + dependency.getManagementKey(), e); } files.add(artifact.getFile().getAbsolutePath()); } return files; }
Source:
<code>public CookieFilter(String username, String password){ Map<String,String> cookieRequestMap = new HashMap<String, String>(); cookieRequestMap.put("name",username); cookieRequestMap.put("password",password); JSONHelper helper = new JSONHelper(); <START> cookieRequestBody = helper.toJson(cookieRequestMap); <END> }</code><technical_language>This is session request body, cookie body</technical_language>

Target:
public CookieFilter(String username, String password){ this.sessionRequestBody = String.format("name=%s&password=%s",username,password); this.username = username; }
Source:
<code>public void putOutOfRotation() { logger.warn("Putting host out of rotation"); outOfRotation.set(true); for (ServiceRegistry serviceRegistry : serviceRegistries) { <START> serviceRegistry.unregister(); <END> } }</code><technical_language>wrap this try / catch in case registry throws exception? try { serviceRegistry.unregister(); } catch (RuntimeException e) { logger.warn(...); }</technical_language>

Target:
public void putOutOfRotation() { logger.warn("Putting host out of rotation"); outOfRotation.set(true); for (ServiceRegistry serviceRegistry : serviceRegistries) { logger.info("Unregistering ServiceRegistry {}", serviceRegistry); try { serviceRegistry.unregister(); } catch (RuntimeException e) { logger.warn("Failed to unregister ServiceRegistry {}. Exception: {}", serviceRegistry, e); } } }
Source:
<code>public List<Map<String, Object>> getRefundsByChargeId(long chargeId) { List<Map<String, Object>> ret = jdbi.withHandle(h -> <START> h.createQuery("SELECT external_id, reference, amount, status, created_date, charge_id, refunded_by " + <END> "FROM refunds r " + "WHERE charge_id = :charge_id") .bind("charge_id", chargeId) .list()); return ret; }</code><technical_language>forget update this</technical_language>

Target:
public List<Map<String, Object>> getRefundsByChargeId(long chargeId) { List<Map<String, Object>> ret = jdbi.withHandle(h -> h.createQuery("SELECT external_id, reference, amount, status, created_date, charge_id, user_external_id " + "FROM refunds r " + "WHERE charge_id = :charge_id") .bind("charge_id", chargeId) .list()); return ret; }
Source:
<code>public String getRestURI(String baseServiceURI) { StringBuilder requestURI = new StringBuilder(); requestURI.append(baseServiceURI); if (StringUtils.isNotBlank(this.getEntityName())) { appendToURI(requestURI, this.getEntityName()); } if (StringUtils.isNotBlank(this.getEntityVersion())) { appendToURI(requestURI, this.schema +"="+ this.getEntityVersion()); <START> } <END> return requestURI.toString(); }</code><technical_language>This do. Schema is in request body, part of uri. Parse string json, set request body. Also, overload schema constructor get a JsonNode schema, body is json in AbstractListhblueMEtadataRequest</technical_language>

Target:
public String getRestURI(String baseServiceURI) { StringBuilder requestURI = new StringBuilder(); requestURI.append(baseServiceURI); if (StringUtils.isNotBlank(this.getEntityName())) { appendToURI(requestURI, this.getEntityName()); } if (StringUtils.isNotBlank(this.getEntityVersion())) { appendToURI(requestURI, "schema="+ this.getEntityVersion()); } return requestURI.toString(); }
Source:
<code>protected void doInvokeListener(ChannelAwareMessageListener listener, Channel channel, Object data) { Message message = null; RabbitResourceHolder resourceHolder = null; Channel channelToUse = channel; boolean boundHere = false; try { if (!isExposeListenerChannel()) { resourceHolder = getTransactionalResourceHolder(); channelToUse = resourceHolder.getChannel(); if (isChannelLocallyTransacted() && !TransactionSynchronizationManager.isActualTransactionActive()) { resourceHolder.setSynchronizedWithTransaction(true); TransactionSynchronizationManager.bindResource(this.getConnectionFactory(), resourceHolder); boundHere = true; } } else { if (isChannelLocallyTransacted()) { RabbitResourceHolder localResourceHolder = new RabbitResourceHolder(channelToUse, false); localResourceHolder.setSynchronizedWithTransaction(true); TransactionSynchronizationManager.bindResource(this.getConnectionFactory(), localResourceHolder); boundHere = true; } } try { if (data instanceof List) { <START> ((ChannelAwareBatchMessagelistener) listener).onMessageBatch((List<Message>) data, channelToUse); <END> } else { message = (Message) data; listener.onMessage(message, channelToUse); } } catch (Exception e) { throw wrapToListenerExecutionFailedExceptionIfNeeded(e, message); } } finally { cleanUpAfterInvoke(resourceHolder, channelToUse, boundHere); } }</code><technical_language>need cast here: ChannelAwareMessageListener onMessageBatch() method</technical_language>

Target:
protected void doInvokeListener(ChannelAwareMessageListener listener, Channel channel, Object data) { Message message = null; RabbitResourceHolder resourceHolder = null; Channel channelToUse = channel; boolean boundHere = false; try { if (!isExposeListenerChannel()) { resourceHolder = getTransactionalResourceHolder(); channelToUse = resourceHolder.getChannel(); if (isChannelLocallyTransacted() && !TransactionSynchronizationManager.isActualTransactionActive()) { resourceHolder.setSynchronizedWithTransaction(true); TransactionSynchronizationManager.bindResource(this.getConnectionFactory(), resourceHolder); boundHere = true; } } else { if (isChannelLocallyTransacted()) { RabbitResourceHolder localResourceHolder = new RabbitResourceHolder(channelToUse, false); localResourceHolder.setSynchronizedWithTransaction(true); TransactionSynchronizationManager.bindResource(this.getConnectionFactory(), localResourceHolder); boundHere = true; } } try { if (data instanceof List) { listener.onMessageBatch((List<Message>) data, channelToUse); } else { message = (Message) data; listener.onMessage(message, channelToUse); } } catch (Exception e) { throw wrapToListenerExecutionFailedExceptionIfNeeded(e, message); } } finally { cleanUpAfterInvoke(resourceHolder, channelToUse, boundHere); } }
Source:
<code>public Person getTech() { <START> if (null != engineer) { return engineer; } return tech; <END> }</code><technical_language>this a ternary</technical_language>

Target:
public @Nullable Person getTech() { return (getEngineer() != null) ? getEngineer() : tech; }
Source:
<code>protected Void doInBackground(Object... voids) { AdvertisingIdClient.Info adInfo = null; try { adInfo = AdvertisingIdClient.getAdvertisingIdInfo(context); } catch (IOException e) { } catch (GooglePlayServicesNotAvailableException e) { } catch (GooglePlayServicesRepairableException e) { e.printStackTrace(); } <START> if (adInfo != null) { <END> id = adInfo.getId(); Log.d(TAG, "Advertising ID: " + id); SeptaServiceFactory.getNotificationsService().setDeviceId(context, id); } return null; }</code><technical_language>Instead of a null check, move rest of method try block</technical_language>

Target:
protected Void doInBackground(Object... voids) { AdvertisingIdClient.Info adInfo; try { adInfo = AdvertisingIdClient.getAdvertisingIdInfo(context); id = adInfo.getId(); Log.d(TAG, "Advertising ID: " + id); SeptaServiceFactory.getNotificationsService().setDeviceId(context, id); } catch (IOException e) { CrashlyticsManager.logException(TAG, e); } catch (GooglePlayServicesNotAvailableException e) { CrashlyticsManager.logException(TAG, e); } catch (GooglePlayServicesRepairableException e) { CrashlyticsManager.logException(TAG, e); CrashlyticsManager.log(Log.ERROR, TAG, e.getMessage()); } catch (Exception e) { CrashlyticsManager.logException(TAG, e); CrashlyticsManager.log(Log.ERROR, TAG, e.getMessage()); } return null; }
Source:
<code>public void testTextBuildWhenCalendarServiceNotAvailable() { String content = builder.buildContentString(notIcs); <START> System.out.println(content); <END> assertTrue(content.matches(serviceNotAvailablePattern)); assertTrue(content.matches(withoutDefaultUrlPattern)); }</code><technical_language>Avoid "System.out.println" replace a logger if needed</technical_language>

Target:
public void testTextBuildWhenCalendarServiceNotAvailable() { String content = builder.buildContentString(notIcs); assertTrue(content.matches(serviceNotAvailablePattern)); assertTrue(content.matches(withoutDefaultUrlPattern)); }
Source:
<code>public void clear() { <START> Arrays.fill(keys, null); <END> count = 0; }</code><technical_language>values fill null? (to GC)</technical_language>

Target:
public void clear() { Arrays.fill(keys, null); Arrays.fill(values, null); count = 0; }
Source:
<code>public Date getEndDate() { <START> return endDate; <END> }</code><technical_language>Dates mutable, return a copy of endDate</technical_language>

Target:
public Date getEndDate() { return endDate == null ? null : new Date(endDate.getTime()); }
Source:
<code>public Query createQuery() { final SearchFactoryImplementor searchFactory = queryContext.getFactory(); final DocumentBuilderIndexedEntity<?> documentBuilder = Helper.getDocumentBuilder( queryContext ); if ( fieldsContext.size() == 0 ) { <START> Integer docId = getLuceneDocumentIdFromEntityId( documentBuilder ); <END> IndexReader indexReader = null; try { indexReader = searchFactory.getIndexReaderAccessor().open( queryContext.getEntityType() ); String[] fieldNames = getAllCompatibleFieldNames( documentBuilder ); return new MoreLikeThisBuilder( documentBuilder, searchFactory ) .fieldNames( fieldNames ) .indexReader( indexReader ) .documentNumber( docId ) .createQuery(); } finally { if ( indexReader != null ) { searchFactory.getIndexReaderAccessor().close( indexReader ); } } } return null; }</code><technical_language>This query fetching _docId_ run in try/catch block _IndexReader_ instance</technical_language>

Target:
public Query createQuery() { Query query; final SearchFactoryImplementor searchFactory = queryContext.getFactory(); final DocumentBuilderIndexedEntity<?> documentBuilder = Helper.getDocumentBuilder( queryContext ); IndexReader indexReader = searchFactory.getIndexReaderAccessor().open( queryContext.getEntityType() ); try { String[] fieldNames = getAllCompatibleFieldNames( documentBuilder ); if ( fieldsContext.size() == 0 ) { fieldsContext.addAll( fieldNames ); } query = new MoreLikeThisBuilder( documentBuilder, searchFactory ) .compatibleFieldNames( fieldNames ) .fieldsContext( fieldsContext ) .queryContext( queryContext ) .indexReader( indexReader ) .inputType( inputType ) .input( input ) .otherMoreLikeThisContext( moreLikeThisContext ) .createQuery(); } finally { searchFactory.getIndexReaderAccessor().close( indexReader ); } return queryCustomizer.setWrappedQuery( query ).createQuery(); }
Source:
<code>public void userCannotSignUpWithExistingUsernameDesktop() { <START> RegisterPage form = performUnsuccessfulSignUpOnDesktopAs(createUserWithExistingUsername()); <END> assertEquals(form.getError(), USERNAME_TAKEN_MSG); }</code><technical_language>verifyCannotSignUpOnDesktopAs</technical_language>

Target:
public void userCannotSignUpWithExistingUsernameDesktop() { RegisterPage form = performSignUpExpectingFailureOnDesktopAs(createUserWithExistingUsername()); assertEquals(form.getError(), USERNAME_TAKEN_MSG); }
Source:
<code>public static BlockChangeFlag fromNativeInt(int flag) { <START> for (SpongeBlockChangeFlag spongeBlockChangeFlag : getInstance().getValues()) { <END> if (spongeBlockChangeFlag.getRawFlag() == flag) { return spongeBlockChangeFlag; } } return BlockChangeFlags.ALL; }</code><technical_language>Int2ObjectHashMap instead</technical_language>

Target:
public static SpongeBlockChangeFlag fromNativeInt(int flag) { final SpongeBlockChangeFlag spongeBlockChangeFlag = getInstance().maskedFlags.get(flag); if (spongeBlockChangeFlag != null) { return spongeBlockChangeFlag; } return (SpongeBlockChangeFlag) BlockChangeFlags.ALL; }
Source:
<code>private SecureStore getSecureStore(String className, Injector injector) { try { @SuppressWarnings("unchecked") Class<? extends SecureStore> clazz = (Class<? extends SecureStore>) Class.forName(className); return injector.getInstance(clazz); } catch (ClassNotFoundException e) { throw new RuntimeException( <START> String.format("Cannot load SecureStore implementation: %s"), e); <END> } }</code><technical_language>Bug: Format string "%s" needs argument 1 0 provided</technical_language>

Target:
private SecureStore getSecureStore(String className, Injector injector) { try { @SuppressWarnings("unchecked") Class<? extends SecureStore> clazz = (Class<? extends SecureStore>) Class.forName(className); return injector.getInstance(clazz); } catch (ClassNotFoundException e) { throw new RuntimeException( String.format("Cannot load SecureStore implementation: %s", className), e); } }
Source:
<code>protected String getMessage(final String key) { String msg = messageProperties.getProperty(key); if (msg == null && key.contains(".")) { String newKey = key; <START> while (msg == null && newKey.contains(".")) { <END> newKey = newKey.substring(0, newKey.lastIndexOf(".")); msg = messageProperties.getProperty(newKey); } } return msg; }</code><technical_language>Implementing this a loop suggests intend support multiple dots, is discussed. thinking here</technical_language>

Target:
protected String getMessage(final String key) { return messageProperties.getProperty(key); }
Source:
<code>static OperationDefinition getOperationDefinition() { return new SimpleOperationDefinitionBuilder(OPERATION_NAME, HostResolver.getResolver("host.server")) <START> .setReplyType(ModelType.STRING) <END> .setRuntimeOnly() .withFlag(OperationEntry.Flag.HOST_CONTROLLER_ONLY) .build(); }</code><technical_language>This a reply value</technical_language>

Target:
static OperationDefinition getOperationDefinition() { return new SimpleOperationDefinitionBuilder(OPERATION_NAME, HostResolver.getResolver("host.server")) .setRuntimeOnly() .withFlag(OperationEntry.Flag.HOST_CONTROLLER_ONLY) .build(); }
Source:
<code>public void addDpdkPort(String bridgeName, String port, String vlan, DpdkHelper.VHostUserMode vHostUserMode, String dpdkOvsPath) { String type = vHostUserMode == DpdkHelper.VHostUserMode.SERVER ? dpdkPortVhostUserType : dpdkPortVhostUserClientType; StringBuilder stringBuilder = new StringBuilder(); if (Integer.parseInt(vlan) > 0 && Integer.parseInt(vlan) < 4095) { stringBuilder.append(String.format("ovs-vsctl add-port %s %s " + <START> "vlan_mode=access tag=%s " + <END> "-- set Interface %s type=%s", bridgeName, port, vlan, port, type)); } else { stringBuilder.append(String.format("ovs-vsctl add-port %s %s " + "-- set Interface %s type=%s", bridgeName, port, port, type)); } if (vHostUserMode == DpdkHelper.VHostUserMode.CLIENT) { stringBuilder.append(String.format(" options:vhost-server-path=%s/%s", dpdkOvsPath, port)); } String cmd = stringBuilder.toString(); s_logger.debug("DPDK property enabled, executing: " + cmd); Script.runSimpleBashScript(cmd); }</code><technical_language>put this vland_mode tag in if-block rest it. other parts of string do depend condition is in else-block</technical_language>

Target:
public void addDpdkPort(String bridgeName, String port, String vlan, DpdkHelper.VHostUserMode vHostUserMode, String dpdkOvsPath) { String type = vHostUserMode == DpdkHelper.VHostUserMode.SERVER ? dpdkPortVhostUserType : dpdkPortVhostUserClientType; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(String.format("ovs-vsctl add-port %s %s ", bridgeName, port)); if (Integer.parseInt(vlan) > 0 && Integer.parseInt(vlan) < 4095) { stringBuilder.append(String.format("vlan_mode=access tag=%s ", vlan)); } stringBuilder.append(String.format("-- set Interface %s type=%s", port, type)); if (vHostUserMode == DpdkHelper.VHostUserMode.CLIENT) { stringBuilder.append(String.format(" options:vhost-server-path=%s/%s", dpdkOvsPath, port)); } String cmd = stringBuilder.toString(); s_logger.debug("DPDK property enabled, executing: " + cmd); Script.runSimpleBashScript(cmd); }
Source:
<code><START> public Matrix muli(final Matrix matrix) { <END> if (matrix.isDense()) { throw new UnsupportedOperationException(); } else { ((NumericOps) breezeMatrix).$colon$times$eq(((CSCMatrix) matrix).breezeMatrix, MatrixOps.EMULI_SS); return this; } }</code><technical_language>UnsupportedOperationException thrown this method</technical_language>

Target:
public Matrix muli(final Matrix matrix) { if (matrix.isDense()) { ((NumericOps) breezeMatrix).$colon$times$eq(((DenseMatrix) matrix).getBreezeMatrix(), MatrixOps.EMULI_MM); } else { ((NumericOps) breezeMatrix).$colon$times$eq(((CSCMatrix) matrix).breezeMatrix, MatrixOps.EMULI_SS); } return this; }
Source:
<code>public void testBasicLogFormatting() { BasicLogger logger = new BasicLogger(); Database.log.setCustom(logger); Log.d(LogDomain.DATABASE, "TEST DEBUG"); assertEquals("TEST DEBUG", logger.getMessage()); Log.d(LogDomain.DATABASE, "TEST DEBUG", new Exception("whoops")); assertEquals("TEST DEBUG (java.lang.Exception: whoops)", logger.getMessage()); Log.d(LogDomain.DATABASE, "TEST DEBUG %s %d %f", "arg", 1, 3.0F); <START> assertEquals("TEST DEBUG arg 1 3.000000", logger.getMessage()); <END> Log.d(LogDomain.DATABASE, "TEST DEBUG %s %d %f", new Exception("whoops"), "arg", 1, 3.0F); assertEquals("TEST DEBUG arg 1 3.000000 (java.lang.Exception: whoops)", logger.getMessage()); }</code><technical_language>is true 6 decimal places in places</technical_language>

Target:
public void testBasicLogFormatting() { BasicLogger logger = new BasicLogger(); Database.log.setCustom(logger); Log.d(LogDomain.DATABASE, "TEST DEBUG"); assertEquals("TEST DEBUG", logger.getMessage()); Log.d(LogDomain.DATABASE, "TEST DEBUG", new Exception("whoops")); assertEquals("TEST DEBUG (java.lang.Exception: whoops)", logger.getMessage()); Log.d(LogDomain.DATABASE, "TEST DEBUG %2$s %1$d %3$.2f", 1, "arg", 3.0F); assertEquals("TEST DEBUG arg 1 3.00", logger.getMessage()); Log.d(LogDomain.DATABASE, "TEST DEBUG %2$s %1$d %3$.2f", new Exception("whoops"), 1, "arg", 3.0F); assertEquals("TEST DEBUG arg 1 3.00 (java.lang.Exception: whoops)", logger.getMessage()); }
Source:
<code>public void testQueueUpdatedUponDownloadComplete() throws Exception { final Context c = InstrumentationRegistry.getInstrumentation().getTargetContext(); { List<FeedItem> queue = writeTestQueue("a"); FeedItem item = DBReader.getFeedItem(queue.get(0).getId()); <START> FeedMedia media = new FeedMedia(item, "<LINK_1>", 12345, "audio/mp3"); <END> item.setMedia(media); DBWriter.setFeedMedia(media).get(); DBWriter.setFeedItem(item).get(); } PlaybackServiceTaskManager pstm = new PlaybackServiceTaskManager(c, defaultPSTM); final FeedItem testItem = pstm.getQueue().get(0); assertThat("The item is not yet downloaded", testItem.getMedia().isDownloaded(), is(false)); { FeedItem item = DBReader.getFeedItem(testItem.getId()); item.getMedia().setDownloaded(true); item.getMedia().setFile_url("file://123"); item.setAutoDownload(false); DBWriter.setFeedMedia(item.getMedia()).get(); DBWriter.setFeedItem(item).get(); } Thread.sleep(10); final FeedItem itemUpdated = pstm.getQueue().get(0); assertThat("The queue in PlaybackService has been updated item after download is completed", itemUpdated.getMedia().isDownloaded(), is(true)); pstm.shutdown(); }</code><technical_language>example.com in other tests. I prefer instead for is a placeholder url meaningful in future</technical_language>

Target:
public void testQueueUpdatedUponDownloadComplete() throws Exception { final Context c = InstrumentationRegistry.getInstrumentation().getTargetContext(); { List<FeedItem> queue = writeTestQueue("a"); FeedItem item = DBReader.getFeedItem(queue.get(0).getId()); FeedMedia media = new FeedMedia(item, "<LINK_0>", 12345, "audio/mp3"); item.setMedia(media); DBWriter.setFeedMedia(media).get(); DBWriter.setFeedItem(item).get(); } PlaybackServiceTaskManager pstm = new PlaybackServiceTaskManager(c, defaultPSTM); final FeedItem testItem = pstm.getQueue().get(0); assertFalse("The item should not yet be downloaded", testItem.getMedia().isDownloaded()); withFeedItemEventListener( feedItemEventListener -> { FeedItem item = DBReader.getFeedItem(testItem.getId()); item.getMedia().setDownloaded(true); item.getMedia().setFile_url("file://123"); item.setAutoDownload(false); DBWriter.setFeedMedia(item.getMedia()).get(); DBWriter.setFeedItem(item).get(); Awaitility.await() .atMost(1000, TimeUnit.MILLISECONDS) .until(() -> feedItemEventListener.getEvents().size() > 0); final FeedItem itemUpdated = pstm.getQueue().get(0); assertTrue("media.isDownloaded() should be true - The queue in PlaybackService should be updated after download is completed", itemUpdated.getMedia().isDownloaded()); }); pstm.shutdown(); }
Source:
<code>public RichText build() { return new <START> RichText(Common.nonNullOrEmpty(mText), <END> mElements); }</code><technical_language>usecase for empty RichText</technical_language>

Target:
public RichText build() { return new RichText(Preconditions.checkNotNull(mText), mElements); }
Source:
<code>public String format(String input) { <START> List<String> sentences = StringUtil.getStringAsSentences(input); <END> StringBuilder result = new StringBuilder(); for (String sentence : sentences) { Title title = new Title(new LowerCaseFormatter().format(sentence)); title.getWords().stream().findFirst().ifPresent(Word::toUpperFirst); result.append(title.toString() + " "); } result.deleteCharAt(result.length() - 1); return result.toString(); }</code><technical_language>Here, power of Java streams used: (then, need hack deleteCharAt. suggestion return StringUtil.getStringAsSentences(input) .stream() .map(sentence -> new LowerCaseFormatter().format(sentence)) .map(lowerCase -> new Title(lowerCase)) .map(title -> { title.getFirstWord().ifPresent(Word::toUpperFirst); return title; }) .map(title -> title.toString()) .collect(Collectors.joining(" "));</technical_language>

Target:
public String format(String input) { return StringUtil.getStringAsSentences(input) .stream() .map(new LowerCaseFormatter()::format) .map(Title::new) .map(title -> { title.getFirstWord().ifPresent(Word::toUpperFirst); return title; }) .map(Object::toString) .collect(Collectors.joining(" ")); }
Source:
<code>public void dispose() { super.dispose(); synchronized (fBuildJobMap) { fBuildJobMap.values().forEach(Job::cancel); } if (fZoomThread != null) { fZoomThread.cancel(); } deactivateContextService(); ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); IWorkbenchPartSite <START> site = <END> getSite(); if (site != null) { IWorkbenchPage page = site.getPage(); if (fPartListener != null) { page.removePartListener(fPartListener); } if (fPartListener2 != null) { page.removePartListener(fPartListener2); } } }</code><technical_language>inline, null</technical_language>

Target:
public void dispose() { super.dispose(); synchronized (fBuildJobMap) { fBuildJobMap.values().forEach(Job::cancel); } if (fZoomThread != null) { fZoomThread.cancel(); } deactivateContextService(); ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); IWorkbenchPage page = getSite().getPage(); if (fPartListener != null) { page.removePartListener(fPartListener); } if (fPartListener2 != null) { page.removePartListener(fPartListener2); } }
Source:
<code>public void setResponse(int status, InputStream entity, MultiValueMap<String, String> headers) throws IOException { RequestContext context = RequestContext.getCurrentContext(); RequestContext.getCurrentContext().setResponseStatusCode(status); if (entity != null) { RequestContext.getCurrentContext().setResponseDataStream(entity); } boolean isOriginResponseGzipped = false; <START> if (headers.containsKey(CONTENT_ENCODING) || headers.containsKey(CONTENT_ENCODING_LOWER)) { <END> Collection<String> collection = null; if (headers.containsKey(CONTENT_ENCODING)) { collection = headers.get(CONTENT_ENCODING); } else { collection = headers.get(CONTENT_ENCODING_LOWER); } for (String header : collection) { if (HTTPRequestUtils.getInstance().isGzipped(header)) { isOriginResponseGzipped = true; break; } } } context.setResponseGZipped(isOriginResponseGzipped); for (Entry<String, List<String>> header : headers.entrySet()) { RequestContext ctx = RequestContext.getCurrentContext(); String name = header.getKey(); for (String value : header.getValue()) { ctx.addOriginResponseHeader(name, value); if (name.equalsIgnoreCase("content-length")) { ctx.setOriginContentLength(value); } if (isIncludedHeader(name)) { ctx.addZuulResponseHeader(name, value); } } } }</code><technical_language>spring's HttpHeaders is for case insensitive headers, avoid this kind of logic. is in buildZuulRequestHeaders above</technical_language>

Target:
public void setResponse(int status, InputStream entity, MultiValueMap<String, String> headers) throws IOException { RequestContext context = RequestContext.getCurrentContext(); RequestContext.getCurrentContext().setResponseStatusCode(status); if (entity != null) { RequestContext.getCurrentContext().setResponseDataStream(entity); } HttpHeaders httpHeaders = new HttpHeaders(); for (Entry<String, List<String>> header : headers.entrySet()) { List<String> values = header.getValue(); for (String value : values) { httpHeaders.add(header.getKey(), value); } } boolean isOriginResponseGzipped = false; if (httpHeaders.containsKey(CONTENT_ENCODING)) { List<String> collection = httpHeaders.get(CONTENT_ENCODING); for (String header : collection) { if (HTTPRequestUtils.getInstance().isGzipped(header)) { isOriginResponseGzipped = true; break; } } } context.setResponseGZipped(isOriginResponseGzipped); for (Entry<String, List<String>> header : headers.entrySet()) { RequestContext ctx = RequestContext.getCurrentContext(); String name = header.getKey(); for (String value : header.getValue()) { ctx.addOriginResponseHeader(name, value); if (name.equalsIgnoreCase(CONTENT_LENGTH)) { ctx.setOriginContentLength(value); } if (isIncludedHeader(name)) { ctx.addZuulResponseHeader(name, value); } } } }
Source:
<code>public void adsTrackingOptOutMercury() { networkTrafficInterceptor.startIntercepting(); Boolean noKikimoraRequestFound = false; Boolean noKruxRequestFound = false; Page page = new Page(TestAdsTrackingOptOutOasis.TEST_WIKI, TestAdsTrackingOptOutOasis.TEST_PAGE); String url = TestAdsTrackingOptOutOasis.appendTrackingOptOutParameters(page.getUrl()); MobileAdsBaseObject mobileAdsBaseObject = new MobileAdsBaseObject(driver, url); try { mobileAdsBaseObject.wait.forSuccessfulResponseByUrlPattern(networkTrafficInterceptor, TestAdsTrackingOptOutOasis.KIKIMORA_PATTERN); <START> } catch (TimeoutException exception) { <END> noKikimoraRequestFound = true; } try { mobileAdsBaseObject.wait.forSuccessfulResponseByUrlPattern(networkTrafficInterceptor, TestAdsTrackingOptOutOasis.KRUX_PATTERN); } catch (TimeoutException exception) { noKruxRequestFound = true; } assertTrue(noKikimoraRequestFound); assertTrue(noKruxRequestFound); }</code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') log rethrow this exception. [![rule](<LINK_1>](http://sonar-s4/coding_rules#rule_key=squid%3AS1166)</technical_language>

Target:
public void adsTrackingOptOutMercury() { networkTrafficInterceptor.startIntercepting(); Boolean noKikimoraRequestFound = false; Boolean noKruxRequestFound = false; Page page = new Page(TestAdsTrackingOptOutOasis.TEST_WIKI, TestAdsTrackingOptOutOasis.TEST_PAGE); String url = TestAdsTrackingOptOutOasis.appendTrackingOptOutParameters(page.getUrl()); MobileAdsBaseObject mobileAdsBaseObject = new MobileAdsBaseObject(driver, url); try { mobileAdsBaseObject.wait.forSuccessfulResponseByUrlPattern(networkTrafficInterceptor, TestAdsTrackingOptOutOasis.KIKIMORA_PATTERN); } catch (TimeoutException exception) { noKikimoraRequestFound = true; } try { mobileAdsBaseObject.wait.forSuccessfulResponseByUrlPattern(networkTrafficInterceptor, TestAdsTrackingOptOutOasis.KRUX_PATTERN); } catch (TimeoutException exception) { noKruxRequestFound = true; } Assertion.assertTrue( noKikimoraRequestFound, "Kikimora tracking is not disabled, request to Data Warehouse was found" ); Assertion.assertTrue( noKruxRequestFound, "Krux tracking is not disabled, request to Krux services was found" ); }
Source:
<code>private Map<String, Map<String, String>> generatePartitionOverrideFromAllDCs() { Map<String, Map<String, String>> partitionOverrideInfos = new HashMap<>(); for (PartitionId partitionId : staticClusterMap.getAllPartitionIds(null)) { String partitionName = partitionId.toPathString(); Map<String, String> partitionProperties = new HashMap<>(); partitionProperties.put(ClusterMapUtils.PARTITION_STATE, ClusterMapUtils.READ_WRITE_STR); <START> for (ReplicaId replicaId : partitionId.getReplicaIds()) { <END> if (replicaId.isSealed()) { partitionProperties.put(ClusterMapUtils.PARTITION_STATE, ClusterMapUtils.READ_ONLY_STR); break; } } partitionOverrideInfos.put(partitionName, partitionProperties); } return partitionOverrideInfos; }</code><technical_language>do this - get PartitionId.getPartitionState() right</technical_language>

Target:
private Map<String, Map<String, String>> generatePartitionOverrideFromAllDCs() { Map<String, Map<String, String>> partitionOverrideInfos = new HashMap<>(); for (PartitionId partitionId : staticClusterMap.getAllPartitionIds(null)) { String partitionName = partitionId.toPathString(); Map<String, String> partitionProperties = new HashMap<>(); partitionProperties.put(ClusterMapUtils.PARTITION_STATE, partitionId.getPartitionState() == PartitionState.READ_WRITE ? ClusterMapUtils.READ_WRITE_STR : ClusterMapUtils.READ_ONLY_STR); partitionOverrideInfos.put(partitionName, partitionProperties); } return partitionOverrideInfos; }
Source:
<code>public void refreshViewer() { <START> Display.getDefault().asyncExec(new Runnable(){ <END> @Override public void run() { IWorkbench wb = PlatformUI.getWorkbench(); IWorkbenchWindow wbWindow = wb.getActiveWorkbenchWindow(); if (wbWindow == null) { return; } IWorkbenchPage activePage = wbWindow.getActivePage(); if (activePage == null) { return; } for (IViewReference viewReference : activePage.getViewReferences()) { IViewPart viewPart = viewReference.getView(false); if (viewPart instanceof CommonNavigator) { CommonViewer commonViewer = ((CommonNavigator) viewPart).getCommonViewer(); Object element = TmfProjectModelElement.this; if (element instanceof TmfProjectElement) { element = getResource(); } commonViewer.refresh(element); } } }}); }</code><technical_language>this a lambda</technical_language>

Target:
public void refreshViewer() { Display.getDefault().asyncExec(() -> { IWorkbench wb = PlatformUI.getWorkbench(); IWorkbenchWindow wbWindow = wb.getActiveWorkbenchWindow(); if (wbWindow == null) { return; } IWorkbenchPage activePage = wbWindow.getActivePage(); if (activePage == null) { return; } for (IViewReference viewReference : activePage.getViewReferences()) { IViewPart viewPart = viewReference.getView(false); if (viewPart instanceof CommonNavigator) { CommonViewer commonViewer = ((CommonNavigator) viewPart).getCommonViewer(); Object element = TmfProjectModelElement.this; if (element instanceof TmfProjectElement) { element = getResource(); } commonViewer.refresh(element); } } }); }
Source:
<code>public <V> DataSet<LocatedRow> readTextFile(SpliceOperation op, String location, String characterDelimiter, String columnDelimiter, int[] baseColumnMap, OperationContext context, Qualifier[][] qualifiers, DataValueDescriptor probeValue, ExecRow execRow) throws StandardException { assert baseColumnMap != null:"baseColumnMap Null"; try { Dataset<Row> table = null; try { table = SpliceSpark.getSession().read().csv(location); <START> if (op == null && baseColumnMap[0] == 1) { <END> for(int index = 0; index< baseColumnMap.length; index++) { StructField ft = table.schema().fields()[index]; Column cl = new Column(ft.name()).cast(execRow.schema().fields()[index].dataType()); table = table.withColumn(ft.name(), cl); } } else { for( int index = 0; index< baseColumnMap.length; index++) { if (baseColumnMap[index] != -1) { StructField ft = table.schema().fields()[index]; Column cl = new Column(ft.name()).cast(execRow.schema().fields()[baseColumnMap[index]].dataType()); table = table.withColumn(ft.name(), cl); } } } } catch (Exception e) { return handleExceptionInCaseOfEmptySet(e,location); } table = processExternalDataset(table,baseColumnMap,qualifiers,probeValue); return new SparkDataSet(table .rdd().toJavaRDD() .map(new RowToLocatedRowFunction(context,execRow))); } catch (Exception e) { throw StandardException.newException( SQLState.EXTERNAL_TABLES_READ_FAILURE,e.getMessage()); } }</code><technical_language>understanding is baseColumnMap parameter tracks columns need collect stats. baseColumnMap[0] 1. Is check "baseColumnMap[0]==1" appropriate? If collect stats is disabled for column, fix triggered</technical_language>

Target:
public <V> DataSet<LocatedRow> readTextFile(SpliceOperation op, String location, String characterDelimiter, String columnDelimiter, int[] baseColumnMap, OperationContext context, Qualifier[][] qualifiers, DataValueDescriptor probeValue, ExecRow execRow) throws StandardException { assert baseColumnMap != null:"baseColumnMap Null"; try { Dataset<Row> table = null; try { table = SpliceSpark.getSession().read().csv(location); if (op == null) { for(int index = 0; index < execRow.schema().fields().length; index++) { StructField ft = table.schema().fields()[index]; Column cl = new Column(ft.name()).cast(execRow.schema().fields()[index].dataType()); table = table.withColumn(ft.name(), cl); } } else { for( int index = 0; index< baseColumnMap.length; index++) { if (baseColumnMap[index] != -1) { StructField ft = table.schema().fields()[index]; Column cl = new Column(ft.name()).cast(execRow.schema().fields()[baseColumnMap[index]].dataType()); table = table.withColumn(ft.name(), cl); } } } } catch (Exception e) { return handleExceptionInCaseOfEmptySet(e,location); } table = processExternalDataset(table,baseColumnMap,qualifiers,probeValue); return new SparkDataSet(table .rdd().toJavaRDD() .map(new RowToLocatedRowFunction(context,execRow))); } catch (Exception e) { throw StandardException.newException( SQLState.EXTERNAL_TABLES_READ_FAILURE,e.getMessage()); } }
Source:
<code>public void testSetInstanceCapacityMap() { <START> Map<String, Integer> capacityDataMap = new HashMap<>(); <END> capacityDataMap.put("item1", 1); capacityDataMap.put("item2", 2); capacityDataMap.put("item3", 3); Map<String, String> capacityDataMapString = new HashMap<>(); capacityDataMapString.put("item1", "1"); capacityDataMapString.put("item2", "2"); capacityDataMapString.put("item3", "3"); InstanceConfig testConfig = new InstanceConfig("testConfig"); testConfig.setInstanceCapacityMap(capacityDataMap); Assert.assertEquals(testConfig.getRecord().getMapField(InstanceConfig.InstanceConfigProperty. INSTANCE_CAPACITY_MAP.name()), capacityDataMapString); }</code><technical_language>I prefer Map<String, Integer> capacityDataMap = ImmutableMap.of("item1", 1, "item2", 2, "item3", 3); shorter</technical_language>

Target:
public void testSetInstanceCapacityMap() { Map<String, Integer> capacityDataMap = ImmutableMap.of("item1", 1, "item2", 2, "item3", 3); Map<String, String> capacityDataMapString = ImmutableMap.of("item1", "1", "item2", "2", "item3", "3"); InstanceConfig testConfig = new InstanceConfig("testConfig"); testConfig.setInstanceCapacityMap(capacityDataMap); Assert.assertEquals(testConfig.getRecord().getMapField(InstanceConfig.InstanceConfigProperty. INSTANCE_CAPACITY_MAP.name()), capacityDataMapString); }
Source:
<code>private Map<Integer, IssueMetadata> processUpdates(Map<Integer, IssueMetadata> metadata) { String currentUser = prefs.getLastLoginUsername(); for (Map.Entry<Integer, IssueMetadata> entry : metadata.entrySet()) { IssueMetadata currentMetadata = entry.getValue(); Date lastNonSelfUpdate = new Date(0); Date lastSelfUpdate = new Date(0); boolean isUpdatedByOthers = false; boolean isUpdatedBySelf = false; for (TurboIssueEvent event : currentMetadata.getEvents()) { if (isNewEventByOther(currentUser, event, lastNonSelfUpdate)) { lastNonSelfUpdate = event.getDate(); isUpdatedByOthers = true; } if (isNewEventBySelf(currentUser, event, lastSelfUpdate)){ lastSelfUpdate = event.getDate(); isUpdatedBySelf = true; } } for (Comment comment : currentMetadata.getComments()) { if (isNewCommentByOther(currentUser, comment, lastNonSelfUpdate)) { lastNonSelfUpdate = comment.getCreatedAt(); isUpdatedByOthers = true; } if (isNewCommentBySelf(currentUser, comment, lastSelfUpdate)){ lastSelfUpdate = comment.getCreatedAt(); isUpdatedBySelf = true; } } entry.setValue(new IssueMetadata(currentMetadata, LocalDateTime.ofInstant(lastNonSelfUpdate.toInstant(), ZoneId.systemDefault()), LocalDateTime.ofInstant(lastSelfUpdate.toInstant(), ZoneId.systemDefault()), calculateCommentCount(currentMetadata.getComments(), currentUser, UpdatedKind.OTHER_UPDATED), <START> calculateCommentCount(currentMetadata.getComments(), currentUser, UpdatedKind.SELF_UPDATED), <END> isUpdatedByOthers, isUpdatedBySelf )); } return metadata; }</code><technical_language>issue before. values of arguments derived others, compute in TurboIssue constructor. want Logic high-level possible</technical_language>

Target:
private Map<Integer, IssueMetadata> processUpdates(Map<Integer, IssueMetadata> metadata) { String currentUser = prefs.getLastLoginUsername(); for (Map.Entry<Integer, IssueMetadata> entry : metadata.entrySet()) { IssueMetadata currentMetadata = entry.getValue(); entry.setValue(new IssueMetadata(currentMetadata, currentUser)); } return metadata; }
Source:
<code>public void earlyStartup() { if (isPlatformKeybindingBug517068Fixed()) { return; } IBindingService service = PlatformUI.getWorkbench().getService(IBindingService.class); if (service != null) { List<Binding> newBindings = new ArrayList<>(); Binding[] bindings = service.getBindings(); for (Binding binding : bindings) { String commandId = null; if (binding != null && binding.getParameterizedCommand() != null && binding.getParameterizedCommand().getCommand() != null) { commandId = binding.getParameterizedCommand().getCommand().getId(); } <START> if (commandId == null || !commandId.equals(OPEN_SYMBOL_IN_WORKSPACE_COMMAND_ID)) { <END> newBindings.add(binding); } } PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { @Override public void run() { try { service.savePreferences(service.getActiveScheme(), newBindings.toArray(new Binding[newBindings.size()])); } catch (IOException e) { e.printStackTrace(); } } }); } }</code><technical_language>Instead of checking for this command here, more generic process command contributed LSP4E, verify if conflicting not, if conflicting remove binding. 100% occurence care about? Also, important for ppl IDE JDT LSP4E bindings remain if is conflict. checking for conflicts necessary. bindingServer.getConflictsFor(binding.getTriggerSequence()) enough check that</technical_language>

Target:
public void earlyStartup() { if (isPlatformKeybindingBug517068Fixed()) { return; } IBindingService service = PlatformUI.getWorkbench().getService(IBindingService.class); if (service != null) { List<Binding> newBindings = new ArrayList<>(); Binding[] bindings = service.getBindings(); for (Binding binding : bindings) { String commandId = null; if (binding != null && binding.getParameterizedCommand() != null && binding.getParameterizedCommand().getCommand() != null) { commandId = binding.getParameterizedCommand().getCommand().getId(); if (commandId == null) { newBindings.add(binding); } else if (!commandId.startsWith(LSP4E_COMMAND_ID_PREFIX)) { newBindings.add(binding); } else { Collection<?> conflicts = service.getConflictsFor(binding.getTriggerSequence()); if (conflicts == null || conflicts.size() == 0) { newBindings.add(binding); } } } else { newBindings.add(binding); } } PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { @Override public void run() { try { service.savePreferences(service.getActiveScheme(), newBindings.toArray(new Binding[newBindings.size()])); } catch (IOException e) { e.printStackTrace(); } } }); } }
Source:
<code>public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = (ConfigurableApplicationContext) applicationContext; Map<String, StreamListenerArgumentAdapter> streamListenerArgumentHandlerMap = this.applicationContext.getBeansOfType( StreamListenerArgumentAdapter.class); <START> for (Map.Entry<String, StreamListenerArgumentAdapter> entry : streamListenerArgumentHandlerMap.entrySet()) { <END> this.streamListenerArgumentAdapters.add(entry.getValue()); } Map<String, StreamListenerResultAdapter> stringStreamListenerResultHandlerMap = applicationContext.getBeansOfType( StreamListenerResultAdapter.class); this.streamListenerResultAdapters.add(new MessageChannelStreamListenerResultAdapter()); for (StreamListenerResultAdapter streamListenerResultAdapter : stringStreamListenerResultHandlerMap.values()) { this.streamListenerResultAdapters.add(streamListenerResultAdapter); } }</code><technical_language>nitpick: call .values() in for loop below</technical_language>

Target:
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = (ConfigurableApplicationContext) applicationContext; Map<String, StreamListenerParameterAdapter> streamListenerArgumentHandlerMap = this.applicationContext.getBeansOfType( StreamListenerParameterAdapter.class); for (StreamListenerParameterAdapter streamListenerParameterAdapter : streamListenerArgumentHandlerMap .values()) { this.streamListenerParameterAdapters.add(streamListenerParameterAdapter); } Map<String, StreamListenerResultAdapter> stringStreamListenerResultHandlerMap = applicationContext.getBeansOfType( StreamListenerResultAdapter.class); this.streamListenerResultAdapters.add(new MessageChannelStreamListenerResultAdapter()); for (StreamListenerResultAdapter streamListenerResultAdapter : stringStreamListenerResultHandlerMap.values()) { this.streamListenerResultAdapters.add(streamListenerResultAdapter); } }