问:
origin 'http://localhost:4200' has been blocked by CORS policy for SignalR using .net core with angular
I am using signal to get real time data in my angular application and using .net core 2.2 API for back-end but when i run project i get CORS error in browser console.

VehicleHub.cs

```<code>using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BusinessLayer.HubConfig
{
    public class VehicleHub:Hub
    {
        public int id { get; set; }
        public string name { get; set; }
        public string vehicleType { get; set; }
        public string modelNo { get; set; }
        public string registrationNo { get; set; }
        public int? lcsVehicleNo { get; set; }
        public int relationShipOfficerId { get; set; }
        public int driverId { get; set; }
        public string driverName { get; set; }
        public string relationShipOfficerName { get; set; }
        public bool isActive { get; set; }
        public DateTime createdOn { get; set; }
        public string createdBy { get; set; }
        public DateTime modifiedOn { get; set; }
        public string modifyBy { get; set; }
        public int locationId { get; set; }
        public int createdById { get; set; }
        public int? modifyById { get; set; }
    }
}
</code>```

here is my starup.cs file

```<code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using BusinessLayer.Helpers;
using MatechEssential;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using WebAPICore.Helpers;
using WebAPICore.middleware;
using WebAPICore.Services;
using WebAPICore.Utility;
using BusinessLayer.HubConfig;

namespace WebAPICore
{
    public class Startup
    {
        private readonly IHostingEnvironment _hostingEnvironment;

        public Startup(IConfiguration configuration, IHostingEnvironment env)
        {
            Configuration = configuration;
            _hostingEnvironment = env;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
            {
                builder.AllowAnyOrigin()
                       .AllowAnyMethod()
                       .AllowAnyHeader()
                       .SetIsOriginAllowed((host) => true);
            }));
            services.AddSignalR();
            services.AddMvc(options =>
            {
                options.Filters.Add(new ErrorHandlingFilter());
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            // configure strongly typed settings objects
            var appSettingsSection = Configuration.GetSection("AppSettings");
            services.Configure<AppSettings>(appSettingsSection);

            // configure jwt authentication
            var appSettings = appSettingsSection.Get<AppSettings>();
            SQLHelper._ConStr = appSettings.ConnectionString != null? appSettings.ConnectionString:"" ;

            var key = Encoding.ASCII.GetBytes(appSettings.Secret);
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = "bearer";
                x.DefaultChallengeScheme = "bearer";
            })
            .AddJwtBearer("bearer", options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience = false,
                    ValidateIssuer = false,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(appSettings.Secret)),
                    ValidateLifetime = true,
                    ClockSkew = TimeSpan.Zero
                    // TimeSpan.Zero //the default for this setting is 5 minutes
                };
                options.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("Token-Expired", "true");
                        }
                        return Task.CompletedTask;
                    }
                };
                options.SaveToken = true;
            });

            var physicalProvider = _hostingEnvironment.ContentRootFileProvider;
            var embeddedProvider = new EmbeddedFileProvider(Assembly.GetEntryAssembly());
            var compositeProvider = new CompositeFileProvider(physicalProvider, embeddedProvider);
             string absolutePath = compositeProvider.GetFileInfo("/SetupFiles/MasterSetupData.xml").PhysicalPath;
            XmlToList.xmlFileType = absolutePath;

            services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();
            services.AddTransient<UserResolverService>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory logger)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
               app.UseApiExceptionHandler(logger);
            }
            else
            {
                // 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.UseApiExceptionHandler(logger); //use global exception handlers
            }
            app.UseSignalR(routes =>
            {
                routes.MapHub<VehicleHub>("/Utility/GetAllVehicles");
            });
            // global cors policy
            app.UseCors("CorsPolicy");

            app.UseAuthentication();
            app.UseHttpsRedirection();
            app.UseResponseWrapper();

            //app.UseAPIResponseWrapperMiddleware();
            app.UseOptions();
            app.UseMvc();
        }
    }
}
</code>```

I also have tried the below code but nothing happen

```<code>services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy", builder => builder.WithOrigins("http://localhost:4200")
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials()
                    .SetIsOriginAllowed((host) => true));
            });
</code>```

UtilityController.cs

```<code>[Route("api/[controller]")]
    [ApiController]
    [EnableCors("CorsPolicy")]
    public class UtilityController : ControllerBase
    {
        private UserModel _currentUser;
        private IHubContext<VehicleHub> _hub;
        public UtilityController(UserResolverService userService, IHubContext<VehicleHub> hub)// , IUserService userService
        {
            _hub = hub;
            _currentUser = userService.getUserInfo();
        }
 [HttpGet]
        [Route("GetAllVehicles")]
        public IActionResult GetAllVehicles()
        {
            try
            {
                _hub.Clients.All.SendAsync("transferchartdata", UtilityFuncation.GetVehicleAll());
                return Ok(new { Message = "Request Completed" });
            }
            catch (Exception exp)
            {
                return NotFound(CommonApiResponse.Create(HttpStatusCode.InternalServerError, "Error Date Not Fetch", exp.Message));
            }
        }
}
</code>```

I have removed other actions/methods from controller for Stackoverflow

signal-r.service.ts

```<code>import { Injectable } from '@angular/core';
import * as signalR from "@aspnet/signalr";
import { HttpClient } from '@angular/common/http';
@Injectable({
  providedIn: 'root'
})

export class SignalRService {
  public data: VehicleModel[]
  private hubConnection: signalR.HubConnection
  options: signalR.IHttpConnectionOptions = {
    accessTokenFactory: () => {
     let token = localStorage.getItem("token")
      return `Bearer ${token}`;
    },
  };
  public startConnection = () => {
    this.hubConnection = new signalR.HubConnectionBuilder()
                            .withUrl('http://localhost:50915/Utility/GetAllVehicles', this.options)
                            .build();

    this.hubConnection
      .start()
      .then(() => console.log('Connection started'))
      .catch(err => console.log('Error while starting connection: ' + err))
  }

  public addTransferChartDataListener = () => {
    this.hubConnection.on('transferchartdata', (data) => {
      this.data = data;
      console.log(data);
    });
  }
  constructor() { }
}

export interface VehicleModel {
  id : any
  name : any
  vehicleType : any
  modelNo : any
  registrationNo : any
  lcsVehicleNo : any
  relationShipOfficerId : any
  driverId : any
  driverName : any
  relationShipOfficerName : any
  isActive : any
  createdOn : any
  createdBy : any
  modifiedOn : any
  modifyBy : any
  locationId : any
  createdById : any
  modifyById : any
}
</code>```

App.component.ts

```<code> ngOnInit() {
    this.signalRService.startConnection();
    this.signalRService.addTransferChartDataListener();
    this.startHttpRequest();
}
</code>```

I have removed other methods from App.component for Stackoverflow

nuget package of signalr

angular version of signar

I get this error in my browser console, but when i added the breakpoint on controller it perfectly hits the action for one time only (you can see the response in console)

below is network snapshot for GetAllVehicles that works for first time

below is network snapshot for negotiate that have CORS issue

I have also tried this url but got nothing.

答:
You need to add CORS on your hub like:

On the configure method

app.UseCors(CorsPolicy);
```

<p>On the AddAditionalServices</p>

<pre class="lang-cs prettyprint-override"><code>services.AddCors(options =>
{
    options.AddPolicy(CorsPolicy, builder => builder.WithOrigins("http://localhost:4200")
        .AllowAnyHeader()
        .AllowAnyMethod()
        .AllowCredentials()
        .SetIsOriginAllowed((host) => true));
});
</code>```

Note that the order of the CORS methods is important!

Also you should not use the @aspnet/signalr package since it was abandoned and is outdated. You should use the new @microsoft/signalr package and it also provides you with AutomaticReconnect feature.

Body:
I am using signal to get real time data in my angular application and using .net core 2.2 API for back-end but when i run project i get CORS error in browser console.

VehicleHub.cs

using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BusinessLayer.HubConfig
{
    public class VehicleHub:Hub
    {
        public int id { get; set; }
        public string name { get; set; }
        public string vehicleType { get; set; }
        public string modelNo { get; set; }
        public string registrationNo { get; set; }
        public int? lcsVehicleNo { get; set; }
        public int relationShipOfficerId { get; set; }
        public int driverId { get; set; }
        public string driverName { get; set; }
        public string relationShipOfficerName { get; set; }
        public bool isActive { get; set; }
        public DateTime createdOn { get; set; }
        public string createdBy { get; set; }
        public DateTime modifiedOn { get; set; }
        public string modifyBy { get; set; }
        public int locationId { get; set; }
        public int createdById { get; set; }
        public int? modifyById { get; set; }
    }
}

here is my starup.cs file

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using BusinessLayer.Helpers;
using MatechEssential;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using WebAPICore.Helpers;
using WebAPICore.middleware;
using WebAPICore.Services;
using WebAPICore.Utility;
using BusinessLayer.HubConfig;

namespace WebAPICore
{
    public class Startup
    {
        private readonly IHostingEnvironment _hostingEnvironment;

        public Startup(IConfiguration configuration, IHostingEnvironment env)
        {
            Configuration = configuration;
            _hostingEnvironment = env;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
            {
                builder.AllowAnyOrigin()
                       .AllowAnyMethod()
                       .AllowAnyHeader()
                       .SetIsOriginAllowed((host) => true);
            }));
            services.AddSignalR();
            services.AddMvc(options =>
            {
                options.Filters.Add(new ErrorHandlingFilter());
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            // configure strongly typed settings objects
            var appSettingsSection = Configuration.GetSection("AppSettings");
            services.Configure<AppSettings>(appSettingsSection);

            // configure jwt authentication
            var appSettings = appSettingsSection.Get<AppSettings>();
            SQLHelper._ConStr = appSettings.ConnectionString != null? appSettings.ConnectionString:"" ;

            var key = Encoding.ASCII.GetBytes(appSettings.Secret);
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = "bearer";
                x.DefaultChallengeScheme = "bearer";
            })
            .AddJwtBearer("bearer", options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience = false,
                    ValidateIssuer = false,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(appSettings.Secret)),
                    ValidateLifetime = true,
                    ClockSkew = TimeSpan.Zero
                    // TimeSpan.Zero //the default for this setting is 5 minutes
                };
                options.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("Token-Expired", "true");
                        }
                        return Task.CompletedTask;
                    }
                };
                options.SaveToken = true;
            });

            var physicalProvider = _hostingEnvironment.ContentRootFileProvider;
            var embeddedProvider = new EmbeddedFileProvider(Assembly.GetEntryAssembly());
            var compositeProvider = new CompositeFileProvider(physicalProvider, embeddedProvider);
             string absolutePath = compositeProvider.GetFileInfo("/SetupFiles/MasterSetupData.xml").PhysicalPath;
            XmlToList.xmlFileType = absolutePath;

            services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();
            services.AddTransient<UserResolverService>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory logger)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
               app.UseApiExceptionHandler(logger);
            }
            else
            {
                // 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.UseApiExceptionHandler(logger); //use global exception handlers
            }
            app.UseSignalR(routes =>
            {
                routes.MapHub<VehicleHub>("/Utility/GetAllVehicles");
            });
            // global cors policy
            app.UseCors("CorsPolicy");

            app.UseAuthentication();
            app.UseHttpsRedirection();
            app.UseResponseWrapper();

            //app.UseAPIResponseWrapperMiddleware();
            app.UseOptions();
            app.UseMvc();
        }
    }
}

I also have tried the below code but nothing happen

services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy", builder => builder.WithOrigins("http://localhost:4200")
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials()
                    .SetIsOriginAllowed((host) => true));
            });

UtilityController.cs

[Route("api/[controller]")]
    [ApiController]
    [EnableCors("CorsPolicy")]
    public class UtilityController : ControllerBase
    {
        private UserModel _currentUser;
        private IHubContext<VehicleHub> _hub;
        public UtilityController(UserResolverService userService, IHubContext<VehicleHub> hub)// , IUserService userService
        {
            _hub = hub;
            _currentUser = userService.getUserInfo();
        }
 [HttpGet]
        [Route("GetAllVehicles")]
        public IActionResult GetAllVehicles()
        {
            try
            {
                _hub.Clients.All.SendAsync("transferchartdata", UtilityFuncation.GetVehicleAll());
                return Ok(new { Message = "Request Completed" });
            }
            catch (Exception exp)
            {
                return NotFound(CommonApiResponse.Create(HttpStatusCode.InternalServerError, "Error Date Not Fetch", exp.Message));
            }
        }
}

I have removed other actions/methods from controller for Stackoverflow

signal-r.service.ts

import { Injectable } from '@angular/core';
import * as signalR from "@aspnet/signalr";
import { HttpClient } from '@angular/common/http';
@Injectable({
  providedIn: 'root'
})

export class SignalRService {
  public data: VehicleModel[]
  private hubConnection: signalR.HubConnection
  options: signalR.IHttpConnectionOptions = {
    accessTokenFactory: () => {
     let token = localStorage.getItem("token")
      return `Bearer ${token}`;
    },
  };
  public startConnection = () => {
    this.hubConnection = new signalR.HubConnectionBuilder()
                            .withUrl('http://localhost:50915/Utility/GetAllVehicles', this.options)
                            .build();

    this.hubConnection
      .start()
      .then(() => console.log('Connection started'))
      .catch(err => console.log('Error while starting connection: ' + err))
  }

  public addTransferChartDataListener = () => {
    this.hubConnection.on('transferchartdata', (data) => {
      this.data = data;
      console.log(data);
    });
  }
  constructor() { }
}

export interface VehicleModel {
  id : any
  name : any
  vehicleType : any
  modelNo : any
  registrationNo : any
  lcsVehicleNo : any
  relationShipOfficerId : any
  driverId : any
  driverName : any
  relationShipOfficerName : any
  isActive : any
  createdOn : any
  createdBy : any
  modifiedOn : any
  modifyBy : any
  locationId : any
  createdById : any
  modifyById : any
}

App.component.ts

 ngOnInit() {
    this.signalRService.startConnection();
    this.signalRService.addTransferChartDataListener();
    this.startHttpRequest();
}

I have removed other methods from App.component for Stackoverflow

nuget package of signalr

angular version of signar

I get this error in my browser console, but when i added the breakpoint on controller it perfectly hits the action for one time only (you can see the response in console)

below is network snapshot for GetAllVehicles that works for first time

below is network snapshot for negotiate that have CORS issue

I have also tried this url but got nothing.

Body:
You need to add CORS on your hub like:

On the configure method

app.UseCors(CorsPolicy);

On the AddAditionalServices

services.AddCors(options =>
{
    options.AddPolicy(CorsPolicy, builder => builder.WithOrigins("http://localhost:4200")
        .AllowAnyHeader()
        .AllowAnyMethod()
        .AllowCredentials()
        .SetIsOriginAllowed((host) => true));
});

Note that the order of the CORS methods is important!

Also you should not use the @aspnet/signalr package since it was abandoned and is outdated. You should use the new @microsoft/signalr package and it also provides you with AutomaticReconnect feature.


来源: stackexchange

问:
ASP.NET MVC | ActionResult not getting called when going back to previous page
I understand that the title of the question may be vague but then that's the best way I could come up with to explain my issue at hand.

I'm overriding the OnActionExecuting function to manage my session related activities and allow/ deny requests to authorized/ unauthorized users, respectively. Along with tracking of the session, I'm also using the OnActionExecuting to load user available features for the current page into a temporary class and accessing from the view using ajax call.

```<code>namespace MyApp.Controllers
{
    public class TESTController : Controller
    {
        [SessionTimeout]
        public ActionResult Index()
        {
            return this.View();
        }
    }
}

public class SessionTimeoutAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpContext ctx = HttpContext.Current;
        if (ctx.Session["AppUser"] == null)
        {
            // Redirect to the login page
            // Or deny request
        }
        else
        {
            var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            var actionName = filterContext.ActionDescriptor.ActionName;
            var methodType = ((ReflectedActionDescriptor)filterContext.ActionDescriptor).MethodInfo.ReturnType;

            if (methodType == typeof(ActionResult))
            {
                // Load all user access rights for the current page into a temporary memory
                // by using the Action and Controller name
            }
        }
        base.OnActionExecuting(filterContext);
    }
}
</code>```

The above works like a charm.. But the issue is when the user clicks on the back button of the browser or hits the backspace key. In that case, the OnActionExecuting function is never called for the ActionResult and further I am unable to load the current page access rights for the user.

Thanks & Regards,
Kshitij

答:
Adding the following to my ActionResult made the above code to work.</p>

```<code>    [SessionTimeout]
    [OutputCache(Duration = 0, NoStore = true)]
    public ActionResult SomeView()
    {
        return this.View();
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I understand that the title of the question may be vague but then that's the best way I could come up with to explain my issue at hand.

I'm overriding the OnActionExecuting function to manage my session related activities and allow/ deny requests to authorized/ unauthorized users, respectively. Along with tracking of the session, I'm also using the OnActionExecuting to load user available features for the current page into a temporary class and accessing from the view using ajax call.

namespace MyApp.Controllers
{
    public class TESTController : Controller
    {
        [SessionTimeout]
        public ActionResult Index()
        {
            return this.View();
        }
    }
}

public class SessionTimeoutAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpContext ctx = HttpContext.Current;
        if (ctx.Session["AppUser"] == null)
        {
            // Redirect to the login page
            // Or deny request
        }
        else
        {
            var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            var actionName = filterContext.ActionDescriptor.ActionName;
            var methodType = ((ReflectedActionDescriptor)filterContext.ActionDescriptor).MethodInfo.ReturnType;

            if (methodType == typeof(ActionResult))
            {
                // Load all user access rights for the current page into a temporary memory
                // by using the Action and Controller name
            }
        }
        base.OnActionExecuting(filterContext);
    }
}

The above works like a charm.. But the issue is when the user clicks on the back button of the browser or hits the backspace key. In that case, the OnActionExecuting function is never called for the ActionResult and further I am unable to load the current page access rights for the user.

Thanks & Regards,
Kshitij

Body:
Adding the following to my ActionResult made the above code to work.

    [SessionTimeout]
    [OutputCache(Duration = 0, NoStore = true)]
    public ActionResult SomeView()
    {
        return this.View();
    }


问:
Should GC.SuppressFinalize be called on objects that do not have a finalizer?
For some reason FXCop seems to think I should be calling GC.SuppressFinalize in Dispose, regardless of whether I have a finalizer or not. </p>

<p>Am I missing something? Is there a reason to call GC.SuppressFinalize on objects that have no finalizer defined? </p>

答:
There's no need to call GC.SuppressFinalize(this) in Dispose, unless:

You are the base class that implements virtual Dispose methods intended for overriding (again, it might not be your responsibility even here, but you might want to do it in that case)

You have a finalizer yourself. Technically, every class in .NET has a finalizer, but if the only finalizer present is the one in Object, then the object is not considered to need finalizing and isn't put on the finalization list upon GC

I would say, assuming you don't have any of the above cases, that you can safely ignore that message.

ContentLicense: CC BY-SA 2.5

Body:
For some reason FXCop seems to think I should be calling GC.SuppressFinalize in Dispose, regardless of whether I have a finalizer or not.

Am I missing something? Is there a reason to call GC.SuppressFinalize on objects that have no finalizer defined?

LastEditorDisplayName: Mitch Wheat

OwnerDisplayName: lassevk


问:
Date formatting and how to print the highest number that occured and on what date
In the following data, I want to get the highest number of Swings that occurred and also on what Date. I can already get the highest number of Swings that occurred but not sure how to get the corresponding Date:

```<code>data = [
    {"Date": "01/06/2020",  "Swings": 350},
    {"Date": "02/06/2020",  "Swings": 370},
]
df = pd.DataFrame(data)

max_swings = max(df['Swings'])

print ("The max number of swings in one day was: " + str(max_swings))
</code>```

(Note: I use DD/MM/YYYY date format)

答:
Usually we convert dates to datetime.

```<code>df['Date'] = pd.to_datetime(df['Date']) # convert to datetime

df.iloc[df['Swings'].idxmax()] # this gives you the row with the highest swings
</code>```

The df['Swings'].idxmax() gives you the index of the first occurence where the maximum value of Swings is. Then you can slice the dataframe on that row with the .iloc[]

Body:
In the following data, I want to get the highest number of Swings that occurred and also on what Date. I can already get the highest number of Swings that occurred but not sure how to get the corresponding Date:

data = [
    {"Date": "01/06/2020",  "Swings": 350},
    {"Date": "02/06/2020",  "Swings": 370},
]
df = pd.DataFrame(data)

max_swings = max(df['Swings'])

print ("The max number of swings in one day was: " + str(max_swings))

(Note: I use DD/MM/YYYY date format)

Body:
Usually we convert dates to datetime.

df['Date'] = pd.to_datetime(df['Date']) # convert to datetime

df.iloc[df['Swings'].idxmax()] # this gives you the row with the highest swings

The df['Swings'].idxmax() gives you the index of the first occurence where the maximum value of Swings is. Then you can slice the dataframe on that row with the .iloc[]


问:
Issue with doubles rounding down to nearest whole
Unlike many of the other posts I am wanting to find out why my code is automatically rounding down to the nearest whole number??

See code here

```<code>    double sixes = 200/3;
    double threes = 100/3;

    System.out.println("Sixes: " + sixes + "\nThrees: " + threes);
</code>```

See the output here:

Sixes: 66.0

Threes: 33.0

These should both be 66.66666666666 and 33.3333333333 respectively but I am not sure why they are being rounded down?

答:
The question is whether you add a decimal point after the number, if you don't add it be double is divided by int and not double divided be double , here examples :

Double divied by int :

```<code>   double sixes = 200/3;
    double threes = 100/3;

    System.out.println("Sixes: " + sixes + "\nThrees: " + threes);
</code>```

Output :

```<code>Sixes: 66.0
Threes: 33.0
</code>```

Double divied by double:

```<code>   double sixes = 200/3.0;
    double threes = 100/3.0;

    System.out.println("Sixes: " + sixes + "\nThrees: " + threes);
</code>```

Output :

```<code>Sixes: 66.66666666666667
Threes: 33.333333333333336
</code>```

Body:
Unlike many of the other posts I am wanting to find out why my code is automatically rounding down to the nearest whole number??

See code here

    double sixes = 200/3;
    double threes = 100/3;

    System.out.println("Sixes: " + sixes + "\nThrees: " + threes);

See the output here:

Sixes: 66.0

Threes: 33.0

These should both be 66.66666666666 and 33.3333333333 respectively but I am not sure why they are being rounded down?

Body:
The question is whether you add a decimal point after the number, if you don't add it be double is divided by int and not double divided be double , here examples :

Double divied by int :

   double sixes = 200/3;
    double threes = 100/3;

    System.out.println("Sixes: " + sixes + "\nThrees: " + threes);

Output :

Sixes: 66.0
Threes: 33.0

Double divied by double:

   double sixes = 200/3.0;
    double threes = 100/3.0;

    System.out.println("Sixes: " + sixes + "\nThrees: " + threes);

Output :

Sixes: 66.66666666666667
Threes: 33.333333333333336


问:
Not able to set default column value in JPA
i'm trying to set default value for column and i have tried with below code in entity

```<code>@Column(columnDefinition = "integer default 1")
private Integer views;
</code>```

now after running server still i could see views as null in sql. Any idea why not able to save default value.

Application.yml

```<code>hibernate:
  ddl-auto: create
</code>```

its always create as still its in development stage

答:
you mean you look at the already existing rows in the table and you
  expect them to have that value ?

if yes, then here is the problem.. you may need to run migration script to set the default value you want where its not set.

And for any future inserted rows I guess the default value should be set.

Body:
i'm trying to set default value for column and i have tried with below code in entity

@Column(columnDefinition = "integer default 1")
private Integer views;

now after running server still i could see views as null in sql. Any idea why not able to save default value.

Application.yml

hibernate:
  ddl-auto: create

its always create as still its in development stage


问:
Angular Material button click tracking using Google Analytics via Google Tag Manager
I am using the Universal Analytics tag in Google Tag Manager to track user interaction. I want to set up click listeners from within GTM that will fire when certain buttons are clicked on the page. The buttons are Angular Material components.

The issue is that Angular Material puts a wrapper element on top of my button, changing the HTML from this:

```<code><button mat-raised-button type="button" class="blue l" (click)="onContinue()">CONTINUE</button>
</code>```

to this:

```<code><button _ngcontent-c20="" class="blue l mat-raised-button" mat-raised-button="" type="button">
    <span class="mat-button-wrapper">CONTINUE</span>
    <div class="mat-button-ripple mat-ripple" matripple="" ng-reflect-centered="false" ng-reflect-disabled="false" ng-reflect-trigger="[object HTMLButtonElement]"></div><div class="mat-button-focus-overlay"></div>
</button>
</code>```

In order to pick up the click events in GTM I have to set the trigger to listen for clicks on the  element rather than the <button> element. Thus I loose all identifying information about the button; Any HTML id or class that I use for the <button> is not reflected in the . GTM is unable to distinguish which button was clicked. How can I uniquely identify my button in a way that is visible to GTM?

Note: Identifying the button using the button text (the inner HTML of the ) is not an option since I have multiple buttons on the page with the same text.

答:
I would reccommend to use a data attribute to seperate the tracking from other code like this:

```<code><button data-gtm-continue-button>...</buttton>
</code>```

and use a GTM-Trigger like this:
Click Element -> matches CSS selector -> [data-gtm-continue-button], [data-gtm-continue-button] *

In your case if you do not want to use data attibutes you could also just adjust your CSS selector to the following:

```<code>button#my-button, button#my-button *
</code>```

this makes use of the css selector * which means any element within the selector.

Body:
I am using the Universal Analytics tag in Google Tag Manager to track user interaction. I want to set up click listeners from within GTM that will fire when certain buttons are clicked on the page. The buttons are Angular Material components.

The issue is that Angular Material puts a wrapper element on top of my button, changing the HTML from this:

<button mat-raised-button type="button" class="blue l" (click)="onContinue()">CONTINUE</button>

to this:

<button _ngcontent-c20="" class="blue l mat-raised-button" mat-raised-button="" type="button">
    CONTINUE

</button>

In order to pick up the click events in GTM I have to set the trigger to listen for clicks on the  element rather than the <button> element. Thus I loose all identifying information about the button; Any HTML id or class that I use for the <button> is not reflected in the . GTM is unable to distinguish which button was clicked. How can I uniquely identify my button in a way that is visible to GTM?

Note: Identifying the button using the button text (the inner HTML of the ) is not an option since I have multiple buttons on the page with the same text.

Body:
I would reccommend to use a data attribute to seperate the tracking from other code like this:

<button data-gtm-continue-button>...</buttton>

and use a GTM-Trigger like this:
Click Element -> matches CSS selector -> [data-gtm-continue-button], [data-gtm-continue-button] *

In your case if you do not want to use data attibutes you could also just adjust your CSS selector to the following:

button#my-button, button#my-button *

this makes use of the css selector * which means any element within the selector.


问:
Error reading data from the old files, writing it into the new files and then deleting the old files in Python
I'm trying to use below code to read 5 files from source, write them in destination and then deleting the files in source. I get the following error: [Errno 13] Permission denied: 'c:\\data\\AM\\Desktop\\tester1. The file by the way look like this:

```<code>import os
import time

source = r'c:\data\AM\Desktop\tester'
destination = r'c:\data\AM\Desktop\tester1'

for file in os.listdir(source):
    file_path = os.path.join(source, file)
    if not os.path.isfile:
        continue
    print(file_path)

with open (file_path, 'r') as IN, open (destination, 'w') as OUT:
    data ={
            'Power': None,
            }
    for line in IN:
        splitter = (ID, Item, Content, Status) = line.strip().split()
        if Item in data == "Power":
            Content = str(int(Content) * 10)

os.remove(IN)
</code>```

答:
I have re-written your entire code. I assume you want to update the value of Power by a multiple of 10 and write the updated content into a new file. The below code will do just that.

Your code had multiple issues, first and foremost, most of what you wanted in your head did not get written in the code (like writing into a new file, providing what and where to write, etc.). The original issue of the permission was because you were trying to open a directory to write instead of a file.

```<code>source = r'c:\data\AM\Desktop\tester'
destination = r'c:\data\AM\Desktop\tester1'

for file in os.listdir(source):
    source_file = os.path.join(source, file)
    destination_file=os.path.join(destination, file)
    if not os.path.isfile:
        continue
    print(source_file)

    with open (source_file, 'r') as IN , open (destination_file, 'w') as OUT:
        data={
            'Power': None,
        }
        for line in IN:
            splitter = (ID, Item, Content, Status) = line.strip().split()
            if Item in data:# == "Power": #Changed
                Content = str(int(Content) * 10)
                OUT.write(ID+'\t'+Item+'\t'+Content+'\t'+Status+'\n') #Added to write the content into destination file.
            else:
                OUT.write(line) #Added to write the content into destination file.

    os.remove(source_file)
</code>```

Hope this works for you.

Body:
I'm trying to use below code to read 5 files from source, write them in destination and then deleting the files in source. I get the following error: [Errno 13] Permission denied: 'c:\\data\\AM\\Desktop\\tester1. The file by the way look like this:

import os
import time

source = r'c:\data\AM\Desktop\tester'
destination = r'c:\data\AM\Desktop\tester1'

for file in os.listdir(source):
    file_path = os.path.join(source, file)
    if not os.path.isfile:
        continue
    print(file_path)

with open (file_path, 'r') as IN, open (destination, 'w') as OUT:
    data ={
            'Power': None,
            }
    for line in IN:
        splitter = (ID, Item, Content, Status) = line.strip().split()
        if Item in data == "Power":
            Content = str(int(Content) * 10)

os.remove(IN)

Body:
I have re-written your entire code. I assume you want to update the value of Power by a multiple of 10 and write the updated content into a new file. The below code will do just that.

Your code had multiple issues, first and foremost, most of what you wanted in your head did not get written in the code (like writing into a new file, providing what and where to write, etc.). The original issue of the permission was because you were trying to open a directory to write instead of a file.

source = r'c:\data\AM\Desktop\tester'
destination = r'c:\data\AM\Desktop\tester1'

for file in os.listdir(source):
    source_file = os.path.join(source, file)
    destination_file=os.path.join(destination, file)
    if not os.path.isfile:
        continue
    print(source_file)

    with open (source_file, 'r') as IN , open (destination_file, 'w') as OUT:
        data={
            'Power': None,
        }
        for line in IN:
            splitter = (ID, Item, Content, Status) = line.strip().split()
            if Item in data:# == "Power": #Changed
                Content = str(int(Content) * 10)
                OUT.write(ID+'\t'+Item+'\t'+Content+'\t'+Status+'\n') #Added to write the content into destination file.
            else:
                OUT.write(line) #Added to write the content into destination file.

    os.remove(source_file)

Hope this works for you.


问:
How to check which options in a multi-select input form are selected from ReactStrap
I'm creating a form that has the option to select multiple values within a multiselect input, for filtering different options for a search. I'm using ReactStraps Form component.

The multiselect option is made up of an Input component, with multiple Option components like so:

```<code>  <Input type="select" name="selectMulti" id="exampleSelectMulti" multiple>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
  </Input>
</code>```

I can't seem to find any value within the option to check if it's currently clicked, which leads me to my next question. Are reactstrap and bootstrap meant almost solely for looks and very basic functionality? If so, should I be setting up the functionality within my input to handle keeping track of whether it has been clicked or not?

答:
you should handel in the 'onChange' event and set value. for example:

```<code><Input type="select" name="selectMulti" id="exampleSelect" multiple value={this.state.StatusFilter} onChange={(event) => {this.onChangeMulti(event);}} >
                            <option value='Val1'>Val1</option>
                            <option value='Val2'>Val2</option>
                        </Input1>
</code>```

and on event you should set

```<code>onChangeMulti = (event) => {
    let opts = [], opt;
    for (let i = 0, len = event.target.options.length; i < len; i++) {
        opt = event.target.options[i];
        if (opt.selected) {
            opts.push(opt.value);
        }
    }
    this.setState({ StatusFilter: opts });
}
</code>```

Body:
I'm creating a form that has the option to select multiple values within a multiselect input, for filtering different options for a search. I'm using ReactStraps Form component.

The multiselect option is made up of an Input component, with multiple Option components like so:

  <Input type="select" name="selectMulti" id="exampleSelectMulti" multiple>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
  </Input>

I can't seem to find any value within the option to check if it's currently clicked, which leads me to my next question. Are reactstrap and bootstrap meant almost solely for looks and very basic functionality? If so, should I be setting up the functionality within my input to handle keeping track of whether it has been clicked or not?

Body:
you should handel in the 'onChange' event and set value. for example:

<Input type="select" name="selectMulti" id="exampleSelect" multiple value={this.state.StatusFilter} onChange={(event) => {this.onChangeMulti(event);}} >
                            <option value='Val1'>Val1</option>
                            <option value='Val2'>Val2</option>
                        </Input1>

and on event you should set

onChangeMulti = (event) => {
    let opts = [], opt;
    for (let i = 0, len = event.target.options.length; i < len; i++) {
        opt = event.target.options[i];
        if (opt.selected) {
            opts.push(opt.value);
        }
    }
    this.setState({ StatusFilter: opts });
}


问:
UnableToExecuteStatementException: Batch entry was aborted. Call getNextException to see the cause
Using @SqlBatch to batch update the DB

```<code>@SqlBatch("<SQL Command>")
@BatchChunkSize(INSERT_BATCH_SIZE)
void insert(@BindBean Iterator<SomeObj> someObj);
</code>```

and I'm getting this error:

org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException:
  java.sql.BatchUpdateException: Batch entry 0 ... was aborted. Call
  getNextException to see the cause.

The problem is the exception that's being caught is a UnableToExecuteStatementException and not the original BatchUpdateException, so I am unable to call getNextException to see the cause. Furthermore, I can run the SQL command in the DB directly just fine.

Any idea how to get to the bottom of the cause or what the issue might be?

答:
I found a similar issue importing from Aurora (MySQL) to Redshift using a DataPipeline CopyActivity.
I was able to solve it by casting the incoming data to the proper target table types in the insertQuery like this:</p>

```<code>INSERT INTO my_table (id, bigint_col, timestamp_col) VALUES (?,cast(? as bigint),cast(? as timestamp))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Using @SqlBatch to batch update the DB

@SqlBatch("<SQL Command>")
@BatchChunkSize(INSERT_BATCH_SIZE)
void insert(@BindBean Iterator<SomeObj> someObj);

and I'm getting this error:

org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException:
  java.sql.BatchUpdateException: Batch entry 0 ... was aborted. Call
  getNextException to see the cause.

The problem is the exception that's being caught is a UnableToExecuteStatementException and not the original BatchUpdateException, so I am unable to call getNextException to see the cause. Furthermore, I can run the SQL command in the DB directly just fine.

Any idea how to get to the bottom of the cause or what the issue might be?

Body:
I found a similar issue importing from Aurora (MySQL) to Redshift using a DataPipeline CopyActivity.
I was able to solve it by casting the incoming data to the proper target table types in the insertQuery like this:

INSERT INTO my_table (id, bigint_col, timestamp_col) VALUES (?,cast(? as bigint),cast(? as timestamp))


问:
How do i access express.js routes from react.js client
i'm trying to access express.js routes from react front end but i don't seem to get how to go about it. my express.js backend runs on localhost:9000 and my react frontend runs on localhost:3000. this is my react code;

```<code>import React from 'react';
import './App.css';
import {BrowserRouter as Router, Link} from 'react-router-dom';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { apiResponse: "" };
}

callAPI() {
    fetch("http://localhost:9000/:username")
        .then(res => res.text())
        .then(res => this.setState({ apiResponse: res }));
}

componentWillMount() {
    this.callAPI();
}

render(){
  return (
    <div className="App">
      <p>{this.state.apiResponse}</p>

    </div>
  );
}
}

export default App;
</code>```

i have created two files on express routes folder, one is testAPI.js and the other is be.js. when i try to acces any of these two files from my browser without using react, on lets say localhost:9000/testAPI it works fine. but when i try to access localhost:3000/testAPI which calls the same file through react, it gives me this messed up error page:

```<code> <!DOCTYPE html><html><head><title></title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>Not Found</h1><h2>404</h2>```NotFoundError: Not Found at C:\Users\Denoh\full\api\app.js:33:8 at Layer.handle [as handle_request] (C:\Users\Denoh\full\api\node_modules\express\lib\router\layer.js:95:5) at trim_prefix (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:317:13) at C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:284:7 at Function.process_params (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:335:12) at next (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:275:10) at C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:635:15 at next (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:260:14) at Function.handle (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:174:3) at router (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:47:12)```</body></html>
</code>```

please assist

答:
you need to use proxy in package.json to achieve this

basically you set the url you  want to proxy too so that React knows how to connect to your server

see this for more info: https://create-react-app.dev/docs/proxying-api-requests-in-development/

Body:
i'm trying to access express.js routes from react front end but i don't seem to get how to go about it. my express.js backend runs on localhost:9000 and my react frontend runs on localhost:3000. this is my react code;

import React from 'react';
import './App.css';
import {BrowserRouter as Router, Link} from 'react-router-dom';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { apiResponse: "" };
}

callAPI() {
    fetch("http://localhost:9000/:username")
        .then(res => res.text())
        .then(res => this.setState({ apiResponse: res }));
}

componentWillMount() {
    this.callAPI();
}

render(){
  return (

{this.state.apiResponse}

  );
}
}

export default App;

i have created two files on express routes folder, one is testAPI.js and the other is be.js. when i try to acces any of these two files from my browser without using react, on lets say localhost:9000/testAPI it works fine. but when i try to access localhost:3000/testAPI which calls the same file through react, it gives me this messed up error page:

 <!DOCTYPE html><title></title><link rel="stylesheet" href="/stylesheets/style.css">
Not Found

404

NotFoundError: Not Found at C:\Users\Denoh\full\api\app.js:33:8 at Layer.handle [as handle_request] (C:\Users\Denoh\full\api\node_modules\express\lib\router\layer.js:95:5) at trim_prefix (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:317:13) at C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:284:7 at Function.process_params (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:335:12) at next (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:275:10) at C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:635:15 at next (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:260:14) at Function.handle (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:174:3) at router (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:47:12)

please assist


问:
Azure Pipelines multi-repo how to get Git Commit ID
For an Azure Pipeline with multi-repositories, how can you get the GIT commit id from a checked out resource repository? Is it supported?

I'm using an Azure repo to store the pipeline yaml file, and checking out the build source on an agent to build there. We're using Delphi so we have to use an agent.

```<code>resources:
  repositories:
  - repository: MyBitBucketRepo
    type: bitbucket
    endpoint: MyBitBucketServiceConnection
    name: MyBitBucketOrgOrUser/MyBitBucketRepo

trigger:
- pilot

pool:
  name: MyAgent
  demands: RADSTUDIO

variables:
  GIT_COMMIT: $(Build.SourceVersion) # <- How can I get the checked out Commit ID for the MyBitBucketRepo?
  GIT_BRANCH: $(Build.SourceBranchName) # And the branch name?

steps:
- checkout: MyBitBucketRepo

- script: dir $(Build.SourcesDirectory)
- script: echo $(GIT_COMMIT)
- script: echo $(GIT_BRANCH)
# todo set environment vars on agent with the Commit and Branch names required by msbuild script on agent
# todo run msbuild script on agent
</code>```

答:
how can you get the GIT commit id from a checked out resource repository? Is it supported?

I am afraid this is not supported by the Azure devops at this moment.

So, we could not use the predefined variables like $(Build.SourceVersion) to get the Git Commit ID from the multi-repositories directly.

To resolve this issue, we could use git command line to get the Commit ID and branch name:

```<code> git rev-parse HEAD
 git branch -r
</code>```

You could check my test YAML file for some details:

```<code>resources:
  repositories:
  - repository: TestProject
    type: github
    name: xxxx/TestProject
    endpoint: GitHub connection 1
  - repository: leotest
    type: bitbucket
    name: Lsgqazwsx/leotest
    endpoint: Lsgqazwsx

variables:
  GIT_COMMIT: $(Build.SourceVersion)
  GIT_BRANCH: $(Build.SourceBranchName)

stages:
- stage:
  jobs:
   - job: A
     pool:
       name: MyPrivateAgent
     steps:
     - checkout: TestProject
     - script: echo $(GIT_COMMIT)

- stage:
  jobs:
   - job: B
     pool:
      name: MyPrivateAgent
     steps:
     - checkout: leotest
     - script: git rev-parse HEAD
     - script: git branch -r
</code>```

The result for job B:

Commit Id from bitbucket.org：

Hope this helps.

Body:
For an Azure Pipeline with multi-repositories, how can you get the GIT commit id from a checked out resource repository? Is it supported?

I'm using an Azure repo to store the pipeline yaml file, and checking out the build source on an agent to build there. We're using Delphi so we have to use an agent.

resources:
  repositories:
  - repository: MyBitBucketRepo
    type: bitbucket
    endpoint: MyBitBucketServiceConnection
    name: MyBitBucketOrgOrUser/MyBitBucketRepo

trigger:
- pilot

pool:
  name: MyAgent
  demands: RADSTUDIO

variables:
  GIT_COMMIT: $(Build.SourceVersion) # <- How can I get the checked out Commit ID for the MyBitBucketRepo?
  GIT_BRANCH: $(Build.SourceBranchName) # And the branch name?

steps:
- checkout: MyBitBucketRepo

- script: dir $(Build.SourcesDirectory)
- script: echo $(GIT_COMMIT)
- script: echo $(GIT_BRANCH)
# todo set environment vars on agent with the Commit and Branch names required by msbuild script on agent
# todo run msbuild script on agent

Body:
how can you get the GIT commit id from a checked out resource repository? Is it supported?

I am afraid this is not supported by the Azure devops at this moment.

So, we could not use the predefined variables like $(Build.SourceVersion) to get the Git Commit ID from the multi-repositories directly.

To resolve this issue, we could use git command line to get the Commit ID and branch name:

 git rev-parse HEAD
 git branch -r

You could check my test YAML file for some details:

resources:
  repositories:
  - repository: TestProject
    type: github
    name: xxxx/TestProject
    endpoint: GitHub connection 1
  - repository: leotest
    type: bitbucket
    name: Lsgqazwsx/leotest
    endpoint: Lsgqazwsx

variables:
  GIT_COMMIT: $(Build.SourceVersion)
  GIT_BRANCH: $(Build.SourceBranchName)

stages:
- stage:
  jobs:
   - job: A
     pool:
       name: MyPrivateAgent
     steps:
     - checkout: TestProject
     - script: echo $(GIT_COMMIT)

- stage:
  jobs:
   - job: B
     pool:
      name: MyPrivateAgent
     steps:
     - checkout: leotest
     - script: git rev-parse HEAD
     - script: git branch -r

The result for job B:

Commit Id from bitbucket.org：

Hope this helps.


问:
change specific columns name in one Go in Python
my dataframe-:

```<code>Unnamed: 0     AsF      demos   Unnamed: 1  Unnamed: 2  Unnamed: 3  Unnamed: 4
1               2        3        3            3           3          3
2               3        4        6             6          6          6

Expected result-:

               AsF     demos
1               2        3        3            3           3          3
2               3        4        6             6          6          6

i tried
df.rename( columns={'Unnamed: 0':'','Unnamed: 1':''}, inplace=True)

</code>```

But I can't do that, because number of this kind of columns("unnamed:0") is not fix

I want to do this,because when i convert DF into CSV, it comes with "Unnamed" name that I do not want.

Thanks in Advance

答:
try this:</p>

```<code> df.columns = df.columns[0:2]+[''] * len(df.columns[2:])
 df.to_csv('filename.csv', header=False)
</code>```

Body:
my dataframe-:

Unnamed: 0     AsF      demos   Unnamed: 1  Unnamed: 2  Unnamed: 3  Unnamed: 4
1               2        3        3            3           3          3
2               3        4        6             6          6          6

Expected result-:

               AsF     demos
1               2        3        3            3           3          3
2               3        4        6             6          6          6

i tried
df.rename( columns={'Unnamed: 0':'','Unnamed: 1':''}, inplace=True)

But I can't do that, because number of this kind of columns("unnamed:0") is not fix

I want to do this,because when i convert DF into CSV, it comes with "Unnamed" name that I do not want.

Thanks in Advance

Body:
try this:

 df.columns = df.columns[0:2]+[''] * len(df.columns[2:])
 df.to_csv('filename.csv', header=False)


问:
Maven plugin jsonschema2pojo-maven-plugin not generating pojos for all the definitions
We are using jsonschema2pojo-maven-plugin to generate the java pojos from a json schema file. The plugin is generating the pojos for the definitions that are referred from the schema but not for all the definitions.

Is there any option to make the plugin generate the pojos for all the definitions in the schmea?

Below are the pom plugin configurations and schema definitions used, here the plugin is

generating POJOs only for the product definition

not generating POJOs for the product subclass definitions ("proprietaryProduct" & "thirdPartyProduct")

this is the problem, we need to have the pojos generated for these subclass definitions as well

Maven Plugin configuration:

```<code>    <plugin>
        <groupId>org.jsonschema2pojo</groupId>
        <artifactId>jsonschema2pojo-maven-plugin</artifactId>
        <executions>
            <execution>
                <id>generate-models</id>
                <configuration>
                    <targetPackage>com.xyz.abc</targetPackage>
                    <useCommonsLang3>true</useCommonsLang3>
                </configuration>
                <goals>
                    <goal>generate</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
</code>```

Json Schema:

```<code>{
  "$schema":"http://json-schema.org/draft-04/schema",
  "definitions":{
    "product":{
      "type":"object",
      "properties":{
        "type":{
          "enum":[
            "THIRD_PARTY",
            "PROPRIETARY"
          ],
          "type":"string"
        },
        "price":{
          "type":"string"
        }
      },
      "additionalProperties": false
    },
    "proprietaryProduct": {
      "type": "object",
      "properties": {
        "batchName": {
          "type": "string"
        }
      },
      "extends": "#/definitions/product"
    },
    "thirdPartyProduct": {
      "type": "object",
      "properties": {
        "thirdPartyName": {
          "type": "string"
        }
      },
      "extends": "#/definitions/product"
    }
  },
  "type":"object",
  "properties":{
    "product":{
      "type":"object",
      "$ref":"#/definitions/product"
    }
  },
  "additionalProperties":false
}
</code>```

答:
I managed to generate unreferenced parts of the definitions by using a custom schema rule factory, in a new maven project :

package my.package;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sun.codemodel.JClassContainer;
import com.sun.codemodel.JType;
import org.jsonschema2pojo.Schema;
import org.jsonschema2pojo.rules.Rule;
import org.jsonschema2pojo.rules.RuleFactory;
import org.jsonschema2pojo.rules.SchemaRule;

import java.util.Iterator;

public class JsonSchemaRuleFactory extends RuleFactory {

    @Override
    public Rule<JClassContainer, JType> getSchemaRule() {
        return new MySchemaRule(this);
    }

    private class MySchemaRule extends SchemaRule {

        public MySchemaRule(JsonSchemaRuleFactory jsonSchemaRuleFactory) {
            super(jsonSchemaRuleFactory);
        }

        @Override
        public JType apply(String nodeName, JsonNode schemaNode, JsonNode parent, JClassContainer generatableType, Schema schema) {
            final JType apply = super.apply(nodeName, schemaNode, parent, generatableType, schema);

            final JsonNode definitions = schemaNode.get("definitions");
            if (definitions != null && definitions.isObject()) {
                ObjectNode objectNode = (ObjectNode) definitions;
                final Iterator<String> nodeIterator = objectNode.fieldNames();
                while (nodeIterator.hasNext()) {
                    final String name = nodeIterator.next();
                    try {
                        final ObjectNode node = (ObjectNode) objectNode.get(name);
                        final Schema currentSchema = getSchemaStore().create(schema, "#/definitions/" + name, getGenerationConfig().getRefFragmentPathDelimiters());
                        getSchemaRule().apply(name, node, schemaNode, generatableType.getPackage(), currentSchema);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            return apply;
        }
    }
}
```

<p>new dedicated maven project :</p>

<pre class="lang-xml prettyprint-override"><code><project>
    <groupId>my.group</groupId>
    <artifactId>jsonschema-with-all-definitions</artifactId>
    <version>1.0.0</version>
    // ...
    <dependencies>
        <dependency>
            <groupId>org.jsonschema2pojo</groupId>
            <artifactId>jsonschema2pojo-core</artifactId>
            <version>1.0.2</version>
        </dependency>
    </dependencies>
</project>
</code>```

Then I modified the configuration of the jsonschema2pojo-maven-plugin as seen below:

                    <plugin>
                        <groupId>org.jsonschema2pojo</groupId>
                        <artifactId>jsonschema2pojo-maven-plugin</artifactId>
                        <version>1.0.2</version>
                        <executions>
                            <execution>
                                <id>generateClassesFromSchema</id>
                                <phase>generate-sources</phase>
                                <goals>
                                    <goal>generate</goal>
                                </goals>

                            </execution>
                        </executions>
                        <configuration>
                            // ...
<customRuleFactory>my.package.JsonSchemaRuleFactory</customRuleFactory>
                        </configuration>

                        <dependencies>
                            <dependency>
                                <groupId>my.group</groupId>
                                <artifactId>jsonschema-with-all-definitions</artifactId>
                                <version>1.0.0</version>
                            </dependency>
                        </dependencies>
                    </plugin>
```

As the jsonschema aren't mine and I can't edit/correct them, I used MixIns which I registered in my ObjectMapper to add some annotations that are missing from generated classes, such as @JsonTypeInfo or else.

Hope it helps!

Body:
We are using jsonschema2pojo-maven-plugin to generate the java pojos from a json schema file. The plugin is generating the pojos for the definitions that are referred from the schema but not for all the definitions.

Is there any option to make the plugin generate the pojos for all the definitions in the schmea?

Below are the pom plugin configurations and schema definitions used, here the plugin is

generating POJOs only for the product definition

not generating POJOs for the product subclass definitions ("proprietaryProduct" & "thirdPartyProduct")

this is the problem, we need to have the pojos generated for these subclass definitions as well

Maven Plugin configuration:

    <plugin>
        <groupId>org.jsonschema2pojo</groupId>
        <artifactId>jsonschema2pojo-maven-plugin</artifactId>
        <executions>
            <execution>
                <id>generate-models</id>
                <configuration>
                    <targetPackage>com.xyz.abc</targetPackage>
                    <useCommonsLang3>true</useCommonsLang3>
                </configuration>
                <goals>
                    <goal>generate</goal>
                </goals>
            </execution>
        </executions>
    </plugin>

Json Schema:

{
  "$schema":"http://json-schema.org/draft-04/schema",
  "definitions":{
    "product":{
      "type":"object",
      "properties":{
        "type":{
          "enum":[
            "THIRD_PARTY",
            "PROPRIETARY"
          ],
          "type":"string"
        },
        "price":{
          "type":"string"
        }
      },
      "additionalProperties": false
    },
    "proprietaryProduct": {
      "type": "object",
      "properties": {
        "batchName": {
          "type": "string"
        }
      },
      "extends": "#/definitions/product"
    },
    "thirdPartyProduct": {
      "type": "object",
      "properties": {
        "thirdPartyName": {
          "type": "string"
        }
      },
      "extends": "#/definitions/product"
    }
  },
  "type":"object",
  "properties":{
    "product":{
      "type":"object",
      "$ref":"#/definitions/product"
    }
  },
  "additionalProperties":false
}

Body:
I managed to generate unreferenced parts of the definitions by using a custom schema rule factory, in a new maven project :

package my.package;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sun.codemodel.JClassContainer;
import com.sun.codemodel.JType;
import org.jsonschema2pojo.Schema;
import org.jsonschema2pojo.rules.Rule;
import org.jsonschema2pojo.rules.RuleFactory;
import org.jsonschema2pojo.rules.SchemaRule;

import java.util.Iterator;

public class JsonSchemaRuleFactory extends RuleFactory {

    @Override
    public Rule<JClassContainer, JType> getSchemaRule() {
        return new MySchemaRule(this);
    }

    private class MySchemaRule extends SchemaRule {

        public MySchemaRule(JsonSchemaRuleFactory jsonSchemaRuleFactory) {
            super(jsonSchemaRuleFactory);
        }

        @Override
        public JType apply(String nodeName, JsonNode schemaNode, JsonNode parent, JClassContainer generatableType, Schema schema) {
            final JType apply = super.apply(nodeName, schemaNode, parent, generatableType, schema);

            final JsonNode definitions = schemaNode.get("definitions");
            if (definitions != null && definitions.isObject()) {
                ObjectNode objectNode = (ObjectNode) definitions;
                final Iterator<String> nodeIterator = objectNode.fieldNames();
                while (nodeIterator.hasNext()) {
                    final String name = nodeIterator.next();
                    try {
                        final ObjectNode node = (ObjectNode) objectNode.get(name);
                        final Schema currentSchema = getSchemaStore().create(schema, "#/definitions/" + name, getGenerationConfig().getRefFragmentPathDelimiters());
                        getSchemaRule().apply(name, node, schemaNode, generatableType.getPackage(), currentSchema);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            return apply;
        }
    }
}

new dedicated maven project :

<project>
    <groupId>my.group</groupId>
    <artifactId>jsonschema-with-all-definitions</artifactId>
    <version>1.0.0</version>
    // ...
    <dependencies>
        <dependency>
            <groupId>org.jsonschema2pojo</groupId>
            <artifactId>jsonschema2pojo-core</artifactId>
            <version>1.0.2</version>
        </dependency>
    </dependencies>
</project>

Then I modified the configuration of the jsonschema2pojo-maven-plugin as seen below:

                    <plugin>
                        <groupId>org.jsonschema2pojo</groupId>
                        <artifactId>jsonschema2pojo-maven-plugin</artifactId>
                        <version>1.0.2</version>
                        <executions>
                            <execution>
                                <id>generateClassesFromSchema</id>
                                <phase>generate-sources</phase>
                                <goals>
                                    <goal>generate</goal>
                                </goals>

                            </execution>
                        </executions>
                        <configuration>
                            // ...
<customRuleFactory>my.package.JsonSchemaRuleFactory</customRuleFactory>
                        </configuration>

                        <dependencies>
                            <dependency>
                                <groupId>my.group</groupId>
                                <artifactId>jsonschema-with-all-definitions</artifactId>
                                <version>1.0.0</version>
                            </dependency>
                        </dependencies>
                    </plugin>

As the jsonschema aren't mine and I can't edit/correct them, I used MixIns which I registered in my ObjectMapper to add some annotations that are missing from generated classes, such as @JsonTypeInfo or else.

Hope it helps!


问:
decimal number as input, but turn the fraction and output as decimal js
I need a function with a decimal number as input (parameter). The function should turn the fraction of the number and output it as decimal number.

I think, in my use caces the numerator can always be 1.
For example I have the  fraction 1/4

and would like to get the output 4/1 (same as 4).

If anyone has an other idea how to solve it, please answer as well.

I am happy about every answer

答:
As log as all of your fractions have the numerator of 1 the function is simply 1/fraction: (1/f)-1 = 1/(1/f) = f.

Whenever you have something that has not a numerator of 1, the result will be different but also not possible with using a "deciaml"/float input, just because of rules of math. The decimal point-number 0.25 is equal to 1/4, 2/8, 4/16, ... This makes it impossible (without saving the fraction) to get back from only the reduced decimal point-number to the "original" fraction.

function denominator(fraction){
  return 1/fraction;
}

// demo only
const test_fractions = ["1/2", "1/3", "1/4", "1/9", "1/35", "2/8"];
for(let i = 0; i < test_fractions.length; i++){
  let f = test_fractions[i].split("/");
  f = parseInt(f[0])/parseInt(f[1]);
  console.log("The denominator of", test_fractions[i], "=", f, "is", denominator(f));
}```


问:
Keras internal weights memory - why multiple fits() with one epoch still sees improvement
I am writing a keras lstm model in python. If I have the below fit() code

```<code>for i in range(0, epochs):
    model.fit(X_train, y_train, epochs=1, batch_size=32, validation_data=[X_test, y_test], shuffle=True)
</code>```

I would expect that each epoch is independent of the previous, i.e. there is no visible improvement with each consecutive epoch. However, this is not the case. The above code works exactly the same as writing:

```<code>model.fit(X_train, y_train, epochs=epochs, batch_size=32, validation_data=[X_test, y_test], shuffle=True)
</code>```

I know that keras has a model.reset_states() function but I don't believe that resetting the states, resets the weights, and starts a new epoch independently in the first code block. So how is keras saving weights and other data between independent fit() functions and how can I reset it?

答: The fit function is only updating the weights. That's why if you call fit several times you'll just update weights every time.

Body:
I am writing a keras lstm model in python. If I have the below fit() code

for i in range(0, epochs):
    model.fit(X_train, y_train, epochs=1, batch_size=32, validation_data=[X_test, y_test], shuffle=True)

I would expect that each epoch is independent of the previous, i.e. there is no visible improvement with each consecutive epoch. However, this is not the case. The above code works exactly the same as writing:

model.fit(X_train, y_train, epochs=epochs, batch_size=32, validation_data=[X_test, y_test], shuffle=True)

I know that keras has a model.reset_states() function but I don't believe that resetting the states, resets the weights, and starts a new epoch independently in the first code block. So how is keras saving weights and other data between independent fit() functions and how can I reset it?


问:
UWP Windows IoT Core Stream Routing
I would like to find out if Windows IoT Core supports Stream Routing. Otherwise, is there any other work around for similar result?
I have multiple USB audio adapter connected to my RaspberryPi and would like route the different 'capture' device(s) to diff 'render' device(s) .. like mixing the audio etc.
Any advise please.. Thank you very much.</p>

答: You can use the APIs in Windows.Media.Audio namespace to create audio graphs for audio routing, mixing, and processing scenarios.An audio graph is a set of interconnected audio nodes through which audio data flows. Please refer to this AudioGraph sample.</p>

Title: UWP Windows IoT Core Stream Routing


问:
Change type of varchar field to integer: "cannot be cast automatically to type integer"
I have a small table and a certain field contains the type "character varying". I'm trying to change it to "Integer" but it gives an error that casting is not possible.

Is there a way around this or should I just create another table and bring the records into it using a query.

The field contains only integer values.

答:
I had the same issue. I started to reset the default of the column.</p>

```<code>change_column :users, :column_name, :boolean, default: nil
change_column :users, :column_name, :integer, using: 'column_name::integer', default: 0, null: false
</code>```

Body:
I had the same issue. I started to reset the default of the column.

change_column :users, :column_name, :boolean, default: nil
change_column :users, :column_name, :integer, using: 'column_name::integer', default: 0, null: false


问:
Create .wav file using C#
I have nessary chunk header bytes for a wave file stored in a text file. What I'd like to do is create a new .wav that will vary in data length and write into it 50ms/10kHz signals(which is stored in separate file). How can I accomplish with .NET/C#?

-Mickey

答: Use the System.IO.BinaryReader and System.IO.BinaryWriter streams to read data from your signals files, write binary datatypes to a file, as per the wav file specification.</p>

Title: Create .wav file using C#


问:
how to set value for WSS -Time to Live in wcf services which is calling anoother SOAP service?
how to set value for WSS -Time to Live in wcf services which is calling another SOAP service?</p>

答:
You can set the value of the inactivitytimeout property in WCF.If more than the InactivityTimeout specified time interval passes with no activity, the session is aborted by the infrastructure and the channel faults.

You can configure it in the configuration file:

```<code>    <bindings>
        <wsHttpBinding>
            <binding name="Binding">
                <reliableSession inactivityTimeout="00:10:00"/>
            </binding>
        </wsHttpBinding>
    </bindings>
</code>```

I set the timeout to 10 minutes. If the client-side does not send any messages to the server-side within 10 minutes, the connection will be interrupted.

For more information about reliablesession and inactivitytimeout,please refer to the following link:

https://learn.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/wcf/reliablesession

https://learn.microsoft.com/en-us/dotnet/api/system.servicemodel.reliablesession.inactivitytimeout?view=netframework-4.8&viewFallbackFrom=dotnet-plat-ext-3.1

Body:
You can set the value of the inactivitytimeout property in WCF.If more than the InactivityTimeout specified time interval passes with no activity, the session is aborted by the infrastructure and the channel faults.

You can configure it in the configuration file:

    <bindings>
        <wsHttpBinding>
            <binding name="Binding">
                <reliableSession inactivityTimeout="00:10:00"/>
            </binding>
        </wsHttpBinding>
    </bindings>

I set the timeout to 10 minutes. If the client-side does not send any messages to the server-side within 10 minutes, the connection will be interrupted.

For more information about reliablesession and inactivitytimeout,please refer to the following link:

https://learn.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/wcf/reliablesession

https://learn.microsoft.com/en-us/dotnet/api/system.servicemodel.reliablesession.inactivitytimeout?view=netframework-4.8&viewFallbackFrom=dotnet-plat-ext-3.1


问:
Laravel package config does not merge
I am developing several packages and would like to have a single config file for all of them if they are to be published.

Inside my service provider I did this:

```<code>public function boot()
{
    $this->publishes([
        __DIR__ . '/config/custom.php' => config_path('custom.php'),
    ]);
}

public function register()
{
    $this->mergeConfigFrom(
        __DIR__ . '/config/custom.php', 'custom'
    );
}
</code>```

Config:

```<code>return [
    'containers' => [
        ...
    ]
];
</code>```

And surely enough, if I publish it, it creates the file with values inside. But if a file already exists, having different keys:

```<code>return [
    'xxxyyy' => [
        ...
    ],
];
</code>```

publishing doesn't do anything. I would expect it to look like:

```<code>return [
    'xxxyyy' => [
        ...
    ],

    'containers' => [
        ...
    ]
];
</code>```

What am I doing wrong?

答:
In case anyone else is baffled by this, I have tested several cases and here is my explanation (official docs).

$this->publishes part enables the package config to be published by vendor:publish command. Nothing to explain here.

$this->mergeConfigFrom part enables the package config to be merged with currently published copy. Merge in this case means merged from Laravel config() scope.

This means that going to artisan tinker and running config('key') (where key is name of your config file) will return nothing if there is no published file and you don't have mergeConfigFrom. If a file is published and has other key value pairs which are not present in your package config and you have mergeConfigFrom present, config('key') will return merged array of values from a published file together with values from your config.

If a file with a same config name exists in your root config folder, and your package internally uses the same config name but you don't have mergeConfigFrom, config('key') will return only contents of a file inside root config folder, and will ignore everything from your package as you didn't provide a way for Laravel to see this as a "global" configuration. Your package will keep internally using the package config, but from app scope you will not be able to fetch it.

Title: Laravel package config does not merge

Body:
I am developing several packages and would like to have a single config file for all of them if they are to be published.

Inside my service provider I did this:

public function boot()
{
    $this->publishes([
        __DIR__ . '/config/custom.php' => config_path('custom.php'),
    ]);
}

public function register()
{
    $this->mergeConfigFrom(
        __DIR__ . '/config/custom.php', 'custom'
    );
}

Config:

return [
    'containers' => [
        ...
    ]
];

And surely enough, if I publish it, it creates the file with values inside. But if a file already exists, having different keys:

return [
    'xxxyyy' => [
        ...
    ],
];

publishing doesn't do anything. I would expect it to look like:

return [
    'xxxyyy' => [
        ...
    ],

    'containers' => [
        ...
    ]
];

What am I doing wrong?


问:
How to write a custom-attribute (directive) in React 16.9?
Is it possible to use React just for writing a custom-attribute for existing HTML tags?

for example, I want to add float-label to an input HTML tag like the following code:

  <input type="text" id="lname" name="lname" float-label="LastName">

```

and call float-labels.js behind the scene. I want to just extend the regular HTML input tag no more.

Is it possible to use React to extend current HTML tags without writing a new component/tag (like float-input)?

答:
You can define HTML standard attribute if you create a new attribute it will consider as props so you can define aria-label that is a built-in attribute</p>

```<code><input type="text" id="lname" name="lname" aria-label="LastName">
</code>```

Body:
Is it possible to use React just for writing a custom-attribute for existing HTML tags?

for example, I want to add float-label to an input HTML tag like the following code:

  <input type="text" id="lname" name="lname" float-label="LastName">

and call float-labels.js behind the scene. I want to just extend the regular HTML input tag no more.

Is it possible to use React to extend current HTML tags without writing a new component/tag (like float-input)?

Body:
You can define HTML standard attribute if you create a new attribute it will consider as props so you can define aria-label that is a built-in attribute

<input type="text" id="lname" name="lname" aria-label="LastName">


问:
Accessing a function inside a function from another module/file?
index.js

```<code>    import React from 'react'
    import ReactDOM from 'react-dom'
    import './index.css'
    import SquareBox from './game-buttons.js'

    const Game = () => {
      return (
        <div className="main-container">
          <i id="reset-icon" className="fas-disabled fas fa-redo-alt" onClick={() => SquareBox.resetGame}></i>
          <SquareBox />
        </div>
      )
    }

    ReactDOM.render(<Game />, document.getElementById('root'));

    export default Game;
</code>```

game-buttons.js

```<code>import React, { useState } from 'react'
import ReactDOM from 'react-dom'
import Game from './index.js'
import './index.css'

const SquareBox = () => {

    // reset game
    function resetGame () {
        console.log("Game reset");
    }

   return (
        <div>
            Testing
        </div >
    )
}

export default SquareBox
</code>```

I am new to reactJS. Trying to figure out how can I access resetGame() function inside game-buttons.js by clicking  tag icon inside index.js.

答:
If I understand correctly what OP would like to do:
You should elevate the method resetGame to the Game component, place  inside of SquareBox and pass down the function resetGame as prop, maybe something like this:

```<code>import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import SquareBox from './game-buttons.js'

class Game extends React.Component {

// reset game
function resetGame () {
        console.log("Game reset");
}

render() {
     return (
         <div className="main-container">

         <SquareBox handleClick={() => this.resetGame} />
        </div>
     )
   }
}

ReactDOM.render(<Game />, document.getElementById('root'));

export default Game;
</code>```

game-buttons.js

```<code>import React, { useState } from 'react'
import ReactDOM from 'react-dom'
import Game from './index.js'
import './index.css'

const SquareBox = ({handleClick}) => {

   return (
        <div>
            <i id="reset-icon" className="fas-disabled fas fa-redo-alt" onClick={() => handleClick}></i>
        </div >
    )
}

export default SquareBox
</code>```

Body:
index.js

    import React from 'react'
    import ReactDOM from 'react-dom'
    import './index.css'
    import SquareBox from './game-buttons.js'

    const Game = () => {
      return (

           SquareBox.resetGame}>
          <SquareBox />

      )
    }

    ReactDOM.render(<Game />, document.getElementById('root'));

    export default Game;

game-buttons.js

import React, { useState } from 'react'
import ReactDOM from 'react-dom'
import Game from './index.js'
import './index.css'

const SquareBox = () => {

    // reset game
    function resetGame () {
        console.log("Game reset");
    }

   return (

            Testing

    )
}

export default SquareBox

I am new to reactJS. Trying to figure out how can I access resetGame() function inside game-buttons.js by clicking  tag icon inside index.js.

Body:
If I understand correctly what OP would like to do:
You should elevate the method resetGame to the Game component, place  inside of SquareBox and pass down the function resetGame as prop, maybe something like this:

import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import SquareBox from './game-buttons.js'

class Game extends React.Component {

// reset game
function resetGame () {
        console.log("Game reset");
}

render() {
     return (
         <div className="main-container">

         <SquareBox handleClick={() => this.resetGame} />
        </div>
     )
   }
}

ReactDOM.render(<Game />, document.getElementById('root'));

export default Game;

game-buttons.js

import React, { useState } from 'react'
import ReactDOM from 'react-dom'
import Game from './index.js'
import './index.css'

const SquareBox = ({handleClick}) => {

   return (
        <div>
            <i id="reset-icon" className="fas-disabled fas fa-redo-alt" onClick={() => handleClick}></i>
        </div >
    )
}

export default SquareBox


问:
OpenGL on Android: Any conflicts when calling OpenGL functions in both Java and C++?
In my application, I'm using a 3rd party custom view that calls OpenGL functions in Java, and I'm also calling OpenGL functions in my native C++ code.

Should this be a problem?

Is there any risk that they could be called at the same time?

What is the threading order of OpenGL calls across java/c++?

答: You can't access single OpenGL context from different threads. But it's legal to mix C++ and Java, the latter are just wrappers on native calls.</p>


问:
Store object from API to state
I am trying to use ReactJS to store info provided by a backend API.
My backend API returns a JSON object which contains:

```<code>"a": 123
"b": 345
"c": 0
</code>```

The above object is stored under data from my backend API.

So now I would like to store these values in data separately in React State as follows:

```<code>this.state = {
first:'',
second: '',
third: '',
}

//ComponentDidMount happen here
.then(result => {
        first: //result.data.data value "a":123 will be stored to State *First*
        //and "b":345 will go to second and "c":0 to third
        }
        debugger;
      })
</code>```

What should I write for that part for storing information to state?

答:
If you are fine with using 0, 1, 2 instead 'first', 'second', 'third', you can map through the values of the object and for each index store it in state

```<code>  .then(result => Object.values(result).map((value, i) => this.setState({ [i]: value })))
</code>```

Do notice that the actual keys in the state gonna be in a type of string, so you can access them like this.state['0']

Title: Store object from API to state

Body:
I am trying to use ReactJS to store info provided by a backend API.
My backend API returns a JSON object which contains:

"a": 123
"b": 345
"c": 0

The above object is stored under data from my backend API.

So now I would like to store these values in data separately in React State as follows:

this.state = {
first:'',
second: '',
third: '',
}

//ComponentDidMount happen here
.then(result => {
        first: //result.data.data value "a":123 will be stored to State *First*
        //and "b":345 will go to second and "c":0 to third
        }
        debugger;
      })

What should I write for that part for storing information to state?

Body:
If you are fine with using 0, 1, 2 instead 'first', 'second', 'third', you can map through the values of the object and for each index store it in state

  .then(result => Object.values(result).map((value, i) => this.setState({ [i]: value })))

Do notice that the actual keys in the state gonna be in a type of string, so you can access them like this.state['0']


问:
Difference between std::fabs(a * b) and std::fabs(a) * std::fabs(b)
I am working on some numerical code and I was looking at the compiler output. One particular case struck me as odd:

In real numbers, it holds that abs(a) * abs(b) = abs(a * b). I would expect the same to hold in floating point numbers. However, the optimization is performed neither by clang nor by g++ and I wonder whether I am missing some subtle difference there. Both compilers do however realize that abs(abs(a) * abs(b)) = abs(a) * abs(b).

Here is the relevant piece of code:

```<code>#include<cmath>

double fabsprod1(double a, double b) {
    return std::fabs(a*b);
}
double fabsprod2(double a, double b) {
    return std::fabs(a) * std::fabs(b);
}
double fabsprod3(double a, double b) {
    return std::fabs(std::fabs(a) * std::fabs(b));
}
</code>```

And here is the confusing compiler output in godbolt with gcc-10.1 (current stable version as of writing this) and -O3: https://godbolt.org/z/ZEFPgF

Notably, even with -Ofast, which as far as I understand is more lenient with the transformations that are allowed, this optimization is not performed.

As was pointed out by @Scheff in the comments, double and float are not real numbers. But I also fail to see where corner cases with float types, such as getting Infinity or NaN as argument, could produce different outputs.

答:
I believe I have found a counter example. I post this as a separate answer, because I don't think that this is at all analogous to the case for integers.

In the cases I considered, I missed that it is possible to change the rounding mode for floating point arithmetic. Problematically, GCC seems to to ignore that when he (I guess) optimizes "known" quantities at compile time. Consider the following code:

```<code>#include <iostream>
#include <cmath>
#include <cfenv>

double fabsprod1(double a, double b) {
    return std::fabs(a*b);
}
double fabsprod2(double a, double b) {
    return std::fabs(a) * std::fabs(b);
}

int main() {
        std::fesetround(FE_DOWNWARD);
        double a  = 0.1;
        double b = -3;
        std::cout << std::hexfloat;
        std::cout << "fabsprod1(" << a << "," << b << "): " << fabsprod1(a,b) << "\n";
        std::cout << "fabsprod2(" << a << "," << b << "): " << fabsprod2(a,b) << "\n";
#ifdef CIN
        std::cin >> b;
#endif
}
</code>```

Output differs, depending on whether I compile with

```<code>g++ -DCIN -O1 -march=native main2.cpp && ./a.out
</code>```

or

```<code>g++ -O1 -march=native main2.cpp && ./a.out
</code>```

Notably, it only takes O1 (what I would consider completely reliable) to change the output in a way that does not seem reasonable to me.

With -DCIN the output is

```<code>fabsprod1(0x1.999999999999ap-4,-0x1.8p+1): 0x1.3333333333334p-2
fabsprod2(0x1.999999999999ap-4,-0x1.8p+1): 0x1.3333333333333p-2
</code>```

without -DCIN the output is

```<code>fabsprod1(0x1.999999999999ap-4,-0x1.8p+1): 0x1.3333333333334p-2
fabsprod2(0x1.999999999999ap-4,-0x1.8p+1): 0x1.3333333333334p-2
</code>```

Edit: Peter Cordes (thank you for the comment) pointed out, that this surprising result was due to my failure in telling GCC to respect the change of rounding mode. By building with the following command, the expected results are achieved:

```<code>g++ -O1 -frounding-math -march=native main2.cpp && ./a.out
</code>```

(works with O2 and O3 as well on my machine).

Body:
I am working on some numerical code and I was looking at the compiler output. One particular case struck me as odd:

In real numbers, it holds that abs(a) * abs(b) = abs(a * b). I would expect the same to hold in floating point numbers. However, the optimization is performed neither by clang nor by g++ and I wonder whether I am missing some subtle difference there. Both compilers do however realize that abs(abs(a) * abs(b)) = abs(a) * abs(b).

Here is the relevant piece of code:

#include<cmath>

double fabsprod1(double a, double b) {
    return std::fabs(a*b);
}
double fabsprod2(double a, double b) {
    return std::fabs(a) * std::fabs(b);
}
double fabsprod3(double a, double b) {
    return std::fabs(std::fabs(a) * std::fabs(b));
}

And here is the confusing compiler output in godbolt with gcc-10.1 (current stable version as of writing this) and -O3: https://godbolt.org/z/ZEFPgF

Notably, even with -Ofast, which as far as I understand is more lenient with the transformations that are allowed, this optimization is not performed.

As was pointed out by @Scheff in the comments, double and float are not real numbers. But I also fail to see where corner cases with float types, such as getting Infinity or NaN as argument, could produce different outputs.

Body:
I believe I have found a counter example. I post this as a separate answer, because I don't think that this is at all analogous to the case for integers.

In the cases I considered, I missed that it is possible to change the rounding mode for floating point arithmetic. Problematically, GCC seems to to ignore that when he (I guess) optimizes "known" quantities at compile time. Consider the following code:

#include <iostream>
#include <cmath>
#include <cfenv>

double fabsprod1(double a, double b) {
    return std::fabs(a*b);
}
double fabsprod2(double a, double b) {
    return std::fabs(a) * std::fabs(b);
}

int main() {
        std::fesetround(FE_DOWNWARD);
        double a  = 0.1;
        double b = -3;
        std::cout << std::hexfloat;
        std::cout << "fabsprod1(" << a << "," << b << "): " << fabsprod1(a,b) << "\n";
        std::cout << "fabsprod2(" << a << "," << b << "): " << fabsprod2(a,b) << "\n";
#ifdef CIN
        std::cin >> b;
#endif
}

Output differs, depending on whether I compile with

g++ -DCIN -O1 -march=native main2.cpp && ./a.out

or

g++ -O1 -march=native main2.cpp && ./a.out

Notably, it only takes O1 (what I would consider completely reliable) to change the output in a way that does not seem reasonable to me.

With -DCIN the output is

fabsprod1(0x1.999999999999ap-4,-0x1.8p+1): 0x1.3333333333334p-2
fabsprod2(0x1.999999999999ap-4,-0x1.8p+1): 0x1.3333333333333p-2

without -DCIN the output is

fabsprod1(0x1.999999999999ap-4,-0x1.8p+1): 0x1.3333333333334p-2
fabsprod2(0x1.999999999999ap-4,-0x1.8p+1): 0x1.3333333333334p-2

Edit: Peter Cordes (thank you for the comment) pointed out, that this surprising result was due to my failure in telling GCC to respect the change of rounding mode. By building with the following command, the expected results are achieved:

g++ -O1 -frounding-math -march=native main2.cpp && ./a.out

(works with O2 and O3 as well on my machine).


问:
Column sorting issue in date field with dd/MM/YYYY format in angular ig-grid
In igx-grid,

When we apply sorting in ascending and descending order with dd-mm-yyyy format, so sorting is not working with actual date, month and year wise. and only apply date wise sorting.

When we apply sorting in ascending and descending order the date filed it is sorted by yyyy-mm-dd format and we display date in dd/MM/yyyy format on UI using pipe. So sorting is not working in this case.

答: If you haven't applied [dataType]="'date'" to the grid column, then the type defaults to string and column values will be sorted as strings. Add the correct dataType and sorting will work on the dates, regardless of formatting.