auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void unblockServiceOnDestination(PerunSession sess, Service service, int destinationId) throws PrivilegeException, FacilityNotExistsException, DestinationNotExistsException { Destination destination = getDestinationById(sess, destinationId); <START> List<Facility> destinationFacilities = perunBl.getFacilitiesManager().getFacilitiesByDestination(sess, destination.getDestination()); <END> boolean isFacilityAdminAtLeastOnce = false; for (Facility facility : destinationFacilities) { if (AuthzResolver.isAuthorized(sess, Role.FACILITYADMIN, facility)) { isFacilityAdminAtLeastOnce = true; } } if (!isFacilityAdminAtLeastOnce && !AuthzResolver.isAuthorized(sess, Role.PERUNADMIN)) { throw new PrivilegeException(sess, "unblockServiceOnDestination"); } getServicesManagerBl().unblockServiceOnDestination(sess, service, destinationId); }</code><technical_language>Bl layer get facilities destination</technical_language>

Target:
public void unblockServiceOnDestination(PerunSession sess, Service service, int destinationId) throws PrivilegeException, FacilityNotExistsException, DestinationNotExistsException { Destination destination = getServicesManagerBl().getDestinationById(sess, destinationId); List<Facility> destinationFacilities = perunBl.getFacilitiesManagerBl().getFacilitiesByDestination(sess, destination.getDestination()); boolean isFacilityAdminAtLeastOnce = false; for (Facility facility : destinationFacilities) { if (AuthzResolver.isAuthorized(sess, Role.FACILITYADMIN, facility)) { isFacilityAdminAtLeastOnce = true; } } if (!isFacilityAdminAtLeastOnce && !AuthzResolver.isAuthorized(sess, Role.PERUNADMIN)) { throw new PrivilegeException(sess, "unblockServiceOnDestination"); } getServicesManagerBl().unblockServiceOnDestination(sess, service, destinationId); }
Source:
<code>public void send(String method) { try { String WNL = "\r\n" ; String boundary = UUID.randomUUID().toString() ; HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection(); connection.setRequestMethod(method); connection.setDoOutput(true) ; connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); try ( PrintStream ps = new PrintStream(connection.getOutputStream()) ; ) { for ( Entry e : items ) { ps.print("--" + boundary+WNL) ; ps.print("Content-Disposition: form-data; name=\"FILE\"; filename=\""+e.fileName+"\""+WNL) ; ps.print("Content-Type: "+e.contentType+";charset=UTF-8"+WNL) ; ps.print(WNL); ps.print(e.content) ; ps.print(WNL); } ps.print("--" + boundary + "--"+WNL); } connection.connect(); <START> connection.getResponseCode(); <END> } catch (IOException ex) { IO.exception(ex); } }</code><technical_language>I prefer assignment - helps debugging</technical_language>

Target:
public void send(String method) { try { String WNL = "\r\n" ; String boundary = UUID.randomUUID().toString() ; HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection(); connection.setRequestMethod(method); connection.setDoOutput(true) ; connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); try ( PrintStream ps = new PrintStream(connection.getOutputStream()) ; ) { for ( Entry e : items ) { ps.print("--" + boundary+WNL) ; ps.print("Content-Disposition: form-data; name=\"FILE\"; filename=\""+e.fileName+"\""+WNL) ; ps.print("Content-Type: "+e.contentType+";charset=UTF-8"+WNL) ; ps.print(WNL); ps.print(e.content) ; ps.print(WNL); } ps.print("--" + boundary + "--"+WNL); } connection.connect(); int responseCode = connection.getResponseCode(); } catch (IOException ex) { IO.exception(ex); } }
Source:
<code>private Guid getStorageDomainId(Guid poolId, StorageDomainType type, StorageDomainStatus status) { return getStorageDomains(poolId, type, <START> status).stream().map(StorageDomain::getId).findFirst().orElse(Guid.Empty); <END> }</code><technical_language>a of get item if present return idea? save mapping of complete list return (IIUC)</technical_language>

Target:
private Guid getStorageDomainId(Guid poolId, StorageDomainType type, StorageDomainStatus status) { return getStorageDomains(poolId, type, status).stream().findFirst().map(StorageDomain::getId).orElse(Guid.Empty); }
Source:
<code>public LiveData<Boolean> downloadFeedbacks() { if (feedbackDownloadResponse == null) feedbackDownloadResponse = new MutableLiveData<>(); try { compositeDisposable.add(APIClient.getOpenEventAPI().getFeedbacks() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(feedbackList -> { Timber.i("Downloaded Feedbacks "); realmRepo.saveFeedbacks(feedbackList).subscribe(); feedbackDownloadResponse.setValue(true); }, throwable -> { Timber.i("Feedbacks Codes download failed"); feedbackDownloadResponse.setValue(false); })); <START> } catch (Exception e) { <END> Timber.e(e); } return feedbackDownloadResponse; }</code><technical_language>catching generic exception</technical_language>

Target:
public LiveData<Boolean> downloadFeedbacks() { if (feedbackDownloadResponse == null) feedbackDownloadResponse = new MutableLiveData<>(); compositeDisposable.add(APIClient.getOpenEventAPI().getFeedbacks() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(feedbackList -> { Timber.i("Downloaded Feedbacks "); realmRepo.saveFeedbacks(feedbackList).subscribe(); feedbackDownloadResponse.setValue(true); }, throwable -> { Timber.i("Feedbacks Codes download failed"); feedbackDownloadResponse.setValue(false); })); return feedbackDownloadResponse; }
Source:
<code>public void openFolderAndSelectFile(Path filePath) throws IOException { <START> String desktopSession = System.getenv("DESKTOP_SESSION"); <END> String cmd = "xdg-open " + filePath.toAbsolutePath().getParent().toString(); if(Objects.nonNull(desktopSession)){ desktopSession = desktopSession.toLowerCase(Locale.ROOT); if (desktopSession.contains("gnome")) { cmd = "nautilus" + filePath.toString().replace(" ", "\\ "); } else if (desktopSession.contains("kde")) { cmd = "dolphin --select " + filePath.toString().replace(" ", "\\ "); } } Runtime.getRuntime().exec(cmd); }</code><technical_language>this Optional.ofNullable(System.get...) check ...isPresent()</technical_language>

Target:
public void openFolderAndSelectFile(Path filePath) throws IOException { String desktopSession = System.getenv("DESKTOP_SESSION"); String cmd = "xdg-open " + filePath.toAbsolutePath().getParent().toString(); if (desktopSession != null) { desktopSession = desktopSession.toLowerCase(Locale.ROOT); if (desktopSession.contains("gnome")) { cmd = "nautilus" + filePath.toString().replace(" ", "\\ "); } else if (desktopSession.contains("kde")) { cmd = "dolphin --select " + filePath.toString().replace(" ", "\\ "); } } Runtime.getRuntime().exec(cmd); }
Source:
<code>private void doGetNettyServerTest(Properties properties, SSLFactory sslFactory) { VerifiableProperties verifiableProperties = new VerifiableProperties(properties); NettyConfig nettyConfig = new NettyConfig(verifiableProperties); NettyServerFactory nettyServerFactory = new NettyServerFactory(verifiableProperties, new MetricRegistry(), REST_REQUEST_HANDLER, PUBLIC_ACCESS_LOGGER, REST_SERVER_STATE, sslFactory); NioServer nioServer = nettyServerFactory.getNioServer(); assertNotNull("No NioServer returned", nioServer); assertEquals("Did not receive a NettyServer instance", NettyServer.class.getCanonicalName(), nioServer.getClass().getCanonicalName()); <START> Map<Integer, ChannelInitializer<SocketChannel>> channelInitializers = nettyServerFactory.getChannelInitializers(); <END> if (nettyConfig.nettyServerSSLEnabled && sslFactory != null) { assertEquals("Expected two ChannelInitializers when SSLFactory is not null", 2, channelInitializers.size()); assertNotNull("No ChannelInitializer for SSL port", channelInitializers.get(nettyConfig.nettyServerSSLPort)); } else { assertEquals("Expected one ChannelInitializer when SSLFactory is null", 1, channelInitializers.size()); } assertNotNull("No ChannelInitializer for plaintext port", channelInitializers.get(nettyConfig.nettyServerPort)); }</code><technical_language>minor: instead of introducing a function, i prefer variable package private</technical_language>

Target:
private void doGetNettyServerTest(Properties properties, SSLFactory sslFactory) { VerifiableProperties verifiableProperties = new VerifiableProperties(properties); NettyConfig nettyConfig = new NettyConfig(verifiableProperties); NettyServerFactory nettyServerFactory = new NettyServerFactory(verifiableProperties, new MetricRegistry(), REST_REQUEST_HANDLER, PUBLIC_ACCESS_LOGGER, REST_SERVER_STATE, sslFactory); NioServer nioServer = nettyServerFactory.getNioServer(); assertNotNull("No NioServer returned", nioServer); assertEquals("Did not receive a NettyServer instance", NettyServer.class.getCanonicalName(), nioServer.getClass().getCanonicalName()); Map<Integer, ChannelInitializer<SocketChannel>> channelInitializers = nettyServerFactory.channelInitializers; if (nettyConfig.nettyServerSSLEnabled && sslFactory != null) { assertEquals("Expected two ChannelInitializers when SSLFactory is not null", 2, channelInitializers.size()); assertNotNull("No ChannelInitializer for SSL port", channelInitializers.get(nettyConfig.nettyServerSSLPort)); } else { assertEquals("Expected one ChannelInitializer when SSLFactory is null", 1, channelInitializers.size()); } assertNotNull("No ChannelInitializer for plaintext port", channelInitializers.get(nettyConfig.nettyServerPort)); }
Source:
<code>private void createAsset(Source source, String assetPath, ResourceResolver r, boolean versioning) throws Exception { try { boolean versioned = false; if (!dryRunMode) { disableWorkflowProcessing(r); AssetManager assetManager = r.adaptTo(AssetManager.class); String type = mimetypeService.getMimeType(source.getName()); if (versioning) { Asset asset = r.getResource(assetPath).adaptTo(Asset.class); versioned = asset != null; assetManager.createRevision(asset, "initial version of asset", asset.getName()); r.commit(); r.refresh(); } Asset asset = assetManager.createAsset(assetPath, source.getStream(), type, false); <START> if (asset == null) { <END> AssetIngestorException ex = new AssetIngestorException("Cannot create asset: asset is null on path " + assetPath); throw ex; } saveMigrationInfo(source, asset); r.commit(); r.refresh(); } if (versioned) { trackDetailedActivity(assetPath, "Revised", "Created new version of asset", source.getLength()); } else { trackDetailedActivity(assetPath, "Create", "Imported asset", source.getLength()); } incrementBytes(importedData, source.getLength()); incrementCount(importedAssets, 1L); } finally { source.close(); } }</code><technical_language>log this properly too, I think</technical_language>

Target:
private void createAsset(Source source, String assetPath, ResourceResolver r, boolean versioning) throws Exception { try { boolean versioned = false; if (!dryRunMode) { disableWorkflowProcessing(r); AssetManager assetManager = r.adaptTo(AssetManager.class); String type = mimetypeService.getMimeType(source.getName()); if (versioning) { Asset asset = r.getResource(assetPath).adaptTo(Asset.class); versioned = asset != null; assetManager.createRevision(asset, "initial version of asset", asset.getName()); r.commit(); r.refresh(); } Asset asset = assetManager.createAsset(assetPath, source.getStream(), type, false); if (asset == null) { String msg = String.format("Cannot create asset 'null' on path %s (type=%s)", assetPath, type); LOG.error(msg); throw new AssetIngestorException(msg); } saveMigrationInfo(source, asset); r.commit(); r.refresh(); } if (versioned) { trackDetailedActivity(assetPath, "Revised", "Created new version of asset", source.getLength()); } else { trackDetailedActivity(assetPath, "Create", "Imported asset", source.getLength()); } incrementBytes(importedData, source.getLength()); incrementCount(importedAssets, 1L); } finally { source.close(); } }
Source:
<code><START> protected Element sign(final Assertion assertion, final X509Certificate certificate, final PrivateKey privateKey, <END> final PublicKey publicKey) throws SAMLAssertionBuilderException { Element assertionElement = null; try { final Signature signature = OpenSAML2ComponentBuilder.getInstance().createSignature(certificate, privateKey, publicKey); final SamlAssertionWrapper wrapper = new SamlAssertionWrapper(assertion); wrapper.setSignature(signature, SignatureConstants.ALGO_ID_DIGEST_SHA1); final MarshallerFactory marshallerFactory = XMLObjectProviderRegistrySupport.getMarshallerFactory(); final Marshaller marshaller = marshallerFactory.getMarshaller(wrapper.getSamlObject()); assertionElement = marshaller.marshall(wrapper.getSamlObject()); Signer.signObject(signature); } catch (final SignatureException | org.apache.wss4j.common.ext.WSSecurityException | org.opensaml.core.xml.io.MarshallingException e) { LOG.error("Unable to sign: {}", e.getLocalizedMessage()); throw new SAMLAssertionBuilderException(e.getLocalizedMessage(), e); } return assertionElement; }</code><technical_language>check code format</technical_language>

Target:
protected Element sign(final Assertion assertion, final X509Certificate certificate, final PrivateKey privateKey, final PublicKey publicKey) throws SAMLAssertionBuilderException { Element assertionElement = null; try { final Signature signature = OpenSAML2ComponentBuilder.getInstance().createSignature(certificate, privateKey, publicKey); final SamlAssertionWrapper wrapper = new SamlAssertionWrapper(assertion); wrapper.setSignature(signature, SignatureConstants.ALGO_ID_DIGEST_SHA1); final MarshallerFactory marshallerFactory = XMLObjectProviderRegistrySupport.getMarshallerFactory(); final Marshaller marshaller = marshallerFactory.getMarshaller(wrapper.getSamlObject()); assertionElement = marshaller.marshall(wrapper.getSamlObject()); Signer.signObject(signature); } catch (final SignatureException | WSSecurityException | MarshallingException e) { LOG.error("Unable to sign: {}", e.getLocalizedMessage()); throw new SAMLAssertionBuilderException(e.getLocalizedMessage(), e); } return assertionElement; }
Source:
<code>protected Control createContents(Composite parent) { IMarker element = Adapters.adapt(getElement(), IMarker.class); IResource resource = null; if (element != null) { marker = element; resource = marker.getResource(); } else if (resource == null) { resource = ResourcesPlugin.getWorkspace().getRoot(); } if (!Util.isEditable(marker)) { noDefaultAndApplyButton(); } Composite composite = new Composite(parent, SWT.NULL); GridLayout layout = new GridLayout(2, false); layout.marginWidth = 0; layout.marginHeight = 0; composite.setLayout(layout); GridData gridData = new GridData(GridData.FILL_HORIZONTAL); composite.setLayoutData(gridData); initializeDialogUnits(composite); createResourceNameArea(composite); createAttributesArea(composite); if (resource != null) { createResourceArea(composite); } if (element != null) { createCreationTimeArea(composite); } createLine(parent); createSeparator(parent); createDescriptionArea(parent); Dialog.applyDialogFont(parent); return <START> parent; <END> }</code><technical_language>return new composite</technical_language>

Target:
protected Control createContents(Composite parent) { IMarker element = Adapters.adapt(getElement(), IMarker.class); IResource resource = null; if (element != null) { marker = element; resource = marker.getResource(); } if (resource == null) { resource = ResourcesPlugin.getWorkspace().getRoot(); } if (!Util.isEditable(marker)) { noDefaultAndApplyButton(); } Composite composite = new Composite(parent, SWT.NULL); GridLayout layout = new GridLayout(2, false); layout.marginWidth = 0; layout.marginHeight = 0; composite.setLayout(layout); GridData gridData = new GridData(GridData.FILL_HORIZONTAL); composite.setLayoutData(gridData); initializeDialogUnits(composite); createAttributesArea(composite); createResourceNameArea(composite); if (resource != null) { createResourceArea(composite); } if (element != null) { createCreationTimeArea(composite); } createSeparator(composite); createDescriptionArea(composite); Dialog.applyDialogFont(composite); return composite; }
Source:
<code>private Cache<RealmCacheKey, RealmCacheEntry> getRealmCache() { try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID); carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); Cache<RealmCacheKey, RealmCacheEntry> realmCache = null; CacheManager cacheManager = Caching.getCacheManagerFactory().getCacheManager(CUSTOM_TENANT_CACHE_MANAGER); for (Cache cache : cacheManager.getCaches()) { if (StringUtils.equals(cache.getName(), CUSTOM_TENANT_CACHE) || StringUtils.equals(cache.getName(), CUSTOM_TENANT_CACHE)) { realmCache = cache; } } if (realmCache == null) { if (log.isDebugEnabled()) { <START> log.debug("Realm cache is null"); <END> } cacheManager.createCacheBuilder(CUSTOM_TENANT_CACHE).setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.MINUTES, DefaultRealm.timeOut)).build(); } if (log.isDebugEnabled()) { log.debug("Authorization cache is created, cache: " + realmCache); } return cacheManager.getCache(CUSTOM_TENANT_CACHE); } finally { PrivilegedCarbonContext.endTenantFlow(); } }</code><technical_language>Missing fullstop</technical_language>

Target:
private Cache<RealmCacheKey, RealmCacheEntry> getRealmCache() { try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID); carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); Cache<RealmCacheKey, RealmCacheEntry> realmCache = null; CacheManager cacheManager = Caching.getCacheManagerFactory().getCacheManager(CUSTOM_TENANT_CACHE_MANAGER); for (Cache cache : cacheManager.getCaches()) { if (StringUtils.equals(cache.getName(), CUSTOM_TENANT_CACHE) || StringUtils.equals(cache.getName(), CUSTOM_TENANT_CACHE)) { realmCache = cache; } } if (realmCache == null) { if (log.isDebugEnabled()) { log.debug("Realm cache is null."); } cacheManager.createCacheBuilder(CUSTOM_TENANT_CACHE).setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.MINUTES, DefaultRealm.timeOut)).build(); } if (log.isDebugEnabled()) { log.debug("Authorization cache is created, cache: " + realmCache); } return cacheManager.getCache(CUSTOM_TENANT_CACHE); } finally { PrivilegedCarbonContext.endTenantFlow(); } }
Source:
<code>public void deleteOldDeployments(final IServer server) throws CoreException { File deploymentsRootFolder = getDeploymentsRootFolder(); Arrays.stream(server.getModules()) <START> .forEach(module -> deleteOldDeployment(module, deploymentsRootFolder)); <END> }</code><technical_language>output name cache reset here, below</technical_language>

Target:
public void deleteOldDeployments(final IServer server) throws CoreException { File deploymentsRootFolder = getDeploymentsRootFolder(); Arrays.stream(server.getModules()) .forEach(module -> deleteOldDeployment(module, deploymentsRootFolder, server)); }
Source:
<code><START> private boolean isNullyComparison(Tree lastElement) { <END> if (lastElement.is(Kind.NOT_EQUAL_TO, Kind.EQUAL_TO)) { BinaryExpressionTree comparison = (BinaryExpressionTree) lastElement; return SymbolicValue.get(comparison.leftOperand()).nullability().isNullOrUndefined().equals(State.YES) || SymbolicValue.get(comparison.rightOperand()).nullability().isNullOrUndefined().equals(State.YES); } return false; }</code><technical_language>![MAJOR](<LINK_1> "isNullyComparison" a "static" method. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
private boolean isNullyComparison(Tree lastElement) { if (lastElement.is(Kind.NOT_EQUAL_TO, Kind.EQUAL_TO)) { BinaryExpressionTree comparison = (BinaryExpressionTree) lastElement; return SymbolicValue.get(comparison.leftOperand()).nullability().isNullOrUndefined() || SymbolicValue.get(comparison.rightOperand()).nullability().isNullOrUndefined(); } return false; }
Source:
<code>public boolean isKind(Kind kind) { <START> return kind.toString().equals(this.event); <END> }</code><technical_language>is this return this.kind == kind</technical_language>

Target:
public boolean isKind(Kind kind) { return this.kind == kind; }
Source:
<code>private String makeOpenSearchRequest(String title) throws FetcherException{ try { URLDownload urlDownload = new URLDownload(getOpenSearchURL(title)); URLDownload.bypassSSLVerification(); String resp = urlDownload.asString(); return resp; } catch (IOException e) { <START> e.printStackTrace(); <END> throw new FetcherException("IO Exception", e); } }</code><technical_language>Remove this printStackTrace please. wrapping exception in a fetcher exception exception stack trace print LOGGER</technical_language>

Target:
private String makeOpenSearchRequest(String title) throws FetcherException { try { URLDownload urlDownload = new URLDownload(getOpenSearchURL(title)); URLDownload.bypassSSLVerification(); String resp = urlDownload.asString(); return resp; } catch (MalformedURLException e) { throw new FetcherException("Bad url", e); } catch (IOException e) { throw new FetcherException("Error with Open Search Request (Worldcat)", e); } }
Source:
<code>public ClusterTemplateV4Responses deleteMultiple(Long workspaceId, @ResourceNameList Set<String> names, String environmentName, String environmentCrn) { Set<ClusterTemplate> clusterTemplates; if (Objects.nonNull(names) && !names.isEmpty()) { clusterTemplates = clusterTemplateService.deleteMultiple(names, workspaceId); } else { Set<String> namesByEnv = clusterTemplateService .findAllByEnvironment(environmentCrn) .stream() .map(ClusterTemplate::getName) <START> .collect(toSet()); <END> clusterTemplates = clusterTemplateService.deleteMultiple(namesByEnv, workspaceId); } return new ClusterTemplateV4Responses(converterUtil.convertAllAsSet(clusterTemplates, ClusterTemplateV4Response.class)); }</code><technical_language>if remove input-independent solution (the usage of NameOrCrn object) please remove unused environmentName arg method arguments</technical_language>

Target:
public ClusterTemplateV4Responses deleteMultiple(Long workspaceId, @ResourceNameList Set<String> names, String environmentName, String environmentCrn) { Set<ClusterTemplate> clusterTemplates; if (Objects.nonNull(names) && !names.isEmpty()) { clusterTemplates = clusterTemplateService.deleteMultiple(names, workspaceId); } else { Set<String> namesByEnv = clusterTemplateService .findAllByEnvironment(environmentCrn) .stream() .map(ClusterTemplateView::getName) .collect(toSet()); clusterTemplates = clusterTemplateService.deleteMultiple(namesByEnv, workspaceId); } return new ClusterTemplateV4Responses(converterUtil.convertAllAsSet(clusterTemplates, ClusterTemplateV4Response.class)); }
Source:
<code><START> public void testExpireDuringSecondObtain() throws Exception { <END> RedisLockRegistry registry = new RedisLockRegistry(this.getConnectionFactoryForTest(), "rlrTests", 1000); registry.setUseWeakReferences(true); Lock foo = registry.obtain("foo"); foo.lockInterruptibly(); waitForExpire("foo"); Lock foo1 = registry.obtain("foo"); assertNotSame(foo, foo1); }</code><technical_language>@artembilan ! I understand correctly this test pass latest changes in RedisLockRegistry class: do registry.obtain("foo") in case Redis key expired return new RedisLock object assertNotSame(foo, foo1) pass. is another case: 1. Thread A obtains LockFoo 2. Thread A locks LockFoo 3. LockFoo expired 4. Another Thread B successfully obtains LockFoo (will get if (lockInStore == null || !lock.equals(lockInStore)) { block) 5. Thread B lock LockFoo is blocked ReentrantLock is locked Thread A expected behaviour in opinion? I Thread B able obtain lock lock expired in Redis</technical_language>

Target:
public void testExpireDuringSecondObtain() throws Exception { RedisLockRegistry registry = new RedisLockRegistry(this.getConnectionFactoryForTest(), this.registryKey, 100); registry.setUseWeakReferences(true); Lock foo = registry.obtain("foo"); foo.lockInterruptibly(); waitForExpire("foo"); Lock foo1 = registry.obtain("foo"); assertNotSame(foo, foo1); try { foo.unlock(); fail("IllegalStateException"); } catch (IllegalStateException e) { assertThat(e.getMessage(), containsString("Lock is not locked")); } }
Source:
<code>public SubversionSCMSource(String id, String remoteBase, String credentialsId, String includes, String excludes) { super(id); this.remoteBase = StringUtils.removeEnd(remoteBase, "/") + "/"; setCredentialsId(credentialsId); setIncludes(StringUtils.defaultIfEmpty(includes, DescriptorImpl.DEFAULT_INCLUDES)); setExcludes(StringUtils.defaultIfEmpty(excludes, DescriptorImpl.DEFAULT_EXCLUDES)); <START> this.additionalCredentials = new ArrayList<AdditionalCredentials>(); <END> }</code><technical_language>Usage of this collection is ineffective if do plan modify flight. Collections.emptyList() instead in code</technical_language>

Target:
public SubversionSCMSource(String id, String remoteBase, String credentialsId, String includes, String excludes) { super(id); this.remoteBase = StringUtils.removeEnd(remoteBase, "/") + "/"; setCredentialsId(credentialsId); setIncludes(StringUtils.defaultIfEmpty(includes, DescriptorImpl.DEFAULT_INCLUDES)); setExcludes(StringUtils.defaultIfEmpty(excludes, DescriptorImpl.DEFAULT_EXCLUDES)); }
Source:
<code>public List<ISearchResultGA> find(IProgressMonitor monitor, SearchType searchType, String query) throws CoreException { int classifier = showClassifiers(searchType) ? getClassifier() : IIndex.SEARCH_ALL; <START> Map<String, IndexedArtifact> res = indexManager.getAllIndexes().search(new UserInputSearchExpression(query), <END> getSearchType(searchType), classifier); if(res.isEmpty()) { return Collections.emptyList(); } List<ISearchResultGA> results = new ArrayList<>(); for(IndexedArtifact art : res.values()) { SearchResult result = new SearchResult(this, art.getGroupId(), art.getArtifactId(), art.getClassname(), art.getPackageName()); for(IndexedArtifactFile file : art.getFiles()) { result.addVersion(file.version, file.getDependency().getClassifier(), file.getDependency().getType(), file.size, file.date, file.fname, file.sourcesExists == IIndex.PRESENT); } } return results; }</code><technical_language>Search yields weird results <LINK_0> Needs filtering</technical_language>

Target:
public List<ISearchResultGA> find(IProgressMonitor monitor, SearchType searchType, String query) throws CoreException { int classifier = showClassifiers(searchType) ? getClassifier() : IIndex.SEARCH_ALL; Map<String, IndexedArtifact> res = indexManager.getAllIndexes().search(new UserInputSearchExpression(query), getSearchType(searchType), classifier); if(res.isEmpty()) { return Collections.emptyList(); } List<ISearchResultGA> results = new ArrayList<>(); for(IndexedArtifact art : res.values()) { SearchResult result = new SearchResult(this, art.getGroupId(), art.getArtifactId(), art.getClassname(), art.getPackageName()); for(IndexedArtifactFile file : art.getFiles()) { result.addVersion(file.version, file.getDependency().getClassifier(), file.getDependency().getType(), file.size, file.date, file.fname, file.sourcesExists == IIndex.PRESENT); } result.setComponents(searchType.filter(result.getComponents())); if(!result.getComponents().isEmpty()) { results.add(result); } } return results; }
Source:
<code>protected void persistColumnSizes() { Tree tree = getTree(); for (TreeColumn <START> treeColumn : <END> tree.getColumns()) { Object id = treeColumn.getData(); fColumnSizes.put(id, Integer.valueOf(treeColumn.getWidth())); } }</code><technical_language>rename column</technical_language>

Target:
protected void persistColumnSizes() { Tree tree = getTree(); for (TreeColumn column : tree.getColumns()) { Object id = column.getData(); fColumnSizes.put(id, Integer.valueOf(column.getWidth())); } }
Source:
<code>public void init(final ServletConfig config) throws ServletException { this.application = SERVICE_PROVIDER.getInstance(AzkabanWebServer.class); if (this.application == null) { throw new IllegalStateException( "No batch application is defined in the servlet context!"); } final Props props = this.application.getServerProps(); this.name = props.getString("azkaban.name", ""); this.label = props.getString("azkaban.label", ""); this.color = props.getString("azkaban.color", "#FF0000"); this.passwordPlaceholder = props.getString("azkaban.password.placeholder", "Password"); <START> this.displayExecutionPageSize = props.getInt("azkaban.display.execution_page_size", 16); <END> if (this.application instanceof AzkabanWebServer) { final AzkabanWebServer server = (AzkabanWebServer) this.application; this.viewerPlugins = PluginRegistry.getRegistry().getViewerPlugins(); this.triggerPlugins = new ArrayList<>(server.getTriggerPlugins().values()); } }</code><technical_language>Please define new config keys in Constants class</technical_language>

Target:
public void init(final ServletConfig config) throws ServletException { this.application = SERVICE_PROVIDER.getInstance(AzkabanWebServer.class); if (this.application == null) { throw new IllegalStateException( "No batch application is defined in the servlet context!"); } final Props props = this.application.getServerProps(); this.name = props.getString("azkaban.name", ""); this.label = props.getString("azkaban.label", ""); this.color = props.getString("azkaban.color", "#FF0000"); this.passwordPlaceholder = props.getString("azkaban.password.placeholder", "Password"); this.displayExecutionPageSize = props.getInt(ConfigurationKeys.DISPLAY_EXECUTION_PAGE_SIZE, 16); if (this.application instanceof AzkabanWebServer) { final AzkabanWebServer server = (AzkabanWebServer) this.application; this.viewerPlugins = PluginRegistry.getRegistry().getViewerPlugins(); this.triggerPlugins = new ArrayList<>(server.getTriggerPlugins().values()); } }
Source:
<code>public void antMatchersPathVariablesCaseInsensitiveCamelCaseVariables() throws Exception { <START> loadConfig(AntPatchersPathVariablesCammelCaseVariables.class); <END> this.request.setServletPath("/USER/user"); this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain); assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); this.setup(); this.request.setServletPath("/USER/deny"); this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain); assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN); }</code><technical_language>Typo: Ant**P**atchersPathVariablesCa**mm**elCaseVariables Ant**M**atchersPathVariablesCa**m**elCaseVariables</technical_language>

Target:
public void antMatchersPathVariablesCaseInsensitiveCamelCaseVariables() throws Exception { loadConfig(AntMatchersPathVariablesCamelCaseVariables.class); this.request.setServletPath("/USER/user"); this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain); assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); this.setup(); this.request.setServletPath("/USER/deny"); this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain); assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN); }
Source:
<code>public void bindFrame() { vp = BufferUtils.createIntBuffer(16); GL11.glGetInteger(GL11.GL_VIEWPORT, vp); GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, frame); <START> GL11.glViewport(0, 0, size.x, size.y); <END> glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, size.x, size.y, 0, 0, 2048f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); }</code><technical_language>is flip textures need manually flipped later</technical_language>

Target:
public void bindFrame() { vp = BufferUtils.createIntBuffer(16); GL11.glGetInteger(GL11.GL_VIEWPORT, vp); GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, frame); GL11.glViewport(0, 0, size.x, size.y); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glTranslatef(0.5f, 0.5f, 0.0f); glScalef(1, -1, 1); glTranslatef(-0.5f, -0.5f, 0.0f); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, size.x, size.y, 0, 0, 2048f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); }
Source:
<code>private static ExecutorService createExecutorService(final Config config) { final Duration executorKeepAliveTime = Duration.parse(config.getString("keepAlive")); return new ThreadPoolExecutor( <START> config.getInt("corePoolSize"), <END> config.getInt("maximumPoolSize"), executorKeepAliveTime.toNanos(), TimeUnit.NANOSECONDS, new ArrayBlockingQueue<>(config.getInt("queueSize")) ); }</code><technical_language>reasonable defaults</technical_language>

Target:
private static ExecutorService createExecutorService(final Config config) { final Duration executorKeepAliveTime = config.hasPath("keepAlive") ? Duration.parse(config.getString("keepAlive")) : Duration.ofSeconds(1); final int corePoolSize = config.hasPath("corePoolSize") ? config.getInt("corePoolSize") : 0; final int maximumPoolSize = config.hasPath("maximumPoolSize") ? config.getInt("maximumPoolSize") : 4; final int queueSize = config.hasPath("queueSize") ? config.getInt("queueSize") : 1024; return new ThreadPoolExecutor( corePoolSize, maximumPoolSize, executorKeepAliveTime.toNanos(), TimeUnit.NANOSECONDS, new ArrayBlockingQueue<>(queueSize) ); }
Source:
<code>public void testPrefixedUnprefixedActorNames() { DocumentModel document = getDocument(); assertNotNull(document); List<String> actors = new ArrayList<>(); actors.add(user1.getName()); actors.add(NuxeoPrincipal.PREFIX + user2.getName()); <START> actors.add("administrators"); <END> actors.add(NuxeoGroup.PREFIX + "members"); taskService.createTask(session, administrator, document, "Task assigned to prefixed ans unprefixed users and groups", actors, true, null, null, null, null, null); session.save(); List<Task> tasks = taskService.getTaskInstances(document, user1, session); assertNotNull(tasks); assertEquals(2, tasks.size()); tasks = taskService.getTaskInstances(document, user2, session); assertNotNull(tasks); assertEquals(2, tasks.size()); tasks = taskService.getTaskInstances(document, user3, session); assertNotNull(tasks); assertEquals(1, tasks.size()); tasks = taskService.getTaskInstances(document, user4, session); assertNotNull(tasks); assertEquals(0, tasks.size()); tasks = taskService.getTaskInstances(document, administrator, session); assertNotNull(tasks); assertEquals(1, tasks.size()); tasks = taskService.getTaskInstances(document, (NuxeoPrincipal) null, session); assertNotNull(tasks); assertEquals(4, tasks.size()); }</code><technical_language>i replaced of List.of java 11, if List.of(user1.getName()), thx</technical_language>

Target:
public void testPrefixedUnprefixedActorNames() { DocumentModel document = getDocument(); assertNotNull(document); List<String> actors = List.of(user1.getName(), NuxeoPrincipal.PREFIX + user2.getName(), "administrators", NuxeoGroup.PREFIX + "members"); taskService.createTask(session, administrator, document, "Task assigned to prefixed ans unprefixed users and groups", actors, true, null, null, null, null, null); session.save(); List<Task> tasks = taskService.getTaskInstances(document, user1, session); assertNotNull(tasks); assertEquals(2, tasks.size()); tasks = taskService.getTaskInstances(document, user2, session); assertNotNull(tasks); assertEquals(2, tasks.size()); tasks = taskService.getTaskInstances(document, user3, session); assertNotNull(tasks); assertEquals(1, tasks.size()); tasks = taskService.getTaskInstances(document, user4, session); assertNotNull(tasks); assertEquals(0, tasks.size()); tasks = taskService.getTaskInstances(document, administrator, session); assertNotNull(tasks); assertEquals(1, tasks.size()); tasks = taskService.getTaskInstances(document, (NuxeoPrincipal) null, session); assertNotNull(tasks); assertEquals(4, tasks.size()); }
Source:
<code>public FetchCommand fetch_() { return new FetchCommand() { public URIish url; public List<RefSpec> refspecs; public boolean prune; public boolean shallow; public Integer timeout; public boolean tags = true; <START> public Integer depth = 1; <END> public FetchCommand from(URIish remote, List<RefSpec> refspecs) { this.url = remote; this.refspecs = refspecs; return this; } public FetchCommand tags(boolean tags) { this.tags = tags; return this; } public FetchCommand prune() { this.prune = true; return this; } public FetchCommand shallow(boolean shallow) { this.shallow = shallow; return this; } public FetchCommand timeout(Integer timeout) { this.timeout = timeout; return this; } public FetchCommand depth(Integer depth) { this.depth = depth; return this; } public void execute() throws GitException, InterruptedException { listener.getLogger().println( "Fetching upstream changes from " + url); ArgumentListBuilder args = new ArgumentListBuilder(); args.add("fetch"); args.add(tags ? "--tags" : "--no-tags"); if (isAtLeastVersion(1,7,1,0)) args.add("--progress"); StandardCredentials cred = credentials.get(url.toPrivateString()); if (cred == null) cred = defaultCredentials; args.add(url); if (refspecs != null) for (RefSpec rs: refspecs) if (rs != null) args.add(rs.toString()); if (prune) args.add("--prune"); if (shallow) args.add("--depth=" + depth); warnIfWindowsTemporaryDirNameHasSpaces(); launchCommandWithCredentials(args, workspace, cred, url, timeout); } }; }</code><technical_language>code work if null? Do want handle nulls instead of primitives? If a designed case i prefer skip tri-state fields</technical_language>

Target:
public FetchCommand fetch_() { return new FetchCommand() { public URIish url; public List<RefSpec> refspecs; public boolean prune; public boolean shallow; public Integer timeout; public boolean tags = true; public Integer depth = 1; public FetchCommand from(URIish remote, List<RefSpec> refspecs) { this.url = remote; this.refspecs = refspecs; return this; } public FetchCommand tags(boolean tags) { this.tags = tags; return this; } public FetchCommand prune() { this.prune = true; return this; } public FetchCommand shallow(boolean shallow) { this.shallow = shallow; return this; } public FetchCommand timeout(Integer timeout) { this.timeout = timeout; return this; } public FetchCommand depth(Integer depth) { this.depth = depth; return this; } public void execute() throws GitException, InterruptedException { listener.getLogger().println( "Fetching upstream changes from " + url); ArgumentListBuilder args = new ArgumentListBuilder(); args.add("fetch"); args.add(tags ? "--tags" : "--no-tags"); if (isAtLeastVersion(1,7,1,0)) args.add("--progress"); StandardCredentials cred = credentials.get(url.toPrivateString()); if (cred == null) cred = defaultCredentials; args.add(url); if (refspecs != null) for (RefSpec rs: refspecs) if (rs != null) args.add(rs.toString()); if (prune) args.add("--prune"); if (shallow) { if (depth == null){ depth = 1; } args.add("--depth=" + depth); } warnIfWindowsTemporaryDirNameHasSpaces(); launchCommandWithCredentials(args, workspace, cred, url, timeout); } }; }
Source:
<code>public int openWizard(final String className) { NewClassCreationWizard wizard = new NewClassCreationWizard() { @Override public void <START> addPages() <END> { super.addPages(); if (className == null || className.isEmpty()) return; IWizardPage[] pages = getPages(); for (IWizardPage page : pages) { if (page instanceof NewClassCreationWizardPage) { NewClassCreationWizardPage p = (NewClassCreationWizardPage) page; p.setClassName(className, true); p.setHeaderFileText(className + ".hpp", true); p.setSourceFileText(className + ".cpp", true); break; } } } }; return new WizardDialog(null, wizard).open(); }</code><technical_language>namespace populated context quick fix invoked. easier override NewClassCreationWizard.getSelection() method instead of addPages()</technical_language>

Target:
public int openWizard(final String className) { NewClassCreationWizard wizard = new NewClassCreationWizard(); wizard.setClassName(className); wizard.init(PlatformUI.getWorkbench(), new StructuredSelection()); return new WizardDialog(null, wizard).open(); }
Source:
<code>private void createWriterIfNecessary() { if (writer == null) { shardUuid = UUID.randomUUID(); File stagingFile = storageService.getStagingFile(shardUuid); storageService.createParents(stagingFile); stagingFiles.add(stagingFile); OrcDataSink sink; <START> try (ThreadContextClassLoader ignored = new ThreadContextClassLoader(FileSystem.class.getClassLoader())) { <END> sink = new OutputStreamOrcDataSink(new FileOutputStream(stagingFile)); } catch (FileNotFoundException e) { throw new PrestoException(RAPTOR_ERROR, format("Failed to find staging file %s", stagingFile), e); } writer = new OrcFileWriter(columnIds, columnTypes, sink, orcOptimizedWriterStage.equals(ENABLED_AND_VALIDATED), stats, typeManager, compression); } }</code><technical_language>do need do this</technical_language>

Target:
private void createWriterIfNecessary() { if (writer == null) { shardUuid = UUID.randomUUID(); Path stagingFile = storageService.getStagingFile(shardUuid); storageService.createParents(stagingFile); stagingFiles.add(stagingFile); OrcDataSink sink; try { sink = orcDataEnvironment.createOrcDataSink(stagingFile); } catch (IOException e) { throw new PrestoException(RAPTOR_ERROR, format("Failed to create staging file %s", stagingFile), e); } writer = new OrcFileWriter(columnIds, columnTypes, sink, orcOptimizedWriterStage.equals(ENABLED_AND_VALIDATED), stats, typeManager, compression); } }
Source:
<code>public void run() { try { LOG.info("CMClearer started"); for (String encryptionZone : encryptionZones) { <START> Path cmroot; <END> if (encryptionZone.equals(NO_ENCRYPTION)) { cmroot = new Path(cmRootDir); } else { cmroot = new Path(encryptionZone + encryptedCmRootDir); } long now = System.currentTimeMillis(); FileSystem fs = cmroot.getFileSystem(conf); FileStatus[] files = fs.listStatus(cmroot); for (FileStatus file : files) { long modifiedTime = file.getModificationTime(); if (now - modifiedTime > secRetain * 1000) { try { if (fs.getXAttrs(file.getPath()).containsKey(REMAIN_IN_TRASH_TAG)) { boolean succ = Trash.moveToAppropriateTrash(fs, file.getPath(), conf); if (succ) { LOG.debug("Move " + file.toString() + " to trash"); } else { LOG.warn("Fail to move " + file.toString() + " to trash"); } } else { boolean succ = fs.delete(file.getPath(), false); if (succ) { LOG.debug("Remove " + file.toString()); } else { LOG.warn("Fail to remove " + file.toString()); } } } catch (UnsupportedOperationException e) { LOG.warn("Error getting xattr for " + file.getPath().toString()); } } } } } catch (IOException e) { LOG.error("Exception when clearing cmroot:" + StringUtils.stringifyException(e)); } }</code><technical_language>Do existing test case for CMCleaner</technical_language>

Target:
public void run() { try { LOG.info("CMClearer started"); for (String cmrootString : encryptionZones.values()) { Path cmroot = new Path(cmrootString); long now = System.currentTimeMillis(); FileSystem fs = cmroot.getFileSystem(conf); FileStatus[] files = fs.listStatus(cmroot); for (FileStatus file : files) { long modifiedTime = file.getModificationTime(); if (now - modifiedTime > secRetain * 1000) { try { if (fs.getXAttrs(file.getPath()).containsKey(REMAIN_IN_TRASH_TAG)) { boolean succ = Trash.moveToAppropriateTrash(fs, file.getPath(), conf); if (succ) { LOG.debug("Move " + file.toString() + " to trash"); } else { LOG.warn("Fail to move " + file.toString() + " to trash"); } } else { boolean succ = fs.delete(file.getPath(), false); if (succ) { LOG.debug("Remove " + file.toString()); } else { LOG.warn("Fail to remove " + file.toString()); } } } catch (UnsupportedOperationException e) { LOG.warn("Error getting xattr for " + file.getPath().toString()); } } } } } catch (IOException e) { LOG.error("Exception when clearing cmroot:" + StringUtils.stringifyException(e)); } }
Source:
<code>public static BinaryData fromStream(InputStream inputStream) { Objects.requireNonNull(inputStream, "'inputStream' cannot be null."); final int bufferSize = 1024; try { ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[bufferSize]; while ((nRead = inputStream.read(data, 0, data.length)) != -1) { dataOutputBuffer.write(data, 0, nRead); } return fromBytes(dataOutputBuffer.toByteArray()); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } <START> } <END></code><technical_language>able handle this in a more efficient manner? stands this means entire input stream is read a buffer, converted a byte array, copied a new byte array? avoid byte array copy</technical_language>

Target:
public static BinaryData fromStream(InputStream inputStream) { if (Objects.isNull(inputStream)) { return EMPTY_DATA; } final int bufferSize = 1024; try { ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[bufferSize]; while ((nRead = inputStream.read(data, 0, data.length)) != -1) { dataOutputBuffer.write(data, 0, nRead); } dataOutputBuffer.flush(); return new BinaryData(dataOutputBuffer.toByteArray()); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }
Source:
<code>public AdministrationPage fillSearchField(String searchTerm) { <START> driver.findElement(SEARCH_FIELD.getBy()).sendKeys(searchTerm); <END> return this; }</code><technical_language>palka - a wrapper sendKeys() method</technical_language>

Target:
public AdministrationPage fillSearchField(String searchTerm) { sendKeys(SEARCH_FIELD,searchTerm); return this; }
Source:
<code>CompactionExecutor(EnumSet<Trigger> triggers, int bundleReadBufferSize) { this.triggers = triggers; <START> bundleReadBuffer = bundleReadBufferSize == 0 ? null : ByteBuffer.allocateDirect(bundleReadBufferSize); <END> }</code><technical_language>add a log message here? logger.info("Buffer size is in compaction thread for {}", bundleReadBufferSize, mountPath");</technical_language>

Target:
CompactionExecutor(EnumSet<Trigger> triggers, int bundleReadBufferSize) { this.triggers = triggers; bundleReadBuffer = bundleReadBufferSize == 0 ? null : ByteBuffer.allocateDirect(bundleReadBufferSize); logger.info("Buffer size is in compaction thread for {}", bundleReadBufferSize, mountPath); }
Source:
<code>protected void executeCommand() { final DiskImage newDiskImage = getParameters().getDiskImage(); <START> if (newDiskImage != null) { <END> addDiskImageToDb(newDiskImage, getCompensationContext()); getReturnValue().setActionReturnValue(newDiskImage.getId()); getReturnValue().setSucceeded(true); } }</code><technical_language>null check in canDoAction(), executeCommand()</technical_language>

Target:
protected void executeCommand() { final DiskImage newDiskImage = getParameters().getDiskImage(); addDiskImageToDb(newDiskImage, getCompensationContext()); getReturnValue().setActionReturnValue(newDiskImage.getId()); getReturnValue().setSucceeded(true); }