问:
ASP.NET Core 3.0 Web API routing not working
I am trying to access a jwt controller in my dotnet core 3.1 solution.

Here is my jwt controller:

```<code>[Authorize]
[ApiController]
[Route("api/[controller]")]
public class JwtController : ControllerBase
{
        #region Variables
        private readonly IUserAuthorisationServices _tokenService;
        private readonly IOptions<JwtTokenOptions> jwtOptions;
        private readonly ILogger logger;
        private readonly JsonSerializerSettings _serializerSettings;
        #endregion

        public JwtController(IUserAuthorisationServices tokenService,
                             IOptions<JwtTokenOptions> jwtOptions,
                             ILoggerFactory loggerFactory)
        {
            if (loggerFactory is null) throw new ArgumentNullException(nameof(loggerFactory));

            _tokenService = tokenService ?? throw new ArgumentNullException(nameof(tokenService));

            jwtOptions = jwtOptions ?? throw new ArgumentNullException(nameof(jwtOptions));
            logger = loggerFactory.CreateLogger<JwtController>();
            _serializerSettings = new JsonSerializerSettings {
                Formatting = Formatting.Indented
            };
            //loggingRepository = _errorRepository;
            //ThrowIfInvalidOptions(this.jwtOptions);
        }

  [AllowAnonymous]
  [Route("authenticate")]
  [HttpPost]
  public async Task<IActionResult> Authenticate([FromBody] LoginViewModel model)
  {
            var userContext = _tokenService.Authenticate(model.Email, model.Password);

            if (userContext.Principal == null) {
                logger.LogInformation($"Invalid username ({model.Email}) or password ({model.Password})");
                return BadRequest(new { message = "Username or password is incorrect" });
            }

            return Ok(await _tokenService.CreateTokenAsync(userContext).ConfigureAwait(false));
  }

   [Route("JWTStatus")]
   [HttpGet]
   public static IActionResult GetJwtStatus()
   {
            // It made it here so it was authenticated.
            return new OkResult();
   }
}
</code>```

I have stepped my way through the process and it gets to this middleware and then cannot find the controller returning immediately and at the same time providing the browser with a 404.

This is what I am using to access this controller action:

```<code>login(email: string, password: string) {
    this.userLogin.Email = email;
    this.userLogin.Password = password;

    // Do the fetch!
    const t = fetch("/api/authenticate",
            {
                method: "POST",
                body: JSON.stringify(this.userLogin),
                headers: new Headers({ "content-type": "application/json" })
            })
        .then(response => {
</code>```

I note the fetch is using "api/authenticate" and when I look at the HttpRequest its got the same url yet it wont find it.

Here is the middleware that it gets to before just returning.

```<code>namespace JobsLedger.AUTHORISATION.API.SessionMiddleware
{
    public class ConfigureSessionMiddleware
    {
        private readonly RequestDelegate _next;

        public ConfigureSessionMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext httpContext, IUserSession userSession, ISessionServices sessionServices)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException(nameof(httpContext));
            }

            if (userSession == null)
            {
                throw new ArgumentNullException(nameof(userSession));
            }

            if (sessionServices == null)
            {
                throw new ArgumentNullException(nameof(sessionServices));
            }

            if (httpContext.User.Identities.Any(id => id.IsAuthenticated))
            {
                if (httpContext.Session.GetString("connectionString") == null) // Session needs to be set..
                {
                    userSession.UserId = httpContext.User.Claims.FirstOrDefault(x => x.Type == "userId")?.Value;
                    userSession.ConnectionString = sessionServices.ConnectionStringFromUserId(userSession.UserId);
                    httpContext.Session.SetString("userId", userSession.UserId);
                    httpContext.Session.SetString("connectionString", userSession.ConnectionString);
                }
                else  //  Session set so all we need to is to build userSession for data access..
                {
                    userSession.UserId = httpContext.Session.GetString("userId");
                    userSession.ConnectionString = httpContext.Session.GetString("connectionString");
                }
            }

            // Call the next delegate/middleware in the pipeline
            await _next.Invoke(httpContext).ConfigureAwait(false);
        }
    }
}
</code>```

Its suppose to jump straight past this as there are no user identities as this hasnt been set yet. So really it goes straight to:

```<code>await _next.Invoke(httpContext).ConfigureAwait(false);
</code>```

Then onto the controller action.. but it just goes straight out with a 404.

In the output window I am getting:

```<code>Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request starting HTTP/2.0 POST https://localhost:44301/api/authenticate text/plain;charset=UTF-8 76
Microsoft.AspNetCore.Cors.Infrastructure.CorsService: Information: CORS policy execution successful.
Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request finished in 17.1363ms 404
</code>```

You can see the 404.

How is it cant find the action?

Is it possibly due to it being https and http 2.0?

For completeness here is the httpContext at the point of that middleware:

UPDATE...

I do not use MVC in the startup either just endpoints...

Maybe its the pipeline in Startup.cs.. here is my startup.cs

```<code>[assembly: NeutralResourcesLanguage("en")]

namespace JobsLedger.API {
    public class Startup {
        //private const string SecretKey = "needtogetthisfromenvironment";

        //private readonly SymmetricSecurityKey
        //  _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));
        private readonly IWebHostEnvironment _env;
        private readonly IConfiguration _configuration;  // { get; }

        public Startup(IWebHostEnvironment env, IConfiguration configuration) {
            _env = env;
            _configuration = configuration;
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services) {
            // Add framework services.
            services.AddCors();
            services.AddControllers();
            services.AddOptions();

            services.AddDbContext<CATALOGContext>(options => options.UseSqlServer(_configuration.GetConnectionString("CatalogConnection"), b => b.MigrationsAssembly("JobsLedger.CATALOG")));
            services.AddDbContext<DATAContext>(options => options.UseSqlServer(_configuration.GetConnectionString("TenantDbConnection"), a => a.MigrationsAssembly("JobsLedger.DATA")));

            // Make authentication compulsory across the board (i.e. shut
            // down EVERYTHING unless explicitly opened up).
            // Use policy auth.
            services.AddAuthorization(options => {
                options.AddPolicy("TenantAdmin", policy => policy.RequireClaim(ClaimTypes.Role, "TenantAdmin"));
                options.AddPolicy("Admin", policy => policy.RequireClaim(ClaimTypes.Role, "Admin"));
                options.AddPolicy("Employee", policy => policy.RequireClaim(ClaimTypes.Role, "Employee"));
            });

            //services.ConfigureApplicationInjection();

            // Get jwt options from app settings
            var tokenOptions = _configuration.GetSection("Authentication").Get<JwtTokenOptions>();

            services.AddAuthentication(x => {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options => {
                options.TokenValidationParameters = new TokenValidationParameters {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    RequireExpirationTime = true,
                    ValidIssuer = tokenOptions.Issuer,
                    ValidAudience = tokenOptions.Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(
                        Encoding.UTF8.GetBytes(tokenOptions.SigningKey)),
                    ClockSkew = TimeSpan.Zero
                };
            });

            services
                .AddDistributedMemoryCache()
                .AddSession()

                // Repositories - DATA
                .AddScoped<IClientDATARepository, ClientDATARepository>()
                .AddScoped<ILoggingDATARepository, LoggingDATARepository>()
                .AddScoped<IJobDATARepository, JobDATARepository>()
                .AddScoped<IBrandDATARepository, BrandDATARepository>()
                .AddScoped<ITypeDATARepository, TypeDATARepository>()
                .AddScoped<IStateDATARepository, StateDATARepository>()
                .AddScoped<IStatusDATARepository, StatusDATARepository>()
                .AddScoped<ISuburbDATARepository, SuburbDATARepository>()
                .AddScoped<ICounterDATARepository, CounterDATARepository>()

                // Repositories - CATALOG
                .AddScoped<ITenantCATALOGRepository, TenantCATALOGRepository>()
                .AddScoped<IUserCATALOGRepository, UserCATALOGRepository>()
                .AddScoped<IRoleCATALOGRepository, RoleCATALOGRepository>()
                .AddScoped<ICounterCATALOGRepository, CounterCATALOGRepository>()
                .AddScoped<ISuburbCATALOGRepository, SuburbCATALOGRepository>()
                .AddScoped<IStateCATALOGRepository, StateCATALOGRepository>()

                // Business services
                // Services - API
                .AddScoped<IClientServices, ClientServices>()
                .AddScoped<IJobServices, JobServices>()

                //Services - Catalog
                .AddScoped<ITenantServices, TenantServices>()
                .AddScoped<IUserServices, UserServices>()
                //.AddScoped<IUserValidateService, UserValidateService>()

                // Services - Shared
                .AddScoped<IAddressDropdownServices, AddressDropdownServices>()

                //Services - Auth
                .AddScoped<ICryptoService, CryptoService>()
                .AddScoped<IUserAuthorisationServices, UserAuthorisationServices>()
                .AddScoped<IUserSession, UserSession>()
                .AddScoped<ISessionServices, SessionServices>()

                // CATALOG services - Initialisations.
                .AddScoped<ICATALOGCounterInitialiser, CATALOGCounterInitialiser>()
                .AddScoped<ICATALOGStateInitialiser, CATALOGStateInitialiser>()
                .AddScoped<ICATALOGSuburbInitialiser, CATALOGSuburbInitialiser>()
                .AddScoped<IRoleInitialiser, CATALOGRoleInitialiser>()
                .AddScoped<ICATALOGTenantAndUserInitialisations, CATALOGTenantAndUserInitialiser>()

                // DATA Services - Initialisations.
                .AddScoped<IBrandInitialiser, BrandInitialiser>()
                .AddScoped<IDATACounterInitialiser, DATACounterInitialiser>()
                .AddScoped<IDATAStateInitialiser, DATAStateInitialiser>()
                .AddScoped<IDATASuburbInitialiser, DATASuburbInitialiser>()
                .AddScoped<IStatusInitialiser, StatusInitialiser>()
                .AddScoped<ITypeInitialiser, TypeInitialiser>()
                .AddScoped<IVisitTypeInitialiser, VisitTypeInitialiser>()

                // TESTDATA Services - Initialisations.
                .AddScoped<ITESTDATAInitialisations, TESTDATAInitialisations>()
                .AddScoped<ITESTDATATenantAndUserInitialisations, TESTDATATenantAndUserInitialisations>()

                .AddTransient<IDATAContextFactory, DATAContextFactory>()
                .AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); // For getting the user.
        }

        public static void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
            if (env.IsDevelopment()) {
                app.UseDeveloperExceptionPage();
            }
            else {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseExceptionHandler(options => {
                options.Run(async context => {
                    var ex = context.Features.Get<IExceptionHandlerPathFeature>();
                    if (ex?.Error != null) {
                        Debugger.Break();
                    }
                });
            });

            app.UseRouting();

            // global cors policy
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());

            app.UseAuthentication();
            app.UseHttpsRedirection();
            app.UseFileServer();
            app.UseStaticFiles();
            app.UseSession();
            app.UseAuthorization();

            app.UseConfigureSession();

            app.EnsureCATALOGMigrationAndInitialise();
            app.EnsureDATAMigrationsAndInitialise();

            app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
        }
    }
}
</code>```

答:
Your controller level route attribute is creating problem.

Both route attributes, at controller and action level, need a change.

First, remove your controller's route attribute

Then, modify action level route attributes as below

```<code>[Route("api/authenticate")]

[Route("api/JWTStatus")]
</code>```

Body:
I am trying to access a jwt controller in my dotnet core 3.1 solution.

Here is my jwt controller:

[Authorize]
[ApiController]
[Route("api/[controller]")]
public class JwtController : ControllerBase
{
        #region Variables
        private readonly IUserAuthorisationServices _tokenService;
        private readonly IOptions<JwtTokenOptions> jwtOptions;
        private readonly ILogger logger;
        private readonly JsonSerializerSettings _serializerSettings;
        #endregion

        public JwtController(IUserAuthorisationServices tokenService,
                             IOptions<JwtTokenOptions> jwtOptions,
                             ILoggerFactory loggerFactory)
        {
            if (loggerFactory is null) throw new ArgumentNullException(nameof(loggerFactory));

            _tokenService = tokenService ?? throw new ArgumentNullException(nameof(tokenService));

            jwtOptions = jwtOptions ?? throw new ArgumentNullException(nameof(jwtOptions));
            logger = loggerFactory.CreateLogger<JwtController>();
            _serializerSettings = new JsonSerializerSettings {
                Formatting = Formatting.Indented
            };
            //loggingRepository = _errorRepository;
            //ThrowIfInvalidOptions(this.jwtOptions);
        }

  [AllowAnonymous]
  [Route("authenticate")]
  [HttpPost]
  public async Task<IActionResult> Authenticate([FromBody] LoginViewModel model)
  {
            var userContext = _tokenService.Authenticate(model.Email, model.Password);

            if (userContext.Principal == null) {
                logger.LogInformation($"Invalid username ({model.Email}) or password ({model.Password})");
                return BadRequest(new { message = "Username or password is incorrect" });
            }

            return Ok(await _tokenService.CreateTokenAsync(userContext).ConfigureAwait(false));
  }

   [Route("JWTStatus")]
   [HttpGet]
   public static IActionResult GetJwtStatus()
   {
            // It made it here so it was authenticated.
            return new OkResult();
   }
}

I have stepped my way through the process and it gets to this middleware and then cannot find the controller returning immediately and at the same time providing the browser with a 404.

This is what I am using to access this controller action:

login(email: string, password: string) {
    this.userLogin.Email = email;
    this.userLogin.Password = password;

    // Do the fetch!
    const t = fetch("/api/authenticate",
            {
                method: "POST",
                body: JSON.stringify(this.userLogin),
                headers: new Headers({ "content-type": "application/json" })
            })
        .then(response => {

I note the fetch is using "api/authenticate" and when I look at the HttpRequest its got the same url yet it wont find it.

Here is the middleware that it gets to before just returning.

namespace JobsLedger.AUTHORISATION.API.SessionMiddleware
{
    public class ConfigureSessionMiddleware
    {
        private readonly RequestDelegate _next;

        public ConfigureSessionMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext httpContext, IUserSession userSession, ISessionServices sessionServices)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException(nameof(httpContext));
            }

            if (userSession == null)
            {
                throw new ArgumentNullException(nameof(userSession));
            }

            if (sessionServices == null)
            {
                throw new ArgumentNullException(nameof(sessionServices));
            }

            if (httpContext.User.Identities.Any(id => id.IsAuthenticated))
            {
                if (httpContext.Session.GetString("connectionString") == null) // Session needs to be set..
                {
                    userSession.UserId = httpContext.User.Claims.FirstOrDefault(x => x.Type == "userId")?.Value;
                    userSession.ConnectionString = sessionServices.ConnectionStringFromUserId(userSession.UserId);
                    httpContext.Session.SetString("userId", userSession.UserId);
                    httpContext.Session.SetString("connectionString", userSession.ConnectionString);
                }
                else  //  Session set so all we need to is to build userSession for data access..
                {
                    userSession.UserId = httpContext.Session.GetString("userId");
                    userSession.ConnectionString = httpContext.Session.GetString("connectionString");
                }
            }

            // Call the next delegate/middleware in the pipeline
            await _next.Invoke(httpContext).ConfigureAwait(false);
        }
    }
}

Its suppose to jump straight past this as there are no user identities as this hasnt been set yet. So really it goes straight to:

await _next.Invoke(httpContext).ConfigureAwait(false);

Then onto the controller action.. but it just goes straight out with a 404.

In the output window I am getting:

Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request starting HTTP/2.0 POST https://localhost:44301/api/authenticate text/plain;charset=UTF-8 76
Microsoft.AspNetCore.Cors.Infrastructure.CorsService: Information: CORS policy execution successful.
Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request finished in 17.1363ms 404

You can see the 404.

How is it cant find the action?

Is it possibly due to it being https and http 2.0?

For completeness here is the httpContext at the point of that middleware:

UPDATE...

I do not use MVC in the startup either just endpoints...

Maybe its the pipeline in Startup.cs.. here is my startup.cs

[assembly: NeutralResourcesLanguage("en")]

namespace JobsLedger.API {
    public class Startup {
        //private const string SecretKey = "needtogetthisfromenvironment";

        //private readonly SymmetricSecurityKey
        //  _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));
        private readonly IWebHostEnvironment _env;
        private readonly IConfiguration _configuration;  // { get; }

        public Startup(IWebHostEnvironment env, IConfiguration configuration) {
            _env = env;
            _configuration = configuration;
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services) {
            // Add framework services.
            services.AddCors();
            services.AddControllers();
            services.AddOptions();

            services.AddDbContext<CATALOGContext>(options => options.UseSqlServer(_configuration.GetConnectionString("CatalogConnection"), b => b.MigrationsAssembly("JobsLedger.CATALOG")));
            services.AddDbContext<DATAContext>(options => options.UseSqlServer(_configuration.GetConnectionString("TenantDbConnection"), a => a.MigrationsAssembly("JobsLedger.DATA")));

            // Make authentication compulsory across the board (i.e. shut
            // down EVERYTHING unless explicitly opened up).
            // Use policy auth.
            services.AddAuthorization(options => {
                options.AddPolicy("TenantAdmin", policy => policy.RequireClaim(ClaimTypes.Role, "TenantAdmin"));
                options.AddPolicy("Admin", policy => policy.RequireClaim(ClaimTypes.Role, "Admin"));
                options.AddPolicy("Employee", policy => policy.RequireClaim(ClaimTypes.Role, "Employee"));
            });

            //services.ConfigureApplicationInjection();

            // Get jwt options from app settings
            var tokenOptions = _configuration.GetSection("Authentication").Get<JwtTokenOptions>();

            services.AddAuthentication(x => {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options => {
                options.TokenValidationParameters = new TokenValidationParameters {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    RequireExpirationTime = true,
                    ValidIssuer = tokenOptions.Issuer,
                    ValidAudience = tokenOptions.Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(
                        Encoding.UTF8.GetBytes(tokenOptions.SigningKey)),
                    ClockSkew = TimeSpan.Zero
                };
            });

            services
                .AddDistributedMemoryCache()
                .AddSession()

                // Repositories - DATA
                .AddScoped<IClientDATARepository, ClientDATARepository>()
                .AddScoped<ILoggingDATARepository, LoggingDATARepository>()
                .AddScoped<IJobDATARepository, JobDATARepository>()
                .AddScoped<IBrandDATARepository, BrandDATARepository>()
                .AddScoped<ITypeDATARepository, TypeDATARepository>()
                .AddScoped<IStateDATARepository, StateDATARepository>()
                .AddScoped<IStatusDATARepository, StatusDATARepository>()
                .AddScoped<ISuburbDATARepository, SuburbDATARepository>()
                .AddScoped<ICounterDATARepository, CounterDATARepository>()

                // Repositories - CATALOG
                .AddScoped<ITenantCATALOGRepository, TenantCATALOGRepository>()
                .AddScoped<IUserCATALOGRepository, UserCATALOGRepository>()
                .AddScoped<IRoleCATALOGRepository, RoleCATALOGRepository>()
                .AddScoped<ICounterCATALOGRepository, CounterCATALOGRepository>()
                .AddScoped<ISuburbCATALOGRepository, SuburbCATALOGRepository>()
                .AddScoped<IStateCATALOGRepository, StateCATALOGRepository>()

                // Business services
                // Services - API
                .AddScoped<IClientServices, ClientServices>()
                .AddScoped<IJobServices, JobServices>()

                //Services - Catalog
                .AddScoped<ITenantServices, TenantServices>()
                .AddScoped<IUserServices, UserServices>()
                //.AddScoped<IUserValidateService, UserValidateService>()

                // Services - Shared
                .AddScoped<IAddressDropdownServices, AddressDropdownServices>()

                //Services - Auth
                .AddScoped<ICryptoService, CryptoService>()
                .AddScoped<IUserAuthorisationServices, UserAuthorisationServices>()
                .AddScoped<IUserSession, UserSession>()
                .AddScoped<ISessionServices, SessionServices>()

                // CATALOG services - Initialisations.
                .AddScoped<ICATALOGCounterInitialiser, CATALOGCounterInitialiser>()
                .AddScoped<ICATALOGStateInitialiser, CATALOGStateInitialiser>()
                .AddScoped<ICATALOGSuburbInitialiser, CATALOGSuburbInitialiser>()
                .AddScoped<IRoleInitialiser, CATALOGRoleInitialiser>()
                .AddScoped<ICATALOGTenantAndUserInitialisations, CATALOGTenantAndUserInitialiser>()

                // DATA Services - Initialisations.
                .AddScoped<IBrandInitialiser, BrandInitialiser>()
                .AddScoped<IDATACounterInitialiser, DATACounterInitialiser>()
                .AddScoped<IDATAStateInitialiser, DATAStateInitialiser>()
                .AddScoped<IDATASuburbInitialiser, DATASuburbInitialiser>()
                .AddScoped<IStatusInitialiser, StatusInitialiser>()
                .AddScoped<ITypeInitialiser, TypeInitialiser>()
                .AddScoped<IVisitTypeInitialiser, VisitTypeInitialiser>()

                // TESTDATA Services - Initialisations.
                .AddScoped<ITESTDATAInitialisations, TESTDATAInitialisations>()
                .AddScoped<ITESTDATATenantAndUserInitialisations, TESTDATATenantAndUserInitialisations>()

                .AddTransient<IDATAContextFactory, DATAContextFactory>()
                .AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); // For getting the user.
        }

        public static void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
            if (env.IsDevelopment()) {
                app.UseDeveloperExceptionPage();
            }
            else {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseExceptionHandler(options => {
                options.Run(async context => {
                    var ex = context.Features.Get<IExceptionHandlerPathFeature>();
                    if (ex?.Error != null) {
                        Debugger.Break();
                    }
                });
            });

            app.UseRouting();

            // global cors policy
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());

            app.UseAuthentication();
            app.UseHttpsRedirection();
            app.UseFileServer();
            app.UseStaticFiles();
            app.UseSession();
            app.UseAuthorization();

            app.UseConfigureSession();

            app.EnsureCATALOGMigrationAndInitialise();
            app.EnsureDATAMigrationsAndInitialise();

            app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
        }
    }
}

Body:
Your controller level route attribute is creating problem.

Both route attributes, at controller and action level, need a change.

First, remove your controller's route attribute

Then, modify action level route attributes as below

[Route("api/authenticate")]

[Route("api/JWTStatus")]


来源: stackexchange

问:
Multiple plots are not showing up in a single figure
Am using following code to print to plot stock prices and a vertical line on one graph. But of them work individually but i cant plot both on one graph

```<code>import datetime as dt
import yfinance as yf
import matplotlib.pyplot as plt

# Get the data for the stock Apple by specifying the stock ticker, start date, and end date
data = yf.download('AAPL','2020-02-01','2020-02-10', interval='15m')

data.Close.plot(figsize=(10, 5))
plt.axvline(dt.datetime(2020, 2, 2)) ## No effect if previous line is there.

plt.show()
</code>```

The vertical line is shown only if i comment data.Close.plot(figsize=(10, 5)) line

答:
Its always good to get the figure and the axes handles such that subsequent manipulation can be done easily.

```<code>import datetime as dt
import yfinance as yf
import matplotlib.pyplot as plt
# added following line to avoid a warning of future support of datetime
# https://github.com/pandas-dev/pandas/issues/18301#issuecomment-344580274
from pandas.plotting import register_matplotlib_converters

# Get the data for the stock Apple by specifying the stock ticker, start date, and end date
data = yf.download('AAPL','2020-02-01','2020-02-10', interval='15m')
register_matplotlib_converters()
fig, ax = plt.subplots(1, figsize=(10, 5))
ax.plot(data.Close)
ax.axvline(dt.datetime(2020, 2, 2), color='red')
plt.show()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Am using following code to print to plot stock prices and a vertical line on one graph. But of them work individually but i cant plot both on one graph

import datetime as dt
import yfinance as yf
import matplotlib.pyplot as plt

# Get the data for the stock Apple by specifying the stock ticker, start date, and end date
data = yf.download('AAPL','2020-02-01','2020-02-10', interval='15m')

data.Close.plot(figsize=(10, 5))
plt.axvline(dt.datetime(2020, 2, 2)) ## No effect if previous line is there.

plt.show()

The vertical line is shown only if i comment data.Close.plot(figsize=(10, 5)) line

Body:
Its always good to get the figure and the axes handles such that subsequent manipulation can be done easily.

import datetime as dt
import yfinance as yf
import matplotlib.pyplot as plt
# added following line to avoid a warning of future support of datetime
# https://github.com/pandas-dev/pandas/issues/18301#issuecomment-344580274
from pandas.plotting import register_matplotlib_converters

# Get the data for the stock Apple by specifying the stock ticker, start date, and end date
data = yf.download('AAPL','2020-02-01','2020-02-10', interval='15m')
register_matplotlib_converters()
fig, ax = plt.subplots(1, figsize=(10, 5))
ax.plot(data.Close)
ax.axvline(dt.datetime(2020, 2, 2), color='red')
plt.show()


问:
What is the cygwin equivalent of the mac command "cd ~/Documents"?
I saw this command on a tutorial and I'm not sure what the Cygwin analogue is. Any support is greatly apprecated. </p>

答:
as ~ means the Cygwin home directory and probably you want the Windows Home Directory that it can be different, so try

```<code>cd /cygdrive/c/users/your_windows_user_name/Documents
</code>```

If instead you want really the Cygwin Home Directory than the command is the same

```<code>cd ~/Documents
</code>```

Body:
as ~ means the Cygwin home directory and probably you want the Windows Home Directory that it can be different, so try

cd /cygdrive/c/users/your_windows_user_name/Documents

If instead you want really the Cygwin Home Directory than the command is the same

cd ~/Documents


问:
Mocking django Form cleaned_data field
I have a simple django form like this:

```<code>class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField(widget=forms.Textarea)
</code>```

My view uses it like this:

```<code>def my_view(request):
  form = ContactForm(request.POST)
  if form.is_valid():
    data = form.cleaned_data

  ...
</code>```

I want to test my view and don't care about what the form actually does. This is what my test looks like so far

```<code>@patch.object(ContactForm, 'is_valid')
def test_my_view(mock_is_valid):
  is_valid.return_value = True

  ...
  assert response.status_code == 201

</code>```

However, this doesn't work because form.cleaned_data is not set until form.is_valid() is called. How do I mock out the form.cleaned_data attribute if it doesn't exist in the first place?

答:
You can mock the whole form class instead of just one method:

```<code>@patch('myapp.views.ContactForm')
def test_my_view(mock_form_class):
    mock_form_class.return_value.is_valid = True
    mock_form_class.return_value.cleaned_data = {}
    ...
    assert response.status_code == 201
</code>```

Where myapp.views needs to be replaced with the dotted path to your app's views module. It assumes that you are importing the ContactForm into that module, e.g., with from .forms import ContactForm.

Title: Mocking django Form cleaned_data field

Body:
I have a simple django form like this:

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField(widget=forms.Textarea)

My view uses it like this:

def my_view(request):
  form = ContactForm(request.POST)
  if form.is_valid():
    data = form.cleaned_data

  ...

I want to test my view and don't care about what the form actually does. This is what my test looks like so far

@patch.object(ContactForm, 'is_valid')
def test_my_view(mock_is_valid):
  is_valid.return_value = True

  ...
  assert response.status_code == 201

However, this doesn't work because form.cleaned_data is not set until form.is_valid() is called. How do I mock out the form.cleaned_data attribute if it doesn't exist in the first place?

Body:
You can mock the whole form class instead of just one method:

@patch('myapp.views.ContactForm')
def test_my_view(mock_form_class):
    mock_form_class.return_value.is_valid = True
    mock_form_class.return_value.cleaned_data = {}
    ...
    assert response.status_code == 201

Where myapp.views needs to be replaced with the dotted path to your app's views module. It assumes that you are importing the ContactForm into that module, e.g., with from .forms import ContactForm.


问:
create a reusable partial or component in Angular (8.0) that will be used in FormGroup & FormArray
```<code>form( [formGroup]="form" )
  div( '[formGroupName]'="formGroupName" )
    .form-group
      label
        | Address
      input.form-control(
        type="text"
        formControlName="address"
      )
  div(formArrayName="sub_addresses_attributes")
    div(
      '*ngFor'="let sub_addresses_attribute of form.get('sub_addresses_attributes')['controls']; let i=index"
    )
      div( '[formGroupName]'="i" )
        .form-group
          label
            | Address
          input.form-control(
            type="text"
            formControlName="address"
          )
</code>```

I would like to create a component or partial or template that can DRY-up the code above.

This is may parent/main component: parent.component.ts

```<code>this.fb.group({
  'sub_addresses_attributes': this.fb.array([]),
  'address_attributes': {
    'id': [],
    'address': []
  }
}
</code>```

Here the partial component I am trying to create

```<code>div( '[formGroup]'="FROM_@INPUT" )
  div( '[formGroupName]'="FROM_@INPUT" )
    .form-group
      label
        | Address
      input.form-control(
        type="text"
        formControlName="address"
      )
</code>```

However, formGroupName is required for the address_attributes, while not on formArray.

答:
I have found that when splitting out forms into reusable components, the form group needs to be set on the innermost component that contains the form control itself.

My component hierarchy is something like this, where each my-* component is a different custom component:

```<code><my-form>
  <my-form-controls>
    <my-form-control *ngFor="let control of controls">
      <div #controlcontainer>
      </div>
    </my-form-control>
  </my-form-controls>
</my-form>
</code>```

I then inject the form control itself into #controlcontainer. The controls themselves looks something like:

```<code><div [formGroup]="formGroup">
  <input [name]="name" />
</div>
</code>```

When creating this hierarchy, I found that [formGroup] has to be set on the component that hosts the input - it doesn't get inherited from parent components.

If I understand your question correctly, I think you want to achieve something fairly similar - reuse form components and use [formGroup].

Body:
form( [formGroup]="form" )
  div( '[formGroupName]'="formGroupName" )
    .form-group
      label
        | Address
      input.form-control(
        type="text"
        formControlName="address"
      )
  div(formArrayName="sub_addresses_attributes")
    div(
      '*ngFor'="let sub_addresses_attribute of form.get('sub_addresses_attributes')['controls']; let i=index"
    )
      div( '[formGroupName]'="i" )
        .form-group
          label
            | Address
          input.form-control(
            type="text"
            formControlName="address"
          )

I would like to create a component or partial or template that can DRY-up the code above.

This is may parent/main component: parent.component.ts

this.fb.group({
  'sub_addresses_attributes': this.fb.array([]),
  'address_attributes': {
    'id': [],
    'address': []
  }
}

Here the partial component I am trying to create

div( '[formGroup]'="FROM_@INPUT" )
  div( '[formGroupName]'="FROM_@INPUT" )
    .form-group
      label
        | Address
      input.form-control(
        type="text"
        formControlName="address"
      )

However, formGroupName is required for the address_attributes, while not on formArray.

Body:
I have found that when splitting out forms into reusable components, the form group needs to be set on the innermost component that contains the form control itself.

My component hierarchy is something like this, where each my-* component is a different custom component:

<my-form>
  <my-form-controls>
    <my-form-control *ngFor="let control of controls">
      <div #controlcontainer>
      </div>
    </my-form-control>
  </my-form-controls>
</my-form>

I then inject the form control itself into #controlcontainer. The controls themselves looks something like:

<div [formGroup]="formGroup">
  <input [name]="name" />
</div>

When creating this hierarchy, I found that [formGroup] has to be set on the component that hosts the input - it doesn't get inherited from parent components.

If I understand your question correctly, I think you want to achieve something fairly similar - reuse form components and use [formGroup].


问:
How to turn a java Json data Fetching class into a method?
I got a method that fetch data from a web service, so Im looking for a way to call it as a method.
How can I turn this code into a method? or can I call a class in a method? because it has a protected method and extended from a class, but if I implemented the extended class AsyncTask to the class I need to use the Json fetching protected method doInBackground it says "Interface expexted here".
Here's my code that I need to convert it to a method or a way to add it to the class I want to use it in:

Notice: I already extended AppCompatActivity to the class I want to call doInBackground in so I cannot extend FetchData class.

Thanks a lot :D

```<code>package com.example.wordspuzzlejsontest;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class FetchData extends AsyncTask<Void, Void, Void> {

    final String update = "4";
    String data = "";
    int currentLevel;

    Context context;

    FetchData(Context context) {
        this.context = context;
    }

    @Override
    protected Void doInBackground(Void... voids) {
        try {
            URL url = new URL("https://api.jsonbin.io/b/5e42776dd18e4016617690ce/" + update);

            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            while (line != null) {
                line = bufferedReader.readLine();
                data = data + line;
            }

            JSONArray JA = new JSONArray(data);

            SharedPreferences sharedPreferences = context.getSharedPreferences("SHARED_PREFS", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();

            currentLevel = sharedPreferences.getInt("currentLevel", 0);

            for (int i = 0; i < JA.length();) {

                i = currentLevel;
                JSONObject JO = (JSONObject) JA.get(i);

                String id = (String) JO.get("id");
                String img = (String) JO.get("img");
                String w1 = (String) JO.get("w1");
                String w2 = (String) JO.get("w2");
                String w3 = (String) JO.get("w3");
                String w4 = (String) JO.get("w4");

                editor.putString("id" + i, id);
                editor.putString("img" + i, img);
                editor.putString("w1" + i, w1);
                editor.putString("w2" + i, w2);
                editor.putString("w3" + i, w3);
                editor.putString("w4" + i, w4);

                editor.apply();
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

}

```
```

答:
Summing up my comments:

Create a new class called NewClass.java

```<code>class NewClass extends FetchData{
  public Void fetchData(Void... voids){ return this.doInBackground(voids);}
}

</code>```

Since doInBackground in a protected method, you will have private access inside NewClass.java

Body:
I got a method that fetch data from a web service, so Im looking for a way to call it as a method.
How can I turn this code into a method? or can I call a class in a method? because it has a protected method and extended from a class, but if I implemented the extended class AsyncTask to the class I need to use the Json fetching protected method doInBackground it says "Interface expexted here".
Here's my code that I need to convert it to a method or a way to add it to the class I want to use it in:

Notice: I already extended AppCompatActivity to the class I want to call doInBackground in so I cannot extend FetchData class.

Thanks a lot :D

package com.example.wordspuzzlejsontest;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class FetchData extends AsyncTask<Void, Void, Void> {

    final String update = "4";
    String data = "";
    int currentLevel;

    Context context;

    FetchData(Context context) {
        this.context = context;
    }

    @Override
    protected Void doInBackground(Void... voids) {
        try {
            URL url = new URL("https://api.jsonbin.io/b/5e42776dd18e4016617690ce/" + update);

            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            while (line != null) {
                line = bufferedReader.readLine();
                data = data + line;
            }

            JSONArray JA = new JSONArray(data);

            SharedPreferences sharedPreferences = context.getSharedPreferences("SHARED_PREFS", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();

            currentLevel = sharedPreferences.getInt("currentLevel", 0);

            for (int i = 0; i < JA.length();) {

                i = currentLevel;
                JSONObject JO = (JSONObject) JA.get(i);

                String id = (String) JO.get("id");
                String img = (String) JO.get("img");
                String w1 = (String) JO.get("w1");
                String w2 = (String) JO.get("w2");
                String w3 = (String) JO.get("w3");
                String w4 = (String) JO.get("w4");

                editor.putString("id" + i, id);
                editor.putString("img" + i, img);
                editor.putString("w1" + i, w1);
                editor.putString("w2" + i, w2);
                editor.putString("w3" + i, w3);
                editor.putString("w4" + i, w4);

                editor.apply();
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

}

```

Body:
Summing up my comments:

Create a new class called NewClass.java

class NewClass extends FetchData{
  public Void fetchData(Void... voids){ return this.doInBackground(voids);}
}

Since doInBackground in a protected method, you will have private access inside NewClass.java


问:
Multiple student entry using structure and functions in cpp
I used structure for multiple entry of students. But I am getting error in the following code:

```<code>#include <iostream>
using namespace std;
struct Student{
   char stuName[30];
   int stuRollNo;
   int stuAge;
};

void printStudentInfo(struct Student s[]);

int main(){
    int i;
    for(i=0;i<3;i++){
   Student s[i];
   cout<<"Enter Student Name: ";
   cin.getline(s[i].stuName, 30);
   cout<<"Enter Student Roll No: ";
   cin>>s[i].stuRollNo;
   cout<<"Enter Student Age: ";
   cin>>s[i].stuAge;
   printStudentInfo(s[i]);}
   return 0;
}

void printStudentInfo(struct Student s[i]){
   cout<<"Student Record:"<<endl;
   cout<<"Name: "<<s[i].stuName<<endl;
   cout<<"Roll No: "<<s[i].stuRollNo<<endl;
   cout<<"Age: "<<s[i].stuAge;
}
</code>```

error:

```<code>main.cpp:29:25: error: cannot convert ‘Student’ to ‘Student*’ for argument ‘1’ to ‘void printStudentInfo(Student*)’
    printStudentInfo(s[i]);}
                         ^
main.cpp: At global scope:
main.cpp:33:40: error: ‘i’ was not declared in this scope
 void printStudentInfo(struct Student s[i]){
                                        ^
main.cpp: In function ‘void printStudentInfo(...)’:
main.cpp:35:20: error: ‘s’ was not declared in this scope
    cout<<"Name: "<<s[i].stuName<<endl;
                    ^
main.cpp:35:22: error: ‘i’ was not declared in this scope
    cout<<"Name: "<<s[i].stuName<<endl;
</code>```

I get the point that I need to define i in the function but how will it take values accordingly. If i take a for loop in the function the values will get printed more than the time required. If i do not take an array it will give a segmentation fault.

Please help me with this code. I am new to c++.

答:
There are several things incorrect. When using C++ please consider adopting the correct objects such as std::string for storing the student name. Also, differently from C, we don't have to specify the struct keyword when passing as a function parameter.

Also, the way you were passing the structure to the printStudentInfo() function was wrong. Additionally, I suggest against using namespace std if possible.

Here follows a minimal correction of your code (please note that it can be further improved, I just got it barely working):

```<code>#include <iostream>
#include <string>

struct Student{
   std::string stuName;
   int stuRollNo;
   int stuAge;
};

void printStudentInfo(const Student& s);

int main()
{
    Student s[3];
    for(int i=0;i<3;i++)
    {
        std::cout<<"Enter Student Name: ";

        if (i) std::cin.ignore();
        std::getline(std::cin, s[i].stuName);

        std::cout<<"Enter Student Roll No: ";
        std::cin>>s[i].stuRollNo;

        std::cout<<"Enter Student Age: ";
        std::cin>>s[i].stuAge;

        printStudentInfo(s[i]);
   }
   return 0;
}

void printStudentInfo(const Student& s){
   std::cout<<"Student Record:"<<std::endl;
   std::cout<<"Name: "<<s.stuName<<std::endl;
   std::cout<<"Roll No: "<<s.stuRollNo<<std::endl;
   std::cout<<"Age: "<<s.stuAge<<std::endl;
}
</code>```

Body:
I used structure for multiple entry of students. But I am getting error in the following code:

#include <iostream>
using namespace std;
struct Student{
   char stuName[30];
   int stuRollNo;
   int stuAge;
};

void printStudentInfo(struct Student s[]);

int main(){
    int i;
    for(i=0;i<3;i++){
   Student s[i];
   cout<<"Enter Student Name: ";
   cin.getline(s[i].stuName, 30);
   cout<<"Enter Student Roll No: ";
   cin>>s[i].stuRollNo;
   cout<<"Enter Student Age: ";
   cin>>s[i].stuAge;
   printStudentInfo(s[i]);}
   return 0;
}

void printStudentInfo(struct Student s[i]){
   cout<<"Student Record:"<<endl;
   cout<<"Name: "<<s[i].stuName<<endl;
   cout<<"Roll No: "<<s[i].stuRollNo<<endl;
   cout<<"Age: "<<s[i].stuAge;
}

error:

main.cpp:29:25: error: cannot convert ‘Student’ to ‘Student*’ for argument ‘1’ to ‘void printStudentInfo(Student*)’
    printStudentInfo(s[i]);}
                         ^
main.cpp: At global scope:
main.cpp:33:40: error: ‘i’ was not declared in this scope
 void printStudentInfo(struct Student s[i]){
                                        ^
main.cpp: In function ‘void printStudentInfo(...)’:
main.cpp:35:20: error: ‘s’ was not declared in this scope
    cout<<"Name: "<<s[i].stuName<<endl;
                    ^
main.cpp:35:22: error: ‘i’ was not declared in this scope
    cout<<"Name: "<<s[i].stuName<<endl;

I get the point that I need to define i in the function but how will it take values accordingly. If i take a for loop in the function the values will get printed more than the time required. If i do not take an array it will give a segmentation fault.

Please help me with this code. I am new to c++.

Body:
There are several things incorrect. When using C++ please consider adopting the correct objects such as std::string for storing the student name. Also, differently from C, we don't have to specify the struct keyword when passing as a function parameter.

Also, the way you were passing the structure to the printStudentInfo() function was wrong. Additionally, I suggest against using namespace std if possible.

Here follows a minimal correction of your code (please note that it can be further improved, I just got it barely working):

#include <iostream>
#include <string>

struct Student{
   std::string stuName;
   int stuRollNo;
   int stuAge;
};

void printStudentInfo(const Student& s);

int main()
{
    Student s[3];
    for(int i=0;i<3;i++)
    {
        std::cout<<"Enter Student Name: ";

        if (i) std::cin.ignore();
        std::getline(std::cin, s[i].stuName);

        std::cout<<"Enter Student Roll No: ";
        std::cin>>s[i].stuRollNo;

        std::cout<<"Enter Student Age: ";
        std::cin>>s[i].stuAge;

        printStudentInfo(s[i]);
   }
   return 0;
}

void printStudentInfo(const Student& s){
   std::cout<<"Student Record:"<<std::endl;
   std::cout<<"Name: "<<s.stuName<<std::endl;
   std::cout<<"Roll No: "<<s.stuRollNo<<std::endl;
   std::cout<<"Age: "<<s.stuAge<<std::endl;
}


问:
How can I install keycloak as a service, so it starts automatically?
I have installed wildfly 10.0 as a service, I ran the service.bat file, but i need keyloak as service too. If I run keycloak's service.bat file it says:

ERROR: Service Wildfly already exists.

My keycloak version is 3.3.0, so basically the service of keycloak wants to install wildfly as service, or I don't understand.

答:
Wildfly is the default name used to create the service. You can change the defaults in the service.bat file. Look for the following entries in the file and update as required before executing service install.

```<code>rem defaults
set SHORTNAME=Wildfly
rem NO quotes around the display name here !
set DISPLAYNAME=WildFly
rem NO quotes around the description here !
set DESCRIPTION=WildFly Application Server
</code>```

Body:
Wildfly is the default name used to create the service. You can change the defaults in the service.bat file. Look for the following entries in the file and update as required before executing service install.

rem defaults
set SHORTNAME=Wildfly
rem NO quotes around the display name here !
set DISPLAYNAME=WildFly
rem NO quotes around the description here !
set DESCRIPTION=WildFly Application Server


问:
if I delete a row in SQLite, how can I make other below rows to go up and fill the deleted row?
```<code>3|banana|sweet|tomato
4|happy|sad|love
</code>```

I deleted the first and the second row, I'd like the others(the 3rd and the 4th) to go up and each of them to become the first and the second. How can I do this?

For example, the query for creating table:

CREATE TABLE IF NOT EXISTS dfl (ID INTEGER PRIMARY KEY AUTOINCREMENT, A TEXT, B TEXT, C TEXT)
```

<p>The query for deleting row:</p>

<pre class="lang-sql prettyprint-override"><code>delete from dfl where ID=1
</code>```

答:
Actually you don't do this!

Don't mess with the autoincrement keys. The DB needs it to identify the record. Leave it. If you need a rank column then you can generate it on-the-fly in your select query:

```<code>SELECT *, RANK () OVER (ORDER BY id) rank_column
FROM dfl
order by id
</code>```

Body:
3|banana|sweet|tomato
4|happy|sad|love

I deleted the first and the second row, I'd like the others(the 3rd and the 4th) to go up and each of them to become the first and the second. How can I do this?

For example, the query for creating table:

CREATE TABLE IF NOT EXISTS dfl (ID INTEGER PRIMARY KEY AUTOINCREMENT, A TEXT, B TEXT, C TEXT)

The query for deleting row:

delete from dfl where ID=1

Body:
Actually you don't do this!

Don't mess with the autoincrement keys. The DB needs it to identify the record. Leave it. If you need a rank column then you can generate it on-the-fly in your select query:

SELECT *, RANK () OVER (ORDER BY id) rank_column
FROM dfl
order by id


问:
How to convert a `const char *` to simply `char *`?
I'm using the pdCurses library and am aiming to only really use strings in my C++ console game but the curses mvinstr() function or any insert function requires a non-const char * as a parameter.

My solution at first to this problem was simply entering in string.c_str(), but that returns a const char * which apparently doesn't work with the function.

Next I put (char *)string.c_str() but this only causes an unhandled exception.

Finally I just tried char *test = string.c_str() but that's not compatible with const either.

What do I do to solve this?

K i just tried const_cast() and i still get an exception thrown and break....
I don't know why PDcurses only takes non-const char pointers.... =(

alright making a char* buffer didn't work when i used this code (time_s is the sting):

```<code>size_t length;
    char buffer[12];
    length=time_s.copy(buffer,5,0);
    buffer[length]='\0';
mvinstr(time_loc_y, time_loc_x, buffer);
</code>```

i even put a stop before mvinstr() and checked the buffer's contents which was "00   /0"
EXACTLY WHAT I WANTED.

but i get an access violation point to "xutility"....

答:
Cautiously - if the code that uses the was-const data tries to modify it, anything can happen.

In short:

```<code>const std::string str = "...";
char *caution = const_cast<char *>(str.c_str());
</code>```

However, given that you are getting unhandled exceptions, you probably need to make a modifiable copy of the constant string before calling mvinstr().  Maybe:

```<code>const std::string str = "...";
char *caution = new char[str.length()+1];
str.copy(caution, str.length()+1);
...call to mvinstr()...
delete[] caution;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using the pdCurses library and am aiming to only really use strings in my C++ console game but the curses mvinstr() function or any insert function requires a non-const char * as a parameter.

My solution at first to this problem was simply entering in string.c_str(), but that returns a const char * which apparently doesn't work with the function.

Next I put (char *)string.c_str() but this only causes an unhandled exception.

Finally I just tried char *test = string.c_str() but that's not compatible with const either.

What do I do to solve this?

K i just tried const_cast() and i still get an exception thrown and break....
I don't know why PDcurses only takes non-const char pointers.... =(

alright making a char* buffer didn't work when i used this code (time_s is the sting):

size_t length;
    char buffer[12];
    length=time_s.copy(buffer,5,0);
    buffer[length]='\0';
mvinstr(time_loc_y, time_loc_x, buffer);

i even put a stop before mvinstr() and checked the buffer's contents which was "00   /0"
EXACTLY WHAT I WANTED.

but i get an access violation point to "xutility"....

Body:
Cautiously - if the code that uses the was-const data tries to modify it, anything can happen.

In short:

const std::string str = "...";
char *caution = const_cast<char *>(str.c_str());

However, given that you are getting unhandled exceptions, you probably need to make a modifiable copy of the constant string before calling mvinstr().  Maybe:

const std::string str = "...";
char *caution = new char[str.length()+1];
str.copy(caution, str.length()+1);
...call to mvinstr()...
delete[] caution;


问:
Getting string input and displaying input with DOS interrupts MASM
In MASM, I created a buffer variable to hold the user string input from keyboard. I am stuck on how to hold the string input into that buffer variable. I don't have any libraries linked like the irvine ones and want to do this with DOS interrupts. So far I have something along the lines of

```<code>            .model small

            .stack 100h

            .data
buff        db  25 dup(0), 10, 13
lbuff       EQU ($ - buff)              ; bytes in a string

            .code
main:
            mov ax, @data
            mov ds, ax

            mov ah, 0Ah         ; doesn't work
            mov buff, ah        ; doesn't seem right
            int 21h

            mov     ax, 4000h       ; display to screen
            mov     bx, 1
            mov     cx, lbuff
            mov     dx, OFFSET buff
            int     21h

            mov ah, 4ch
            int 21h

            end main
</code>```

I assume using 0Ah is correct as it is for reading array of input of buffered characters.

答:
;try this one, it takes a 10 character string input from user and displays it after in this manner, "Hello *10character string input"</p>

```<code>.MODEL TINY
.CODE
.286
ORG 100h

    START:
     MOV DX, OFFSET BUFFER
     MOV AH, 0ah
     INT 21h
     JMP PRINT
     BUFFER DB 10,?, 10 dup(' ')

     PRINT:
     MOV AH, 02
     MOV DL, 0ah
     INT 21h
     MOV AH, 9
     MOV DX, OFFSET M1
     INT 21h
     XOR BX, BX
     MOV BL, BUFFER[1]
     MOV BUFFER [BX+2], '$'
     MOV DX, OFFSET BUFFER +2
     MOV AH, 9
     INT 21h

    M1: db 'Hello $'

 END START
 END
</code>```

Body:
In MASM, I created a buffer variable to hold the user string input from keyboard. I am stuck on how to hold the string input into that buffer variable. I don't have any libraries linked like the irvine ones and want to do this with DOS interrupts. So far I have something along the lines of

            .model small

            .stack 100h

            .data
buff        db  25 dup(0), 10, 13
lbuff       EQU ($ - buff)              ; bytes in a string

            .code
main:
            mov ax, @data
            mov ds, ax

            mov ah, 0Ah         ; doesn't work
            mov buff, ah        ; doesn't seem right
            int 21h

            mov     ax, 4000h       ; display to screen
            mov     bx, 1
            mov     cx, lbuff
            mov     dx, OFFSET buff
            int     21h

            mov ah, 4ch
            int 21h

            end main

I assume using 0Ah is correct as it is for reading array of input of buffered characters.

Body:
;try this one, it takes a 10 character string input from user and displays it after in this manner, "Hello *10character string input"

.MODEL TINY
.CODE
.286
ORG 100h

    START:
     MOV DX, OFFSET BUFFER
     MOV AH, 0ah
     INT 21h
     JMP PRINT
     BUFFER DB 10,?, 10 dup(' ')

     PRINT:
     MOV AH, 02
     MOV DL, 0ah
     INT 21h
     MOV AH, 9
     MOV DX, OFFSET M1
     INT 21h
     XOR BX, BX
     MOV BL, BUFFER[1]
     MOV BUFFER [BX+2], '$'
     MOV DX, OFFSET BUFFER +2
     MOV AH, 9
     INT 21h

    M1: db 'Hello $'

 END START
 END


问:
Swift: Keep assignment made in closure
Trying to keep a changed value outside a closure. Assigning length from a child in a Firebase database within the observeSingleEvent() call. However, after the function, length's assignment is not kept for use in the for loop, the initial value is used.

Furthermore, I append() a bunch of GMSMarker Objects to the list markers but again the appends are not kept and the list is returned empty

How can I keep the assignments done in the closures. I know in C++ you can use & like [&varName] to pass by reference. Have not found something similar regarding Swift.

```<code>func loadMarkersFromDatabase(ref:DatabaseReference, node:String) -> [GMSMarker] {
        var markers = [GMSMarker]()
        var length:Int? = 1
        ref.child("Config").observeSingleEvent(of: .value, with: { (snapshot) in
                let value = snapshot.value as? NSDictionary
                length = (value?["AcademicBuildingsLength"] as? Int ?? 0)
            })
        print(length!)
        for i in 0...length! {
            ref.child(node).child(String(i)).observeSingleEvent(of: .value, with: { (snapshot) in
                let value = snapshot.value as? NSDictionary
                let building = value?["building"] as? String ?? ""
                let lat = value?["lat"] as? Double ?? 0.0
                let lon = value?["long"] as? Double ?? 0.0
                let marker = GMSMarker()
                marker.position = CLLocationCoordinate2D(latitude: lat, longitude: lon)
                marker.title = building
                marker.snippet = node
                markers.append(marker)
            })

        }
        return markers

    }
</code>```

I have tried adding a closure block [length] like this but then get this compile error: Cannot assign to value: 'length' is an immutable capture

```<code>ref.child("Config").observeSingleEvent(of: .value, with: { [length](snapshot) in
                let value = snapshot.value as? NSDictionary
                length = (value?["AcademicBuildingsLength"] as? Int ?? 0)
            })
</code>```

答:
Closures are asynchronously executed on another background thread. Because of this, you cannot mutate variables outside of this block and may have to use completion closures. To accomplish what you want, you will can call another function within your closure:

```<code>func loadMarkersFromDatabase(ref:DatabaseReference, node:String, completion: @escaping ([GMSMarker]) -> Void) {
    ref.child("Config").observeSingleEvent(of: .value, with: { [length](snapshot) in
        let value = snapshot.value as? NSDictionary
        let markers = myFunction((value?["AcademicBuildingsLength"] as? Int ?? 0))
        completion(markers)
    }
}
</code>```

and then:

```<code>func myFunction(length: Int) -> [GMSMarker] {
    var markers: [GMSMarker] = []
    for i in 0...length! {
            ref.child(node).child(String(i)).observeSingleEvent(of: .value, with: { (snapshot) in
                let value = snapshot.value as? NSDictionary
                let building = value?["building"] as? String ?? ""
                let lat = value?["lat"] as? Double ?? 0.0
                let lon = value?["long"] as? Double ?? 0.0
                let marker = GMSMarker()
                marker.position = CLLocationCoordinate2D(latitude: lat, longitude: lon)
                marker.title = building
                marker.snippet = node
                markers.append(marker)
            })
        }
    return markers
}
</code>```

Title: Swift: Keep assignment made in closure

Body:
Trying to keep a changed value outside a closure. Assigning length from a child in a Firebase database within the observeSingleEvent() call. However, after the function, length's assignment is not kept for use in the for loop, the initial value is used.

Furthermore, I append() a bunch of GMSMarker Objects to the list markers but again the appends are not kept and the list is returned empty

How can I keep the assignments done in the closures. I know in C++ you can use & like [&varName] to pass by reference. Have not found something similar regarding Swift.

func loadMarkersFromDatabase(ref:DatabaseReference, node:String) -> [GMSMarker] {
        var markers = [GMSMarker]()
        var length:Int? = 1
        ref.child("Config").observeSingleEvent(of: .value, with: { (snapshot) in
                let value = snapshot.value as? NSDictionary
                length = (value?["AcademicBuildingsLength"] as? Int ?? 0)
            })
        print(length!)
        for i in 0...length! {
            ref.child(node).child(String(i)).observeSingleEvent(of: .value, with: { (snapshot) in
                let value = snapshot.value as? NSDictionary
                let building = value?["building"] as? String ?? ""
                let lat = value?["lat"] as? Double ?? 0.0
                let lon = value?["long"] as? Double ?? 0.0
                let marker = GMSMarker()
                marker.position = CLLocationCoordinate2D(latitude: lat, longitude: lon)
                marker.title = building
                marker.snippet = node
                markers.append(marker)
            })

        }
        return markers

    }

I have tried adding a closure block [length] like this but then get this compile error: Cannot assign to value: 'length' is an immutable capture

ref.child("Config").observeSingleEvent(of: .value, with: { [length](snapshot) in
                let value = snapshot.value as? NSDictionary
                length = (value?["AcademicBuildingsLength"] as? Int ?? 0)
            })

Body:
Closures are asynchronously executed on another background thread. Because of this, you cannot mutate variables outside of this block and may have to use completion closures. To accomplish what you want, you will can call another function within your closure:

func loadMarkersFromDatabase(ref:DatabaseReference, node:String, completion: @escaping ([GMSMarker]) -> Void) {
    ref.child("Config").observeSingleEvent(of: .value, with: { [length](snapshot) in
        let value = snapshot.value as? NSDictionary
        let markers = myFunction((value?["AcademicBuildingsLength"] as? Int ?? 0))
        completion(markers)
    }
}

and then:

func myFunction(length: Int) -> [GMSMarker] {
    var markers: [GMSMarker] = []
    for i in 0...length! {
            ref.child(node).child(String(i)).observeSingleEvent(of: .value, with: { (snapshot) in
                let value = snapshot.value as? NSDictionary
                let building = value?["building"] as? String ?? ""
                let lat = value?["lat"] as? Double ?? 0.0
                let lon = value?["long"] as? Double ?? 0.0
                let marker = GMSMarker()
                marker.position = CLLocationCoordinate2D(latitude: lat, longitude: lon)
                marker.title = building
                marker.snippet = node
                markers.append(marker)
            })
        }
    return markers
}


问:
Preserve file last modified date time while copying it from source to target
I am trying to copy a file from one location to another. While copying it from source to target, target file is taking current date time. How can i make target file date as same as source file.</p>

```<code>FileInputStream source = new FileInputStream("D:\\test\\test.txt");
OutputStream target = new FileOutputStream("D:\\test.txt");
byte[] buffer = new byte[source.available()];
source.read(buffer);
target.write(buffer);
source.close();
target.close();`
</code>```

答:
This is provided by the java.io.File class. You need to create an instance of it first and pass it to the streams:

```<code>File input = new File("D:\\test\\test.txt");
File output = new File("D:\\test.txt");
try( FileInputStream source = new FileInputStream(input);
     OutputStream target = new FileOutputStream(output)){
    byte[] buffer = new byte[source.available()];
    source.read(buffer);
    target.write(buffer);
}
long modified = input.lastModified();
output.setLastModified(modified);
</code>```

BTW: I assume you use at least Java 7, so I changed your code to use the try-with-resources feature. This is strongly recommended since it also takes care of closing resources in case an exception is raised.

Body:
I am trying to copy a file from one location to another. While copying it from source to target, target file is taking current date time. How can i make target file date as same as source file.

FileInputStream source = new FileInputStream("D:\\test\\test.txt");
OutputStream target = new FileOutputStream("D:\\test.txt");
byte[] buffer = new byte[source.available()];
source.read(buffer);
target.write(buffer);
source.close();
target.close();`

Body:
This is provided by the java.io.File class. You need to create an instance of it first and pass it to the streams:

File input = new File("D:\\test\\test.txt");
File output = new File("D:\\test.txt");
try( FileInputStream source = new FileInputStream(input);
     OutputStream target = new FileOutputStream(output)){
    byte[] buffer = new byte[source.available()];
    source.read(buffer);
    target.write(buffer);
}
long modified = input.lastModified();
output.setLastModified(modified);

BTW: I assume you use at least Java 7, so I changed your code to use the try-with-resources feature. This is strongly recommended since it also takes care of closing resources in case an exception is raised.


问:
Shrink image file using ImageSharp
I need to shrink every image I get that is more than 10MB.
File types are png, jpg and gif.
I saw that ImageSharp has an option to resize an image:

```<code>Resize(new ResizeOptions
{
    Mode = ResizeMode.Max,
    Size = new Size(maxFileSize)
}
</code>```

I saw a lot of examples using the resize function with width and height, but none using this one size option, and no documentation explain exactly what "size" means.

I've tried the following: Shrinking an image of 22.2MB using maxFileSize=1024 yielded a picture of 527.9MB.
"Shrinking" the same image with maxFileSize=1024*2*10 yielded a 47.4MB picture.

How can I shrink an image to a size of roughly 10MB (can be a bit less)?
My goal here is to limit to 10MB, and, if exceeded, reduce the image to the maximal possible size under 10MB without affecting the ratio.

答:
After looking some more into the documentation I now see the single int constructor simply insert the same number to both width and height.

For now, I shrink the image way too much using the following:

```<code>            using (var image = Image.Load(imageFile))
            {
                var proportion = (double)imageFile.Length / maxFileSize;
                var maxWidth = (int)(image.Width / proportion);
                var maxHeight = (int)(image.Height / proportion);
                image.Mutate(x => x
                    .Resize(new ResizeOptions
                    {
                        Mode = ResizeMode.Max,
                        Size = new Size(maxWidth, maxHeight)
                    }));
                // Save the Image
            }
</code>```

If anyone has  better Idea I would love to hear it.

The goal is to have the image shrink to just under 10MB (as close as possible).

Title: Shrink image file using ImageSharp

Body:
I need to shrink every image I get that is more than 10MB.
File types are png, jpg and gif.
I saw that ImageSharp has an option to resize an image:

Resize(new ResizeOptions
{
    Mode = ResizeMode.Max,
    Size = new Size(maxFileSize)
}

I saw a lot of examples using the resize function with width and height, but none using this one size option, and no documentation explain exactly what "size" means.

I've tried the following: Shrinking an image of 22.2MB using maxFileSize=1024 yielded a picture of 527.9MB.
"Shrinking" the same image with maxFileSize=1024*2*10 yielded a 47.4MB picture.

How can I shrink an image to a size of roughly 10MB (can be a bit less)?
My goal here is to limit to 10MB, and, if exceeded, reduce the image to the maximal possible size under 10MB without affecting the ratio.

Body:
After looking some more into the documentation I now see the single int constructor simply insert the same number to both width and height.

For now, I shrink the image way too much using the following:

            using (var image = Image.Load(imageFile))
            {
                var proportion = (double)imageFile.Length / maxFileSize;
                var maxWidth = (int)(image.Width / proportion);
                var maxHeight = (int)(image.Height / proportion);
                image.Mutate(x => x
                    .Resize(new ResizeOptions
                    {
                        Mode = ResizeMode.Max,
                        Size = new Size(maxWidth, maxHeight)
                    }));
                // Save the Image
            }

If anyone has  better Idea I would love to hear it.

The goal is to have the image shrink to just under 10MB (as close as possible).


答:
you can use this code for finding average evrey key in your list, but do not calculate null value in process

var data = JSON.parse("[{\"ts\":1581669310,\"cpu\":45,\"mem\":3550.67,\"mema\":1443.55,\"batt\":100,\"temp\":21.4,\"comuniqlocacatalogue_cpu\":1,\"comuniqlocacatalogue_mem\":null,\"comuniqlocacatalogue_netr\":null,\"comuniqlocacatalogue_nets\":null}, {\"ts\":1581669311,\"cpu\":34,\"mem\":3550.67,\"mema\":1441,\"batt\":100,\"temp\":21.4,\"comuniqlocacatalogue_cpu\":null,\"comuniqlocacatalogue_mem\":null,\"comuniqlocacatalogue_netr\":null,\"comuniqlocacatalogue_nets\":null}]");

var avgerage = Array.from(data.reduce(
  (acc, obj) => Object.keys(obj).reduce(
      (acc, key) => typeof obj[key] == "number"
          ? acc.set(key, (acc.get(key) || []).concat(obj[key]))
          : acc,
  acc),
new Map()),
  ([name, values]) =>
      ({ name, average: values.reduce( (a,b) => a+b ) / values.length })
);

console.log(avgerage);```

Title: How to get the average of the total values from json file using nodejs


问:
awk print 1st row with condition
The command:

```<code>kubectl get pods -n hello | awk '$1 ~ "hello-uwsgi-deployment"  {print $1}'
</code>```

outputs

```<code>hello-uwsgi-deployment-5b7498f864-4bfrx
hello-uwsgi-deployment-5b7498f864-h9rxz
hello-uwsgi-deployment-5b7498f864-qlg8z
hello-uwsgi-deployment-5b7498f864-r5nfs
hello-uwsgi-deployment-5b7498f864-vxr6x
</code>```

How can I print only the first line with the above condition using awk?

I tried

```<code>kubectl get pods -n hello |
awk '($1 ~ "hello-uwsgi-deployment") && ('NR==1') {print $1}'
</code>```

but it outputs nothing.

EDIT:kubectl get pods -n hello | awk '($1 ~ /hello-uwsgi-deployment/){print;exit}' this works perfectly.

How to get the same working with multiple conditional statements using == and NR==?

答:
You can redirect the output to head command:</p>

```<code>kubectl get pods -n hello | awk '$1 ~ "hello-uwsgi-deployment"  {print $1}' | head -n 1
</code>```

Title: awk print 1st row with condition

Body:
The command:

kubectl get pods -n hello | awk '$1 ~ "hello-uwsgi-deployment"  {print $1}'

outputs

hello-uwsgi-deployment-5b7498f864-4bfrx
hello-uwsgi-deployment-5b7498f864-h9rxz
hello-uwsgi-deployment-5b7498f864-qlg8z
hello-uwsgi-deployment-5b7498f864-r5nfs
hello-uwsgi-deployment-5b7498f864-vxr6x

How can I print only the first line with the above condition using awk?

I tried

kubectl get pods -n hello |
awk '($1 ~ "hello-uwsgi-deployment") && ('NR==1') {print $1}'

but it outputs nothing.

EDIT:kubectl get pods -n hello | awk '($1 ~ /hello-uwsgi-deployment/){print;exit}' this works perfectly.

How to get the same working with multiple conditional statements using == and NR==?

Body:
You can redirect the output to head command:

kubectl get pods -n hello | awk '$1 ~ "hello-uwsgi-deployment"  {print $1}' | head -n 1


问:
Cordova - CSP refuses to load media blob
I'm trying to load get some audio data from an HTTP POST request and then play it from an Android device. This is the code that handles that operation:

```<code>var xhr = new XMLHttpRequest();
xhr.open('POST', encodeURI(myURLString), true);
xhr.responseType = 'blob';
xhr.onload = function(evt) {
    var blob = new Blob([xhr.response], {type: 'audio/wav'});
    var audio = new Audio();
    audio.src = URL.createObjectURL(blob);
    audio.play();
};
xhr.send(myData);
</code>```

When I run it, I get the following error:

```<code>Refused to load media from 'blob:file:///d181cef8-136d-4dab-b5c6-598a0481755c'
because it violates the following Content Security Policy directive: "media-src *".
</code>```

I'm not sure how to set this directive to allow this file to be played, and I can't get this to work.

Any ideas? Thanks in advance!

答:
I had same issue with electron app below meta tag solved my problem </p>

```<code>  <meta http-equiv="Content-Security-Policy" content="default-src 'self' file: data: blob: filesystem:; default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'"/>
</code>```

Body:
I'm trying to load get some audio data from an HTTP POST request and then play it from an Android device. This is the code that handles that operation:

var xhr = new XMLHttpRequest();
xhr.open('POST', encodeURI(myURLString), true);
xhr.responseType = 'blob';
xhr.onload = function(evt) {
    var blob = new Blob([xhr.response], {type: 'audio/wav'});
    var audio = new Audio();
    audio.src = URL.createObjectURL(blob);
    audio.play();
};
xhr.send(myData);

When I run it, I get the following error:

Refused to load media from 'blob:file:///d181cef8-136d-4dab-b5c6-598a0481755c'
because it violates the following Content Security Policy directive: "media-src *".

I'm not sure how to set this directive to allow this file to be played, and I can't get this to work.

Any ideas? Thanks in advance!

Body:
I had same issue with electron app below meta tag solved my problem

  <meta http-equiv="Content-Security-Policy" content="default-src 'self' file: data: blob: filesystem:; default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'"/>


问:
Javascript, jQuery, Do function after another function
I have this javascript function.

```<code><script type="text/javascript">
  $(document).ready(function () {
  $('#load').html('<img style="display:block; margin:10px auto;background-color: #EEE;" src="<?echo $site["url"];?>images/icons/loading.gif"/>');
  $('#loaded').fadeIn(1500);
     $('#load').fadeOut(2000);
  });
</script>
</code>```

As you may see it simply runs a loading image for a tot of seconds, then shows the div and hide the loading image.
This is not good for me. I need a function that will work in this way. The logic of the code would be:

```<code>As soon as $('#load').html('<img style="display:block; margin:10px auto;background-color: #EEE;" src="<?echo $site["url"];?>images/icons/loading.gif"/>'); is running, then wait 4 seconds, and then show the #loaded DIV.
</code>```

In this way the #loaded DIV will be fully loaded and it will work fine, since it is an heavy one.

In few words I must to be sure that #loaded has been fully loaded by the browser before showing it.
How can I create a function that will do that?

On document ready show the loading DIV. Then WAIT for 3-4 seconds, then make the loading disappear and the loaded DIV visible.

Is this possible?

答:
make your fadein launch as a callback of your fadeout.

```<code>    $(document).ready(function() {
        $('#load')
          .html('<img style="display:block; margin:10px auto;background-color: #EEE;" src="<?echo $site["url"];?>images/icons/loading.gif"/>')
          .fadeOut(2000, function() {
                $('#loaded').fadeIn(1500);
           });
    });
</code>```

But to do this properly i would add the #load div to the html, hide it via css. Then simply do the fadeOut on document.ready.

update.

Mixing the best of both Andrew and my answer, this should work flawlessly:

```<code><div id="load" style="display:none">Loading, please wait</div>

$(document).ready(function() {
        $('#load').show();
    $('#loaded').load(function() {
        $('#load').fadeOut(500,function(){  $(this).fadeIn(500);});
    });
});
</code>```

Body:
I have this javascript function.

As you may see it simply runs a loading image for a tot of seconds, then shows the div and hide the loading image.
This is not good for me. I need a function that will work in this way. The logic of the code would be:

As soon as $('#load').html('<img style="display:block; margin:10px auto;background-color: #EEE;" src="<?echo $site["url"];?>images/icons/loading.gif"/>'); is running, then wait 4 seconds, and then show the #loaded DIV.

In this way the #loaded DIV will be fully loaded and it will work fine, since it is an heavy one.

In few words I must to be sure that #loaded has been fully loaded by the browser before showing it.
How can I create a function that will do that?

On document ready show the loading DIV. Then WAIT for 3-4 seconds, then make the loading disappear and the loaded DIV visible.

Is this possible?

Body:
make your fadein launch as a callback of your fadeout.

    $(document).ready(function() {
        $('#load')
          .html('<img style="display:block; margin:10px auto;background-color: #EEE;" src="<?echo $site["url"];?>images/icons/loading.gif"/>')
          .fadeOut(2000, function() {
                $('#loaded').fadeIn(1500);
           });
    });

But to do this properly i would add the #load div to the html, hide it via css. Then simply do the fadeOut on document.ready.

update.

Mixing the best of both Andrew and my answer, this should work flawlessly:

<div id="load" style="display:none">Loading, please wait</div>

$(document).ready(function() {
        $('#load').show();
    $('#loaded').load(function() {
        $('#load').fadeOut(500,function(){  $(this).fadeIn(500);});
    });
});


问:
How do I read this Syntax?
I have a question interpret regarding to a syntax that I'm studying.

I do not understand how the sessional variable (@variable) work in this case.

I understand the logic of the syntax but I thought @variable is used something like below

```<code>SET @expired_date = STR_TO_DATE(expired_date, '%m/%d/%Y').
</code>```

Can anyone explain why is the other way around?

Thank you for the help

答:
The statement you have shown:

```<code>SET @expired_date = STR_TO_DATE(expired_date, '%m/%d/%Y')
</code>```

is to set a variable from the value of a column. In your LOAD DATA INFILE query a column is being set from the value of a variable. Specifically, the query reads the values from the csv file into

the column title;

the variable @expired_date; and

the column amount

and the value for the column expired_date is then generated from the @expired_date variable using STR_TO_DATE.

Title: How do I read this Syntax?

Body:
I have a question interpret regarding to a syntax that I'm studying.

I do not understand how the sessional variable (@variable) work in this case.

I understand the logic of the syntax but I thought @variable is used something like below

SET @expired_date = STR_TO_DATE(expired_date, '%m/%d/%Y').

Can anyone explain why is the other way around?

Thank you for the help

Body:
The statement you have shown:

SET @expired_date = STR_TO_DATE(expired_date, '%m/%d/%Y')

is to set a variable from the value of a column. In your LOAD DATA INFILE query a column is being set from the value of a variable. Specifically, the query reads the values from the csv file into

the column title;

the variable @expired_date; and

the column amount

and the value for the column expired_date is then generated from the @expired_date variable using STR_TO_DATE.