问:
Can I use IDXGIFactory2::CreateSwapChainForHwnd for directx 11.0
As I undrestood, IDXGIFactory2::CreateSwapChainForHwnd was added in DXGI 1.2 API so if the method D3D11CreateDevice will return pFeatureLevel equal D3D_FEATURE_LEVEL_11_0 we able to use only DXGI 1.1 API, therefore we should call IDXGIFactory::CreateSwapChain instead of IDXGIFactory2::CreateSwapChainForHwnd. Am I right?</p>
```<code>    HRESULT D3D11CreateDevice(
  [in, optional]  IDXGIAdapter            *pAdapter,
                  D3D_DRIVER_TYPE         DriverType,
                  HMODULE                 Software,
                  UINT                    Flags,
  [in, optional]  const D3D_FEATURE_LEVEL *pFeatureLevels,
                  UINT                    FeatureLevels,
                  UINT                    SDKVersion,
  [out, optional] ID3D11Device            **ppDevice,
  [out, optional] D3D_FEATURE_LEVEL       *pFeatureLevel,
  [out, optional] ID3D11DeviceContext     **ppImmediateContex
</code>```

答:
My guess here is that your customer is running Windows 7, and is missing the DirectX 11.1 Runtime which is installed by the KB2670838 update.

See Microsoft Docs, as well as this blog post and this follow-up post.

It's probably best to just tell customers you require KB 2670838 if they are using Windows 7. Supporting the DirectX 11.0 Runtime is certainly possible, but there are a number of quirks and you have to use DXGI 1.1 interfaces for the swapchain. See this blog post.

KB 2670838 is also available from Microsoft Download as MSU files if the customer has Internet access issues.

You should recheck the error handling of your application. You should have gotten an error HRESULT when you tried to QueryInterface the IDXGIFactory2 interface if the system only had DirectX 11.0 on it. Remember if a function returns HRESULT, it's not safe to ignore the return value: Use FAILED or SUCCEEDED or a fast-fail like ThrowIfFailed to make sure you hit the failure when it happens and not sometime later.

These days it's best to require Windows 7 Service Pack 1 if you support Windows 7. For example, the last few releases of Visual C++ only support Windows 7 SP1. That said, KB2670838 is not included in the Service Pack 1 package. It's pushed out via Windows Update as a recommended update, but if you have WU turned off or have created a fresh install of even Windows 7 SP1, you can be missing it. Note that KB2670838 doesn't support Windows 7 RTM in any case.

Don't use 'Direct3D Hardware Feature Level' to infer the supported DirectX APIs. It's best to just QueryInterface for the ID3D11Device1 if you want to check after creating the ID3D11Device to see if DirectX 11.1 is present, but a more direct test is to try to QUeryInterface the IDXGIFactory2 interface.

Body:
As I undrestood, IDXGIFactory2::CreateSwapChainForHwnd was added in DXGI 1.2 API so if the method D3D11CreateDevice will return pFeatureLevel equal D3D_FEATURE_LEVEL_11_0 we able to use only DXGI 1.1 API, therefore we should call IDXGIFactory::CreateSwapChain instead of IDXGIFactory2::CreateSwapChainForHwnd. Am I right?

    HRESULT D3D11CreateDevice(
  [in, optional]  IDXGIAdapter            *pAdapter,
                  D3D_DRIVER_TYPE         DriverType,
                  HMODULE                 Software,
                  UINT                    Flags,
  [in, optional]  const D3D_FEATURE_LEVEL *pFeatureLevels,
                  UINT                    FeatureLevels,
                  UINT                    SDKVersion,
  [out, optional] ID3D11Device            **ppDevice,
  [out, optional] D3D_FEATURE_LEVEL       *pFeatureLevel,
  [out, optional] ID3D11DeviceContext     **ppImmediateContex


来源: stackexchange

问:
Package cairo was not found in the pkg-config search path. Node j.s install canvas issue
I am having a problem installing installing the canvas module in node..It seems to be something with cairo I am getting this error...

```<code>npm http GET https://registry.npmjs.org/canvas
npm http 304 https://registry.npmjs.org/canvas
npm http GET https://registry.npmjs.org/nan
npm http 304 https://registry.npmjs.org/nan

> canvas@1.1.3 install /Users/plimb/Desktop/motion-therapy/node_modules/canvas
> node-gyp rebuild

Package cairo was not found in the pkg-config search path.
Perhaps you should add the directory containing `cairo.pc'
to the PKG_CONFIG_PATH environment variable
No package 'cairo' found
gyp: Call to './util/has_cairo_freetype.sh' returned exit status 0. while trying to load binding.gyp
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:424:16)
gyp ERR! stack     at ChildProcess.EventEmitter.emit (events.js:98:17)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (child_process.js:789:12)
gyp ERR! System Darwin 13.0.0
gyp ERR! command "node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/plimb/Desktop/motion-therapy/node_modules/canvas
gyp ERR! node -v v0.10.21
gyp ERR! node-gyp -v v0.10.10
gyp ERR! not ok
npm ERR! weird error 1
npm ERR! not ok code 0
</code>```

I'm not sure what it all means! Would appreciate any help!For example how to a mkdir cairo pc in the pkg_config_path environment variable?

答:
Try this on mac:</p>
```<code>brew install pkg-config cairo pango libpng jpeg giflib
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am having a problem installing installing the canvas module in node..It seems to be something with cairo I am getting this error...

npm http GET https://registry.npmjs.org/canvas
npm http 304 https://registry.npmjs.org/canvas
npm http GET https://registry.npmjs.org/nan
npm http 304 https://registry.npmjs.org/nan

> canvas@1.1.3 install /Users/plimb/Desktop/motion-therapy/node_modules/canvas
> node-gyp rebuild

Package cairo was not found in the pkg-config search path.
Perhaps you should add the directory containing `cairo.pc'
to the PKG_CONFIG_PATH environment variable
No package 'cairo' found
gyp: Call to './util/has_cairo_freetype.sh' returned exit status 0. while trying to load binding.gyp
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:424:16)
gyp ERR! stack     at ChildProcess.EventEmitter.emit (events.js:98:17)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (child_process.js:789:12)
gyp ERR! System Darwin 13.0.0
gyp ERR! command "node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/plimb/Desktop/motion-therapy/node_modules/canvas
gyp ERR! node -v v0.10.21
gyp ERR! node-gyp -v v0.10.10
gyp ERR! not ok
npm ERR! weird error 1
npm ERR! not ok code 0

I'm not sure what it all means! Would appreciate any help!For example how to a mkdir cairo pc in the pkg_config_path environment variable?

Body:
Try this on mac:

brew install pkg-config cairo pango libpng jpeg giflib


问:
What is $$ and $x in Chrome Javascript console?
I saw Chrome's autocomplete suggestions when I was testing JQuery and saw $$ and $x are defined. What are they and where did they come from? I saw What is the variable $x used for in Chrome?, but what is $$?

```<code>> $
  function ( selector, context ) {
        // The jQuery object is actually just the init constructor 'enhanced'
        return new jQuery.fn.init( selector, context, rootjQuery );
    } jquery.js?body=1:62
> $$
  function $$() { [Command Line API] }
> $x
  function $x() { [Command Line API] }
</code>```

This is something ogooglebar.

答: There is also $x() function for those who want to use xpath

ContentLicense: CC BY-SA 3.0

Body:
I saw Chrome's autocomplete suggestions when I was testing JQuery and saw $$ and $x are defined. What are they and where did they come from? I saw What is the variable $x used for in Chrome?, but what is $$?

> $
  function ( selector, context ) {
        // The jQuery object is actually just the init constructor 'enhanced'
        return new jQuery.fn.init( selector, context, rootjQuery );
    } jquery.js?body=1:62
> $$
  function $$() { [Command Line API] }
> $x
  function $x() { [Command Line API] }

This is something ogooglebar.


问:
EFCore5, using FromSqlRaw and [Owned] attribute
I am trying to take advantage of the EF Core "[Owned]" attribute when returning data from a stored procedure. My model is as follows...

```<code>[Keyless]
public class TestResult
{

    public TestResultManifest Manifest { get; set; } = new TestResultManifest();

    public Int32 TransportJobID { get; set; }

}

[Owned]
public class TestResultManifest
{

    public Int32 ManifestID { get; set; }

}
</code>```

and this is implemented within my DbContext as follows...

```<code>public DbSet<TestResult> TestItems { get; set; }

public async Task<List<TestResult>> SelectTestItemsAsync()
{
    return await TestItems.FromSqlRaw($"EXECUTE [dbo].[SelectTestItems]").ToListAsync();
}
</code>```

It is my understanding from here that when this is mapped directly to a physical table it would result in columns named "TransportJobID" and "Manifest_ManifestID", therefore I am using the following stored procedure to pull back the necessary data...

```<code>CREATE PROCEDURE [dbo].[SelectTestItems]

as

    select Manifest_ManifestID = 3,
        TransportJobID = 22;

    return @@error;
</code>```

Which as you would expect results in...

However, whenever I run this I get a NullReferenceException thrown deep inside Entity Framework...

```<code>System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder.HasRelationship(EntityType targetEntityType, Nullable`1 navigationToTarget, Nullable`1 inverseNavigation, Nullable`1 setTargetAsPrincipal, ConfigurationSource configurationSource, Nullable`1 required)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder.HasOwnership(TypeIdentity& targetEntityType, MemberIdentity navigation, Nullable`1 inverse, ConfigurationSource configurationSource)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder.HasOwnership(Type targetEntityType, MemberInfo navigationMember, ConfigurationSource configurationSource)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder.Microsoft.EntityFrameworkCore.Metadata.Builders.IConventionEntityTypeBuilder.HasOwnership(Type targetEntityType, MemberInfo navigation, Boolean fromDataAnnotation)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.RelationshipDiscoveryConvention.CreateRelationships(IEnumerable`1 relationshipCandidates, IConventionEntityTypeBuilder entityTypeBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.RelationshipDiscoveryConvention.DiscoverRelationships(IConventionEntityTypeBuilder entityTypeBuilder, IConventionContext context)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.RelationshipDiscoveryConvention.Process(IConventionEntityType entityType, String navigationName, MemberInfo memberInfo, IConventionContext context)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.RelationshipDiscoveryConvention.ProcessNavigationRemoved(IConventionEntityTypeBuilder sourceEntityTypeBuilder, IConventionEntityTypeBuilder targetEntityTypeBuilder, String navigationName, MemberInfo memberInfo, IConventionContext`1 context)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnNavigationRemoved(IConventionEntityTypeBuilder sourceEntityTypeBuilder, IConventionEntityTypeBuilder targetEntityTypeBuilder, String navigationName, MemberInfo memberInfo)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnNavigationRemovedNode.Run(ConventionDispatcher dispatcher)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.DelayedConventionScope.Run(ConventionDispatcher dispatcher)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ConventionBatch.Run()
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ConventionBatch.Dispose()
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnModelInitialized(IConventionModelBuilder modelBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnModelInitialized(IConventionModelBuilder modelBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.Model..ctor(ConventionSet conventions, ModelDependencies modelDependencies)
   at Microsoft.EntityFrameworkCore.ModelBuilder..ctor(ConventionSet conventions, ModelDependencies modelDependencies, Boolean _)
   at Microsoft.EntityFrameworkCore.ModelBuilder..ctor(ConventionSet conventions, ModelDependencies modelDependencies)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, ModelDependencies modelDependencies)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder, ModelDependencies modelDependencies)
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
   at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.<>c.<TryAddCoreServices>b__7_3(IServiceProvider p)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.get_Model()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityType()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.CheckState()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityQueryable()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.System.Linq.IQueryable.get_Provider()
   at Microsoft.EntityFrameworkCore.RelationalQueryableExtensions.FromSqlRaw[TEntity](DbSet`1 source, String sql, Object[] parameters)
</code>```

I would expect this to work given that I am merely using (what I believe to be) standard functionality - at least I would have thought it would work if mapped to a real table and retrieved via LINQ and Entities are also supposed to be retrievable using FromRawSql(...); can anybody please explain what I am doing wrong and/or missing.

I don't expect this to make any difference, but the underlying database being used is SQL2014.

EDIT #1:

I Have just discovered that another FromSqlRaw method call within the same context also now fails when the DbSet<TestResult> TestItems {get; set;} is included within the DbContext.

This FromSqlRaw call worked previously and works again if I comment out the DbSet<TestResult> TestItems {get; set;} which make me think this is an issue with the configuration of the TestResult and or TestResultManifest classes?

EDIT #2:

I have tried flattening the result class...

```<code>public class TestResult2
{

    public Int32 Manifest_ManifestID { get; set; }

    public Int32 TransportJobID { get; set; }

}
</code>```

If I now use the same FromSqlRaw to call the same stored procedure (though with the result type changed to TestResult2 of course), this works. It therefore has to be something to do with the configuration of the [Owned] entity.

EDIT #3

Following the advice from @ivan-stoev, I tried changing the model as follows since the TransportJobID property could be made unique...

```<code>public class TestResult
{

    public TestResultManifest Manifest { get; set; } = new TestResultManifest();

    [Key]
    public Int32 TransportJobID { get; set; }

}

[Owned]
public class TestResultManifest
{

    public Int32 ManifestID { get; set; }

}
</code>```

This instead resulted in a new exception...

```<code>An unhandled exception of type 'System.InvalidOperationException' occurred in System.Private.CoreLib.dll
'FromSqlRaw' or 'FromSqlInterpolated' was called with non-composable SQL and with a query composing over it. Consider calling 'AsEnumerable' after the method to perform the composition on the client side.
</code>```

As a result, I then tried...

```<code>var e = TestItems.FromSqlRaw($"EXECUTE [dbo].[SelectTestItems]").AsEnumerable();
</code>```

And this too resulted in the same exception.

答:
I had the same problem with dotnet core 5.0 and 6.0 and I solved it like this:

Install the nuget package System.Linq.Async depending of you dotnet version https://www.nuget.org/packages/System.Linq.Async

and then in your query you would be able to add the .ToAsyncEnumerable()

This a example in case you use async method:

```<code>        public async Task<IEnumerable<ProductTableView>> GetProduct(Pagination pagination, string identifier)
    {

        var ListProductsTable = await _context.ModelView
                                       .FromSqlRaw("GetProductByIdentifier {0}", identifier)
                                       .ToAsyncEnumerable()
                                       .Select(a => new ProductTableView
                                       {
                                           ID = a.ID,
                                           Guid = a.Guid,
                                           Guid_Product_Category = a.Guid_Product_Category,
                                           Guid_Currency = a.Guid_Currency,
                                           NameProduct = a.NameProduct,
                                       }).ToListAsync();

        return ListProductsTable;
    }
</code>```

In case you don't use the async method, you haven't need to add the above nuget package:

```<code>        public Task<IEnumerable<ProductTableView>> GetProduct(Pagination pagination, string identifier)
    {

        var ListProductsTable = _context.ModelView
                                       .FromSqlRaw("GetProductByIdentifier {0}", identifier)
                                       .AsEnumerable()
                                       .Select(a => new ProductTableView
                                       {
                                           ID = a.ID,
                                           Guid = a.Guid,
                                           Guid_Product_Category = a.Guid_Product_Category,
                                           Guid_Currency = a.Guid_Currency,
                                           NameProduct = a.NameProduct,
                                       }).ToList();

        return ListProductsTable;
    }
</code>```

Body:
I am trying to take advantage of the EF Core "[Owned]" attribute when returning data from a stored procedure. My model is as follows...

[Keyless]
public class TestResult
{

    public TestResultManifest Manifest { get; set; } = new TestResultManifest();

    public Int32 TransportJobID { get; set; }

}

[Owned]
public class TestResultManifest
{

    public Int32 ManifestID { get; set; }

}

and this is implemented within my DbContext as follows...

public DbSet<TestResult> TestItems { get; set; }

public async Task<List<TestResult>> SelectTestItemsAsync()
{
    return await TestItems.FromSqlRaw($"EXECUTE [dbo].[SelectTestItems]").ToListAsync();
}

It is my understanding from here that when this is mapped directly to a physical table it would result in columns named "TransportJobID" and "Manifest_ManifestID", therefore I am using the following stored procedure to pull back the necessary data...

CREATE PROCEDURE [dbo].[SelectTestItems]

as

    select Manifest_ManifestID = 3,
        TransportJobID = 22;

    return @@error;

Which as you would expect results in...

However, whenever I run this I get a NullReferenceException thrown deep inside Entity Framework...

System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder.HasRelationship(EntityType targetEntityType, Nullable`1 navigationToTarget, Nullable`1 inverseNavigation, Nullable`1 setTargetAsPrincipal, ConfigurationSource configurationSource, Nullable`1 required)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder.HasOwnership(TypeIdentity& targetEntityType, MemberIdentity navigation, Nullable`1 inverse, ConfigurationSource configurationSource)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder.HasOwnership(Type targetEntityType, MemberInfo navigationMember, ConfigurationSource configurationSource)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder.Microsoft.EntityFrameworkCore.Metadata.Builders.IConventionEntityTypeBuilder.HasOwnership(Type targetEntityType, MemberInfo navigation, Boolean fromDataAnnotation)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.RelationshipDiscoveryConvention.CreateRelationships(IEnumerable`1 relationshipCandidates, IConventionEntityTypeBuilder entityTypeBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.RelationshipDiscoveryConvention.DiscoverRelationships(IConventionEntityTypeBuilder entityTypeBuilder, IConventionContext context)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.RelationshipDiscoveryConvention.Process(IConventionEntityType entityType, String navigationName, MemberInfo memberInfo, IConventionContext context)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.RelationshipDiscoveryConvention.ProcessNavigationRemoved(IConventionEntityTypeBuilder sourceEntityTypeBuilder, IConventionEntityTypeBuilder targetEntityTypeBuilder, String navigationName, MemberInfo memberInfo, IConventionContext`1 context)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnNavigationRemoved(IConventionEntityTypeBuilder sourceEntityTypeBuilder, IConventionEntityTypeBuilder targetEntityTypeBuilder, String navigationName, MemberInfo memberInfo)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnNavigationRemovedNode.Run(ConventionDispatcher dispatcher)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.DelayedConventionScope.Run(ConventionDispatcher dispatcher)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ConventionBatch.Run()
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ConventionBatch.Dispose()
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnModelInitialized(IConventionModelBuilder modelBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnModelInitialized(IConventionModelBuilder modelBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.Model..ctor(ConventionSet conventions, ModelDependencies modelDependencies)
   at Microsoft.EntityFrameworkCore.ModelBuilder..ctor(ConventionSet conventions, ModelDependencies modelDependencies, Boolean _)
   at Microsoft.EntityFrameworkCore.ModelBuilder..ctor(ConventionSet conventions, ModelDependencies modelDependencies)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, ModelDependencies modelDependencies)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder, ModelDependencies modelDependencies)
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
   at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.<>c.<TryAddCoreServices>b__7_3(IServiceProvider p)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.get_Model()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityType()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.CheckState()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityQueryable()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.System.Linq.IQueryable.get_Provider()
   at Microsoft.EntityFrameworkCore.RelationalQueryableExtensions.FromSqlRaw[TEntity](DbSet`1 source, String sql, Object[] parameters)

I would expect this to work given that I am merely using (what I believe to be) standard functionality - at least I would have thought it would work if mapped to a real table and retrieved via LINQ and Entities are also supposed to be retrievable using FromRawSql(...); can anybody please explain what I am doing wrong and/or missing.

I don't expect this to make any difference, but the underlying database being used is SQL2014.

EDIT #1:

I Have just discovered that another FromSqlRaw method call within the same context also now fails when the DbSet<TestResult> TestItems {get; set;} is included within the DbContext.

This FromSqlRaw call worked previously and works again if I comment out the DbSet<TestResult> TestItems {get; set;} which make me think this is an issue with the configuration of the TestResult and or TestResultManifest classes?

EDIT #2:

I have tried flattening the result class...

public class TestResult2
{

    public Int32 Manifest_ManifestID { get; set; }

    public Int32 TransportJobID { get; set; }

}

If I now use the same FromSqlRaw to call the same stored procedure (though with the result type changed to TestResult2 of course), this works. It therefore has to be something to do with the configuration of the [Owned] entity.

EDIT #3

Following the advice from @ivan-stoev, I tried changing the model as follows since the TransportJobID property could be made unique...

public class TestResult
{

    public TestResultManifest Manifest { get; set; } = new TestResultManifest();

    [Key]
    public Int32 TransportJobID { get; set; }

}

[Owned]
public class TestResultManifest
{

    public Int32 ManifestID { get; set; }

}

This instead resulted in a new exception...

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Private.CoreLib.dll
'FromSqlRaw' or 'FromSqlInterpolated' was called with non-composable SQL and with a query composing over it. Consider calling 'AsEnumerable' after the method to perform the composition on the client side.

As a result, I then tried...

var e = TestItems.FromSqlRaw($"EXECUTE [dbo].[SelectTestItems]").AsEnumerable();

And this too resulted in the same exception.

Body:
I had the same problem with dotnet core 5.0 and 6.0 and I solved it like this:

Install the nuget package System.Linq.Async depending of you dotnet version https://www.nuget.org/packages/System.Linq.Async

and then in your query you would be able to add the .ToAsyncEnumerable()

This a example in case you use async method:

        public async Task<IEnumerable<ProductTableView>> GetProduct(Pagination pagination, string identifier)
    {

        var ListProductsTable = await _context.ModelView
                                       .FromSqlRaw("GetProductByIdentifier {0}", identifier)
                                       .ToAsyncEnumerable()
                                       .Select(a => new ProductTableView
                                       {
                                           ID = a.ID,
                                           Guid = a.Guid,
                                           Guid_Product_Category = a.Guid_Product_Category,
                                           Guid_Currency = a.Guid_Currency,
                                           NameProduct = a.NameProduct,
                                       }).ToListAsync();

        return ListProductsTable;
    }

In case you don't use the async method, you haven't need to add the above nuget package:

        public Task<IEnumerable<ProductTableView>> GetProduct(Pagination pagination, string identifier)
    {

        var ListProductsTable = _context.ModelView
                                       .FromSqlRaw("GetProductByIdentifier {0}", identifier)
                                       .AsEnumerable()
                                       .Select(a => new ProductTableView
                                       {
                                           ID = a.ID,
                                           Guid = a.Guid,
                                           Guid_Product_Category = a.Guid_Product_Category,
                                           Guid_Currency = a.Guid_Currency,
                                           NameProduct = a.NameProduct,
                                       }).ToList();

        return ListProductsTable;
    }


问:
Azure DevOps REST API Response doesn't contain results when using $top parameter in Wiql request
I'm using this Azure API to request workitems from our server.
Unfortunately if I set the $top parameter in the URL to some value the response doesn't return any resulting workitems. I don't get any error message. If don't set the $top parameter everything works fine and I get all workitems that matched the query.

My request looks like this:

```<code>POST https://dev.azure.com/{organization}/{project}/{team}/_apis/wit/wiql?$top=5&api-version=5.1
</code>```

With the request body:

```<code>SELECT [System.Id] FROM WorkItems WHERE [System.Id] > 0 ORDER BY [System.Id] ASC
</code>```

The response looks like this:

{
  "asOf": "2022-02-08T11:20:45.633Z",
  "columns": [
    {
      "name": "ID",
      "referenceName": "System.Id",
      "url": "https://dev.azure.com/{organization}/{project}/{team}/_apis/wit/fields/System.Id"
    }
  ],
  "queryResultType": "workItem",
  "queryType": "flat",
  "sortColumns": [
    {
      "descending": false,
      "field": {
        "name": "ID",
        "referenceName": "System.Id",
        "url": "https://dev.azure.com/{organization}/{project}/{team}/_apis/wit/fields/System.Id"
      }
    }
  ],
  "workItems": []
}
```

答:
This issue might be caused by request sql body,
try this one:

```<code>{
  "query": "SELECT [System.Id] FROM workitems WHERE [System.TeamProject] = @project ORDER BY [System.ID] ASC"
}
</code>```

more information see WIQL syntax

Body:
I'm using this Azure API to request workitems from our server.
Unfortunately if I set the $top parameter in the URL to some value the response doesn't return any resulting workitems. I don't get any error message. If don't set the $top parameter everything works fine and I get all workitems that matched the query.

My request looks like this:

POST https://dev.azure.com/{organization}/{project}/{team}/_apis/wit/wiql?$top=5&api-version=5.1

With the request body:

SELECT [System.Id] FROM WorkItems WHERE [System.Id] > 0 ORDER BY [System.Id] ASC

The response looks like this:

{
  "asOf": "2022-02-08T11:20:45.633Z",
  "columns": [
    {
      "name": "ID",
      "referenceName": "System.Id",
      "url": "https://dev.azure.com/{organization}/{project}/{team}/_apis/wit/fields/System.Id"
    }
  ],
  "queryResultType": "workItem",
  "queryType": "flat",
  "sortColumns": [
    {
      "descending": false,
      "field": {
        "name": "ID",
        "referenceName": "System.Id",
        "url": "https://dev.azure.com/{organization}/{project}/{team}/_apis/wit/fields/System.Id"
      }
    }
  ],
  "workItems": []
}

Body:
This issue might be caused by request sql body,
try this one:

{
  "query": "SELECT [System.Id] FROM workitems WHERE [System.TeamProject] = @project ORDER BY [System.ID] ASC"
}

more information see WIQL syntax


问:
Pods unable to resolve hostnames in Kubernetes cluster
I'm working on aws eks, and I'm having issues with networking because none of the pods can resolve hostnames.

Checking the kube-config pods, I found this:

```<code>NAME                                     READY   STATUS             RESTARTS   AGE
alb-ingress-controller-68b7d9dd9-4mpnc   1/1     Running            0          3d20h
alb-ingress-controller-68b7d9dd9-kqmsl   1/1     Running            8          17d
alb-ingress-controller-68b7d9dd9-q4m87   1/1     Running            11         26d
aws-node-m6ncq                           1/1     Running            34         31d
aws-node-r8bs5                           1/1     Running            31         28d
aws-node-vfvjn                           1/1     Running            34         31d
coredns-f47955f89-4bfb5                  1/1     Running            11         26d
coredns-f47955f89-7mqp7                  1/1     Running            8          17d
kube-flannel-ds-chv64                    0/1     CrashLoopBackOff   1814       28d
kube-flannel-ds-fct45                    0/1     CrashLoopBackOff   1831       31d
kube-flannel-ds-zs8z4                    0/1     CrashLoopBackOff   1814       28d
kube-proxy-6lcst                         1/1     Running            18         31d
kube-proxy-9qfkg                         1/1     Running            17         28d
kube-proxy-l5qvd                         1/1     Running            18         31d
</code>```

and kube-flannel logs are this:

```<code>I0208 21:01:23.542634       1 main.go:218] CLI flags config: {etcdEndpoints:http://127.0.0.1:4001,http://127.0.0.1:2379 etcdPrefix:/coreos.com/network etcdKeyfile: etcdCertfile: etcdCAFile: etcdUsername: etcdPassword: help:false version:false autoDetectIPv4:false autoDetectIPv6:false kubeSubnetMgr:true kubeApiUrl: kubeAnnotationPrefix:flannel.alpha.coreos.com kubeConfigFile: iface:[] ifaceRegex:[] ipMasq:true subnetFile:/run/flannel/subnet.env subnetDir: publicIP: publicIPv6: subnetLeaseRenewMargin:60 healthzIP:0.0.0.0 healthzPort:0 charonExecutablePath: charonViciUri: iptablesResyncSeconds:5 iptablesForwardRules:true netConfPath:/etc/kube-flannel/net-conf.json setNodeNetworkUnavailable:true}
W0208 21:01:23.542713       1 client_config.go:608] Neither --kubeconfig nor --master was specified.  Using the inClusterConfig.  This might not work.
I0208 21:01:23.647398       1 kube.go:120] Waiting 10m0s for node controller to sync
I0208 21:01:23.647635       1 kube.go:378] Starting kube subnet manager
I0208 21:01:24.647775       1 kube.go:127] Node controller sync successful
I0208 21:01:24.647801       1 main.go:238] Created subnet manager: Kubernetes Subnet Manager - ip-10-23-21-240.us-east-2.compute.internal
I0208 21:01:24.647811       1 main.go:241] Installing signal handlers
I0208 21:01:24.647887       1 main.go:460] Found network config - Backend type: vxlan
I0208 21:01:24.647916       1 main.go:652] Determining IP address of default interface
I0208 21:01:24.648449       1 main.go:699] Using interface with name eth0 and address 10.23.21.240
I0208 21:01:24.648476       1 main.go:721] Defaulting external address to interface address (10.23.21.240)
I0208 21:01:24.648482       1 main.go:734] Defaulting external v6 address to interface address (<nil>)
I0208 21:01:24.648543       1 vxlan.go:137] VXLAN config: VNI=1 Port=0 GBP=false Learning=false DirectRouting=false
E0208 21:01:24.648871       1 main.go:326] Error registering network: failed to acquire lease: node "ip-10-23-21-240.us-east-2.compute.internal" pod cidr not assigned
W0208 21:01:24.649006       1 reflector.go:424] github.com/flannel-io/flannel/subnet/kube/kube.go:379: watch of *v1.Node ended with: an error on the server ("unable to decode an event from the watch stream: context canceled") has prevented the request from succeeding
I0208 21:01:24.649060       1 main.go:440] Stopping shutdownHandler...
</code>```

Any idea what could be the issue or what to try?

Thanks!

答: Amazon VPC CNI and Flannel cannot co-exist on EKS. Note Flannel is not on the suggested alternate compatible CNI. To get an idea what does it take to use Flannel on EKS checkout this excellent blog.</p>

Body:
I'm working on aws eks, and I'm having issues with networking because none of the pods can resolve hostnames.

Checking the kube-config pods, I found this:

NAME                                     READY   STATUS             RESTARTS   AGE
alb-ingress-controller-68b7d9dd9-4mpnc   1/1     Running            0          3d20h
alb-ingress-controller-68b7d9dd9-kqmsl   1/1     Running            8          17d
alb-ingress-controller-68b7d9dd9-q4m87   1/1     Running            11         26d
aws-node-m6ncq                           1/1     Running            34         31d
aws-node-r8bs5                           1/1     Running            31         28d
aws-node-vfvjn                           1/1     Running            34         31d
coredns-f47955f89-4bfb5                  1/1     Running            11         26d
coredns-f47955f89-7mqp7                  1/1     Running            8          17d
kube-flannel-ds-chv64                    0/1     CrashLoopBackOff   1814       28d
kube-flannel-ds-fct45                    0/1     CrashLoopBackOff   1831       31d
kube-flannel-ds-zs8z4                    0/1     CrashLoopBackOff   1814       28d
kube-proxy-6lcst                         1/1     Running            18         31d
kube-proxy-9qfkg                         1/1     Running            17         28d
kube-proxy-l5qvd                         1/1     Running            18         31d

and kube-flannel logs are this:

I0208 21:01:23.542634       1 main.go:218] CLI flags config: {etcdEndpoints:http://127.0.0.1:4001,http://127.0.0.1:2379 etcdPrefix:/coreos.com/network etcdKeyfile: etcdCertfile: etcdCAFile: etcdUsername: etcdPassword: help:false version:false autoDetectIPv4:false autoDetectIPv6:false kubeSubnetMgr:true kubeApiUrl: kubeAnnotationPrefix:flannel.alpha.coreos.com kubeConfigFile: iface:[] ifaceRegex:[] ipMasq:true subnetFile:/run/flannel/subnet.env subnetDir: publicIP: publicIPv6: subnetLeaseRenewMargin:60 healthzIP:0.0.0.0 healthzPort:0 charonExecutablePath: charonViciUri: iptablesResyncSeconds:5 iptablesForwardRules:true netConfPath:/etc/kube-flannel/net-conf.json setNodeNetworkUnavailable:true}
W0208 21:01:23.542713       1 client_config.go:608] Neither --kubeconfig nor --master was specified.  Using the inClusterConfig.  This might not work.
I0208 21:01:23.647398       1 kube.go:120] Waiting 10m0s for node controller to sync
I0208 21:01:23.647635       1 kube.go:378] Starting kube subnet manager
I0208 21:01:24.647775       1 kube.go:127] Node controller sync successful
I0208 21:01:24.647801       1 main.go:238] Created subnet manager: Kubernetes Subnet Manager - ip-10-23-21-240.us-east-2.compute.internal
I0208 21:01:24.647811       1 main.go:241] Installing signal handlers
I0208 21:01:24.647887       1 main.go:460] Found network config - Backend type: vxlan
I0208 21:01:24.647916       1 main.go:652] Determining IP address of default interface
I0208 21:01:24.648449       1 main.go:699] Using interface with name eth0 and address 10.23.21.240
I0208 21:01:24.648476       1 main.go:721] Defaulting external address to interface address (10.23.21.240)
I0208 21:01:24.648482       1 main.go:734] Defaulting external v6 address to interface address (<nil>)
I0208 21:01:24.648543       1 vxlan.go:137] VXLAN config: VNI=1 Port=0 GBP=false Learning=false DirectRouting=false
E0208 21:01:24.648871       1 main.go:326] Error registering network: failed to acquire lease: node "ip-10-23-21-240.us-east-2.compute.internal" pod cidr not assigned
W0208 21:01:24.649006       1 reflector.go:424] github.com/flannel-io/flannel/subnet/kube/kube.go:379: watch of *v1.Node ended with: an error on the server ("unable to decode an event from the watch stream: context canceled") has prevented the request from succeeding
I0208 21:01:24.649060       1 main.go:440] Stopping shutdownHandler...

Any idea what could be the issue or what to try?

Thanks!


问:
How to capture the single-click or double-click on window title in JavaFX?
As we all know, when a user double-clicks on a window title bar, that window gets resized to the full available screen size. At least I have seen this happening in Mac OS. Any idea how to capture this event? What should I listen to in my code so that I know that the user has single or double-clicked the Window title?</p>

答:
Capturing clicks is a bad idea as @jewelsea mentioned in his comment. The effort in the question was to know why the behavior. Upon research, I found that it is a bug already listed by Oracle - please find below: Each window when double-clicked on the title bar is expected to assume full-screen height and width (Maximised) and on double-clicking title bar again should get back to its previous size. This is not working beyond JDK8 is what I understood from this link. However, on macOS Monterey 12.1 (OpenJDK 17) the window is assuming maximized size on double-clicking the title bar, but, is unable to go back to the previous size when double-clicking again.

https://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8232812


问:
cannot set background color on dropdown from React native paper dropdown
I used a react-native-paper-dropdown and the styles I am applying wont get set for example the background color wont change;</p>
```<code><DropDown
      // label={''}
      mode="flat"
      visible={showDropDown}
      showDropDown={() => setShowDropDown(true)}
      onDismiss={() => setShowDropDown(false)}
      value={country}
      setValue={setCountry}
      list={countriesList}
      dropDownStyle={{
        width: 100,
        backgroundColor: 'white',
        borderColor: 'white',
        shadowColor: 'white',
    }}
  />
</code>```

答:
I would highly recommend you to use the below library for implementing dropdown

https://www.npmjs.com/package/react-native-dropdown-picker

Much easier to use and it is popular library

Body:
I used a react-native-paper-dropdown and the styles I am applying wont get set for example the background color wont change;

<DropDown
      // label={''}
      mode="flat"
      visible={showDropDown}
      showDropDown={() => setShowDropDown(true)}
      onDismiss={() => setShowDropDown(false)}
      value={country}
      setValue={setCountry}
      list={countriesList}
      dropDownStyle={{
        width: 100,
        backgroundColor: 'white',
        borderColor: 'white',
        shadowColor: 'white',
    }}
  />


问:
Assosiation help in ruby on rails
I have fully linked everything together so a contact belongs_to :company and a company has_many :contacts everything works. The only question i have is in the contacts#new form you have to enter a companies ID is it possible to input the name of the company somehow and for it too translate to an ID in the back end? at the moment my form looks like this. You may notice company_id at the bottom of the form this is the field which i want to change. So that it is more user friendly instead of inserting an ID you insert a name or some kind of list of companies that you select. Please help?

```<code><%= form_for(@contact) do |f| %>
  <% if @contact.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@contact.errors.count, "error") %> prohibited this contact from being saved:</h2>

      <ul>
      <% @contact.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :position %><br />
    <%= f.text_field :position %>
  </div>
  <div class="field">
    <%= f.label :email %><br />
    <%= f.text_field :email %>
  </div>
  <div class="field">
    <%= f.label :telephone %><br />
    <%= f.text_field :telephone %>
  </div>
  <div class="field">
    <%= f.label :source %><br />
    <%= f.text_field :source %>
  </div>
  <div class="field">
    <%= f.label :company_id %><br />
    <%= f.text_field :company_id %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
</code>```

答:
You can use collection_select helper or simply select helper to achieve this:

```<code><%= f.select(:company_id, Company.all.collect {|company| [company.name, company.id]}) %>
</code>```

Title: Assosiation help in ruby on rails

Body:
I have fully linked everything together so a contact belongs_to :company and a company has_many :contacts everything works. The only question i have is in the contacts#new form you have to enter a companies ID is it possible to input the name of the company somehow and for it too translate to an ID in the back end? at the moment my form looks like this. You may notice company_id at the bottom of the form this is the field which i want to change. So that it is more user friendly instead of inserting an ID you insert a name or some kind of list of companies that you select. Please help?

<%= form_for(@contact) do |f| %>
  <% if @contact.errors.any? %>

<%= pluralize(@contact.errors.count, "error") %> prohibited this contact from being saved:

      <% @contact.errors.full_messages.each do |msg| %>

<%= msg %>

      <% end %>

  <% end %>

    <%= f.label :name %>

    <%= f.text_field :name %>

    <%= f.label :position %>

    <%= f.text_field :position %>

    <%= f.label :email %>

    <%= f.text_field :email %>

    <%= f.label :telephone %>

    <%= f.text_field :telephone %>

    <%= f.label :source %>

    <%= f.text_field :source %>

    <%= f.label :company_id %>

    <%= f.text_field :company_id %>

    <%= f.submit %>

<% end %>

Body:
You can use collection_select helper or simply select helper to achieve this:

<%= f.select(:company_id, Company.all.collect {|company| [company.name, company.id]}) %>


问:
how to just access the count of products through another model which are connected by foreign key
```<code>class Category(models.Model):
    category_name = models.CharField(max_length=50, unique=True)

class Product(models.Model):
    category        = models.ForeignKey(Category, on_delete=models.CASCADE)
    product_name    = models.CharField(max_length=200, unique=True)
    slug            = models.SlugField(max_length=200, unique=True)
</code>```

Here what i want is just the number of the product present in each category just the number of product i know i have can fire somequery

```<code>cat = Category.objects.all()
</code>```

run loop for cat

```<code>prod_cat = Product.object.filter(category=cat)
</code>```

But i belive its not the efficient way to achive this

答:
By using annotate like this:

from django.db.models import Count

>>> categories = Category.objects.annotate(Count('product'))

>>> categories[0].product__count

```

Body:
class Category(models.Model):
    category_name = models.CharField(max_length=50, unique=True)

class Product(models.Model):
    category        = models.ForeignKey(Category, on_delete=models.CASCADE)
    product_name    = models.CharField(max_length=200, unique=True)
    slug            = models.SlugField(max_length=200, unique=True)

Here what i want is just the number of the product present in each category just the number of product i know i have can fire somequery

cat = Category.objects.all()

run loop for cat

prod_cat = Product.object.filter(category=cat)

But i belive its not the efficient way to achive this


问:
Getting error while updating laravel from 5.5 to 5.7 (Undefined class constant 'HEADER_CLIENT_IP')
i am getting this error.

Undefined class constant 'HEADER_CLIENT_IP' Script @php artisan
  package:discover handling the post-autoload-dump event returned with
  error code 1

I changed

```<code>app\Http\Middleware\TrustedProxies.php by:

    <?php

  namespace App\Http\Middleware;

  use Illuminate\Http\Request;
  use Fideloper\Proxy\TrustProxies as Middleware;

  class TrustProxies extends Middleware
  {
    protected $proxies;
    protected $headers = Request::HEADER_X_FORWARDED_ALL;
  }
</code>```

Here is my .composerjson file

```<code>{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=7.0.0",
        "fideloper/proxy": "~3.3",
        "laravel/framework": "5.7.*",
        "laravel/tinker": "~1.0",
        "tymon/jwt-auth": "^0.5.12"
    },
    "require-dev": {
        "filp/whoops": "~2.0",
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "~1.0",
        "phpunit/phpunit": "~6.0",
        "symfony/thanks": "^1.0"
    },
    "autoload": {
        "classmap": [
            "database/seeds",
            "database/factories"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "extra": {
        "laravel": {
            "dont-discover": [
            ]
        }
    },
    "scripts": {
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate"
        ],
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover"
        ]
    },
    "config": {
        "preferred-install": "dist",
        "sort-packages": true,
        "optimize-autoloader": true
    } }
</code>```

I am still handling the same error. Can you guys figure it out where the problem is ?

答:
If you guys getting this error while updating to laravel 9.0 then remove below line of code from composer.json

```<code>"fideloper/proxy": "^4.4.1",
</code>```

And run composer update command in terminal

```<code>composer update
</code>```

Then, change the use Fideloper\Proxy\TrustProxies as Middleware; to use Illuminate\Http\Middleware\TrustProxies as Middleware; in a file app\Http\Middleware\TrustProxies.php file

Body:
i am getting this error.

Undefined class constant 'HEADER_CLIENT_IP' Script @php artisan
  package:discover handling the post-autoload-dump event returned with
  error code 1

I changed

app\Http\Middleware\TrustedProxies.php by:

    <?php

  namespace App\Http\Middleware;

  use Illuminate\Http\Request;
  use Fideloper\Proxy\TrustProxies as Middleware;

  class TrustProxies extends Middleware
  {
    protected $proxies;
    protected $headers = Request::HEADER_X_FORWARDED_ALL;
  }

Here is my .composerjson file

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=7.0.0",
        "fideloper/proxy": "~3.3",
        "laravel/framework": "5.7.*",
        "laravel/tinker": "~1.0",
        "tymon/jwt-auth": "^0.5.12"
    },
    "require-dev": {
        "filp/whoops": "~2.0",
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "~1.0",
        "phpunit/phpunit": "~6.0",
        "symfony/thanks": "^1.0"
    },
    "autoload": {
        "classmap": [
            "database/seeds",
            "database/factories"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "extra": {
        "laravel": {
            "dont-discover": [
            ]
        }
    },
    "scripts": {
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate"
        ],
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover"
        ]
    },
    "config": {
        "preferred-install": "dist",
        "sort-packages": true,
        "optimize-autoloader": true
    } }

I am still handling the same error. Can you guys figure it out where the problem is ?

Body:
If you guys getting this error while updating to laravel 9.0 then remove below line of code from composer.json

"fideloper/proxy": "^4.4.1",

And run composer update command in terminal

composer update

Then, change the use Fideloper\Proxy\TrustProxies as Middleware; to use Illuminate\Http\Middleware\TrustProxies as Middleware; in a file app\Http\Middleware\TrustProxies.php file


问:
Is there a way to restore a SQL Server backup in RDS from S3 by using cloudformation?
I am using CFN to create an HA environment and RDS seems to be the best way for SQL Server DB rather than instances. Now I have tried manual deployment taking RDS and restoring .bak using option group and connecting it with S3 by IAM and EC2. But I am facing a wall when doing the same with CFN automation. Is there a way?

答:
I don't have this in a state where I can "package it up for you", but this should give you a good head start....</p>
```<code>public abstract class DatabaseFunctionBase
{
    protected static bool IsTaskComplete(SqlConnection sqlConnection, int task)
    {
        try
        {
            using var command = sqlConnection.CreateCommand();
            command.CommandText = "msdb.dbo.rds_task_status";
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add("task_id", SqlDbType.Int).Value = task;
            using var reader = command.ExecuteReader();
            while (reader.Read())
            {
                if (reader.HasRows)
                {
                    var s = new StringBuilder();

                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                        s.AppendLine($"{i}={reader[i]}");
                    }
                    //LambdaLogger.Log(s.ToString());

                    var status = reader.GetString(5);
                    return status == "SUCCESS";
                }
            }

            return false;

        }
        catch (Exception e)
        {
            //LambdaLogger.Log(e.ToString());
            throw;
        }

    }

    protected int GetTaskId(SqlConnection sqlConnection, string dbName)
    {
        try
        {
            using var command = sqlConnection.CreateCommand();
            command.CommandText = "msdb.dbo.rds_task_status";
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add("db_name", SqlDbType.VarChar).Value = dbName;
            do
            {

                using var reader = command.ExecuteReader();
                while (reader.Read())
                {
                    if (reader.HasRows)
                    {
                        var s = new StringBuilder();

                        for (int i = 0; i < reader.FieldCount; i++)
                        {
                            s.AppendLine($"{i}={reader[i]}");
                        }

                        //LambdaLogger.Log(s.ToString());

                        var status = reader.GetString(5);
                        var id = reader.GetInt32(0);
                        var db = reader.GetString(2);
                        if ((status == "CREATED" || status == "IN_PROGRESS") && db == dbName)
                        {
                            return id;
                        }
                    }
                    Thread.Sleep(TimeSpan.FromSeconds(5));
                }
            } while (true);

            throw new InvalidOperationException();

        }
        catch (Exception e)
        {
            //LambdaLogger.Log(e.ToString());
            throw;
        }
    }

    protected async Task BackupDatabaseAsync(BackupRestoreDatabaseInfo info, ILambdaContext context)
    {
        var sqlConnectionStringBuilder = new Microsoft.Data.SqlClient.SqlConnectionStringBuilder
        {

            DataSource = info.DbServer,
            InitialCatalog = info.DbCatalog,
            UserID = info.DbUserId,
            Password = info.DbPassword,
            Authentication = SqlAuthenticationMethod.SqlPassword,
            MultipleActiveResultSets = true
        };

        var connectionString = sqlConnectionStringBuilder.ConnectionString;
        //LambdaLogger.Log($"{nameof(this.BackupDatabaseFunctionAsync)}:{nameof(connectionString)}:{connectionString}");
        await using var sqlConnection = new SqlConnection(connectionString);
        sqlConnection.Open();
        await using var command = sqlConnection.CreateCommand();
        command.CommandText = "msdb.dbo.rds_backup_database";
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.Add("source_db_name", SqlDbType.VarChar).Value = info.DbCatalog.ToString();
        command.Parameters.Add("s3_arn_to_backup_to", SqlDbType.VarChar).Value =
            $"{info.BackupBucket}/{info.DbCatalog}{DateTime.Now:O}.bak";
        command.Parameters.Add("overwrite_S3_backup_file", SqlDbType.TinyInt).Value = 1;
        command.ExecuteNonQuery();

        var taskId = this.GetTaskId(sqlConnection, info.DbCatalog);
        //LambdaLogger.Log($"{nameof(taskId)}={taskId}");

        do
        {
            if (IsTaskComplete(sqlConnection, taskId))
            {
                //LambdaLogger.Log("Complete");
                break;
            }
            //LambdaLogger.Log("Sleeping...");
            await Task.Delay(TimeSpan.FromSeconds(15));
        } while (true);

    }

    protected async Task CreateDatabaseAsync(BackupRestoreDatabaseInfo info, ILambdaContext context)
    {
        var sqlConnectionStringBuilder = new Microsoft.Data.SqlClient.SqlConnectionStringBuilder
        {
            DataSource = info.DbServer,
            UserID = info.DbUserId,
            Password = info.DbPassword,
            Authentication = SqlAuthenticationMethod.SqlPassword,
            MultipleActiveResultSets = true,
            InitialCatalog = info.DbCatalog
        };

        await using (var sqlConnection = new SqlConnection(sqlConnectionStringBuilder.ConnectionString))
        {

            try
            {
                sqlConnection.Open();
                // already present - exit
                return;

            }
            catch (Exception e)
            {
                //LambdaLogger.Log(e.ToString());
            }
        }

        // remove the catalog so we can connect to the server directly
        sqlConnectionStringBuilder.InitialCatalog = string.Empty;

        await using (var sqlConnection = new SqlConnection(sqlConnectionStringBuilder.ConnectionString))
        {

            sqlConnection.Open();

            await using var restoreCommand = sqlConnection.CreateCommand();

            restoreCommand.CommandText = "msdb.dbo.rds_restore_database";
            restoreCommand.CommandType = CommandType.StoredProcedure;
            restoreCommand.Parameters.Add("restore_db_name", SqlDbType.VarChar).Value = info.DbCatalog.ToString();
            restoreCommand.Parameters.Add("s3_arn_to_restore_from", SqlDbType.VarChar).Value =
                $"{info.BackupBucket}/{info.FromCatalog}.bak";
            restoreCommand.ExecuteNonQuery();

            var taskId = GetTaskId(sqlConnection, info.DbCatalog);

            do
            {
                if (IsTaskComplete(sqlConnection, taskId))
                {
                    //LambdaLogger.Log("Complete");
                    break;
                }
                //LambdaLogger.Log("Sleeping...");
                await Task.Delay(TimeSpan.FromSeconds(15));
            } while (true);

        }
        // this might be redundant in a merge
        sqlConnectionStringBuilder.InitialCatalog = info.DbCatalog;

        do
        {
            await using var sqlConnection = new SqlConnection(sqlConnectionStringBuilder.ConnectionString);
            try
            {
                sqlConnection.Open();
                break;
            }
            catch (Exception exception)
            {
                //LambdaLogger.Log(exception.ToString());
                await Task.Delay(TimeSpan.FromSeconds(5));
            }
        } while (context.RemainingTime > TimeSpan.FromMinutes(1));

        // this should already be in merged code
        sqlConnectionStringBuilder.InitialCatalog = info.DbCatalog;
        do
        {
            try
            {
                await using var sqlConnection2 = new SqlConnection(sqlConnectionStringBuilder.ConnectionString);
                sqlConnection2.Open();
                break;

            }
            catch (Exception e)
            {
                //LambdaLogger.Log(e.ToString());
                await Task.Delay(TimeSpan.FromSeconds(15));
            }
        } while (context.RemainingTime > TimeSpan.FromMinutes(1));
        // this should already be in merged code
    }

    protected async Task DeleteDatabase(BackupRestoreDatabaseInfo info, ILambdaContext context)
    {
        if (string.Equals(info.DbCatalog.ToString(), "app", StringComparison.InvariantCultureIgnoreCase))
        {
            return;
        }
        var sqlConnectionStringBuilder = new Microsoft.Data.SqlClient.SqlConnectionStringBuilder
        {
            DataSource = info.DbServer,
            UserID = info.DbUserId,
            Password = info.DbPassword,
            Authentication = SqlAuthenticationMethod.SqlPassword,
            MultipleActiveResultSets = true
        };

        var connectionString = sqlConnectionStringBuilder.ConnectionString;
        //LambdaLogger.Log($"{nameof(this.BackupDatabaseFunctionAsync)}:{nameof(connectionString)}:{connectionString}");
        await using var sqlConnection = new SqlConnection(connectionString);
        sqlConnection.Open();

        await using var dropCommand = sqlConnection.CreateCommand();

        dropCommand.CommandText = "msdb.dbo.rds_drop_database";
        dropCommand.CommandType = CommandType.StoredProcedure;
        dropCommand.Parameters.Add("db_name", SqlDbType.VarChar).Value = info.DbCatalog.ToString();
        dropCommand.ExecuteNonQuery();
    }
}
</code>```

Body:
I don't have this in a state where I can "package it up for you", but this should give you a good head start....

public abstract class DatabaseFunctionBase
{
    protected static bool IsTaskComplete(SqlConnection sqlConnection, int task)
    {
        try
        {
            using var command = sqlConnection.CreateCommand();
            command.CommandText = "msdb.dbo.rds_task_status";
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add("task_id", SqlDbType.Int).Value = task;
            using var reader = command.ExecuteReader();
            while (reader.Read())
            {
                if (reader.HasRows)
                {
                    var s = new StringBuilder();

                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                        s.AppendLine($"{i}={reader[i]}");
                    }
                    //LambdaLogger.Log(s.ToString());

                    var status = reader.GetString(5);
                    return status == "SUCCESS";
                }
            }

            return false;

        }
        catch (Exception e)
        {
            //LambdaLogger.Log(e.ToString());
            throw;
        }

    }

    protected int GetTaskId(SqlConnection sqlConnection, string dbName)
    {
        try
        {
            using var command = sqlConnection.CreateCommand();
            command.CommandText = "msdb.dbo.rds_task_status";
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add("db_name", SqlDbType.VarChar).Value = dbName;
            do
            {

                using var reader = command.ExecuteReader();
                while (reader.Read())
                {
                    if (reader.HasRows)
                    {
                        var s = new StringBuilder();

                        for (int i = 0; i < reader.FieldCount; i++)
                        {
                            s.AppendLine($"{i}={reader[i]}");
                        }

                        //LambdaLogger.Log(s.ToString());

                        var status = reader.GetString(5);
                        var id = reader.GetInt32(0);
                        var db = reader.GetString(2);
                        if ((status == "CREATED" || status == "IN_PROGRESS") && db == dbName)
                        {
                            return id;
                        }
                    }
                    Thread.Sleep(TimeSpan.FromSeconds(5));
                }
            } while (true);

            throw new InvalidOperationException();

        }
        catch (Exception e)
        {
            //LambdaLogger.Log(e.ToString());
            throw;
        }
    }

    protected async Task BackupDatabaseAsync(BackupRestoreDatabaseInfo info, ILambdaContext context)
    {
        var sqlConnectionStringBuilder = new Microsoft.Data.SqlClient.SqlConnectionStringBuilder
        {

            DataSource = info.DbServer,
            InitialCatalog = info.DbCatalog,
            UserID = info.DbUserId,
            Password = info.DbPassword,
            Authentication = SqlAuthenticationMethod.SqlPassword,
            MultipleActiveResultSets = true
        };

        var connectionString = sqlConnectionStringBuilder.ConnectionString;
        //LambdaLogger.Log($"{nameof(this.BackupDatabaseFunctionAsync)}:{nameof(connectionString)}:{connectionString}");
        await using var sqlConnection = new SqlConnection(connectionString);
        sqlConnection.Open();
        await using var command = sqlConnection.CreateCommand();
        command.CommandText = "msdb.dbo.rds_backup_database";
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.Add("source_db_name", SqlDbType.VarChar).Value = info.DbCatalog.ToString();
        command.Parameters.Add("s3_arn_to_backup_to", SqlDbType.VarChar).Value =
            $"{info.BackupBucket}/{info.DbCatalog}{DateTime.Now:O}.bak";
        command.Parameters.Add("overwrite_S3_backup_file", SqlDbType.TinyInt).Value = 1;
        command.ExecuteNonQuery();

        var taskId = this.GetTaskId(sqlConnection, info.DbCatalog);
        //LambdaLogger.Log($"{nameof(taskId)}={taskId}");

        do
        {
            if (IsTaskComplete(sqlConnection, taskId))
            {
                //LambdaLogger.Log("Complete");
                break;
            }
            //LambdaLogger.Log("Sleeping...");
            await Task.Delay(TimeSpan.FromSeconds(15));
        } while (true);

    }

    protected async Task CreateDatabaseAsync(BackupRestoreDatabaseInfo info, ILambdaContext context)
    {
        var sqlConnectionStringBuilder = new Microsoft.Data.SqlClient.SqlConnectionStringBuilder
        {
            DataSource = info.DbServer,
            UserID = info.DbUserId,
            Password = info.DbPassword,
            Authentication = SqlAuthenticationMethod.SqlPassword,
            MultipleActiveResultSets = true,
            InitialCatalog = info.DbCatalog
        };

        await using (var sqlConnection = new SqlConnection(sqlConnectionStringBuilder.ConnectionString))
        {

            try
            {
                sqlConnection.Open();
                // already present - exit
                return;

            }
            catch (Exception e)
            {
                //LambdaLogger.Log(e.ToString());
            }
        }

        // remove the catalog so we can connect to the server directly
        sqlConnectionStringBuilder.InitialCatalog = string.Empty;

        await using (var sqlConnection = new SqlConnection(sqlConnectionStringBuilder.ConnectionString))
        {

            sqlConnection.Open();

            await using var restoreCommand = sqlConnection.CreateCommand();

            restoreCommand.CommandText = "msdb.dbo.rds_restore_database";
            restoreCommand.CommandType = CommandType.StoredProcedure;
            restoreCommand.Parameters.Add("restore_db_name", SqlDbType.VarChar).Value = info.DbCatalog.ToString();
            restoreCommand.Parameters.Add("s3_arn_to_restore_from", SqlDbType.VarChar).Value =
                $"{info.BackupBucket}/{info.FromCatalog}.bak";
            restoreCommand.ExecuteNonQuery();

            var taskId = GetTaskId(sqlConnection, info.DbCatalog);

            do
            {
                if (IsTaskComplete(sqlConnection, taskId))
                {
                    //LambdaLogger.Log("Complete");
                    break;
                }
                //LambdaLogger.Log("Sleeping...");
                await Task.Delay(TimeSpan.FromSeconds(15));
            } while (true);

        }
        // this might be redundant in a merge
        sqlConnectionStringBuilder.InitialCatalog = info.DbCatalog;

        do
        {
            await using var sqlConnection = new SqlConnection(sqlConnectionStringBuilder.ConnectionString);
            try
            {
                sqlConnection.Open();
                break;
            }
            catch (Exception exception)
            {
                //LambdaLogger.Log(exception.ToString());
                await Task.Delay(TimeSpan.FromSeconds(5));
            }
        } while (context.RemainingTime > TimeSpan.FromMinutes(1));

        // this should already be in merged code
        sqlConnectionStringBuilder.InitialCatalog = info.DbCatalog;
        do
        {
            try
            {
                await using var sqlConnection2 = new SqlConnection(sqlConnectionStringBuilder.ConnectionString);
                sqlConnection2.Open();
                break;

            }
            catch (Exception e)
            {
                //LambdaLogger.Log(e.ToString());
                await Task.Delay(TimeSpan.FromSeconds(15));
            }
        } while (context.RemainingTime > TimeSpan.FromMinutes(1));
        // this should already be in merged code
    }

    protected async Task DeleteDatabase(BackupRestoreDatabaseInfo info, ILambdaContext context)
    {
        if (string.Equals(info.DbCatalog.ToString(), "app", StringComparison.InvariantCultureIgnoreCase))
        {
            return;
        }
        var sqlConnectionStringBuilder = new Microsoft.Data.SqlClient.SqlConnectionStringBuilder
        {
            DataSource = info.DbServer,
            UserID = info.DbUserId,
            Password = info.DbPassword,
            Authentication = SqlAuthenticationMethod.SqlPassword,
            MultipleActiveResultSets = true
        };

        var connectionString = sqlConnectionStringBuilder.ConnectionString;
        //LambdaLogger.Log($"{nameof(this.BackupDatabaseFunctionAsync)}:{nameof(connectionString)}:{connectionString}");
        await using var sqlConnection = new SqlConnection(connectionString);
        sqlConnection.Open();

        await using var dropCommand = sqlConnection.CreateCommand();

        dropCommand.CommandText = "msdb.dbo.rds_drop_database";
        dropCommand.CommandType = CommandType.StoredProcedure;
        dropCommand.Parameters.Add("db_name", SqlDbType.VarChar).Value = info.DbCatalog.ToString();
        dropCommand.ExecuteNonQuery();
    }
}


问:
C++ Visual Studio 2010 not linking native static library
I am converting a C++ Visual Studio 2005 project to Visual Studio 2010, and I have used this guide in the process.
I have one issue left which is, that the linker does not link a native static library (it is not a .NET assembly but a third part library sqsapi32.lib). I have included the library sqsapi32.lib in the Properties->Configuration Properties->Linker->Input->Additional Dependencies, but the linker keep notifying the following warning:

```<code>warning LNK4248: unresolved typeref token (01000014) for 'SQLDA'; image may not run
</code>```

running the .exe file produces the following error: "The program can't start because sqsapi32.dll is missing from your computer".

How can I fix this? It worked using Visual Studio 2005.

答:
Since you are using C++/CLI, this warning is expected from linker. There are many structs which are just declared as:

struct ABC;

and ABC is used by underlying library (you dont have source code), and ABC is presented by library to you in opaque manner. You can avoid this warning by declaring a fake structure in your source code:

```<code>struct ABC
{
};
</code>```

So for your case:

struct SQLDA{};

will do the job.

This is just to satisy the C++/CLI linker and wont do any harm.

Body:
I am converting a C++ Visual Studio 2005 project to Visual Studio 2010, and I have used this guide in the process.
I have one issue left which is, that the linker does not link a native static library (it is not a .NET assembly but a third part library sqsapi32.lib). I have included the library sqsapi32.lib in the Properties->Configuration Properties->Linker->Input->Additional Dependencies, but the linker keep notifying the following warning:

warning LNK4248: unresolved typeref token (01000014) for 'SQLDA'; image may not run

running the .exe file produces the following error: "The program can't start because sqsapi32.dll is missing from your computer".

How can I fix this? It worked using Visual Studio 2005.

Body:
Since you are using C++/CLI, this warning is expected from linker. There are many structs which are just declared as:

struct ABC;

and ABC is used by underlying library (you dont have source code), and ABC is presented by library to you in opaque manner. You can avoid this warning by declaring a fake structure in your source code:

struct ABC
{
};

So for your case:

struct SQLDA{};

will do the job.

This is just to satisy the C++/CLI linker and wont do any harm.


问:
Ajax request giving id NULL
Good Morning...I am trying to update the data in table using ajax, while passing the data to controller using id, ID preview is showing NULL and so not able to update the data in Table.
I am trying to add new data in one table and at same time update data in another table using same ajax...
Ajax -

```<code>$.ajaxSetup({

    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }

});

$(document).on('click', '#footer_addnewinspectiondata_button', function() {

    $.ajax({

        type: 'put',
        url: '/addbuffaloinspectiondata',
        dataType: 'json',
        data: {
            'buffaloID': $('#buffaloID').val(),
            'inspectiondate': $('#inspectiondate').val(),
            'pregnantstatus': $('#pregnantstatus').val(),
            'healthstatus': $('#healthstatus').val(),
            'weight': $('#weight').val(),
            'height': $('#height').val(),
            'weeklytika': $('#weeklytika').val(),
            'monthlytika': $('#monthlytika').val(),
            'inspection': $('#inspection').val(),
            'inspectionby': $('#inspectionby').val(),
            'inspectionnote': $('#inspectionnote').val(),

        },
        success: function(data) {

            console.log(data);

        },
        error: function(e) {
            console.log(e);
        }
    });
});
</code>```

Web.php File

```<code>Route:: put('/addbuffaloinspectiondata',
       [viewbuffaloController::class,'addbuffaloinspectiondata'])->name('addbuffaloinspectiondata');
</code>```

Controller File -

```<code>public function addbuffaloinspectiondata(Request $req)
{
    // add new data in buffaloinspection table for Buffalo ID

    $newdata = new buffaloinspectiondata;

    $newdata->buffaloID            = $req->buffaloID;
    $newdata->inspectiondate       = $req->inspectiondate;

    $newdata->weight               = $req->weight;
    $newdata->height               = $req->height;
    $newdata->pregnant             = $req->pregnantstatus;

    $newdata->health               = $req->healthstatus;
    $newdata->weeklytika           = $req->weeklytika;
    $newdata->monthlytika          = $req->monthlytika;

    $newdata->inspection           = $req->inspection;
    $newdata->inspectionby         = $req->inspectionby;
    $newdata->inspectionnote       = $req->inspectionnote;

    // update data in BuffaloDATA Table

    $updatedata = buffalodata::find($req->buffaloID);

        $updatedata->weight             = $req->get('weight');
        $updatedata->height             = $req->get('height');

        $newdata->save ();
        $updatedata->save ();

        return response()->json([$newdata,$updatedata],200);
}
</code>```

Did i miss something or doing wrong in code... Thanks in Advance.

答:
Try this

```<code>public function addbuffaloinspectiondata(Request $req)
{
    // add or update operation.

    if(isset($req->buffaloID)){

        //buffalodata model
        $newdata = buffaloinspectiondata::find($req->buffaloID);

        //buffalodata model
        $updatedata = buffalodata::find($req->buffaloID);

        $updatedata->weight             = isset($req->get('weight'))? $req->get('weight') : 0 ;
        $updatedata->height             = isset($req->get('weight'))? $req->get('height') : 0 ;
        $updatedata->save ();

    }else{
        $newdata = new buffaloinspectiondata;
    }

    $newdata->buffaloID            = $req->buffaloID;
    $newdata->inspectiondate       = $req->inspectiondate;
    $newdata->weight               = isset($req->get('weight'))? $req->get('weight') : 0 ;
    $newdata->height               = isset($req->get('weight'))? $req->get('height') : 0 ;
    $newdata->pregnant             = $req->pregnantstatus;
    $newdata->health               = $req->healthstatus;
    $newdata->weeklytika           = $req->weeklytika;
    $newdata->monthlytika          = $req->monthlytika;
    $newdata->inspection           = $req->inspection;
    $newdata->inspectionby         = $req->inspectionby;
    $newdata->inspectionnote       = $req->inspectionnote;
    $newdata->save();

    return response()->json([$newdata,$updatedata],200);
}
</code>```

Title: Ajax request giving id NULL

Body:
Good Morning...I am trying to update the data in table using ajax, while passing the data to controller using id, ID preview is showing NULL and so not able to update the data in Table.
I am trying to add new data in one table and at same time update data in another table using same ajax...
Ajax -

$.ajaxSetup({

    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }

});

$(document).on('click', '#footer_addnewinspectiondata_button', function() {

    $.ajax({

        type: 'put',
        url: '/addbuffaloinspectiondata',
        dataType: 'json',
        data: {
            'buffaloID': $('#buffaloID').val(),
            'inspectiondate': $('#inspectiondate').val(),
            'pregnantstatus': $('#pregnantstatus').val(),
            'healthstatus': $('#healthstatus').val(),
            'weight': $('#weight').val(),
            'height': $('#height').val(),
            'weeklytika': $('#weeklytika').val(),
            'monthlytika': $('#monthlytika').val(),
            'inspection': $('#inspection').val(),
            'inspectionby': $('#inspectionby').val(),
            'inspectionnote': $('#inspectionnote').val(),

        },
        success: function(data) {

            console.log(data);

        },
        error: function(e) {
            console.log(e);
        }
    });
});

Web.php File

Route:: put('/addbuffaloinspectiondata',
       [viewbuffaloController::class,'addbuffaloinspectiondata'])->name('addbuffaloinspectiondata');

Controller File -

public function addbuffaloinspectiondata(Request $req)
{
    // add new data in buffaloinspection table for Buffalo ID

    $newdata = new buffaloinspectiondata;

    $newdata->buffaloID            = $req->buffaloID;
    $newdata->inspectiondate       = $req->inspectiondate;

    $newdata->weight               = $req->weight;
    $newdata->height               = $req->height;
    $newdata->pregnant             = $req->pregnantstatus;

    $newdata->health               = $req->healthstatus;
    $newdata->weeklytika           = $req->weeklytika;
    $newdata->monthlytika          = $req->monthlytika;

    $newdata->inspection           = $req->inspection;
    $newdata->inspectionby         = $req->inspectionby;
    $newdata->inspectionnote       = $req->inspectionnote;

    // update data in BuffaloDATA Table

    $updatedata = buffalodata::find($req->buffaloID);

        $updatedata->weight             = $req->get('weight');
        $updatedata->height             = $req->get('height');

        $newdata->save ();
        $updatedata->save ();

        return response()->json([$newdata,$updatedata],200);
}

Did i miss something or doing wrong in code... Thanks in Advance.

Body:
Try this

public function addbuffaloinspectiondata(Request $req)
{
    // add or update operation.

    if(isset($req->buffaloID)){

        //buffalodata model
        $newdata = buffaloinspectiondata::find($req->buffaloID);

        //buffalodata model
        $updatedata = buffalodata::find($req->buffaloID);

        $updatedata->weight             = isset($req->get('weight'))? $req->get('weight') : 0 ;
        $updatedata->height             = isset($req->get('weight'))? $req->get('height') : 0 ;
        $updatedata->save ();

    }else{
        $newdata = new buffaloinspectiondata;
    }

    $newdata->buffaloID            = $req->buffaloID;
    $newdata->inspectiondate       = $req->inspectiondate;
    $newdata->weight               = isset($req->get('weight'))? $req->get('weight') : 0 ;
    $newdata->height               = isset($req->get('weight'))? $req->get('height') : 0 ;
    $newdata->pregnant             = $req->pregnantstatus;
    $newdata->health               = $req->healthstatus;
    $newdata->weeklytika           = $req->weeklytika;
    $newdata->monthlytika          = $req->monthlytika;
    $newdata->inspection           = $req->inspection;
    $newdata->inspectionby         = $req->inspectionby;
    $newdata->inspectionnote       = $req->inspectionnote;
    $newdata->save();

    return response()->json([$newdata,$updatedata],200);
}


问:
Python - How to filter out files that contain char at specific index?
I would like to filter out all files that doesn't contain "-" at index 82.

Sorry, real new to programming in general, any help is appreciated.

答:
Use a string slice:

# assuming "files" is a list of file names
files = [f for f in files if f[81:82] == '-']
```
<p>The above checks if the 82nd character be <code>-</code> or not.  If instead you want to check the 82nd <em>index</em>, then use:</p>
<pre class="lang-py prettyprint-override"><code>files = [f for f in files if f[82:83] == '-']
</code>```

Body:
Use a string slice:

# assuming "files" is a list of file names
files = [f for f in files if f[81:82] == '-']

The above checks if the 82nd character be - or not.  If instead you want to check the 82nd index, then use:

files = [f for f in files if f[82:83] == '-']


问:
MySQL: Package 'mysql-server' has no installation candidate
This error is being shown whenever I want to install any software via command line.
Even if i try to install softwares which I know are present at the source from where I am downloading.

Below is the full error message i am getting :

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
Package mysql-server is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'mysql-server' has no installation candidate
</code>```

答:
You can install mysql by</p>
```<code>sudo apt install default-mysql-server

--------
sudo service mysql status
● mariadb.service - MariaDB 10.3.31 database server
   Loaded: loaded (/lib/systemd/system/mariadb.service; enabled; vendor preset: enabled)
   Active: active (running) since Wed 2022-02-09 13:19:33 +08; 33s ago
     Docs: man:mysqld(8)
           https://mariadb.com/kb/en/library/systemd/
 Main PID: 18537 (mysqld)
   Status: "Taking your SQL requests now..."
    Tasks: 31 (limit: 4915)
   Memory: 73.1M
   CGroup: /system.slice/mariadb.service
           └─18537 /usr/sbin/mysqld
</code>```

Body:
This error is being shown whenever I want to install any software via command line.
Even if i try to install softwares which I know are present at the source from where I am downloading.

Below is the full error message i am getting :

Reading package lists... Done
Building dependency tree
Reading state information... Done
Package mysql-server is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'mysql-server' has no installation candidate

Body:
You can install mysql by

sudo apt install default-mysql-server

--------
sudo service mysql status
● mariadb.service - MariaDB 10.3.31 database server
   Loaded: loaded (/lib/systemd/system/mariadb.service; enabled; vendor preset: enabled)
   Active: active (running) since Wed 2022-02-09 13:19:33 +08; 33s ago
     Docs: man:mysqld(8)
           https://mariadb.com/kb/en/library/systemd/
 Main PID: 18537 (mysqld)
   Status: "Taking your SQL requests now..."
    Tasks: 31 (limit: 4915)
   Memory: 73.1M
   CGroup: /system.slice/mariadb.service
           └─18537 /usr/sbin/mysqld


问:
Redirect to Next after login in Django
When a user accesses a url which requires login. The view decorator redirects to the login page. after the user enters his username and password how can I redirect the user to the page he was trying to access ('next') ?

Views.py

```<code>def login_view(request):
    template = 'pos/login.html'
    form = LoginForm
    if request.method == 'POST':
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                messages.success(request, "You have logged in!")
                return redirect('home')
            else:
                messages.warning(request, "Your account is disabled!")
                return redirect('/login')
        else:
            messages.warning(request, "The username or password are not valid!")
            return redirect('/login')
    context = {'form': form}
    return render(request, template, context)

@login_required(redirect_field_name='next', login_url='/login')
def bar(request):
    template = 'pos/bar.html'
    drink = OrderItem.objects.filter(product__catgory__gt=1).order_by('-created')
    context = {'drink': drink}
    return render(request, template, context)
</code>```

Login.html

```<code><form action="/login" id="login_form" method="post" class="form-signin">
    {% csrf_token %}
    {{ form.as_p }}
    <button class="btn btn-lg btn-primary btn-block" type="submit" value="login">Sign in</button>
    <input type="hidden" name="next" value="{{next}}" />
</form>
</code>```

url.py

```<code>     url(r'^login', views.login_view, name='login'),
</code>```

forms.py

```<code>class LoginForm(AuthenticationForm):
    username = forms.CharField(label="Username", required=True, max_length=30,
                           widget=forms.TextInput(attrs={
                               'class': 'form-control',
                               'name': 'username'}))
    password = forms.CharField(label="Password", required=True, max_length=30,
                           widget=forms.PasswordInput(attrs={
                               'class': 'form-control',
                               'name': 'password'}))
</code>```

答:
Yes Arun Ghosh option is better but it leads to an exception in cases where there is no next value is found.

Hence I used this approach.

try: return redirect(request.GET.get('next')) except TypeError: return HttpResponseRedirect(reverse("default_app:url_name"))

OR

except Exception as e: return HttpResponseRedirect(reverse("default_app:url_name"))

Title: Redirect to Next after login in Django

Body:
When a user accesses a url which requires login. The view decorator redirects to the login page. after the user enters his username and password how can I redirect the user to the page he was trying to access ('next') ?

Views.py

def login_view(request):
    template = 'pos/login.html'
    form = LoginForm
    if request.method == 'POST':
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                messages.success(request, "You have logged in!")
                return redirect('home')
            else:
                messages.warning(request, "Your account is disabled!")
                return redirect('/login')
        else:
            messages.warning(request, "The username or password are not valid!")
            return redirect('/login')
    context = {'form': form}
    return render(request, template, context)

@login_required(redirect_field_name='next', login_url='/login')
def bar(request):
    template = 'pos/bar.html'
    drink = OrderItem.objects.filter(product__catgory__gt=1).order_by('-created')
    context = {'drink': drink}
    return render(request, template, context)

Login.html

<form action="/login" id="login_form" method="post" class="form-signin">
    {% csrf_token %}
    {{ form.as_p }}
    <button class="btn btn-lg btn-primary btn-block" type="submit" value="login">Sign in</button>
    <input type="hidden" name="next" value="{{next}}" />
</form>

url.py

     url(r'^login', views.login_view, name='login'),

forms.py

class LoginForm(AuthenticationForm):
    username = forms.CharField(label="Username", required=True, max_length=30,
                           widget=forms.TextInput(attrs={
                               'class': 'form-control',
                               'name': 'username'}))
    password = forms.CharField(label="Password", required=True, max_length=30,
                           widget=forms.PasswordInput(attrs={
                               'class': 'form-control',
                               'name': 'password'}))


问:
compileSdkVersion is not specified error in React Native Android
I get the build error when I try to build an Android app in my React Native project.

When I run react-native run-android, it says:

```<code>> Configure project :react-native-os
WARNING: Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.
It will be removed at the end of 2018. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':react-native-os'.
> compileSdkVersion is not specified.
</code>```

In Android Studio, I can see that it says the same thing:
Cause: compileSdkVersion is not specified.

So I edited build.gradle(Module: app) file in Android Studio, but the problem persists and the error message doesn't change.

```<code>android {
//    compileSdkVersion rootProject.ext.compileSdkVersion
    compileSdkVersion 28
    buildToolsVersion "28.0.3"
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
</code>```

I tried solutions in other threads like this one but nothing worked. Does anyone know what the problem is here?

答:
Go to node_module>@react-native-firebase>messaging>android>build.gradle

Find code which defines min and target sdk and define the sdk and build version same as you have in your main project build.gradle file.

Then run command cd android && ./gradlew clean && cd ..

Also make sure you had defined default firebase config in your app level build.gradle
Make sure you have this import on top your build.gradle :
apply plugin: "com.google.gms.google-services"
and an default config as :
defaultConfig { applicationId "..." minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 00 versionName "... multiDexEnabled true }

Body:
I get the build error when I try to build an Android app in my React Native project.

When I run react-native run-android, it says:

> Configure project :react-native-os
WARNING: Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.
It will be removed at the end of 2018. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':react-native-os'.
> compileSdkVersion is not specified.

In Android Studio, I can see that it says the same thing:
Cause: compileSdkVersion is not specified.

So I edited build.gradle(Module: app) file in Android Studio, but the problem persists and the error message doesn't change.

android {
//    compileSdkVersion rootProject.ext.compileSdkVersion
    compileSdkVersion 28
    buildToolsVersion "28.0.3"
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

I tried solutions in other threads like this one but nothing worked. Does anyone know what the problem is here?