问:
Entity Framework : an existing connection was forcibly closed by the remote host
I am using Entity Framework 6.2.0 with my WCF service hosted in IIS. I am getting this error when trying to eager load related table data. I have two tables Product and Category joined by CategoryID.

Trying to fetch products data and their related category Name but getting that error (I have tried almost every solution on web from last 24 hours).

```<code>public List<Product> GetAllProducts(int start, int end)
{
    return _context.Products.Include(x=>x.Category).ToList();
}
</code>```

I have also set following properties to false.

```<code>public Intelliventory_DBEntities()
    : base("name=Intelliventory_DBEntities")
{
    this.Configuration.ProxyCreationEnabled = false;
    this.Configuration.LazyLoadingEnabled = false;
}
</code>```

App.config

```<code><configuration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IIntelliventoryService"
                         closeTimeout="10:01:00" openTimeout="10:01:00"
                         receiveTimeout="10:10:00" sendTimeout="10:01:00"
                         allowCookies="false" bypassProxyOnLocal="false"
                         maxBufferPoolSize="2147483647"
                         maxReceivedMessageSize="2147483647"
                         useDefaultWebProxy="true">
                    <readerQuotas maxDepth="2147483647"
                                  maxStringContentLength="2147483647"
                                  maxArrayLength="2147483647"
                                  maxBytesPerRead="2147483647"
                                  maxNameTableCharCount="2147483647" />
                </binding>
            </basicHttpBinding>
        </bindings>
        <behaviors>
            <endpointBehaviors>
                <behavior name="ServiceBehavior">
                     <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
                </behavior>
            </endpointBehaviors>
        </behaviors>
        <client>
            <endpoint name="BasicHttpBinding_IIntelliventoryService"
                address="http://localhost:5050/IntelliventoryService.svc"
                behaviorConfiguration="ServiceBehavior"
                binding="basicHttpBinding"
                bindingConfiguration="BasicHttpBinding_IIntelliventoryService"
                contract="IntelliventoryService.IIntelliventoryService" />
        </client>
    </system.serviceModel>
</configuration>
</code>```

Web.Config

```<code><configuration>
    <configSections>
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </configSections>
    <appSettings>
        <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
    </appSettings>
    <system.web>
        <compilation debug="true" targetFramework="4.8" />
        <httpRuntime targetFramework="4.8" />
    </system.web>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IIntelliventoryService"
                         closeTimeout="10:01:00" openTimeout="10:01:00"
                         receiveTimeout="10:10:00" sendTimeout="10:01:00"
                         allowCookies="false" bypassProxyOnLocal="false"
                         maxBufferPoolSize="2147483647"
                         maxReceivedMessageSize="2147483647"
                         useDefaultWebProxy="true">
                    <readerQuotas maxDepth="2147483647"
                                  maxStringContentLength="2147483647"
                                  maxArrayLength="2147483647"
                                  maxBytesPerRead="2147483647"
                                  maxNameTableCharCount="2147483647" />
                </binding>
            </basicHttpBinding>
        </bindings>
        <behaviors>
            <serviceBehaviors>
                <behavior>
                    <dataContractSerializer maxItemsInObjectGraph ="2147483647"/>
                    <serviceThrottling maxConcurrentCalls="16" maxConcurrentInstances="26" maxConcurrentSessions="10" />
                    <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="true" />
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <protocolMapping>
            <add binding="basicHttpsBinding" scheme="https" />
        </protocolMapping>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
        </system.serviceModel>
    <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    <directoryBrowse enabled="true" />
  </system.webServer>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
<connectionStrings>
  <add name="Intelliventory_DBEntities"
                        connectionString="metadata=res://*/ADOModel.csdl|res://*/ADOModel.ssdl|res://*/ADOModel.msl;provider=System.Data.SqlClient;
                        provider connection string="data source=RAO-HAMMAS-PC;initial catalog=Intelliventory_DB;persist security info=True;
                        user id=admin;password=admin;MultipleActiveResultSets=True;App=EntityFramework""
                        providerName="System.Data.EntityClient" />
</connectionStrings></configuration>
</code>```

I don't get this error when i don't eager load category table.

Also if I try to load just specific column, I get this error.

```<code>_context.Products.Include(x=>x.Category.CategoryName).ToList();
</code>```

A specified Include path is not valid. The EntityType 'Intelliventory_DBModel.Category' does not declare a navigation

Category Table from Db Context

```<code>public int CategoryID { get; set; }
public string CategoryName { get; set; }
</code>```

Product Table from Db Context

```<code>public partial class Product
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Product()
    {
        this.Purchases = new HashSet<Purchase>();
    }

    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public int CategoryID { get; set; }
    public System.DateTime Date { get; set; }
    public double Quantity { get; set; }
    public string Model { get; set; }
    public string Details { get; set; }
    public double SellPrice { get; set; }
    public double PurchasePrice { get; set; }
    public int SupplierID { get; set; }
    public Nullable<double> PaidAmount { get; set; }
    public Nullable<int> NoOfSales { get; set; }
    public Nullable<double> DueAmountToPay { get; set; }
    public Nullable<System.DateTime> ExpiryDate { get; set; }

    public virtual Category Category { get; set; }
    public virtual Supplier Supplier { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Purchase> Purchases { get; set; }
}
</code>```

As @Andy pointed that Category is not ICollection also Supplier is not ICollection but Purchases is ICollection. But it was all auto generated. Did i do something wrong ?

This is what happens during data fetch event (SSMS Live Event)

Update: I created a console app and directly used EF and it worked

But again when i used WCF in this console app to fetch Products, i got same error !

StackTrace of Exception

```<code>System.ComponentModel.AsyncCompletedEventArgs.RaiseExceptionIfNecessary()
   at Intelliventory.IntelliventoryService.GetAllProductsCompletedEventArgs.get_Result() in E:\\2- Development\\2-NATIVE WORLD\\Projects\\Intelliventory\\Intelliventory\\Connected Services\\IntelliventoryService\\Reference.cs:line 321
   at Intelliventory.UserControls.ProductControl.ClientOnGetAllProductsCompleted(Object sender, GetAllProductsCompletedEventArgs e) in E:\\2- Development\\2-NATIVE WORLD\\Projects\\Intelliventory\\Intelliventory\\UserControls\\ProductControl.xaml.cs:line 89
   at Intelliventory.IntelliventoryService.IntelliventoryServiceClient.OnGetAllProductsCompleted(Object state) in E:\\2- Development\\2-NATIVE WORLD\\Projects\\Intelliventory\\Intelliventory\\Connected Services\\IntelliventoryService\\Reference.cs:line 1082
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.DispatcherOperation.InvokeImpl()
   at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
   at MS.Internal.CulturePreservingExecutionContext.CallbackWrapper(Object obj)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Windows.Threading.DispatcherOperation.Invoke()
   at System.Windows.Threading.Dispatcher.ProcessQueue()
   at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at System.Windows.Application.Run(Window window)
   at System.Windows.Application.Run()
   at Intelliventory.App.Main()
</code>```

All three Exceptions !

Update: i have got the exception details (Category contains Cycles)

'IntelliventoryWcfService.Category' contains cycles and cannot be serialized if reference tracking is disabled

答:
So finally i found and solved the issue with the help of some really good people :)

Issue was

'IntelliventoryWcfService.Category' contains cycles and cannot be serialized if reference tracking is disabled

So, basically Category contained cycles or circular reference that was causing server to drop the connection. Solution is to put [DataContract(IsReference = true)] on Category class. So the class now look like this.

```<code>using System.Runtime.Serialization;

[DataContract(IsReference = true)]
public partial class Category
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Category()
    {
        this.Products = new HashSet<Product>();
    }
    [DataMember]
    public int CategoryID { get; set; }
    [DataMember]
    public string CategoryName { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    [DataMember]
    public virtual ICollection<Product> Products { get; set; }
}
</code>```

Help Reference: http://themvcclub.blogspot.com/2014/11/how-to-fix-WCF-Web-API-Error-contains-cycles-and-cannot-be-serialized-if-reference-tracking-is-disabled.html

Body:
I am using Entity Framework 6.2.0 with my WCF service hosted in IIS. I am getting this error when trying to eager load related table data. I have two tables Product and Category joined by CategoryID.

Trying to fetch products data and their related category Name but getting that error (I have tried almost every solution on web from last 24 hours).

public List<Product> GetAllProducts(int start, int end)
{
    return _context.Products.Include(x=>x.Category).ToList();
}

I have also set following properties to false.

public Intelliventory_DBEntities()
    : base("name=Intelliventory_DBEntities")
{
    this.Configuration.ProxyCreationEnabled = false;
    this.Configuration.LazyLoadingEnabled = false;
}

App.config

<configuration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IIntelliventoryService"
                         closeTimeout="10:01:00" openTimeout="10:01:00"
                         receiveTimeout="10:10:00" sendTimeout="10:01:00"
                         allowCookies="false" bypassProxyOnLocal="false"
                         maxBufferPoolSize="2147483647"
                         maxReceivedMessageSize="2147483647"
                         useDefaultWebProxy="true">
                    <readerQuotas maxDepth="2147483647"
                                  maxStringContentLength="2147483647"
                                  maxArrayLength="2147483647"
                                  maxBytesPerRead="2147483647"
                                  maxNameTableCharCount="2147483647" />
                </binding>
            </basicHttpBinding>
        </bindings>
        <behaviors>
            <endpointBehaviors>
                <behavior name="ServiceBehavior">
                     <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
                </behavior>
            </endpointBehaviors>
        </behaviors>
        <client>
            <endpoint name="BasicHttpBinding_IIntelliventoryService"
                address="http://localhost:5050/IntelliventoryService.svc"
                behaviorConfiguration="ServiceBehavior"
                binding="basicHttpBinding"
                bindingConfiguration="BasicHttpBinding_IIntelliventoryService"
                contract="IntelliventoryService.IIntelliventoryService" />
        </client>
    </system.serviceModel>
</configuration>

Web.Config

<configuration>
    <configSections>

    </configSections>
    <appSettings>
        <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
    </appSettings>
    <system.web>
        <compilation debug="true" targetFramework="4.8" />
        <httpRuntime targetFramework="4.8" />
    </system.web>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IIntelliventoryService"
                         closeTimeout="10:01:00" openTimeout="10:01:00"
                         receiveTimeout="10:10:00" sendTimeout="10:01:00"
                         allowCookies="false" bypassProxyOnLocal="false"
                         maxBufferPoolSize="2147483647"
                         maxReceivedMessageSize="2147483647"
                         useDefaultWebProxy="true">
                    <readerQuotas maxDepth="2147483647"
                                  maxStringContentLength="2147483647"
                                  maxArrayLength="2147483647"
                                  maxBytesPerRead="2147483647"
                                  maxNameTableCharCount="2147483647" />
                </binding>
            </basicHttpBinding>
        </bindings>
        <behaviors>
            <serviceBehaviors>
                <behavior>
                    <dataContractSerializer maxItemsInObjectGraph ="2147483647"/>
                    <serviceThrottling maxConcurrentCalls="16" maxConcurrentInstances="26" maxConcurrentSessions="10" />
                    <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="true" />
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <protocolMapping>
            <add binding="basicHttpsBinding" scheme="https" />
        </protocolMapping>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
        </system.serviceModel>
    <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    <directoryBrowse enabled="true" />
  </system.webServer>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
<connectionStrings>
  <add name="Intelliventory_DBEntities"
                        connectionString="metadata=res://*/ADOModel.csdl|res://*/ADOModel.ssdl|res://*/ADOModel.msl;provider=System.Data.SqlClient;
                        provider connection string="data source=RAO-HAMMAS-PC;initial catalog=Intelliventory_DB;persist security info=True;
                        user id=admin;password=admin;MultipleActiveResultSets=True;App=EntityFramework""
                        providerName="System.Data.EntityClient" />
</connectionStrings></configuration>

I don't get this error when i don't eager load category table.

Also if I try to load just specific column, I get this error.

_context.Products.Include(x=>x.Category.CategoryName).ToList();

A specified Include path is not valid. The EntityType 'Intelliventory_DBModel.Category' does not declare a navigation

Category Table from Db Context

public int CategoryID { get; set; }
public string CategoryName { get; set; }

Product Table from Db Context

public partial class Product
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Product()
    {
        this.Purchases = new HashSet<Purchase>();
    }

    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public int CategoryID { get; set; }
    public System.DateTime Date { get; set; }
    public double Quantity { get; set; }
    public string Model { get; set; }
    public string Details { get; set; }
    public double SellPrice { get; set; }
    public double PurchasePrice { get; set; }
    public int SupplierID { get; set; }
    public Nullable<double> PaidAmount { get; set; }
    public Nullable<int> NoOfSales { get; set; }
    public Nullable<double> DueAmountToPay { get; set; }
    public Nullable<System.DateTime> ExpiryDate { get; set; }

    public virtual Category Category { get; set; }
    public virtual Supplier Supplier { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Purchase> Purchases { get; set; }
}

As @Andy pointed that Category is not ICollection also Supplier is not ICollection but Purchases is ICollection. But it was all auto generated. Did i do something wrong ?

This is what happens during data fetch event (SSMS Live Event)

Update: I created a console app and directly used EF and it worked

But again when i used WCF in this console app to fetch Products, i got same error !

StackTrace of Exception

System.ComponentModel.AsyncCompletedEventArgs.RaiseExceptionIfNecessary()
   at Intelliventory.IntelliventoryService.GetAllProductsCompletedEventArgs.get_Result() in E:\\2- Development\\2-NATIVE WORLD\\Projects\\Intelliventory\\Intelliventory\\Connected Services\\IntelliventoryService\\Reference.cs:line 321
   at Intelliventory.UserControls.ProductControl.ClientOnGetAllProductsCompleted(Object sender, GetAllProductsCompletedEventArgs e) in E:\\2- Development\\2-NATIVE WORLD\\Projects\\Intelliventory\\Intelliventory\\UserControls\\ProductControl.xaml.cs:line 89
   at Intelliventory.IntelliventoryService.IntelliventoryServiceClient.OnGetAllProductsCompleted(Object state) in E:\\2- Development\\2-NATIVE WORLD\\Projects\\Intelliventory\\Intelliventory\\Connected Services\\IntelliventoryService\\Reference.cs:line 1082
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.DispatcherOperation.InvokeImpl()
   at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
   at MS.Internal.CulturePreservingExecutionContext.CallbackWrapper(Object obj)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Windows.Threading.DispatcherOperation.Invoke()
   at System.Windows.Threading.Dispatcher.ProcessQueue()
   at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at System.Windows.Application.Run(Window window)
   at System.Windows.Application.Run()
   at Intelliventory.App.Main()

All three Exceptions !

Update: i have got the exception details (Category contains Cycles)

'IntelliventoryWcfService.Category' contains cycles and cannot be serialized if reference tracking is disabled

Body:
So finally i found and solved the issue with the help of some really good people :)

Issue was

'IntelliventoryWcfService.Category' contains cycles and cannot be serialized if reference tracking is disabled

So, basically Category contained cycles or circular reference that was causing server to drop the connection. Solution is to put [DataContract(IsReference = true)] on Category class. So the class now look like this.

using System.Runtime.Serialization;

[DataContract(IsReference = true)]
public partial class Category
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Category()
    {
        this.Products = new HashSet<Product>();
    }
    [DataMember]
    public int CategoryID { get; set; }
    [DataMember]
    public string CategoryName { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    [DataMember]
    public virtual ICollection<Product> Products { get; set; }
}

Help Reference: http://themvcclub.blogspot.com/2014/11/how-to-fix-WCF-Web-API-Error-contains-cycles-and-cannot-be-serialized-if-reference-tracking-is-disabled.html


来源: stackexchange

问:
EF core Access list through Include
I have a Model named as Blog:

```<code>public class Blog
    {
        [Key]
        public int blogId { get; set; }
        [Required]
        public string blogTitle { get; set; }
        public string imagePath { get; set; }
        [Required, DataType(DataType.Html)]
        public string blogDescription { get; set; }
        [DataType(DataType.DateTime)]
        public DateTime blogDateTime { get; set; }
        [Required]
        public bool isPublished { get; set; }

        [Required]
        public BlogCategory blogCategory { get; set; }
        public List<Comments> blogComments { get; set; }
    }
</code>```

And another model Comment:

```<code>public class Comments
    {
        [Key]
        public int authorId { get; set; }
        [Required]
        public string commentAuthor { get; set; }
        [DataType(DataType.Date)]
        public DateTime commentDate { get; set; }
        public bool isHidden { get; set; }
        [Required, DataType(DataType.EmailAddress)]
        public string commentAuthorEmail { get; set; }
        [Required]
        public string commentDescription { get; set; }
        public Blog Blog { get; set; }
    }
</code>```

In the blogs controller I want to access all the comments where isHidden = false

What I have tried is:

```<code>var blog = await _context.Blog
           .Include(cat => cat.blogCategory)
           .Include(comments => comments.blogComments.Any(c => !c.isHidden))
           .FirstOrDefaultAsync(m => m.blogId == id);
</code>```

But all I am getting exception is

```<code>An unhandled exception occurred while processing the request.
InvalidOperationException: The Include property lambda expression 'comments => comments.blogComments.Find(c => Not(c.isHidden))' is invalid. The expression should represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, specify an explicitly typed lambda parameter of the target type, E.g. '(Derived d) => d.MyProperty'.
</code>```

How can I solve this problem?

答:
bool value is true of false so try:
//untested</p>

```<code>(comments => comments.blogComments.where(c=>c.isHidden==false))
</code>```

ContentLicense: CC BY-SA 4.0

Title: EF core Access list through Include

Body:
I have a Model named as Blog:

public class Blog
    {
        [Key]
        public int blogId { get; set; }
        [Required]
        public string blogTitle { get; set; }
        public string imagePath { get; set; }
        [Required, DataType(DataType.Html)]
        public string blogDescription { get; set; }
        [DataType(DataType.DateTime)]
        public DateTime blogDateTime { get; set; }
        [Required]
        public bool isPublished { get; set; }

        [Required]
        public BlogCategory blogCategory { get; set; }
        public List<Comments> blogComments { get; set; }
    }

And another model Comment:

public class Comments
    {
        [Key]
        public int authorId { get; set; }
        [Required]
        public string commentAuthor { get; set; }
        [DataType(DataType.Date)]
        public DateTime commentDate { get; set; }
        public bool isHidden { get; set; }
        [Required, DataType(DataType.EmailAddress)]
        public string commentAuthorEmail { get; set; }
        [Required]
        public string commentDescription { get; set; }
        public Blog Blog { get; set; }
    }

In the blogs controller I want to access all the comments where isHidden = false

What I have tried is:

var blog = await _context.Blog
           .Include(cat => cat.blogCategory)
           .Include(comments => comments.blogComments.Any(c => !c.isHidden))
           .FirstOrDefaultAsync(m => m.blogId == id);

But all I am getting exception is

An unhandled exception occurred while processing the request.
InvalidOperationException: The Include property lambda expression 'comments => comments.blogComments.Find(c => Not(c.isHidden))' is invalid. The expression should represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, specify an explicitly typed lambda parameter of the target type, E.g. '(Derived d) => d.MyProperty'.

How can I solve this problem?

Body:
bool value is true of false so try:
//untested

(comments => comments.blogComments.where(c=>c.isHidden==false))


问:
Android LinearLayout and RecyclerView BottomNavigation Alignment
so I can't figure out how to align my bottom navigation in a LinearLayout under a RecyclerView. The items are RecyclerView:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".CategoryActivity">

   <android.support.design.widget.AppBarLayout
           android:theme="@style/AppTheme.AppBarOverlay"
           android:layout_width="match_parent"
           android:layout_height="wrap_content">

       <android.support.v7.widget.Toolbar
               android:id="@+id/toolbar"
               android:background="?attr/colorPrimary"
               app:popupTheme="@style/AppTheme.PopupOverlay"
               android:layout_width="match_parent"
               android:layout_height="?attr/actionBarSize">
       </android.support.v7.widget.Toolbar>

   </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_category"
            android:layout_margin="8dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
    </android.support.v7.widget.RecyclerView>

    <android.support.design.widget.BottomNavigationView
            android:id="@+id/nav_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?android:attr/windowBackground"
            android:layout_alignParentBottom="true"
            app:menu="@menu/bottom_nav_menu"/>

</LinearLayout>
</code>```

The navigation should be always at the bottom.

答:
Okay, here is your layout, it should work as you expected</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_category"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/nav_view"
        android:layout_below="@+id/appbar"
        android:layout_margin="8dp"
        android:orientation="vertical" />

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="?android:attr/windowBackground"
        app:menu="@menu/menu_navigation" />

</RelativeLayout>
</code>```

Body:
so I can't figure out how to align my bottom navigation in a LinearLayout under a RecyclerView. The items are RecyclerView:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".CategoryActivity">

   <android.support.design.widget.AppBarLayout
           android:theme="@style/AppTheme.AppBarOverlay"
           android:layout_width="match_parent"
           android:layout_height="wrap_content">

       <android.support.v7.widget.Toolbar
               android:id="@+id/toolbar"
               android:background="?attr/colorPrimary"
               app:popupTheme="@style/AppTheme.PopupOverlay"
               android:layout_width="match_parent"
               android:layout_height="?attr/actionBarSize">
       </android.support.v7.widget.Toolbar>

   </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_category"
            android:layout_margin="8dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
    </android.support.v7.widget.RecyclerView>

    <android.support.design.widget.BottomNavigationView
            android:id="@+id/nav_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?android:attr/windowBackground"
            android:layout_alignParentBottom="true"
            app:menu="@menu/bottom_nav_menu"/>

</LinearLayout>

The navigation should be always at the bottom.

Body:
Okay, here is your layout, it should work as you expected

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_category"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/nav_view"
        android:layout_below="@+id/appbar"
        android:layout_margin="8dp"
        android:orientation="vertical" />

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="?android:attr/windowBackground"
        app:menu="@menu/menu_navigation" />

</RelativeLayout>


问:
Disable WordPress Multisite Modifying Media URL
I'm using DigitalOcean Spaces to store my static assets. All is working fine, my media library url point to my Spaces (e.g. foobar.sgp1.digitaloceanspaces.com).

The problem starts when I install multisite, as it's default WordPress behavior to add "sites/xxx" to all sub site's media url (e.g. foobar.sgp1.digitaloceanspaces.com/sites/2). Which of course, my assets are not there, and can't be found.

I've found this link:

https://wordpress.stackexchange.com/questions/307530/remove-multisite-part-from-wordpress-multisite-upload-directory

Which gave me an idea.

I've tried this on functions.php

add_filter('upload_dir', 'multisite_path');

function multisite_path( $param ){
    $path = str_replace('sites/2/', '', $param['path']);
    $url = str_replace('sites/2/', '', $param['url']);
    $param['path'] = $path;
    $param['url'] = $url;

    return $param;
}
```

But it's not working.

If there's a hook to remove "sites/2/" from the url, or any other way to disable this functionality, I'm open for suggestions.

Thanks.

答:
Found the solution here:

wordpress multisite remove /sites/{ID}/ automatic upload url

Here's the working code:

```<code>add_filter( 'upload_dir', 'same_upload_dir' );
function same_upload_dir( array $uploads ) {
    $baseurl = WP_CONTENT_URL . '/uploads';
    $basedir = ABSPATH . 'wp-content/uploads';
    $subdir = $uploads['subdir'];

    return array(
        'path'    => $basedir . $subdir,
        'url'     => $baseurl . $subdir,
        'subdir'  => $subdir,
        'basedir' => $basedir,
        'baseurl' => $baseurl,
        'error'   => false,
    );
}
</code>```

Body:
I'm using DigitalOcean Spaces to store my static assets. All is working fine, my media library url point to my Spaces (e.g. foobar.sgp1.digitaloceanspaces.com).

The problem starts when I install multisite, as it's default WordPress behavior to add "sites/xxx" to all sub site's media url (e.g. foobar.sgp1.digitaloceanspaces.com/sites/2). Which of course, my assets are not there, and can't be found.

I've found this link:

https://wordpress.stackexchange.com/questions/307530/remove-multisite-part-from-wordpress-multisite-upload-directory

Which gave me an idea.

I've tried this on functions.php

add_filter('upload_dir', 'multisite_path');

function multisite_path( $param ){
    $path = str_replace('sites/2/', '', $param['path']);
    $url = str_replace('sites/2/', '', $param['url']);
    $param['path'] = $path;
    $param['url'] = $url;

    return $param;
}

But it's not working.

If there's a hook to remove "sites/2/" from the url, or any other way to disable this functionality, I'm open for suggestions.

Thanks.

Body:
Found the solution here:

wordpress multisite remove /sites/{ID}/ automatic upload url

Here's the working code:

add_filter( 'upload_dir', 'same_upload_dir' );
function same_upload_dir( array $uploads ) {
    $baseurl = WP_CONTENT_URL . '/uploads';
    $basedir = ABSPATH . 'wp-content/uploads';
    $subdir = $uploads['subdir'];

    return array(
        'path'    => $basedir . $subdir,
        'url'     => $baseurl . $subdir,
        'subdir'  => $subdir,
        'basedir' => $basedir,
        'baseurl' => $baseurl,
        'error'   => false,
    );
}


问:
Intellisense for C# not working in ASP.net project | Visual Studio 2017
I am making an ASP.Net application, but for some reason Intellisense is not working for the C# code. The Code is white and Errors are not shown as well. It is working great for HTML though. Does anybody know how to fix this?</p>

答:
Just close visual studio and open it again and then check..
Open solution and build again because intellisense uses metadata to get property and all other things. There are changes metadata not loaded properly

Or

Go to Tools -> Options -> Text Editor -> All Languages -> General and enable "Auto list members"


问:
How to select only certain tag and text using xpath?
For example, html block:

```<code><p><b>text1</b> (<span><a href="#1">asdf</a>text2</span>)</p>
</code>```

I need to select all tags "a" and all the rest must be the plain text just like we see in browser:

```<code>result = ["text1", " (", <tag_a>, "text2", ")"]
</code>```

or something like that.

Tried:

```<code>hxs.select('.//a|text()')
</code>```

in this case it finds all tags "a" but text is returned only from direct children.

At the same time:

```<code>hxs.select('.//text()|a')
</code>```

gets all texts, but tags "a" only from direct children.

UPDATE

```<code>    elements = []
    for i in hxs.select('.//node()'):
        try:
            tag_name = i.select('name()').extract()[0]
        except TypeError:
            tag_name = '_text'

        if tag_name == 'a':
            elements.append(i)
        elif tag_name == '_text':
            elements.append(i.extract())
</code>```

is there a better way?

答:
Is this the kind of thing you're looking for?

You can remove the descendant tags from the block using etree.strip_tags

```<code>from lxml import etree
d = etree.HTML('<html><body><p><b>text1</b> (<span><a href="#1">asdf</a>text2</span>)</p></body></html>')
block = d.xpath('/html/body/p')[0]
# etree.strip_tags apparently takes a list of tags to strip, but it wasn't working for me
for tag in set(x.tag for x in block.iterdescendants() if x.tag != 'a'):
  etree.strip_tags(block,tag)

block.xpath('./text()|a')
</code>```

Yields:

```<code>['text1', ' (', <Element a at fa4a48>, 'text2', ')']
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For example, html block:

text1 (asdftext2)

I need to select all tags "a" and all the rest must be the plain text just like we see in browser:

result = ["text1", " (", <tag_a>, "text2", ")"]

or something like that.

Tried:

hxs.select('.//a|text()')

in this case it finds all tags "a" but text is returned only from direct children.

At the same time:

hxs.select('.//text()|a')

gets all texts, but tags "a" only from direct children.

UPDATE

    elements = []
    for i in hxs.select('.//node()'):
        try:
            tag_name = i.select('name()').extract()[0]
        except TypeError:
            tag_name = '_text'

        if tag_name == 'a':
            elements.append(i)
        elif tag_name == '_text':
            elements.append(i.extract())

is there a better way?

Body:
Is this the kind of thing you're looking for?

You can remove the descendant tags from the block using etree.strip_tags

from lxml import etree
d = etree.HTML('<html><body><p><b>text1</b> (<span><a href="#1">asdf</a>text2</span>)</p></body></html>')
block = d.xpath('/html/body/p')[0]
# etree.strip_tags apparently takes a list of tags to strip, but it wasn't working for me
for tag in set(x.tag for x in block.iterdescendants() if x.tag != 'a'):
  etree.strip_tags(block,tag)

block.xpath('./text()|a')

Yields:

['text1', ' (', <Element a at fa4a48>, 'text2', ')']


问:
Creating a thread-safe temporary file name
When using Tempfile Ruby is creating a file with a thread-safe and inter-process-safe name. I only need a file name in that way.

I was wondering if there is a more straight forward approach way than:

```<code>t = Tempfile.new(['fleischwurst', '.png'])
temp_path = t.path
t.close
t.unlink
</code>```

答:
Since Dir::Tmpname.make_tmpname was removed in Ruby 2.5.0, this one falls back to using SecureRandom:

```<code>require "tmpdir"

def generate_temp_filename(ext=".png")
  filename = begin
    Dir::Tmpname.make_tmpname(["x", ext], nil)
  rescue NoMethodError
    require "securerandom"
    "#{SecureRandom.urlsafe_base64}#{ext}"
  end
  File.join(Dir.tmpdir, filename)
end
</code>```

Body:
When using Tempfile Ruby is creating a file with a thread-safe and inter-process-safe name. I only need a file name in that way.

I was wondering if there is a more straight forward approach way than:

t = Tempfile.new(['fleischwurst', '.png'])
temp_path = t.path
t.close
t.unlink

Body:
Since Dir::Tmpname.make_tmpname was removed in Ruby 2.5.0, this one falls back to using SecureRandom:

require "tmpdir"

def generate_temp_filename(ext=".png")
  filename = begin
    Dir::Tmpname.make_tmpname(["x", ext], nil)
  rescue NoMethodError
    require "securerandom"
    "#{SecureRandom.urlsafe_base64}#{ext}"
  end
  File.join(Dir.tmpdir, filename)
end


问:
Why does promise chaining not work here in Node.js?
I have a script that scrapes a website and is supposed to send data back to client... JUST SO YOU KNOW IT'S ALL WITHIN app.get

Here is the code... The second .then does not work. It's supposed to send the arrays to the client after they have been populated once cheerio iterated through them. Yet it does not work... Maybe something wrong with the way I set up the second promise? Please help.

```<code>  axios.get("https://www.sciencenews.org/").then(function(response){
     var $ = cheerio.load(response.data);
     $("div.field-item-node-ref").each(function(i,element){
       if($(element).children('.ad').length == 0 && $(element).children('article').length > 0) {
                    array1.push($(element).find('h2.node-title').text());
                    array2.push($(element).find('div.content').text());
 array3.push(`https://www.sciencenews.org${$(element).find('a').attr('href')}`);
                    array4.push(`${$(element).find('img').attr('src')}`);
                 }
            })
        }).then(()=>{
            res.send({titles:array1,summaries:array2,links:array3,base64img:array4});
         })
</code>```

答:
In the provided code snippet, none of the arrays are declared and there is no res object to call 'send' on since none is passed into the function.

Once the arrays are declared and res is temporarily replaced with a console.log, it appears to work on my end.

Working Repl.it

I'm assuming on your end that this function is called within a route, so there should be a 'res' object available within the scope of this function. If that's the case, it looks like it was just a matter of declaring your arrays before pushing data to them.

Body:
I have a script that scrapes a website and is supposed to send data back to client... JUST SO YOU KNOW IT'S ALL WITHIN app.get

Here is the code... The second .then does not work. It's supposed to send the arrays to the client after they have been populated once cheerio iterated through them. Yet it does not work... Maybe something wrong with the way I set up the second promise? Please help.

  axios.get("https://www.sciencenews.org/").then(function(response){
     var $ = cheerio.load(response.data);
     $("div.field-item-node-ref").each(function(i,element){
       if($(element).children('.ad').length == 0 && $(element).children('article').length > 0) {
                    array1.push($(element).find('h2.node-title').text());
                    array2.push($(element).find('div.content').text());
 array3.push(`https://www.sciencenews.org${$(element).find('a').attr('href')}`);
                    array4.push(`${$(element).find('img').attr('src')}`);
                 }
            })
        }).then(()=>{
            res.send({titles:array1,summaries:array2,links:array3,base64img:array4});
         })


问:
Controlling the width of content in a Flexbox HTML CSS
I have a flexbox and in it, I have an image and text. For some reason, there is a big area of the flexbox where I can't place content in. It is like there is padding there and it won't let it go past it. I'm not too sure why the content can't go in this area.

The part highlighted in yellow is where I can't place anything. If it goes over this area, it will just go to the next line.

What I want it for it to stretch across because right now, the text looks too close together. how can I achieve this?

/*Header for picture, and description*/
#display {
    padding-top: 2em;
    border: solid .125em black;
    display: flex;
    flex-flow: wrap;
    background-color: white;
    opacity: 0.9;
}

#display > * {
    flex: 1 1 5%;
    padding: 1em;
}

article{
    margin-right:20em;
}

article h1{
    font-size: 2em;
    text-align: center;
}

article p{
    padding-top: 2em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>   <section id="display">
        <figure id="headshot">
            <img src="images/GM05.png" alt="headshot"/>
        </figure>
        <article>
            <h1>Name Goes Here</h1>
            <p>Cras tristique gravida tellus, id fringilla lorem pellentesque iaculis. Donec vitae risus mauris. Interdum et malesuada fames ac ante ipsum primis in faucibus. Nunc consectetur purus sed diam iaculis congue. Morbi vitae nisl est. Sed sed justo vitae risus porta commodo vestibulum eget est. Cras eu augue enim. Etiam at commodo tellus, at posuere ligula. Vivamus at dolor eget sem faucibus aliquet sed et diam. Mauris vel leo eget nulla pulvinar suscipit vitae eu sem. Quisque nisi nibh, aliquet sit amet urna non, commodo fringilla tellus. Nullam tincidunt est nec tellus laoreet, id mollis urna pulvinar. Donec ligula ipsum, ultrices in venenatis quis, ultricies ut enim. Vivamus porttitor lobortis dui, id aliquam ipsum imperdiet non.</p>
        </article>
    </section></code>```

Removing the margin-right in the article tag fixes the issue, but now they aren't aligned correctly.

答:
You must note that you have set a margin on the article.

The problem might be here:

```<code>article{
    margin-right:20em;
}
</code>```

This pushes your article 20em's away from the right end of your display. Just remove the margin and run the code.

Body:
I have a flexbox and in it, I have an image and text. For some reason, there is a big area of the flexbox where I can't place content in. It is like there is padding there and it won't let it go past it. I'm not too sure why the content can't go in this area.

The part highlighted in yellow is where I can't place anything. If it goes over this area, it will just go to the next line.

What I want it for it to stretch across because right now, the text looks too close together. how can I achieve this?

/*Header for picture, and description*/
#display {
    padding-top: 2em;
    border: solid .125em black;
    display: flex;
    flex-flow: wrap;
    background-color: white;
    opacity: 0.9;
}

#display > * {
    flex: 1 1 5%;
    padding: 1em;
}

article{
    margin-right:20em;
}

article h1{
    font-size: 2em;
    text-align: center;
}

article p{
    padding-top: 2em;
}

Name Goes Here

Cras tristique gravida tellus, id fringilla lorem pellentesque iaculis. Donec vitae risus mauris. Interdum et malesuada fames ac ante ipsum primis in faucibus. Nunc consectetur purus sed diam iaculis congue. Morbi vitae nisl est. Sed sed justo vitae risus porta commodo vestibulum eget est. Cras eu augue enim. Etiam at commodo tellus, at posuere ligula. Vivamus at dolor eget sem faucibus aliquet sed et diam. Mauris vel leo eget nulla pulvinar suscipit vitae eu sem. Quisque nisi nibh, aliquet sit amet urna non, commodo fringilla tellus. Nullam tincidunt est nec tellus laoreet, id mollis urna pulvinar. Donec ligula ipsum, ultrices in venenatis quis, ultricies ut enim. Vivamus porttitor lobortis dui, id aliquam ipsum imperdiet non.

Removing the margin-right in the article tag fixes the issue, but now they aren't aligned correctly.

Body:
You must note that you have set a margin on the article.

The problem might be here:

article{
    margin-right:20em;
}

This pushes your article 20em's away from the right end of your display. Just remove the margin and run the code.


问:
Using class variable in @compnent animation Angular 7
I have an animation that is expanding the height on hover. I am taking the height of the label in ngOnInit because that label is auto height and doesn't animate properly with just :hover this is my ts @Component with the animation:

```<code>@Component({
  selector: 'app-create',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css'],
  animations: [
    trigger('buttonState', [
      state('inactive', style({
        height: '100%'
       })),
      state('active', style({
        height: this.buttonHeight
       })),
      transition('inactive => active', animate('1.5s ease-in')),
      transition('active => inactive', animate('1.5s ease-out'))
    ])
  ]
})
</code>```

The problem is that the this.buttonHeight gives me Cannot read property 'buttonHeight' of undefined. I guess that 'this' is not the class in the @Compnent or is not defined yet. How can I make it work?

This is how i take the height:

```<code>  @ViewChild('button') button : ElementRef;
  buttonHeight : number;

  ngOnInit() {
    this.buttonHeight = this.button.nativeElement.offsetHeight
  }
</code>```

In html:

```<code><label [@buttonState]="state" (mouseover)="toggleState()" (mouseout)="toggleState()">
</code>```

答:
I don't see how this can be bind to the component instance, because it is used in an array instead of a function that could be bind somehow. I haven't found this possibility on documentation either.
I think what you want to accomplish can be done with CSS.

```<code>@Component({
  selector: 'app-create',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css']
})
export class Create implements OnInit {
  @ViewChild('button') button : ElementRef;
  buttonHeight : number;
  isActive = false;

  animate() {
   isActive = !isActive;
   if (isActive) {
     this.buttonState.nativeElment.height = `${this.buttonHeight}px`;
   } else {
     this.buttonState.nativeElment.height = '100%';
   }
  }
  ngOnInit() {
    this.buttonHeight = this.button.nativeElement.offsetHeight
  }

</code>```

.active {
  transition: all 1.5s ease-out;
}

.inactive {
  transition: all 1.5s ease-in;
}
```

<pre class="lang-html prettyprint-override"><code><label [ngClass]="{active: isActive, inactive: !isActive}" (mouseover)="animate()" (mouseout)="animate()">
</code>```

Body:
I have an animation that is expanding the height on hover. I am taking the height of the label in ngOnInit because that label is auto height and doesn't animate properly with just :hover this is my ts @Component with the animation:

@Component({
  selector: 'app-create',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css'],
  animations: [
    trigger('buttonState', [
      state('inactive', style({
        height: '100%'
       })),
      state('active', style({
        height: this.buttonHeight
       })),
      transition('inactive => active', animate('1.5s ease-in')),
      transition('active => inactive', animate('1.5s ease-out'))
    ])
  ]
})

The problem is that the this.buttonHeight gives me Cannot read property 'buttonHeight' of undefined. I guess that 'this' is not the class in the @Compnent or is not defined yet. How can I make it work?

This is how i take the height:

  @ViewChild('button') button : ElementRef;
  buttonHeight : number;

  ngOnInit() {
    this.buttonHeight = this.button.nativeElement.offsetHeight
  }

In html:

Body:
I don't see how this can be bind to the component instance, because it is used in an array instead of a function that could be bind somehow. I haven't found this possibility on documentation either.
I think what you want to accomplish can be done with CSS.

@Component({
  selector: 'app-create',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css']
})
export class Create implements OnInit {
  @ViewChild('button') button : ElementRef;
  buttonHeight : number;
  isActive = false;

  animate() {
   isActive = !isActive;
   if (isActive) {
     this.buttonState.nativeElment.height = `${this.buttonHeight}px`;
   } else {
     this.buttonState.nativeElment.height = '100%';
   }
  }
  ngOnInit() {
    this.buttonHeight = this.button.nativeElement.offsetHeight
  }

.active {
  transition: all 1.5s ease-out;
}

.inactive {
  transition: all 1.5s ease-in;
}

<label [ngClass]="{active: isActive, inactive: !isActive}" (mouseover)="animate()" (mouseout)="animate()">


问:
Warning "Potential leak of an object allocated on line ..." when declaring a 2D array
Initially i declared a 2D array in this way:

```<code>subUrb = [[NSArray alloc] initWithObjects:
     [[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"East",@"South", @"West", @"North", nil] ,
     [[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"Kuala Lumpur SubUrb1", @"Kuala Lumpur SubUrb2", nil],
     [[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"Jakarta SubUrb1",nil],
     nil];
</code>```

But when i try to 'analyze' the warnings of the project, i got three same type of issues in this chunk of code - "potential leak of an object allocated on line xxx"

I noticed that to get rid of it, i have to write sth like this:

```<code>subUrb =
    [[NSArray alloc] initWithObjects:
        [[[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"East",@"South", @"West", @"North", nil] autorelease],
        [[[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"Kuala Lumpur SubUrb1", @"Kuala Lumpur SubUrb2", nil] autorelease],
        [[[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"Jakarta SubUrb1",nil] autorelease],
        nil];
</code>```

Then i will not get any analyze warnings. But i dun like this...it is not logical. This 2D array should never be released in my controller actually, the entire 2D array should be retained for the entire life time of the controller for a PickerView.

How should I declare the 2D array more elegantly?

答: When you add a child array to the parent array, the parent array retains the child array. Thus increasing the retain count to 2.  Since you're aren't keeping a reference to the child array(s) anywhere else the retain count should only be 1, hence you should use autorelease.  So your second version is correct.</p>

Body:
Initially i declared a 2D array in this way:

subUrb = [[NSArray alloc] initWithObjects:
     [[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"East",@"South", @"West", @"North", nil] ,
     [[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"Kuala Lumpur SubUrb1", @"Kuala Lumpur SubUrb2", nil],
     [[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"Jakarta SubUrb1",nil],
     nil];

But when i try to 'analyze' the warnings of the project, i got three same type of issues in this chunk of code - "potential leak of an object allocated on line xxx"

I noticed that to get rid of it, i have to write sth like this:

subUrb =
    [[NSArray alloc] initWithObjects:
        [[[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"East",@"South", @"West", @"North", nil] autorelease],
        [[[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"Kuala Lumpur SubUrb1", @"Kuala Lumpur SubUrb2", nil] autorelease],
        [[[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"Jakarta SubUrb1",nil] autorelease],
        nil];

Then i will not get any analyze warnings. But i dun like this...it is not logical. This 2D array should never be released in my controller actually, the entire 2D array should be retained for the entire life time of the controller for a PickerView.

How should I declare the 2D array more elegantly?


问:
How I can retrieve Latest NAV for Mutual Fund from Amfi RSS site
favorite  Hello Everyone,

I want retrieve daily latest NAV based on AMFI RSS Feeds tell me how I can retrieve it.

Thanks..

答:
I assume you know basic excel. Here is how you can get the AMFI Mutual Fund data using an excel connection. To get the current date data in a excel sheet create a connection to AMFI (current working URL is   https://www.amfiindia.com/spages/NAVAll.txt ) Once you have raw data in excel, use TextToColumn function to split the data across columns, then use formula to pick column that you need.

You can use this samlle formula to extract data you want from the downloaded data (13Feb is worksheet name)
=IFERROR(INDEX('13Feb'!$E$1:'13Feb'!$E$119999,MATCH(B2,'13Feb'!$B$1:'13Feb'!$B$119999,0)), "***")

The image below is self explanatory.

ContentLicense: CC BY-SA 2.5


问:
Wait 50 run loop ticks in iOS
I would like to wait for the run loop to run and the screen to be rendered 50 times before performing an operation.

Is it necessary to use CAMediaTiming and a counter for that? Is there a way to hook into the NSRunLoop directly? Can I achieve this using 50 nested DispatchQueue.async calls like so?

import Dispatch

func wait(ticks: UInt, queue: DispatchQueue = DispatchQueue.main, _ handler: @escaping () -> Void) {
    var ticks = ticks

    func predicate() {
        queue.async {
            ticks -= 1
            if ticks < 1 {
                handler()
                return
            }
            queue.async(execute: predicate)
        }
    }

    predicate()
}
```

EDIT: if anyone is wondering, the snippet does work and it performs very well when we're talking about apps run loop.

答:
You can use CADisplayLink, which is called every screen update.

```<code>let displayLink = CADisplayLink(target: self, selector: #selector(drawFunction(displayLink:)))
displayLink.add(to: .main, forMode: .commonModes)
</code>```

In drawFunction (or predicate, etc.) we can subtract from ticks. When they reach 0, we've hit the 50th frame and invalidate displayLink.

```<code>var ticks = 50
@objc private func drawFunction(displayLink: CADisplayLink) {
    doSomething()
    ticks -= 1
    if ticks == 0 {
        displayLink.invalidate()
        displayLink = nil
        return
    }
}
</code>```

CADisplayLink can also provide the amount of time between frames. A similar discussion can be found here. If you're concerned about absolute accuracy here, you could calculate the time between frames. From the docs:

The duration property provides the amount of time between frames at the maximumFramesPerSecond. To calculate the actual frame duration, use targetTimestamp - timestamp. You can use this value in your application to calculate the frame rate of the display, the approximate time that the next frame will be displayed, and to adjust the drawing behavior so that the next frame is prepared in time to be displayed.

Title: Wait 50 run loop ticks in iOS

Body:
I would like to wait for the run loop to run and the screen to be rendered 50 times before performing an operation.

Is it necessary to use CAMediaTiming and a counter for that? Is there a way to hook into the NSRunLoop directly? Can I achieve this using 50 nested DispatchQueue.async calls like so?

import Dispatch

func wait(ticks: UInt, queue: DispatchQueue = DispatchQueue.main, _ handler: @escaping () -> Void) {
    var ticks = ticks

    func predicate() {
        queue.async {
            ticks -= 1
            if ticks < 1 {
                handler()
                return
            }
            queue.async(execute: predicate)
        }
    }

    predicate()
}

EDIT: if anyone is wondering, the snippet does work and it performs very well when we're talking about apps run loop.

Body:
You can use CADisplayLink, which is called every screen update.

let displayLink = CADisplayLink(target: self, selector: #selector(drawFunction(displayLink:)))
displayLink.add(to: .main, forMode: .commonModes)

In drawFunction (or predicate, etc.) we can subtract from ticks. When they reach 0, we've hit the 50th frame and invalidate displayLink.

var ticks = 50
@objc private func drawFunction(displayLink: CADisplayLink) {
    doSomething()
    ticks -= 1
    if ticks == 0 {
        displayLink.invalidate()
        displayLink = nil
        return
    }
}

CADisplayLink can also provide the amount of time between frames. A similar discussion can be found here. If you're concerned about absolute accuracy here, you could calculate the time between frames. From the docs:

The duration property provides the amount of time between frames at the maximumFramesPerSecond. To calculate the actual frame duration, use targetTimestamp - timestamp. You can use this value in your application to calculate the frame rate of the display, the approximate time that the next frame will be displayed, and to adjust the drawing behavior so that the next frame is prepared in time to be displayed.


问:
Keycloak Docker HTTPS required
I have initialized https://hub.docker.com/r/jboss/keycloak/ on my Digital Ocean Docker Droplet.

$docker run -e KEYCLOAK_USER=admin -e -p 8080:8080 KEYCLOAK_PASSWORD={password with upcase etc.} jboss/keycloak

success

Everything worked well and the server started in the Droplets IP address on a port :8080.

Problems started when I entered the admin console from the UI in the URL. There was a message: "HTTPS required". This was a real issue and the only solution I have found is to login to the Keycloak from the console and to change the setting of HTTPS=required from admin console without the UI.

I then opened the bash for my Docker container :

$docker exec -it keycloak bash

success

As I entered my command to login in the keycloak/bin folder:

cd keycloak/bin

keycloak/bin $./kcadm.sh config credentials --server http://<droplet IP>:8080/auth --realm master --user admin --password {password with upcase etc.}

the bash freezes and gives a timeout message after some time

Reason for logging in from bash would be complete this:

keycloak/bin $ ./kcadm.sh update realms/master -s sslRequired=NONE.

which would hopefully solve the original problem of HTTPS required.

答:
I also experienced bash freezing when trying to config credentials.

Adding the --password argument to the config credentials command resulted in a successful execution:

```<code>./kcadm.sh config credentials --server http://localhost:8080/auth --realm master --user admin --password {YOUR_PASSWORD_HERE}
</code>```

Execute ./kcadm.sh config credentials for examples of secure/alternate ways to pass the argument.

Title: Keycloak Docker HTTPS required

Body:
I also experienced bash freezing when trying to config credentials.

Adding the --password argument to the config credentials command resulted in a successful execution:

./kcadm.sh config credentials --server http://localhost:8080/auth --realm master --user admin --password {YOUR_PASSWORD_HERE}

Execute ./kcadm.sh config credentials for examples of secure/alternate ways to pass the argument.


答:
If you don't want to change to RelativeLayout, set this attribute to the RecyclerView:

```<code>android:layout_weight="1"
</code>```

This way the RecyclerView will take all the available space pushing the BottomNavigationView to the bottom.

Title: Android LinearLayout and RecyclerView BottomNavigation Alignment

Body:
so I can't figure out how to align my bottom navigation in a LinearLayout under a RecyclerView. The items are RecyclerView:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".CategoryActivity">

   <android.support.design.widget.AppBarLayout
           android:theme="@style/AppTheme.AppBarOverlay"
           android:layout_width="match_parent"
           android:layout_height="wrap_content">

       <android.support.v7.widget.Toolbar
               android:id="@+id/toolbar"
               android:background="?attr/colorPrimary"
               app:popupTheme="@style/AppTheme.PopupOverlay"
               android:layout_width="match_parent"
               android:layout_height="?attr/actionBarSize">
       </android.support.v7.widget.Toolbar>

   </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_category"
            android:layout_margin="8dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
    </android.support.v7.widget.RecyclerView>

    <android.support.design.widget.BottomNavigationView
            android:id="@+id/nav_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?android:attr/windowBackground"
            android:layout_alignParentBottom="true"
            app:menu="@menu/bottom_nav_menu"/>

</LinearLayout>

The navigation should be always at the bottom.

Body:
If you don't want to change to RelativeLayout, set this attribute to the RecyclerView:

android:layout_weight="1"

This way the RecyclerView will take all the available space pushing the BottomNavigationView to the bottom.


问:
glGenTextures not returning a texture name
I am creating an OpenGL game on a Windows 7 machine using VS2010. In addition, SDL, QtCore, QtXML and FbxSdk are also used to assist in development. I am experiencing a very peculiar problem with glGenTextures when running outside debug mode. Let me explain.

When I compile and run the application in Debug mode, the models are textured and displayed properly. As soon as I debug the application or compile and run the application using release mode textures are no longer being applied to the models.

I have tracked down the problem to glGenTextures not giving me a valid name. It does not give me any errors either. The way I am loading everything is as follows:

Models are loaded as FBX through FbxSdk, Required textures are loaded as the model is loaded. All models are loaded in another thread, I made sure that no OpenGL functions get called anywhere while this thread is loading models. If I don't load models in another thread everything works. I tried everything I can think of including halting the main thread while the models get loaded to guarantee nothing else if happening while models get loaded. None of it works.

Again this wouldn't be as weird except compiling as debug works. Release and Debugging the application doesn't work. Any thoughts?

答:
I can only guess, but did you maybe not make the GL context current on the model loading thread? Remember that the OpenGL context is thread specific!

On the other hand, it's usually advised against to use the same GL context in different threads. Either use a different context and share resources, or defer all the GL calls to the main GL thread.

The difference when using the debugging mode is that VS will use the debug-heap when you debug, but won't use it when you just run a debug build without actual debugging.

However, if you get the threads thing wrong, all kinds of crazy side-effects can happen which the debug heap might "hide".


问:
Which polymorphism types are supported in Haskell?
Reading the Wikipedia definition of polymorphism, I come with a question:

Which polymorphism types are supported in Haskell and which are not?

Looks like Wikipedia do not contain a description for some polymorphism types like Levity Polymorphism which is new for me and supported in Haskell.

I wondering to have an extended list of Haskell Polymorphism followed with examples to explore deeply.

Looks like the main two are:

Parametric polymorphism

Ad-hoc polymorphism

答:
There are at least four things that can count as polymorphism in current Haskell:

Parametric polymorphism. (Also kind polymorphism, polymorphism in the kinds instead of the types. Which I guess is parametric polymorphism one level above, so I'm not counting it as a separate entry.)

Ad-hoc polymorphism, the one enabled by typeclasses. Introduced in the How to make ad-hoc polymorphism less ad hoc paper.

Structural polymorphism. This is the one enabled by generics. A function can work over multiple data types that have different number of fields and constructors. For example, a generic equality function for records.

Levity polymorphism. Polymorphism over calling conventions / runtime representations of types. Described in the Levity Polymorphism paper.

There are two more types of polymorphism that might be introduced in future versions of Haskell:

Matchability polymorphism. Would allow higher-order type families to work with both type constructors and type families as arguments. Described in the paper Higher-order Type-level Programming in Haskell.

Multiplicity polymorphism. Would allow higher-order functions to work with both normal functions and linear functions as arguments. Described in the paper Linear Haskell Practical Linearity in a Higher-Order Polymorphic Language.

One might ask, why this whole panoply of polymorphisms? There seems to exist an overall design principle in Haskell that, whenever some challenge could be solved with either subtyping or polymorphism, polymorphism should be preferred.

For example, from the levity polymorphism paper:

We can now present the main idea of the paper: replace sub-kinding
  with kind polymorphism.

From the paper introducing matchability polymorphism:

At first you might think that we need subtyping, but instead we turn to polymorphism

From the linear Haskell paper:

The lack of subtyping is a deliberate choice in our design

Simon Peyton Jones himself makes the point at 47:00 in this talk.

Whenever you want to use subtyping, use polymorphism instead.


问:
Change the color of a TextInput placeholder with Styled Components in React Native
How do you set the color of TextInput its placeholder with Styled Components in React Native?

I tried the following without any luck:

1.

```<code>const Input = styled.TextInput`
   border: 1px solid green;
   display: block;
   margin: 0 0 1em;

   ::placeholder {
       color: green;
   }
`
</code>```

2.

```<code>const Input = styled.TextInput`
   border: 1px solid green;
   display: block;
   margin: 0 0 1em;

   &::placeholder {
       color: green;
   }
`
</code>```

答:
To change the textinputs placeholder's text color user prperty
"placeholderTextColor"
eg</p>

```<code><TextInput
        style={{height: 40, borderColor: 'gray', borderWidth: 1}}
        onChangeText={(text) => this.setState({text})}
        placeholder = 'Enter text'
        placeholderTextColor = 'red'
        value={this.state.text}
      />
</code>```

Body:
How do you set the color of TextInput its placeholder with Styled Components in React Native?

I tried the following without any luck:

1.

const Input = styled.TextInput`
   border: 1px solid green;
   display: block;
   margin: 0 0 1em;

   ::placeholder {
       color: green;
   }
`

2.

const Input = styled.TextInput`
   border: 1px solid green;
   display: block;
   margin: 0 0 1em;

   &::placeholder {
       color: green;
   }
`

Body:
To change the textinputs placeholder's text color user prperty
"placeholderTextColor"
eg

<TextInput
        style={{height: 40, borderColor: 'gray', borderWidth: 1}}
        onChangeText={(text) => this.setState({text})}
        placeholder = 'Enter text'
        placeholderTextColor = 'red'
        value={this.state.text}
      />


答:
Could you please share the version of your Visual Studio,as i am guessing you are using old version. i.e. 15.2 or lower.
Upgrade your visual studio and the issue will be resolved.

Hope this answer helps.

Title: Intellisense for C# not working in ASP.net project | Visual Studio 2017

Body: I am making an ASP.Net application, but for some reason Intellisense is not working for the C# code. The Code is white and Errors are not shown as well. It is working great for HTML though. Does anybody know how to fix this?


答:
I think better solution to use CADisplayLink instead of Dispatch.  Here is an example:

```<code>    class Waiter {
        let handler: () -> Void
        let ticksLimit: UInt
        var ticks: UInt = 0
        var displayLink: CADisplayLink?

        init(ticks: UInt, handler: @escaping () -> Void) {
            self.handler = handler
            self.ticksLimit = ticks
        }

        func wait() {
            createDisplayLink()
        }

        private func createDisplayLink() {
            displayLink = CADisplayLink(target: self,
                                      selector: #selector(step))
            displayLink?.add(to: .current,
                        forMode: RunLoop.Mode.default)
        }

        @objc private func step(displaylink: CADisplayLink) {
            print(ticks)
            if ticks >= ticksLimit {
                displayLink?.invalidate()
                handler()
            }
            ticks += 1
        }
    }
</code>```

Here is an example of usage:

```<code>    let waiter = Waiter(ticks: 50) {
        print("Handled")
    }
    waiter.wait()
</code>```

Title: Wait 50 run loop ticks in iOS

Body:
I think better solution to use CADisplayLink instead of Dispatch.  Here is an example:

    class Waiter {
        let handler: () -> Void
        let ticksLimit: UInt
        var ticks: UInt = 0
        var displayLink: CADisplayLink?

        init(ticks: UInt, handler: @escaping () -> Void) {
            self.handler = handler
            self.ticksLimit = ticks
        }

        func wait() {
            createDisplayLink()
        }

        private func createDisplayLink() {
            displayLink = CADisplayLink(target: self,
                                      selector: #selector(step))
            displayLink?.add(to: .current,
                        forMode: RunLoop.Mode.default)
        }

        @objc private func step(displaylink: CADisplayLink) {
            print(ticks)
            if ticks >= ticksLimit {
                displayLink?.invalidate()
                handler()
            }
            ticks += 1
        }
    }

Here is an example of usage:

    let waiter = Waiter(ticks: 50) {
        print("Handled")
    }
    waiter.wait()


问:
SailsJS / Waterline : Get only specific attributes from association
I'm trying to get only the serialNumber of the tags associated to my Site model. Here is what i'm doing:

```<code>const site = await Site.findOne({
    id: siteId
}).populate('tags', { select: ['serialNumber'] });
</code>```

It doesn't work. Where is my mistake ?

答:
First it seems Models needs for populate select to work

```<code>schema: true
</code>```

And then also it will only ignore other normal attributes

Means It will still return primary key field of tags and other associative attributes also.

Body:
I'm trying to get only the serialNumber of the tags associated to my Site model. Here is what i'm doing:

const site = await Site.findOne({
    id: siteId
}).populate('tags', { select: ['serialNumber'] });

It doesn't work. Where is my mistake ?

Body:
First it seems Models needs for populate select to work

schema: true

And then also it will only ignore other normal attributes

Means It will still return primary key field of tags and other associative attributes also.


问:
How to define a morphology operation in a Neural Network as an activation function?
I recently completed a task to study how to use morphological operation as an activation function for neural networks. But I had no idea and didn't know how to use keras for custom functionality. Can anyone provide Suggestions or related papers?</p>

答:
I don't know if morphological operations will work as activation function. I don't think so.
I think you should use or combine morphological operations like dilation and erosion, and, after that, use a ReLU or softmax layer as activation function.

Morphological operations are available in tensorflow, and you can call them in your Keras application.

Reference links:

https://www.tensorflow.org/api_docs/python/tf/nn/dilation2d

https://www.tensorflow.org/api_docs/python/tf/nn/erosion2d


问:
Make container go slightly above the footer
I have a container with mainly all the content of the page with a fixed width (so not 100%) and I have a footer at the bottom that is width:100%.

I want to make that part of the container go above the footer, and that's what I came with:

https://jsfiddle.net/84weu9nz/

Doing that, as you can notice, footer content is no longer clickable or selectable, due to z-index. I could set the container to have a relative position, like  https://jsfiddle.net/rLmuq2of/, but the problem of that solution is that I can't make the whole content of the page inside a position:relative element, some popups or some functionality inside that element may have unexpected behaviours, so I don't think it is a good practice.

Any solution? Thanks.

答:
One solution i can think of is to use the css-rule for pointer-events, as long as you dont have any clickable-content in the main-element:

main {
  pointer-events: none;
}
```

<p>If you have clickable elements inside your main-element, then you must extend the rules:</p>

<pre class="lang-css prettyprint-override"><code>main {
  pointer-events: none;
}
main * {
  pointer-events: all;
}
</code>```

Example

main {
  position: relative;
  background-color: red;
  width: 400px;
  margin: 0 auto;
  pointer-events: none;
}

main * {
  pointer-events: all;
}

footer {
  background-color: green;
  padding-top: 20px;
  margin-top: -20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore clickable element et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</main>
<footer>
  <li>#1</li>
  <li>#2</li>
  <li>#3</li>
</footer></code>```

Body:
One solution i can think of is to use the css-rule for pointer-events, as long as you dont have any clickable-content in the main-element:

main {
  pointer-events: none;
}

If you have clickable elements inside your main-element, then you must extend the rules:

main {
  pointer-events: none;
}
main * {
  pointer-events: all;
}

Example

main {
  position: relative;
  background-color: red;
  width: 400px;
  margin: 0 auto;
  pointer-events: none;
}

main * {
  pointer-events: all;
}

footer {
  background-color: green;
  padding-top: 20px;
  margin-top: -20px;
}

<main>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore <a href="#">clickable element</a> et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</main>
<footer>
  <li><a href="#">#1</a></li>
  <li><a href="#">#2</a></li>
  <li><a href="#">#3</a></li>
</footer>


问:
CMake FetchContent downloads external dependencies multiple times
I started to use FetchContent for automatical download of external dependencies. It works nicely compared to older approaches but I have one problem which is probably not related to FetchContent itself - external dependencies are downloaded multiple times. I'm actually building for Android platform but that doesn't matter much.
I call CMake like this cmake -B build/arm64-v8a ... or cmake -B build/x86 .... I need separate build folders for each ABI (arm64-v8a, x86, ...) to avoid rebuilds because I switch between ABIs frequently.
But when I use simple FetchContent constructions like:

```<code>FetchContent_Declare(
  googletest
  GIT_REPOSITORY https://github.com/google/googletest.git
  GIT_TAG        release-1.8.0
)

FetchContent_GetProperties(googletest)
if(NOT googletest_POPULATED)
  FetchContent_Populate(googletest)
  add_subdirectory(${googletest_SOURCE_DIR} ${googletest_BINARY_DIR})
endif()
</code>```

it will download external project once per ABI (in other words - once per CMake call using different build folder), because googletest_POPULATED is not visible in next CMake call using different build folder. It would be awesome if sources would be downloaded once.

So I tried passing SOURCE_DIR in FetchContent_Declare to save source one level up (in build/_deps/googletest-src not build/<abi>/_deps/googletest-src folder). It saved sources correctly but re-download was still triggered as it seems that googletest-subbuild folder (located under build/<abi>/_deps) manages googletest_POPULATED flag.

How can I fix this?

答:
Try using FETCHCONTENT_BASE_DIR to share the CMake project that is created that handles downloading management.  Then make sure to use separate build directories for building the software.

```<code>cmake_minimum_required(VERSION 3.13)
project(fc_twice)

include (FetchContent)
set(FETCHCONTENT_QUIET off)
get_filename_component(fc_base "../fc_base"
                       REALPATH BASE_DIR "${CMAKE_BINARY_DIR}")
set(FETCHCONTENT_BASE_DIR ${fc_base})

FetchContent_Declare(
  googletest
  GIT_REPOSITORY https://github.com/google/googletest.git
  GIT_TAG        release-1.8.0
)

FetchContent_GetProperties(googletest)
if(NOT googletest_POPULATED)
  FetchContent_Populate(googletest)
  #create gt build directory in binary tree
  add_subdirectory(${googletest_SOURCE_DIR} gt)
endif()
</code>```

When switching between build directories some bookkeeping items are repeated but the actual download will only occur once.  You should see the message:

```<code>  Performing download step (git clone) for 'googletest-populate'
  -- Avoiding repeated git clone, stamp file is up to date: 'C:/Users/XXX/Desktop/temp/so_fc/fc_base/googletest-subbuild/googletest-populate-prefix/src/googletest-populate-stamp/googletest-populate-gitclone-lastrun.txt'
</code>```

I tested using the commands cmake -S src/ -B bld1 and cmake -S src/ -B bld2 and switched back and for building them.

Body:
I started to use FetchContent for automatical download of external dependencies. It works nicely compared to older approaches but I have one problem which is probably not related to FetchContent itself - external dependencies are downloaded multiple times. I'm actually building for Android platform but that doesn't matter much.
I call CMake like this cmake -B build/arm64-v8a ... or cmake -B build/x86 .... I need separate build folders for each ABI (arm64-v8a, x86, ...) to avoid rebuilds because I switch between ABIs frequently.
But when I use simple FetchContent constructions like:

FetchContent_Declare(
  googletest
  GIT_REPOSITORY https://github.com/google/googletest.git
  GIT_TAG        release-1.8.0
)

FetchContent_GetProperties(googletest)
if(NOT googletest_POPULATED)
  FetchContent_Populate(googletest)
  add_subdirectory(${googletest_SOURCE_DIR} ${googletest_BINARY_DIR})
endif()

it will download external project once per ABI (in other words - once per CMake call using different build folder), because googletest_POPULATED is not visible in next CMake call using different build folder. It would be awesome if sources would be downloaded once.

So I tried passing SOURCE_DIR in FetchContent_Declare to save source one level up (in build/_deps/googletest-src not build/<abi>/_deps/googletest-src folder). It saved sources correctly but re-download was still triggered as it seems that googletest-subbuild folder (located under build/<abi>/_deps) manages googletest_POPULATED flag.

How can I fix this?

Body:
Try using FETCHCONTENT_BASE_DIR to share the CMake project that is created that handles downloading management.  Then make sure to use separate build directories for building the software.

cmake_minimum_required(VERSION 3.13)
project(fc_twice)

include (FetchContent)
set(FETCHCONTENT_QUIET off)
get_filename_component(fc_base "../fc_base"
                       REALPATH BASE_DIR "${CMAKE_BINARY_DIR}")
set(FETCHCONTENT_BASE_DIR ${fc_base})

FetchContent_Declare(
  googletest
  GIT_REPOSITORY https://github.com/google/googletest.git
  GIT_TAG        release-1.8.0
)

FetchContent_GetProperties(googletest)
if(NOT googletest_POPULATED)
  FetchContent_Populate(googletest)
  #create gt build directory in binary tree
  add_subdirectory(${googletest_SOURCE_DIR} gt)
endif()

When switching between build directories some bookkeeping items are repeated but the actual download will only occur once.  You should see the message:

  Performing download step (git clone) for 'googletest-populate'
  -- Avoiding repeated git clone, stamp file is up to date: 'C:/Users/XXX/Desktop/temp/so_fc/fc_base/googletest-subbuild/googletest-populate-prefix/src/googletest-populate-stamp/googletest-populate-gitclone-lastrun.txt'

I tested using the commands cmake -S src/ -B bld1 and cmake -S src/ -B bld2 and switched back and for building them.


问:
Jcarousel lite not showing up on page load in safari and chrome
I have this plug-in in use on my home page which is running on WAMP. It works great in every browser except Safari and Google Chrome. In those browsers the carousel doesn’t show up when I first load the page, nor when I hit reload. When I navigate to the home page via the on page navigation link then it shows up.

Any ideas what could be causing this?

Thanks,
Jeremy

答:
I faced the similar issue. Make sure you are giving width and height to your images.
For some reason google chrome and safari are not fetching/calculating the height/width automatically.</p>

OwnerDisplayName: Jeremy


问:
how to convert post values form '_' to '.' in php
```<code>if (isset($_POST['reg_user'])) {
    // receive all input values from the form
    $CUSTOMER_ID=($_POST['customerid']);
    $CUST_TYPE = ($_POST['customer_type']);
    $APP_DATE=( $_POST['input_date']);
    $PRODUCT_ID = ( $_POST['productid']);
    $ACTION = ($_POST['new_loan']);
    $CURRENCY= ($_POST['currency']);
    $LOAN_PURPOSE = ( $_POST['loan_purpose']);
    $AA_SECTOR= ( $_POST['aa_sector']);
    $GU_RECORD_ID=( $_POST['record_id']);
    $DISB_ACCOUNT = ( $_POST['disb_account']);
    $REPAY_ACCOUNT= ( $_POST['repay_account']);
    $CHARGE_ACCOUNT=($_POST['charge_account']);
</code>```

I want to convert my values to have '.' eg.  $CUSTOMER_ID to $CUSTOMER.ID, CUST_TYPE to CUST.TYPE

答:
```<code>$subject = 'CUST_TYPE';
$pattern = '/_/';
$replacement = '.';

$result = preg_replace($pattern, $replacement, $subject);

echo $result;
</code>```

gives:

```<code>CUST.TYPE
</code>```

so the quick and dirty solution is:

```<code>$pattern = '/_/';
$replacement = '.';

$CUSTOMER_ID=($_POST['customerid']);
$CUST_TYPE = ($_POST['customer_type']);
$APP_DATE=( $_POST['input_date']);
$PRODUCT_ID = ( $_POST['productid']);
$ACTION = ($_POST['new_loan']);
$CURRENCY= ($_POST['currency']);
$LOAN_PURPOSE = ( $_POST['loan_purpose']);
$AA_SECTOR= ( $_POST['aa_sector']);
$GU_RECORD_ID=( $_POST['record_id']);
$DISB_ACCOUNT = ( $_POST['disb_account']);
$REPAY_ACCOUNT= ( $_POST['repay_account']);
$CHARGE_ACCOUNT=($_POST['charge_account']);

$CUSTOMER_ID= preg_replace($pattern, $replacement, $CUSTOMER_ID);
$CUST_TYPE = preg_replace($pattern, $replacement, $CUST_TYPE);
$APP_DATE= preg_replace($pattern, $replacement, $APP_DATE);
$PRODUCT_ID = preg_replace($pattern, $replacement, $PRODUCT_ID);
$ACTION = preg_replace($pattern, $replacement, $ACTION);
$CURRENCY= preg_replace($pattern, $replacement, $CURRENCY);
$LOAN_PURPOSE = preg_replace($pattern, $replacement, $LOAN_PURPOSE);
$AA_SECTOR= preg_replace($pattern, $replacement, $AA_SECTOR);
$GU_RECORD_ID= preg_replace($pattern, $replacement, $GU_RECORD_ID);
$DISB_ACCOUNT = preg_replace($pattern, $replacement, $DISB_ACCOUNT);
$REPAY_ACCOUNT= preg_replace($pattern, $replacement, $REPAY_ACCOUNT);
$CHARGE_ACCOUNT= preg_replace($pattern, $replacement, $CHARGE_ACCOUNT);
</code>```

Body:
if (isset($_POST['reg_user'])) {
    // receive all input values from the form
    $CUSTOMER_ID=($_POST['customerid']);
    $CUST_TYPE = ($_POST['customer_type']);
    $APP_DATE=( $_POST['input_date']);
    $PRODUCT_ID = ( $_POST['productid']);
    $ACTION = ($_POST['new_loan']);
    $CURRENCY= ($_POST['currency']);
    $LOAN_PURPOSE = ( $_POST['loan_purpose']);
    $AA_SECTOR= ( $_POST['aa_sector']);
    $GU_RECORD_ID=( $_POST['record_id']);
    $DISB_ACCOUNT = ( $_POST['disb_account']);
    $REPAY_ACCOUNT= ( $_POST['repay_account']);
    $CHARGE_ACCOUNT=($_POST['charge_account']);

I want to convert my values to have '.' eg.  $CUSTOMER_ID to $CUSTOMER.ID, CUST_TYPE to CUST.TYPE

Body:
$subject = 'CUST_TYPE';
$pattern = '/_/';
$replacement = '.';

$result = preg_replace($pattern, $replacement, $subject);

echo $result;

gives:

CUST.TYPE

so the quick and dirty solution is:

$pattern = '/_/';
$replacement = '.';

$CUSTOMER_ID=($_POST['customerid']);
$CUST_TYPE = ($_POST['customer_type']);
$APP_DATE=( $_POST['input_date']);
$PRODUCT_ID = ( $_POST['productid']);
$ACTION = ($_POST['new_loan']);
$CURRENCY= ($_POST['currency']);
$LOAN_PURPOSE = ( $_POST['loan_purpose']);
$AA_SECTOR= ( $_POST['aa_sector']);
$GU_RECORD_ID=( $_POST['record_id']);
$DISB_ACCOUNT = ( $_POST['disb_account']);
$REPAY_ACCOUNT= ( $_POST['repay_account']);
$CHARGE_ACCOUNT=($_POST['charge_account']);

$CUSTOMER_ID= preg_replace($pattern, $replacement, $CUSTOMER_ID);
$CUST_TYPE = preg_replace($pattern, $replacement, $CUST_TYPE);
$APP_DATE= preg_replace($pattern, $replacement, $APP_DATE);
$PRODUCT_ID = preg_replace($pattern, $replacement, $PRODUCT_ID);
$ACTION = preg_replace($pattern, $replacement, $ACTION);
$CURRENCY= preg_replace($pattern, $replacement, $CURRENCY);
$LOAN_PURPOSE = preg_replace($pattern, $replacement, $LOAN_PURPOSE);
$AA_SECTOR= preg_replace($pattern, $replacement, $AA_SECTOR);
$GU_RECORD_ID= preg_replace($pattern, $replacement, $GU_RECORD_ID);
$DISB_ACCOUNT = preg_replace($pattern, $replacement, $DISB_ACCOUNT);
$REPAY_ACCOUNT= preg_replace($pattern, $replacement, $REPAY_ACCOUNT);
$CHARGE_ACCOUNT= preg_replace($pattern, $replacement, $CHARGE_ACCOUNT);


问:
join previous line with next depending of pattern of previous line
I have this Input:

```<code>1 a
a
2 b b
3 c
c
4 d d
5 e e
6 f
f
7 g
g
</code>```

I want this output using sed command

```<code>1 a a
2 b b
3 c c
4 d d
5 e e
6 f f
7 g g
</code>```

I'm trying this without success

```<code>sed '/^[^0-9]/ x; N; { s/\n/ / }; n' file
</code>```

答:
```<code>awk 'NR>1 && /^[0-9]/ {print substr(s,2); s=""} {s=s FS $0} END {print substr(s,2)}' file
</code>```

NR>1 && /^[0-9]/: If a line is not the first and begins with a digit,

{print substr(s,2); s=""}: print "s" without the leading space, then clear it.

{s=s FS $0}: On every line, append the current line to the value of "s". FS is a space by default.

edit: Added END condition to catch last line, hated it, made a better separate answer.

Body:
I have this Input:

1 a
a
2 b b
3 c
c
4 d d
5 e e
6 f
f
7 g
g

I want this output using sed command

1 a a
2 b b
3 c c
4 d d
5 e e
6 f f
7 g g

I'm trying this without success

sed '/^[^0-9]/ x; N; { s/\n/ / }; n' file

Body:
awk 'NR>1 && /^[0-9]/ {print substr(s,2); s=""} {s=s FS $0} END {print substr(s,2)}' file

NR>1 && /^[0-9]/: If a line is not the first and begins with a digit,

{print substr(s,2); s=""}: print "s" without the leading space, then clear it.

{s=s FS $0}: On every line, append the current line to the value of "s". FS is a space by default.

edit: Added END condition to catch last line, hated it, made a better separate answer.