问:
Temporary tables in stored procedure for Oracle
I have a stored procedure that runs fine on MS SQL and DB2. But cannot get it to run on Oracle as it uses temporary tables created within the procedure. I would like to know any suggestions on my stored procedure if possible. Please do not suggest execute immediate as i do not have the permission for that. This is a huge procedure so please guide me how i can do this without a temporary table. Please note that creating a temporary table before creating the procedure is also not an option.

Thanks in advance!

```<code>`CREATE OR REPLACE PROCEDURE LEAD_PURGE(closed IN DATE,
oprtr IN INTEGER,
leadscount OUT INTEGER)
is
BEGIN

CREATE TABLE LEADS_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

CREATE TABLE ASSIGNMENTS_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

CREATE TABLE MAPRESULTS_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

CREATE TABLE COMMAND_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

CREATE TABLE PROGRESS_STATUS_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

CREATE TABLE DETAILS_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

CREATE TABLE NEEDS_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);
if oprtr = 0 then
INSERT INTO ASSIGNMENTS_DELETED
SELECT SEQID FROM ASSIGNMENT WHERE ROLE = 6 AND STATUS = 8 AND CLOSINGTIME < closed;

elsif oprtr = 1 then
INSERT INTO ASSIGNMENTS_DELETED
SELECT SEQID FROM ASSIGNMENT WHERE ROLE = 6 AND STATUS = 8 AND EXTRACT(YEAR FROM CLOSINGTIME) = EXTRACT(YEAR FROM closed)
                                                            AND EXTRACT(MONTH FROM CLOSINGTIME) = EXTRACT(MONTH FROM closed)
                                                            AND EXTRACT(DAY FROM CLOSINGTIME) = EXTRACT(DAY FROM closed);

elsif oprtr = 2 then
INSERT INTO ASSIGNMENTS_DELETED
SELECT SEQID FROM ASSIGNMENT WHERE ROLE = 6 AND STATUS = 8 AND CLOSINGTIME > closed;
end if;

INSERT INTO LEADS_DELETED
SELECT DISTINCT LEADSEQ FROM ASSIGNMENT WHERE SEQID IN (SELECT ID FROM ASSIGNMENTS_DELETED);

if oprtr = 0 then
insert into ASSIGNMENTS_DELETED
select SEQID FROM ASSIGNMENT WHERE LEADSEQ IN (SELECT ID FROM LEADS_DELETED) AND
SEQID NOT IN (SELECT SEQID FROM ASSIGNMENT WHERE ROLE = 6 AND STATUS = 8 AND CLOSINGTIME < closed);

elsif oprtr = 1 then
insert into ASSIGNMENTS_DELETED
select SEQID FROM ASSIGNMENT WHERE LEADSEQ IN (SELECT ID FROM LEADS_DELETED) AND
SEQID NOT IN (SELECT SEQID FROM ASSIGNMENT WHERE ROLE = 6 AND STATUS = 8 AND EXTRACT(YEAR FROM CLOSINGTIME) = EXTRACT(YEAR FROM closed)
                                                                         AND EXTRACT(MONTH FROM CLOSINGTIME) = EXTRACT(MONTH FROM closed)
                                                                         AND EXTRACT(DAY FROM CLOSINGTIME) = EXTRACT(DAY FROM closed));

elsif oprtr = 2 then
insert into ASSIGNMENTS_DELETED
select SEQID FROM ASSIGNMENT WHERE LEADSEQ IN (SELECT ID FROM LEADS_DELETED) AND
SEQID NOT IN (SELECT SEQID FROM ASSIGNMENT WHERE ROLE = 6 AND STATUS = 8 AND CLOSINGTIME > closed);
end if;

SET leadscount = (SELECT COUNT(*) FROM LEADS_DELETED);

INSERT INTO MAPRESULTS_DELETED
SELECT ID FROM MAPRESULT WHERE ASSIGNMENTSEQ IN (SELECT ID FROM ASSIGNMENTS_DELETED);

INSERT INTO COMMAND_DELETED
SELECT ID FROM EXECUTERULECOMMAND WHERE MAPRESULTID IN (SELECT ID FROM MAPRESULTS_DELETED);

INSERT INTO PROGRESS_STATUS_DELETED
SELECT PROGRESS_STATUS_ID FROM COMMAND WHERE ID IN (SELECT ID FROM COMMAND_DELETED);

INSERT INTO DETAILS_DELETED
SELECT DETAILID FROM LEAD WHERE SEQID IN (SELECT ID FROM LEADS_DELETED);

INSERT INTO NEEDS_DELETED
SELECT NEEDSID FROM LEAD WHERE SEQID IN (SELECT ID FROM LEADS_DELETED);

DELETE FROM PROGRESS_STATUS WHERE ID IN (SELECT ID FROM PROGRESS_STATUS_DELETED);

DELETE FROM EXECUTERULECOMMAND WHERE ID IN (SELECT ID FROM COMMAND_DELETED);

DELETE FROM COMMAND WHERE ID IN (SELECT ID FROM COMMAND_DELETED);

DELETE FROM SIMPLECONDITIONAL WHERE RESULT IN (SELECT ID FROM MAPRESULTS_DELETED);

DELETE FROM MAPPREDICATE WHERE ROWBP IN (SELECT ID FROM MAPROW WHERE RESULT IN (SELECT ID FROM MAPRESULTS_DELETED));

DELETE FROM MAPROW WHERE RESULT IN (SELECT ID FROM MAPRESULTS_DELETED);

DELETE FROM MAPRESULT WHERE ID IN (SELECT ID FROM MAPRESULTS_DELETED);

DELETE FROM ASSIGNMENTATTACHMENTS WHERE ASSIGNMENTSEQ IN (SELECT ID FROM ASSIGNMENTS_DELETED);

DELETE FROM LEADOBSERVER WHERE ASSIGNSEQ IN (SELECT ID FROM ASSIGNMENTS_DELETED);

DELETE FROM MAPDESTINATIONS WHERE SUGGESTEDASSIGNID IN
    (SELECT ID FROM SUGGESTEDASSIGNMENT WHERE ASSIGNMENT_SEQID IN (SELECT ID FROM ASSIGNMENTS_DELETED));

DELETE FROM SUGGESTEDASSIGNMENT WHERE ASSIGNMENT_SEQID IN (SELECT ID FROM ASSIGNMENTS_DELETED);

DELETE FROM PRODUCTINTEREST WHERE LEADSEQ IN (SELECT ID FROM LEADS_DELETED);

CREATE TABLE SALE_DELETED_EX
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

INSERT into SALE_DELETED_EX SELECT SALEEXSEQ FROM SALE WHERE SEQID IN (SELECT SALEID FROM LEADSALES WHERE LEADID IN (SELECT ID FROM LEADS_DELETED));

DELETE FROM SALE WHERE SEQID IN (SELECT SALEID FROM LEADSALES WHERE LEADID IN (SELECT ID FROM LEADS_DELETED));

DELETE FROM SALEEXTENSIONS WHERE
    SEQID IN (SELECT ID FROM SALE_DELETED_EX);

DELETE FROM LEADSALES WHERE LEADID IN (SELECT ID FROM LEADS_DELETED);

DELETE FROM NOTES WHERE OBJECTID IN (SELECT ID FROM NEEDS_DELETED) OR OBJECTID IN (SELECT ID FROM DETAILS_DELETED);

DELETE FROM HISTORYRECORD WHERE OBJECTID IN (SELECT ID FROM DETAILS_DELETED);

DELETE FROM DETAIL WHERE SEQID IN (SELECT ID FROM NEEDS_DELETED UNION SELECT ID FROM DETAILS_DELETED);

DELETE FROM MESSAGES WHERE PROVIDERID IN (SELECT ID FROM LEADS_DELETED);

DELETE FROM ASSIGNMENT WHERE LEADSEQ IN (SELECT ID FROM LEADS_DELETED);

DELETE FROM LEAD WHERE SEQID IN (SELECT ID FROM LEADS_DELETED);

CREATE TABLE LEADS_DELETED_E
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

InSERT into LEADS_DELETED_E Select SEQID FROM LEADEXTENSIONS WHERE
    SEQID NOT IN (SELECT LEADEXSEQ FROM LEAD);

DELETE FROM LEADEXTENSIONS WHERE
    SEQID  IN (SELECT ID FROM LEADS_DELETED_E);

DROP TABLE LEADS_DELETED;

DROP TABLE ASSIGNMENTS_DELETED;

DROP TABLE MAPRESULTS_DELETED;

DROP TABLE COMMAND_DELETED;

DROP TABLE PROGRESS_STATUS_DELETED;

DROP TABLE DETAILS_DELETED;

DROP TABLE NEEDS_DELETED;

DROP TABLE LEADS_DELETED_E;

DROP TABLE SALE_DELETED_EX;

COMMIT;
END LEAD_PURGE;
</code>```

`

答:
Use Oracle collections (and potentially table functions) instead of your current temporary tables, then you could use your procedure almost "as is".

The link to the Oracle Collections Docs is: http://download.oracle.com/docs/cd/B10501_01/appdev.920/a96624/05_colls.htm

http://download.oracle.com/docs/cd/B28359_01/appdev.111/b28425/pipe_paral_tbl.htm

Body:
I have a stored procedure that runs fine on MS SQL and DB2. But cannot get it to run on Oracle as it uses temporary tables created within the procedure. I would like to know any suggestions on my stored procedure if possible. Please do not suggest execute immediate as i do not have the permission for that. This is a huge procedure so please guide me how i can do this without a temporary table. Please note that creating a temporary table before creating the procedure is also not an option.

Thanks in advance!

`CREATE OR REPLACE PROCEDURE LEAD_PURGE(closed IN DATE,
oprtr IN INTEGER,
leadscount OUT INTEGER)
is
BEGIN

CREATE TABLE LEADS_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

CREATE TABLE ASSIGNMENTS_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

CREATE TABLE MAPRESULTS_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

CREATE TABLE COMMAND_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

CREATE TABLE PROGRESS_STATUS_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

CREATE TABLE DETAILS_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

CREATE TABLE NEEDS_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);
if oprtr = 0 then
INSERT INTO ASSIGNMENTS_DELETED
SELECT SEQID FROM ASSIGNMENT WHERE ROLE = 6 AND STATUS = 8 AND CLOSINGTIME < closed;

elsif oprtr = 1 then
INSERT INTO ASSIGNMENTS_DELETED
SELECT SEQID FROM ASSIGNMENT WHERE ROLE = 6 AND STATUS = 8 AND EXTRACT(YEAR FROM CLOSINGTIME) = EXTRACT(YEAR FROM closed)
                                                            AND EXTRACT(MONTH FROM CLOSINGTIME) = EXTRACT(MONTH FROM closed)
                                                            AND EXTRACT(DAY FROM CLOSINGTIME) = EXTRACT(DAY FROM closed);

elsif oprtr = 2 then
INSERT INTO ASSIGNMENTS_DELETED
SELECT SEQID FROM ASSIGNMENT WHERE ROLE = 6 AND STATUS = 8 AND CLOSINGTIME > closed;
end if;

INSERT INTO LEADS_DELETED
SELECT DISTINCT LEADSEQ FROM ASSIGNMENT WHERE SEQID IN (SELECT ID FROM ASSIGNMENTS_DELETED);

if oprtr = 0 then
insert into ASSIGNMENTS_DELETED
select SEQID FROM ASSIGNMENT WHERE LEADSEQ IN (SELECT ID FROM LEADS_DELETED) AND
SEQID NOT IN (SELECT SEQID FROM ASSIGNMENT WHERE ROLE = 6 AND STATUS = 8 AND CLOSINGTIME < closed);

elsif oprtr = 1 then
insert into ASSIGNMENTS_DELETED
select SEQID FROM ASSIGNMENT WHERE LEADSEQ IN (SELECT ID FROM LEADS_DELETED) AND
SEQID NOT IN (SELECT SEQID FROM ASSIGNMENT WHERE ROLE = 6 AND STATUS = 8 AND EXTRACT(YEAR FROM CLOSINGTIME) = EXTRACT(YEAR FROM closed)
                                                                         AND EXTRACT(MONTH FROM CLOSINGTIME) = EXTRACT(MONTH FROM closed)
                                                                         AND EXTRACT(DAY FROM CLOSINGTIME) = EXTRACT(DAY FROM closed));

elsif oprtr = 2 then
insert into ASSIGNMENTS_DELETED
select SEQID FROM ASSIGNMENT WHERE LEADSEQ IN (SELECT ID FROM LEADS_DELETED) AND
SEQID NOT IN (SELECT SEQID FROM ASSIGNMENT WHERE ROLE = 6 AND STATUS = 8 AND CLOSINGTIME > closed);
end if;

SET leadscount = (SELECT COUNT(*) FROM LEADS_DELETED);

INSERT INTO MAPRESULTS_DELETED
SELECT ID FROM MAPRESULT WHERE ASSIGNMENTSEQ IN (SELECT ID FROM ASSIGNMENTS_DELETED);

INSERT INTO COMMAND_DELETED
SELECT ID FROM EXECUTERULECOMMAND WHERE MAPRESULTID IN (SELECT ID FROM MAPRESULTS_DELETED);

INSERT INTO PROGRESS_STATUS_DELETED
SELECT PROGRESS_STATUS_ID FROM COMMAND WHERE ID IN (SELECT ID FROM COMMAND_DELETED);

INSERT INTO DETAILS_DELETED
SELECT DETAILID FROM LEAD WHERE SEQID IN (SELECT ID FROM LEADS_DELETED);

INSERT INTO NEEDS_DELETED
SELECT NEEDSID FROM LEAD WHERE SEQID IN (SELECT ID FROM LEADS_DELETED);

DELETE FROM PROGRESS_STATUS WHERE ID IN (SELECT ID FROM PROGRESS_STATUS_DELETED);

DELETE FROM EXECUTERULECOMMAND WHERE ID IN (SELECT ID FROM COMMAND_DELETED);

DELETE FROM COMMAND WHERE ID IN (SELECT ID FROM COMMAND_DELETED);

DELETE FROM SIMPLECONDITIONAL WHERE RESULT IN (SELECT ID FROM MAPRESULTS_DELETED);

DELETE FROM MAPPREDICATE WHERE ROWBP IN (SELECT ID FROM MAPROW WHERE RESULT IN (SELECT ID FROM MAPRESULTS_DELETED));

DELETE FROM MAPROW WHERE RESULT IN (SELECT ID FROM MAPRESULTS_DELETED);

DELETE FROM MAPRESULT WHERE ID IN (SELECT ID FROM MAPRESULTS_DELETED);

DELETE FROM ASSIGNMENTATTACHMENTS WHERE ASSIGNMENTSEQ IN (SELECT ID FROM ASSIGNMENTS_DELETED);

DELETE FROM LEADOBSERVER WHERE ASSIGNSEQ IN (SELECT ID FROM ASSIGNMENTS_DELETED);

DELETE FROM MAPDESTINATIONS WHERE SUGGESTEDASSIGNID IN
    (SELECT ID FROM SUGGESTEDASSIGNMENT WHERE ASSIGNMENT_SEQID IN (SELECT ID FROM ASSIGNMENTS_DELETED));

DELETE FROM SUGGESTEDASSIGNMENT WHERE ASSIGNMENT_SEQID IN (SELECT ID FROM ASSIGNMENTS_DELETED);

DELETE FROM PRODUCTINTEREST WHERE LEADSEQ IN (SELECT ID FROM LEADS_DELETED);

CREATE TABLE SALE_DELETED_EX
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

INSERT into SALE_DELETED_EX SELECT SALEEXSEQ FROM SALE WHERE SEQID IN (SELECT SALEID FROM LEADSALES WHERE LEADID IN (SELECT ID FROM LEADS_DELETED));

DELETE FROM SALE WHERE SEQID IN (SELECT SALEID FROM LEADSALES WHERE LEADID IN (SELECT ID FROM LEADS_DELETED));

DELETE FROM SALEEXTENSIONS WHERE
    SEQID IN (SELECT ID FROM SALE_DELETED_EX);

DELETE FROM LEADSALES WHERE LEADID IN (SELECT ID FROM LEADS_DELETED);

DELETE FROM NOTES WHERE OBJECTID IN (SELECT ID FROM NEEDS_DELETED) OR OBJECTID IN (SELECT ID FROM DETAILS_DELETED);

DELETE FROM HISTORYRECORD WHERE OBJECTID IN (SELECT ID FROM DETAILS_DELETED);

DELETE FROM DETAIL WHERE SEQID IN (SELECT ID FROM NEEDS_DELETED UNION SELECT ID FROM DETAILS_DELETED);

DELETE FROM MESSAGES WHERE PROVIDERID IN (SELECT ID FROM LEADS_DELETED);

DELETE FROM ASSIGNMENT WHERE LEADSEQ IN (SELECT ID FROM LEADS_DELETED);

DELETE FROM LEAD WHERE SEQID IN (SELECT ID FROM LEADS_DELETED);

CREATE TABLE LEADS_DELETED_E
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

InSERT into LEADS_DELETED_E Select SEQID FROM LEADEXTENSIONS WHERE
    SEQID NOT IN (SELECT LEADEXSEQ FROM LEAD);

DELETE FROM LEADEXTENSIONS WHERE
    SEQID  IN (SELECT ID FROM LEADS_DELETED_E);

DROP TABLE LEADS_DELETED;

DROP TABLE ASSIGNMENTS_DELETED;

DROP TABLE MAPRESULTS_DELETED;

DROP TABLE COMMAND_DELETED;

DROP TABLE PROGRESS_STATUS_DELETED;

DROP TABLE DETAILS_DELETED;

DROP TABLE NEEDS_DELETED;

DROP TABLE LEADS_DELETED_E;

DROP TABLE SALE_DELETED_EX;

COMMIT;
END LEAD_PURGE;

`


来源: stackexchange

问:
Authorize attribute with role redirects to Access denied
I have simple ASP .NET MVC application.
I'm trying to do authentication and authorization.

For authentication I have setup Azure AD and I'm adding role to the HttpContext.User using a middleware.
I know that the role is added because on the View if I do conditional rendering with User.IsInRole("Admin") the UI is correctly rendered. But the controller with Authorize[Roles = "Admin"] redirects me to

http://localhost:5433/MicrosoftIdentity/Account/AccessDenied?ReturnUrl=%2FHome%2FAdd

I even tired Authorize[Policy = "Admin"] but the result is same.

From services if I remove AddMicrosoftIdentityUI() then it is redirected to

http://localhost:5433/Account/AccessDenied?ReturnUrl=%2FHome%2FAdd

I don't know how does the Authorize attributes work. Does it not check User.IsInRole("Admin")?  Please let me know

Also for me the roles are added in UserDetails table and I do have a role as 'Admin'

Also I could have written a custom attribute and make it work. I just want to know what is the real issue right now.

Code:

Startup.cs

 public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContextPool<EmpDBContext>(
            options => options.UseSqlServer(Configuration.GetConnectionString("EmployeeDBConnection")));

            services.AddMicrosoftIdentityWebAppAuthentication(Configuration, "AzureAd");

            services.AddControllersWithViews(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                 .RequireAuthenticatedUser()
                 .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            }).AddMicrosoftIdentityUI().AddNewtonsoftJson();

            services.AddAuthorization(options =>
            {
                options.AddPolicy("Admin", policy => policy.RequireRole("Admin"));
                options.AddPolicy("Employee", policy => policy.RequireRole("Employee"));
            });
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseAddClaimsFromDb(); // CUSTOM MIDDLEWARE TO ADD ROLE TO USER

            // CHECKING IF ROLE WAS ADDED
            app.Use(async (context, next) =>
            {
                if (context.User != null && context.User.Identity.IsAuthenticated)
                {
                    bool x = context.User.IsInRole("Admin");
                    System.Console.WriteLine(x); // RETURNS TRUE

                }
                await next();
            });
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
```
<p><strong>UseAddClaimsFromDb (AddClaimMiddleware.cs)</strong></p>
<pre class="lang-cs prettyprint-override"><code>public class AddClaimMiddleware
    {
        private readonly RequestDelegate next;

        public AddClaimMiddleware(RequestDelegate next)
        {
            this.next = next;
        }

        public async Task InvokeAsync(HttpContext httpContext, EmpDBContext dBContext)
        {
            var user = httpContext.User;

            // does not perist between request
            if(user != null && user.Identity.IsAuthenticated)
            {
                string email = user.Identity.Name;

                UserDetail userDetail = await dBContext.UserDetails.FirstOrDefaultAsync(e => e.EmailId == email);
                string role = userDetail?.Role ?? "Employee";

                ClaimsIdentity claimsIdentity = new ClaimsIdentity();
                claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, role));

                user.AddIdentity(claimsIdentity);

               // httpContext.Session.SetString("employeeId", userDetail.EmployeeId.ToString());

            }

            await next(httpContext);
        }
    }
</code>```

答:
I fixed the above by rearranging the middleware sequence

```<code>app.UseAuthentication();
app.UseAddClaimsFromDb();
app.UseAuthorization();
</code>```

I still don't know the real reason why it worked. It would be great if someone can update this or add a new answer.

ContentLicense: CC BY-SA 4.0

Body:
I have simple ASP .NET MVC application.
I'm trying to do authentication and authorization.

For authentication I have setup Azure AD and I'm adding role to the HttpContext.User using a middleware.
I know that the role is added because on the View if I do conditional rendering with User.IsInRole("Admin") the UI is correctly rendered. But the controller with Authorize[Roles = "Admin"] redirects me to

http://localhost:5433/MicrosoftIdentity/Account/AccessDenied?ReturnUrl=%2FHome%2FAdd

I even tired Authorize[Policy = "Admin"] but the result is same.

From services if I remove AddMicrosoftIdentityUI() then it is redirected to

http://localhost:5433/Account/AccessDenied?ReturnUrl=%2FHome%2FAdd

I don't know how does the Authorize attributes work. Does it not check User.IsInRole("Admin")?  Please let me know

Also for me the roles are added in UserDetails table and I do have a role as 'Admin'

Also I could have written a custom attribute and make it work. I just want to know what is the real issue right now.

Code:

Startup.cs

 public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContextPool<EmpDBContext>(
            options => options.UseSqlServer(Configuration.GetConnectionString("EmployeeDBConnection")));

            services.AddMicrosoftIdentityWebAppAuthentication(Configuration, "AzureAd");

            services.AddControllersWithViews(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                 .RequireAuthenticatedUser()
                 .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            }).AddMicrosoftIdentityUI().AddNewtonsoftJson();

            services.AddAuthorization(options =>
            {
                options.AddPolicy("Admin", policy => policy.RequireRole("Admin"));
                options.AddPolicy("Employee", policy => policy.RequireRole("Employee"));
            });
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseAddClaimsFromDb(); // CUSTOM MIDDLEWARE TO ADD ROLE TO USER

            // CHECKING IF ROLE WAS ADDED
            app.Use(async (context, next) =>
            {
                if (context.User != null && context.User.Identity.IsAuthenticated)
                {
                    bool x = context.User.IsInRole("Admin");
                    System.Console.WriteLine(x); // RETURNS TRUE

                }
                await next();
            });
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }

UseAddClaimsFromDb (AddClaimMiddleware.cs)

public class AddClaimMiddleware
    {
        private readonly RequestDelegate next;

        public AddClaimMiddleware(RequestDelegate next)
        {
            this.next = next;
        }

        public async Task InvokeAsync(HttpContext httpContext, EmpDBContext dBContext)
        {
            var user = httpContext.User;

            // does not perist between request
            if(user != null && user.Identity.IsAuthenticated)
            {
                string email = user.Identity.Name;

                UserDetail userDetail = await dBContext.UserDetails.FirstOrDefaultAsync(e => e.EmailId == email);
                string role = userDetail?.Role ?? "Employee";

                ClaimsIdentity claimsIdentity = new ClaimsIdentity();
                claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, role));

                user.AddIdentity(claimsIdentity);

               // httpContext.Session.SetString("employeeId", userDetail.EmployeeId.ToString());

            }

            await next(httpContext);
        }
    }

Body:
I fixed the above by rearranging the middleware sequence

app.UseAuthentication();
app.UseAddClaimsFromDb();
app.UseAuthorization();

I still don't know the real reason why it worked. It would be great if someone can update this or add a new answer.


问:
Using Same Node ids for Different Content Type Drupal
Is it possible to use different node ids for different content types. Consider two content types Questions and Quizzes. I want each question and quiz has its own node id starting from one. Is there a module that can do this.?

Expected Result:

Question Table

Node Id,Question

1,Define Speed

2,Define Gravity

Quiz Table

Node Id,Quiz

1,Phy Quiz 1

2,Phy Quiz 2

答: You can't use Node Ids this way. Serial Field Module can help with this. Each content type will have its unique id starting form 1.</p>


问:
How to manage a button with disabled attribute using Python Selenium?
Having this button:

```<code><button id="btn-login-5" type="button" class="m-1 btn btn-warning" disabled="">Update</button>
</code>```

I want to remove the disable attribute in order to click the button.

This is the code i see everytime:

```<code>button = self.driver.find_element(
        By.XPATH, "/html/body/div/div/button")
self.driver.execute_script(
        'arguments[0].removeAttribute("disabled");', button)
</code>```

But I can't figure me out how that can work for anyone, I mean, if the element is disabled, selenium cannot run that very first line, is not able to asign the var "button" because he can't find that element.

Am I missing something? I am getting this error if a run that:

```<code>selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div/div/button"}
</code>```

Update

I just realized this is related to selenium grid, I tried to click the button in a lot of ways, and no one works, but if instead of using selenium grid I use a local webdriver all of them works! So I have no idea what to do now.

答:
All works fine, the problem is a different one, my code couldn't find the element because the element was not there, something very strange, I have a docker with the page server and if I open the page I can see the button but the selenium grid webdriver doesn't load the button at all, I don't know why, maybe that button depends of some server wich is not accesible from the webdriver.

I'll ask the page developer for this, but the code was good :)

I lost a full day of work for nothing :)

Body:
Having this button:

<button id="btn-login-5" type="button" class="m-1 btn btn-warning" disabled="">Update</button>

I want to remove the disable attribute in order to click the button.

This is the code i see everytime:

button = self.driver.find_element(
        By.XPATH, "/html/body/div/div/button")
self.driver.execute_script(
        'arguments[0].removeAttribute("disabled");', button)

But I can't figure me out how that can work for anyone, I mean, if the element is disabled, selenium cannot run that very first line, is not able to asign the var "button" because he can't find that element.

Am I missing something? I am getting this error if a run that:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div/div/button"}

Update

I just realized this is related to selenium grid, I tried to click the button in a lot of ways, and no one works, but if instead of using selenium grid I use a local webdriver all of them works! So I have no idea what to do now.


问:
React Router v6 - how to handle nested routes but with only current page showing instead of previous pages
I am trying to understand how to handle nested routes but with different pages using react-router v6.

For instance, say the "/" path returns a list of companies. ":companyId" takes you to the company page and ":/productId" takes you to the product of that company.

What I would like to know is how to only show the content page for that product instead of showing the list of products and the list of companies too.

I think this should be nested as I need the underlying params of both company id and product id to know where I am. How do I properly use Outlet in this case?

Companies has a list of companies. Company has a list of products.

My routes currently:

```<code>const routes = [
  {
    path: "/",
    element: <Companies />,
    children: [
      {
        path: ":companyId",
        element: <Company />,
        children: [{ path: ":productId", element: <Product /> }],
      },
    ],
  },
]
</code>```

```<code>const routes = [
  {
    path: "/",
    children: [
      {
        index: true,
        element: <Companies />,
      },
      {
        path: ":companyId",
        children: [
          { index: true, element: <Company /> },
          { path: ":productId", element: <Product /> },
        ],
      },
    ],
  },
];
</code>```

答:
If I understand your question/issue correctly, it seems that Companies is rendered as a layout component, in other words, it is rendered along with the nested children routes, but you want one or the other.

If you want to render one or the other then move Companies down into a child route, specifically as an index route, so it is rendered when the path is exactly "/" but not when another nested route matches.

```<code>const routes = [
  {
    path: "/",
    children: [
      {
        index: true,
        element: <Companies />,
      },
      {
        path: ":companyId",
        element: <Company />,
        children: [
          {
            path: ":productId",
            element: <Product />
          }
        ],
      },
    ],
  },
]
</code>```

Body:
I am trying to understand how to handle nested routes but with different pages using react-router v6.

For instance, say the "/" path returns a list of companies. ":companyId" takes you to the company page and ":/productId" takes you to the product of that company.

What I would like to know is how to only show the content page for that product instead of showing the list of products and the list of companies too.

I think this should be nested as I need the underlying params of both company id and product id to know where I am. How do I properly use Outlet in this case?

Companies has a list of companies. Company has a list of products.

My routes currently:

const routes = [
  {
    path: "/",
    element: <Companies />,
    children: [
      {
        path: ":companyId",
        element: <Company />,
        children: [{ path: ":productId", element: <Product /> }],
      },
    ],
  },
]

const routes = [
  {
    path: "/",
    children: [
      {
        index: true,
        element: <Companies />,
      },
      {
        path: ":companyId",
        children: [
          { index: true, element: <Company /> },
          { path: ":productId", element: <Product /> },
        ],
      },
    ],
  },
];

Body:
If I understand your question/issue correctly, it seems that Companies is rendered as a layout component, in other words, it is rendered along with the nested children routes, but you want one or the other.

If you want to render one or the other then move Companies down into a child route, specifically as an index route, so it is rendered when the path is exactly "/" but not when another nested route matches.

const routes = [
  {
    path: "/",
    children: [
      {
        index: true,
        element: <Companies />,
      },
      {
        path: ":companyId",
        element: <Company />,
        children: [
          {
            path: ":productId",
            element: <Product />
          }
        ],
      },
    ],
  },
]


问:
Generate random integer rounded to nearest whole number
I am wondering how to generate a random integer that gets rounded to nearest whole number,
e.g. random number: 436, == 440, or 521, == 520. basically just rounding the random number to the nearest whole number. (JavaScript)</p>
```<code>Math.floor(Math.random() * max) + min; //gets random number
//then I want to round the number here, maybe even in the same line as where the number is
//being generated.
</code>```

答:
I think this should do the job:</p>
```<code>result = Math.round((Math.floor(Math.random() * max) + min) / 10) * 10;
</code>```

Body:
I am wondering how to generate a random integer that gets rounded to nearest whole number,
e.g. random number: 436, == 440, or 521, == 520. basically just rounding the random number to the nearest whole number. (JavaScript)

Math.floor(Math.random() * max) + min; //gets random number
//then I want to round the number here, maybe even in the same line as where the number is
//being generated.

Body:
I think this should do the job:

result = Math.round((Math.floor(Math.random() * max) + min) / 10) * 10;


问:
Create Postgres Policy for Row Level Security on foreign key attribute
I'm trying to create a Policy on Postgres to enable Row Level Security but I'm having a bit of trouble. Many examples I've found have a direct FK on the table, but I'm trying to do it on an attribute on the foreign table.

The context here is that I'm trying to have users only be able to see other users from the same organization. The user is set on a configuration parameter organization.current_tenant, which takes on the value of the Organization.key

Setup:

```<code>CREATE TABLE organization (id serial primary key, name text, key text);
CREATE TABLE myuser (id serial primary key, name text, user_organization_id integer);

INSERT INTO organization (name, key) values ('org1', 'org1-key');
INSERT INTO organization (name, key) values ('org2', 'org2-key');

INSERT INTO myuser (name, user_organization_id) values ('org1_agent1', 1);
INSERT INTO myuser (name, user_organization_id) values ('org2_agent1', 2);
INSERT INTO myuser (name, user_organization_id) values ('org2_agent2', 2);

ALTER TABLE myuser ENABLE ROW LEVEL SECURITY;
ALTER TABLE myuser FORCE ROW LEVEL SECURITY;
</code>```

When using a direct FK, organization_id:

```<code>CREATE POLICY access_tenant_data ON myuser
USING (user_organization_id::TEXT = current_setting('organization.current_tenant'));
</code>```

This works since user_organization_id is the foreign key available on the user table.

However, what I want to use is instead something like user.organization.key.

```<code>CREATE POLICY access_tenant_data ON myuser
USING (
    key IN (
        SELECT key FROM
        myuser U INNER JOIN organization O
        ON U.organization_id = O.id
    )::TEXT = current_setting('organization.current_tenant')
);
</code>```

But this obviously doesn't work. I'm not sure how to proceed from here.

Testing it out:

```<code>SET organization.current_tenant = "org1-key";
SELECT * from myuser;

</code>```

答:
You need to define a function that returns BOOLEAN.
Within the function you will determine logic and return TRUE or FALSE.
The vital piece is that : USING clause of a policy expects a BOOLEAN value and we can dictate the behavior of the policy (allow/disallow) based on what gets returned by the function - True or False.

Here is the sample FUNCTION to be used in the policy:

```<code>create function KeyExist(organization_id int, env_current_tenant text)  returns boolean
language plpgsql
as
$$
declare
    flag boolean;
    keyValue text;
begin
select key into keyValue from organization where id=organization_id;
if not found then
    flag := false;
else
    if keyValue = env_current_tenant then
        flag := true;
    else
        flag := false;
    end if;
end if;
return flag;
end; $$;

</code>```

Policy:

```<code>CREATE POLICY access_tenant_data ON myuser for select
USING (KeyExist(user_organization_id,current_setting('organization.current_tenant')));

</code>```

Demonstration:

```<code>postgres=# create function KeyExist(organization_id int, env_current_tenant text)  returns boolean
postgres-# language plpgsql
postgres-# as
postgres-# $$
postgres$# declare
postgres$# flag boolean;
postgres$# keyValue text;
postgres$# begin
postgres$# select key into keyValue from organization where id=organization_id;
postgres$# if not found then
postgres$# flag := false;
postgres$# else
postgres$# if keyValue = env_current_tenant then
postgres$#
postgres$# flag := true;
postgres$# else
postgres$#
postgres$# flag := false;
postgres$# end if;
postgres$# end if;
postgres$# return flag;
postgres$# end; $$;
CREATE FUNCTION

postgres=# CREATE POLICY access_tenant_data ON myuser for select
postgres-# USING (KeyExist(user_organization_id,current_setting('organization.current_tenant')));
CREATE POLICY
</code>```

Verification:

```<code>postgres=> SET organization.current_tenant = "org1-key";
SET
postgres=> select * from myuser;
 id |    name     | user_organization_id
----+-------------+----------------------
  1 | org1_agent1 |                    1
(1 row)

postgres=> SET organization.current_tenant = 'org2-key';
SET
postgres=> select * from myuser;
 id |    name     | user_organization_id
----+-------------+----------------------
  2 | org2_agent1 |                    2
  3 | org2_agent2 |                    2
(2 rows)

</code>```

Tables:

```<code>postgres=# \d myuser
                                   Table "public.myuser"
        Column        |  Type   | Collation | Nullable |              Default
----------------------+---------+-----------+----------+------------------------------------
 id                   | integer |           | not null | nextval('myuser_id_seq'::regclass)
 name                 | text    |           |          |
 user_organization_id | integer |           |          |
Indexes:
    "myuser_pkey" PRIMARY KEY, btree (id)
Policies (forced row security enabled):
    POLICY "access_tenant_data" FOR SELECT
      USING (keyexist(user_organization_id, current_setting('organization.current_tenant'::text)))

postgres=# select * from myuser;
 id |    name     | user_organization_id
----+-------------+----------------------
  1 | org1_agent1 |                    1
  2 | org2_agent1 |                    2
  3 | org2_agent2 |                    2
(3 rows)

postgres=# select * from organization;
 id | name |   key
----+------+----------
  1 | org1 | org1-key
  2 | org2 | org2-key
(2 rows)
</code>```

Body:
I'm trying to create a Policy on Postgres to enable Row Level Security but I'm having a bit of trouble. Many examples I've found have a direct FK on the table, but I'm trying to do it on an attribute on the foreign table.

The context here is that I'm trying to have users only be able to see other users from the same organization. The user is set on a configuration parameter organization.current_tenant, which takes on the value of the Organization.key

Setup:

CREATE TABLE organization (id serial primary key, name text, key text);
CREATE TABLE myuser (id serial primary key, name text, user_organization_id integer);

INSERT INTO organization (name, key) values ('org1', 'org1-key');
INSERT INTO organization (name, key) values ('org2', 'org2-key');

INSERT INTO myuser (name, user_organization_id) values ('org1_agent1', 1);
INSERT INTO myuser (name, user_organization_id) values ('org2_agent1', 2);
INSERT INTO myuser (name, user_organization_id) values ('org2_agent2', 2);

ALTER TABLE myuser ENABLE ROW LEVEL SECURITY;
ALTER TABLE myuser FORCE ROW LEVEL SECURITY;

When using a direct FK, organization_id:

CREATE POLICY access_tenant_data ON myuser
USING (user_organization_id::TEXT = current_setting('organization.current_tenant'));

This works since user_organization_id is the foreign key available on the user table.

However, what I want to use is instead something like user.organization.key.

CREATE POLICY access_tenant_data ON myuser
USING (
    key IN (
        SELECT key FROM
        myuser U INNER JOIN organization O
        ON U.organization_id = O.id
    )::TEXT = current_setting('organization.current_tenant')
);

But this obviously doesn't work. I'm not sure how to proceed from here.

Testing it out:

SET organization.current_tenant = "org1-key";
SELECT * from myuser;

Body:
You need to define a function that returns BOOLEAN.
Within the function you will determine logic and return TRUE or FALSE.
The vital piece is that : USING clause of a policy expects a BOOLEAN value and we can dictate the behavior of the policy (allow/disallow) based on what gets returned by the function - True or False.

Here is the sample FUNCTION to be used in the policy:

create function KeyExist(organization_id int, env_current_tenant text)  returns boolean
language plpgsql
as
$$
declare
    flag boolean;
    keyValue text;
begin
select key into keyValue from organization where id=organization_id;
if not found then
    flag := false;
else
    if keyValue = env_current_tenant then
        flag := true;
    else
        flag := false;
    end if;
end if;
return flag;
end; $$;

Policy:

CREATE POLICY access_tenant_data ON myuser for select
USING (KeyExist(user_organization_id,current_setting('organization.current_tenant')));

Demonstration:

postgres=# create function KeyExist(organization_id int, env_current_tenant text)  returns boolean
postgres-# language plpgsql
postgres-# as
postgres-# $$
postgres$# declare
postgres$# flag boolean;
postgres$# keyValue text;
postgres$# begin
postgres$# select key into keyValue from organization where id=organization_id;
postgres$# if not found then
postgres$# flag := false;
postgres$# else
postgres$# if keyValue = env_current_tenant then
postgres$#
postgres$# flag := true;
postgres$# else
postgres$#
postgres$# flag := false;
postgres$# end if;
postgres$# end if;
postgres$# return flag;
postgres$# end; $$;
CREATE FUNCTION

postgres=# CREATE POLICY access_tenant_data ON myuser for select
postgres-# USING (KeyExist(user_organization_id,current_setting('organization.current_tenant')));
CREATE POLICY

Verification:

postgres=> SET organization.current_tenant = "org1-key";
SET
postgres=> select * from myuser;
 id |    name     | user_organization_id
----+-------------+----------------------
  1 | org1_agent1 |                    1
(1 row)

postgres=> SET organization.current_tenant = 'org2-key';
SET
postgres=> select * from myuser;
 id |    name     | user_organization_id
----+-------------+----------------------
  2 | org2_agent1 |                    2
  3 | org2_agent2 |                    2
(2 rows)

Tables:

postgres=# \d myuser
                                   Table "public.myuser"
        Column        |  Type   | Collation | Nullable |              Default
----------------------+---------+-----------+----------+------------------------------------
 id                   | integer |           | not null | nextval('myuser_id_seq'::regclass)
 name                 | text    |           |          |
 user_organization_id | integer |           |          |
Indexes:
    "myuser_pkey" PRIMARY KEY, btree (id)
Policies (forced row security enabled):
    POLICY "access_tenant_data" FOR SELECT
      USING (keyexist(user_organization_id, current_setting('organization.current_tenant'::text)))

postgres=# select * from myuser;
 id |    name     | user_organization_id
----+-------------+----------------------
  1 | org1_agent1 |                    1
  2 | org2_agent1 |                    2
  3 | org2_agent2 |                    2
(3 rows)

postgres=# select * from organization;
 id | name |   key
----+------+----------
  1 | org1 | org1-key
  2 | org2 | org2-key
(2 rows)


问:
How do I create a column with the time in the previous column + a certain amount of time, only if that time has been entered?
I want to create a spreadsheet where I enter the time on a row and the next column over gives me the time plus 5 minutes. But I don't want it for every row, I only want it if there is some time entered.

This is what I've come up with:

```<code>=IF(ISBLANK(B2), "", B2+TIME(0, 5, 0)) //for one cell
=ARRAYFORMULA(IF(ISBLANK(B2:B), "", B2:B+TIME(0, 5, 0))) //attempt at entire column
</code>```

And this only works somewhat. The first command works perfectly fine for one row, but if I enter it into the array formula, it returns a number between 0-1.

```<code>12:16:01 PM 0.5145949074
11:23:49 PM 0.9783448032
1:16:24 AM  0.05652777778
5:16:44 PM  0.7234259259
</code>```

How do I make it so that the formula works for the entire column, without having to manually do it?

答:
ISBLANK() formula returns false when it detects any content in a cell. Even if there is a formula that generates no output.

You can use:

```<code>=ARRAYFORMULA(IF(B2:B="", "", B2:B+TIME(0, 5, 0)))
</code>```

Body:
I want to create a spreadsheet where I enter the time on a row and the next column over gives me the time plus 5 minutes. But I don't want it for every row, I only want it if there is some time entered.

This is what I've come up with:

=IF(ISBLANK(B2), "", B2+TIME(0, 5, 0)) //for one cell
=ARRAYFORMULA(IF(ISBLANK(B2:B), "", B2:B+TIME(0, 5, 0))) //attempt at entire column

And this only works somewhat. The first command works perfectly fine for one row, but if I enter it into the array formula, it returns a number between 0-1.

12:16:01 PM 0.5145949074
11:23:49 PM 0.9783448032
1:16:24 AM  0.05652777778
5:16:44 PM  0.7234259259

How do I make it so that the formula works for the entire column, without having to manually do it?

Body:
ISBLANK() formula returns false when it detects any content in a cell. Even if there is a formula that generates no output.

You can use:

=ARRAYFORMULA(IF(B2:B="", "", B2:B+TIME(0, 5, 0)))


问:
R: Recode cells in matrix with no symmetric match
I have an adjacency matrix of 0s and 1s that indicate tie nominations. Some nominations are not reciprocated, so the matrix is asymmetrical.

I would like to recode the cell values from 1 to 0 if they do not have a symmetrical match.

Sample small matrix:

```<code>     [,1] [,2] [,3] [,4]
[1,]    0    1    0    1
[2,]    0    0    1    0
[3,]    0    0    0    1
[4,]    1    0    1    0
</code>```

Output desired:

```<code>     [,1] [,2] [,3] [,4]
[1,]    0    0    0    1
[2,]    0    0    0    0
[3,]    0    0    0    1
[4,]    1    0    1    0
</code>```

Body:
I have an adjacency matrix of 0s and 1s that indicate tie nominations. Some nominations are not reciprocated, so the matrix is asymmetrical.

I would like to recode the cell values from 1 to 0 if they do not have a symmetrical match.

Sample small matrix:

     [,1] [,2] [,3] [,4]
[1,]    0    1    0    1
[2,]    0    0    1    0
[3,]    0    0    0    1
[4,]    1    0    1    0

Output desired:

     [,1] [,2] [,3] [,4]
[1,]    0    0    0    1
[2,]    0    0    0    0
[3,]    0    0    0    1
[4,]    1    0    1    0

Body:
We can use pmin like below

> pmin(x,t(x))
     [,1] [,2] [,3] [,4]
[1,]    0    0    0    1
[2,]    0    0    0    0
[3,]    0    0    0    1
[4,]    1    0    1    0


问:
What parameter i have to assign inside my variable so i can start it from my Main?
im new to C# and Tia Openness and have an problem. I dont know what parameter goes inside my ImportSingleTextList();.Its an example from Siemens but there is never mentioned how to call it inisde the main. That is my code.</p>
```<code>private static void ImportSingleTextList(HmiTarget hmitarget)
        {
            TextListComposition textListsComposition = hmitarget.TextLists;
            IList<TextList> importedTextLists = textListsComposition.Import(new FileInfo(@"D:\SamplesImport\myTextList.xml"), ImportOptions.Override);
        }
</code>```

答:
Presumably you have a Project instance.  You have to drill down from Project->Device->DeviceItem(->DeviceItem) until you find a DeviceItem that can provide a SoftwareContainer service.  It may be that all such DeviceItems reside at the first level below Device; I haven't checked.  Anyway, here's a method I wrote that searches the first and second DeviceItem levels:

```<code>public static HmiTarget GetHmiTarget(Device hmiDevice)
    {
        //search first level of DeviceItems
        foreach (DeviceItem di in hmiDevice.DeviceItems)
        {
            SoftwareContainer container =
            di.GetService<SoftwareContainer>();
            if (container != null)
            {
                HmiTarget hmi = container.Software as HmiTarget;
                if (hmi != null)
                    return hmi;
            }

            //search second level of DeviceItems
            foreach (DeviceItem devItem in di.DeviceItems)
            {
                SoftwareContainer subContainer = devItem.GetService<SoftwareContainer>();
                if(subContainer != null)
                {
                    HmiTarget hmi = subContainer.Software as HmiTarget;
                    if (hmi != null)
                        return hmi;
                }
            }
        }
        return null; //nothing was found at the first or second levels

    }
</code>```

to get the Device, you can use PROJECT.Devices.Find(NAME) where PROJECT is your TIA portal project instance, and NAME is the string name of your HMI device.

Body:
im new to C# and Tia Openness and have an problem. I dont know what parameter goes inside my ImportSingleTextList();.Its an example from Siemens but there is never mentioned how to call it inisde the main. That is my code.

private static void ImportSingleTextList(HmiTarget hmitarget)
        {
            TextListComposition textListsComposition = hmitarget.TextLists;
            IList<TextList> importedTextLists = textListsComposition.Import(new FileInfo(@"D:\SamplesImport\myTextList.xml"), ImportOptions.Override);
        }

Body:
Presumably you have a Project instance.  You have to drill down from Project->Device->DeviceItem(->DeviceItem) until you find a DeviceItem that can provide a SoftwareContainer service.  It may be that all such DeviceItems reside at the first level below Device; I haven't checked.  Anyway, here's a method I wrote that searches the first and second DeviceItem levels:

public static HmiTarget GetHmiTarget(Device hmiDevice)
    {
        //search first level of DeviceItems
        foreach (DeviceItem di in hmiDevice.DeviceItems)
        {
            SoftwareContainer container =
            di.GetService<SoftwareContainer>();
            if (container != null)
            {
                HmiTarget hmi = container.Software as HmiTarget;
                if (hmi != null)
                    return hmi;
            }

            //search second level of DeviceItems
            foreach (DeviceItem devItem in di.DeviceItems)
            {
                SoftwareContainer subContainer = devItem.GetService<SoftwareContainer>();
                if(subContainer != null)
                {
                    HmiTarget hmi = subContainer.Software as HmiTarget;
                    if (hmi != null)
                        return hmi;
                }
            }
        }
        return null; //nothing was found at the first or second levels

    }

to get the Device, you can use PROJECT.Devices.Find(NAME) where PROJECT is your TIA portal project instance, and NAME is the string name of your HMI device.


问:
How to do the multiplication with array objects
How to do the multiplication with array objects and get the all 3 outputs

const size = [
  { hight: 20, width: 23, length: 54 },
  { hight: 40, width: 43, length: 44 },
  { hight: 20, width: 23, length: 54 },
];
const total = (size) => {
  const totalvalue = size.hight * size.width * size.length;
};
console.log(total)```

答:
You can make use of the reduce function

```<code>var sum = array.reduce(function(pv, cv) { return pv + cv; }, 0);
</code>```

Link to follow https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Body:
You can make use of the reduce function

var sum = array.reduce(function(pv, cv) { return pv + cv; }, 0);

Link to follow https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce


答:
To round a number, you can use Math.floor(n / 10) * 10. Example:

function randomRoundNumber(min, max) {
  return Math.round((Math.floor(Math.random() * (max - min)) + min) / 10) * 10;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="console.log(randomRoundNumber(parseInt(prompt('min?')),parseInt(prompt('max?'))))">Random number</button></code>```

Title: Generate random integer rounded to nearest whole number

Body:
To round a number, you can use Math.floor(n / 10) * 10. Example:

function randomRoundNumber(min, max) {
  return Math.round((Math.floor(Math.random() * (max - min)) + min) / 10) * 10;
}

<button onclick="console.log(randomRoundNumber(parseInt(prompt('min?')),parseInt(prompt('max?'))))">Random number</button>


问:
Sum of all equal entries in sqlite
Is it possible to take the sum of all values where another field is the same ?

I have a table which looks like this :

id
symbol
rate

0
USD
0.98

1
USD
1.93

2
EUR
2.08

3
EUR
0.42

4
USD
0.18

So when I like to only get the list of symbols I do this:

```<code>select DISTINCT symbol from myTable
</code>```

Which returns me

id

EUR

USD

What would I need to do to get a sum of all the rates ?

id
rates

EUR
2,5

USD
3,09

Thanks

答:
Use an aggregation query:

SELECT symbol, SUM(rate) AS rates
FROM myTable
GROUP BY symbol;
```

Title: Sum of all equal entries in sqlite

Body:
Is it possible to take the sum of all values where another field is the same ?

I have a table which looks like this :

id
symbol
rate

0
USD
0.98

1
USD
1.93

2
EUR
2.08

3
EUR
0.42

4
USD
0.18

So when I like to only get the list of symbols I do this:

select DISTINCT symbol from myTable

Which returns me

id

EUR

USD

What would I need to do to get a sum of all the rates ?

id
rates

EUR
2,5

USD
3,09

Thanks


问:
AttributeError: module 'mnist' has no attribute 'train_images'
I was reproducing the Video from freecodecamp.org YouTube - 2:50:00

The teacher is using colab.research. His Code is as follows:

```<code>!pip install pillow mnist numpy sklearn

from PIL import Image
import mnist
import numpy as np
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import confusion_matrix

# training variables
x_train = mnist.train_images()
y_train = mnist.train_labels()
</code>```

When He is doing that, there is no problem at all. But I get the following error message:

```<code>---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-22-b693104c2566> in <module>()
      1 # training variables
----> 2 x_train = mnist.train_images()

AttributeError: module 'mnist' has no attribute 'train_images'
</code>```

If I try the same thing on Pycharm, I dont have any issues with train_images() but a different one:

raise EOFError("Compressed file ended before the " EOFError:
Compressed file ended before the end-of-stream marker was reached

I tried to find a solution using google stackoverflow etc. No Success :(

Edit:

I checked the init.py inside of mnist and I can find the train_images() there:

```<code>def train_images():
    """Return train images from Yann LeCun MNIST database as a numpy array.
    Download the file, if not already found in the temporary directory of
    the system.

    Returns
    -------
    train_images : numpy.ndarray
        Numpy array with the images in the train MNIST database. The first
        dimension indexes each sample, while the other two index rows and
        columns of the image
    """
    return download_and_parse_mnist_file('train-images-idx3-ubyte.gz')

def test_images():
    """Return test images from Yann LeCun MNIST database as a numpy array.
    Download the file, if not already found in the temporary directory of
    the system.

    Returns
    -------
    test_images : numpy.ndarray
        Numpy array with the images in the train MNIST database. The first
        dimension indexes each sample, while the other two index rows and
        columns of the image
    """
    return download_and_parse_mnist_file('t10k-images-idx3-ubyte.gz'
</code>```

答:
For Google Colab

At the top write !pip install mnist.
 Use import mnist.

Then simply store the images and labels:

For Train data usage

```<code>train_images = mnist.train_images()
train_labels = mnist.train_labels()
</code>```

For Test data usage

```<code>test_images = mnist.test_images()
test_labels = mnist.test_labels()
</code>```

That's it!!!
After that you will be able to import and use mnist dataset

Body:
I was reproducing the Video from freecodecamp.org YouTube - 2:50:00

The teacher is using colab.research. His Code is as follows:

!pip install pillow mnist numpy sklearn

from PIL import Image
import mnist
import numpy as np
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import confusion_matrix

# training variables
x_train = mnist.train_images()
y_train = mnist.train_labels()

When He is doing that, there is no problem at all. But I get the following error message:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-22-b693104c2566> in <module>()
      1 # training variables
----> 2 x_train = mnist.train_images()

AttributeError: module 'mnist' has no attribute 'train_images'

If I try the same thing on Pycharm, I dont have any issues with train_images() but a different one:

raise EOFError("Compressed file ended before the " EOFError:
Compressed file ended before the end-of-stream marker was reached

I tried to find a solution using google stackoverflow etc. No Success :(

Edit:

I checked the init.py inside of mnist and I can find the train_images() there:

def train_images():
    """Return train images from Yann LeCun MNIST database as a numpy array.
    Download the file, if not already found in the temporary directory of
    the system.

    Returns
    -------
    train_images : numpy.ndarray
        Numpy array with the images in the train MNIST database. The first
        dimension indexes each sample, while the other two index rows and
        columns of the image
    """
    return download_and_parse_mnist_file('train-images-idx3-ubyte.gz')

def test_images():
    """Return test images from Yann LeCun MNIST database as a numpy array.
    Download the file, if not already found in the temporary directory of
    the system.

    Returns
    -------
    test_images : numpy.ndarray
        Numpy array with the images in the train MNIST database. The first
        dimension indexes each sample, while the other two index rows and
        columns of the image
    """
    return download_and_parse_mnist_file('t10k-images-idx3-ubyte.gz'

Body:
For Google Colab

At the top write !pip install mnist.
 Use import mnist.

Then simply store the images and labels:

For Train data usage

train_images = mnist.train_images()
train_labels = mnist.train_labels()

For Test data usage

test_images = mnist.test_images()
test_labels = mnist.test_labels()

That's it!!!
After that you will be able to import and use mnist dataset


问:
How to import a class object from a project that is in different folder in Python using ide pycharm?
my project directory looks like this

```<code>-- PycharmProjects   #foldrname
     - imp_func      #foldrname
            - funcs.py  #having a class name "specs"
     - project1      #foldrname
            - projct.py
</code>```

I want to import class "specs" which is in funcs.py into projct.py

Code tried:

```<code> from PycharmProjects.imp_func.funcs import specs   # UnResolved reference PycharmProjects
</code>```

答:
Oops... Python packages are indeed represented as subdirectories, but not all directories are packages! The from x import y only makes sense if x is a python module or a Python package and if it is accessible from the Python path.

Here the correct way would be to put the imp_func folder in the Python path, for example by putting it into the PYTHONPATH environment variable. Then you will be able to use:

```<code>from funcs import specs
</code>```

Body:
my project directory looks like this

-- PycharmProjects   #foldrname
     - imp_func      #foldrname
            - funcs.py  #having a class name "specs"
     - project1      #foldrname
            - projct.py

I want to import class "specs" which is in funcs.py into projct.py

Code tried:

 from PycharmProjects.imp_func.funcs import specs   # UnResolved reference PycharmProjects

Body:
Oops... Python packages are indeed represented as subdirectories, but not all directories are packages! The from x import y only makes sense if x is a python module or a Python package and if it is accessible from the Python path.

Here the correct way would be to put the imp_func folder in the Python path, for example by putting it into the PYTHONPATH environment variable. Then you will be able to use:

from funcs import specs


问:
Modify all values in a dictionary
Code goes below:

```<code>d = {'a':0, 'b':0, 'c':0, 'd':0}  #at the beginning, all the values are 0.
s = 'cbad'  #a string
indices = map(s.index, d.keys())  #get every key's index in s, i.e., a-2, b-1, c-0, d-3
#then set the values to keys' index
d = dict(zip(d.keys(), indices))  #this is how I do it, any better way?
print d  #{'a':2, 'c':0, 'b':1, 'd':3}
</code>```

Any other way to do that?

PS. the code above is just a simple one to demonstrate my question.

答:
Dict comprehension for python 2.7 and above</p>

```<code>{key : indice for key, indice in zip(d.keys(), map(s.index, d.keys()))}
</code>```

Title: Modify all values in a dictionary

Body:
Code goes below:

d = {'a':0, 'b':0, 'c':0, 'd':0}  #at the beginning, all the values are 0.
s = 'cbad'  #a string
indices = map(s.index, d.keys())  #get every key's index in s, i.e., a-2, b-1, c-0, d-3
#then set the values to keys' index
d = dict(zip(d.keys(), indices))  #this is how I do it, any better way?
print d  #{'a':2, 'c':0, 'b':1, 'd':3}

Any other way to do that?

PS. the code above is just a simple one to demonstrate my question.

Body:
Dict comprehension for python 2.7 and above

{key : indice for key, indice in zip(d.keys(), map(s.index, d.keys()))}

ContentLicense: CC BY-SA 3.0


答:
This sould get the job done</p>
```<code> Math.round((Math.floor(Math.random() * max) + min) / 10) * 10
</code>```

Body:
I am wondering how to generate a random integer that gets rounded to nearest whole number,
e.g. random number: 436, == 440, or 521, == 520. basically just rounding the random number to the nearest whole number. (JavaScript)

Math.floor(Math.random() * max) + min; //gets random number
//then I want to round the number here, maybe even in the same line as where the number is
//being generated.

Body:
This sould get the job done

 Math.round((Math.floor(Math.random() * max) + min) / 10) * 10


问:
how to rename apk output file with agp 7.0+?
Before agp 7.0, I can rename apk file name as this:

android.applicationVariants.all { variant ->

        def date = new Date().format("yyyyMMddHHmm")

        variant.outputs.all {
            outputFileName = "${variant.name}_${date}.apk"
        }
    }
```

After agp 7.0, outputs has no outputFileName field.So how to rename with apg 7.0?

Thanks.

答:
I have a slightly different configuration with my Android project, but it is still working with AGP 7.1.
Here is what I did, using the property archivesBaseName :

```<code>android {
compileSdkVersion 32
buildToolsVersion '32.0.0'
defaultConfig {
    applicationId "xxx.yyy"
    minSdkVersion 21
    targetSdkVersion 32
    versionCode 86
    versionName "1.12.0"
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    setProperty("archivesBaseName", "myapp-$versionName")
    vectorDrawables.useSupportLibrary = true
}
...
</code>```

It results in having two APK (variants) :

./app/build/outputs/apk/release/myapp-1.12.0-release.apk

./app/build/outputs/apk/debug/myapp-1.12.0-debug.apk

I hope it can be helpful.

Body:
Before agp 7.0, I can rename apk file name as this:

android.applicationVariants.all { variant ->

        def date = new Date().format("yyyyMMddHHmm")

        variant.outputs.all {
            outputFileName = "${variant.name}_${date}.apk"
        }
    }

After agp 7.0, outputs has no outputFileName field.So how to rename with apg 7.0?

Thanks.

Body:
I have a slightly different configuration with my Android project, but it is still working with AGP 7.1.
Here is what I did, using the property archivesBaseName :

android {
compileSdkVersion 32
buildToolsVersion '32.0.0'
defaultConfig {
    applicationId "xxx.yyy"
    minSdkVersion 21
    targetSdkVersion 32
    versionCode 86
    versionName "1.12.0"
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    setProperty("archivesBaseName", "myapp-$versionName")
    vectorDrawables.useSupportLibrary = true
}
...

It results in having two APK (variants) :

./app/build/outputs/apk/release/myapp-1.12.0-release.apk

./app/build/outputs/apk/debug/myapp-1.12.0-debug.apk

I hope it can be helpful.


问:
Time Series Prediction with statsmodels.tsa.arima.model import ARIMA
I am trying to make prediction on my ARIMA Model but I stucked in one point

```<code>from statsmodels.tsa.arima.model import ARIMA
train2 = trainData1["meantemp"][:1170]
test2 = trainData1["meantemp"][1170:]
# p,d,q ARIMA Model
model = ARIMA(train2, order=(1,1,50))
model_fit = model.fit()
print(model_fit.summary())
</code>```

Here , trainData1 has date as index (both train2 and test2 as you guess) and trained model with train2 data  , after that I tried to make prediction on test2 data as follows ;

```<code># make predictions
predictions = model_fit.predict(test2)
rmse = mean_squared_error(test2.values, predictions)
rmse
</code>```

But it gives me the following error ;

```<code>TypeError: Cannot convert input [date
2016-03-17    2.375000
2016-03-18   -0.125000
2016-03-19    0.598214
2016-03-20    0.347619
2016-03-21   -0.508333
                ...
2016-12-28    0.367391
2016-12-29   -1.979296
2016-12-30   -1.142857
2016-12-31    0.957393
2017-01-01   -5.052632
Name: meantemp, Length: 291, dtype: float64] of type <class 'pandas.core.series.Series'> to Timestamp
</code>```

What should be added to inside of predict function as data ?

train2 as follows ;

```<code>2013-01-02   -2.600000
2013-01-03   -0.233333
2013-01-04    1.500000
2013-01-05   -2.666667
2013-01-06    1.000000
                ...
2016-03-12   -0.504167
2016-03-13   -0.312500
2016-03-14   -1.875000
2016-03-15    1.691667
2016-03-16   -0.129167
Name: meantemp, Length: 1170, dtype: float64
</code>```

test2 as follows ;

```<code>date
2016-03-17    2.375000
2016-03-18   -0.125000
2016-03-19    0.598214
2016-03-20    0.347619
2016-03-21   -0.508333
                ...
2016-12-28    0.367391
2016-12-29   -1.979296
2016-12-30   -1.142857
2016-12-31    0.957393
2017-01-01   -5.052632
Name: meantemp, Length: 291, dtype: float64
</code>```

答:
I solved my own problem as follows ;

```<code># make predictions
predictions = model_fit.forecast(291)
print(f'ARIMA Model Test Data MSE: {np.mean((predictions.values - test2.values)**2):.3f}')
</code>```

with forecast function  , model predicted next 291 step which is day here as it is daily time-series and made evaluation with MSE metric using predictions and actual test values.

Body:
I am trying to make prediction on my ARIMA Model but I stucked in one point

from statsmodels.tsa.arima.model import ARIMA
train2 = trainData1["meantemp"][:1170]
test2 = trainData1["meantemp"][1170:]
# p,d,q ARIMA Model
model = ARIMA(train2, order=(1,1,50))
model_fit = model.fit()
print(model_fit.summary())

Here , trainData1 has date as index (both train2 and test2 as you guess) and trained model with train2 data  , after that I tried to make prediction on test2 data as follows ;

# make predictions
predictions = model_fit.predict(test2)
rmse = mean_squared_error(test2.values, predictions)
rmse

But it gives me the following error ;

TypeError: Cannot convert input [date
2016-03-17    2.375000
2016-03-18   -0.125000
2016-03-19    0.598214
2016-03-20    0.347619
2016-03-21   -0.508333
                ...
2016-12-28    0.367391
2016-12-29   -1.979296
2016-12-30   -1.142857
2016-12-31    0.957393
2017-01-01   -5.052632
Name: meantemp, Length: 291, dtype: float64] of type <class 'pandas.core.series.Series'> to Timestamp

What should be added to inside of predict function as data ?

train2 as follows ;

2013-01-02   -2.600000
2013-01-03   -0.233333
2013-01-04    1.500000
2013-01-05   -2.666667
2013-01-06    1.000000
                ...
2016-03-12   -0.504167
2016-03-13   -0.312500
2016-03-14   -1.875000
2016-03-15    1.691667
2016-03-16   -0.129167
Name: meantemp, Length: 1170, dtype: float64

test2 as follows ;

date
2016-03-17    2.375000
2016-03-18   -0.125000
2016-03-19    0.598214
2016-03-20    0.347619
2016-03-21   -0.508333
                ...
2016-12-28    0.367391
2016-12-29   -1.979296
2016-12-30   -1.142857
2016-12-31    0.957393
2017-01-01   -5.052632
Name: meantemp, Length: 291, dtype: float64

Body:
I solved my own problem as follows ;

# make predictions
predictions = model_fit.forecast(291)
print(f'ARIMA Model Test Data MSE: {np.mean((predictions.values - test2.values)**2):.3f}')

with forecast function  , model predicted next 291 step which is day here as it is daily time-series and made evaluation with MSE metric using predictions and actual test values.


问:
C# object sender - getting the Method from which it was called
I've got these Methods:

```<code>    private void button_Click(object sender, EventArgs e)
    {
          //Changes the Text in the RichBox, EXAMPLE:
          richtTextBox.Text = "Now Changed and calling Method richTextBox_TextChanged";
    }
</code>```

And,

```<code> private void richTextBox_TextChanged(object sender, EventArgs e)
 {
         //Wants something like that
         if(called from button_click)
         {
           //DO SOMETHING
         }
         else
         {
           //DO SOMETHING
         }
 }
</code>```

How can I handle this, to know if it was called from the Button_click?
Do I have to use the object sender to get informations? But how?

Hope u guys can help me

答:
Just use a flag:</p>

```<code>private bool _isInButtonClick;

private void button_Click(object sender, EventArgs e)
{
      try
      {
          _isInButtonClick = true;
          //Changes the Text in the RichBox, EXAMPLE:
          richtTextBox.Text = "Now Changed and calling Method richTextBox_TextChanged";
      }
      finally
      {
          _isInButtonClick = false;
      }
}

 private void richTextBox_TextChanged(object sender, EventArgs e)
 {
         if(_isInButtonClick)
         {
           //DO SOMETHING
         }
         else
         {
           //DO SOMETHING
         }
 }
</code>```

Body:
I've got these Methods:

    private void button_Click(object sender, EventArgs e)
    {
          //Changes the Text in the RichBox, EXAMPLE:
          richtTextBox.Text = "Now Changed and calling Method richTextBox_TextChanged";
    }

And,

 private void richTextBox_TextChanged(object sender, EventArgs e)
 {
         //Wants something like that
         if(called from button_click)
         {
           //DO SOMETHING
         }
         else
         {
           //DO SOMETHING
         }
 }

How can I handle this, to know if it was called from the Button_click?
Do I have to use the object sender to get informations? But how?

Hope u guys can help me

Body:
Just use a flag:

private bool _isInButtonClick;

private void button_Click(object sender, EventArgs e)
{
      try
      {
          _isInButtonClick = true;
          //Changes the Text in the RichBox, EXAMPLE:
          richtTextBox.Text = "Now Changed and calling Method richTextBox_TextChanged";
      }
      finally
      {
          _isInButtonClick = false;
      }
}

 private void richTextBox_TextChanged(object sender, EventArgs e)
 {
         if(_isInButtonClick)
         {
           //DO SOMETHING
         }
         else
         {
           //DO SOMETHING
         }
 }


问:
Power Query - Extract Text after some chactacters only
I want to get text after 5 first dashes only, but jus tried some ways still extract text after 6 dashes.

```<code>if Text.Contains([Column1],"-") and
       Text.StartsWith([Column1],"- - - - - ")
then Text.AfterDelimiter([Column1],"- - - - - ")
else null
</code>```

Input:

Raw column

----- Kitchen - IL

------ Self-serve

Output:

Raw column
Level 1
Level 2

----- Kitchen - IL
Kitchen - IL
null

------ Self-serve
null
Self-serve

答:
Little snippet:

```<code>    #"get Level 2" = Table.AddColumn(#"get Raw Column", "Level 2", each if Text.Contains([Raw column],"-") and
       Text.StartsWith([Raw column],"------") then Text.AfterDelimiter([Raw column],"------") else null),
    #"get Level 1" = Table.AddColumn(#"get Level 2", "Level 1", each if [Level 2] = null then if Text.Contains([Raw column],"-") and
       Text.StartsWith([Raw column],"-----") then Text.AfterDelimiter([Raw column],"-----") else null else null),
    #"Reorder Columns" = Table.ReorderColumns(#"get Level 1",{"Raw column", "Level 1", "Level 2"})
</code>```

Body:
I want to get text after 5 first dashes only, but jus tried some ways still extract text after 6 dashes.

if Text.Contains([Column1],"-") and
       Text.StartsWith([Column1],"- - - - - ")
then Text.AfterDelimiter([Column1],"- - - - - ")
else null

Input:

Raw column

----- Kitchen - IL

------ Self-serve

Output:

Raw column
Level 1
Level 2

----- Kitchen - IL
Kitchen - IL
null

------ Self-serve
null
Self-serve

Body:
Little snippet:

    #"get Level 2" = Table.AddColumn(#"get Raw Column", "Level 2", each if Text.Contains([Raw column],"-") and
       Text.StartsWith([Raw column],"------") then Text.AfterDelimiter([Raw column],"------") else null),
    #"get Level 1" = Table.AddColumn(#"get Level 2", "Level 1", each if [Level 2] = null then if Text.Contains([Raw column],"-") and
       Text.StartsWith([Raw column],"-----") then Text.AfterDelimiter([Raw column],"-----") else null else null),
    #"Reorder Columns" = Table.ReorderColumns(#"get Level 1",{"Raw column", "Level 1", "Level 2"})


问:
Why can't add free ClearDB MySQL to my app on heroku?
I got this error
Item could not be created:
Please verify your account to install this add-on plan (please enter a credit card) For more information, see https://devcenter.heroku.com/categories/billing Verify now at https://heroku.com/verify

Is there a solution to it?

答:
I have faced the same situation, but don't worry about it.
This verification step is just in order to make sure that you can afford to pay the expenses afterwards.

Even if you select a free plan, you still have to bind the credit card for it.


答:
You can use Array.prototype.map.

const size = [
  { hight: 20, width: 23, length: 54 },
  { hight: 40, width: 43, length: 44 },
  { hight: 20, width: 23, length: 54 },
];

 const total = (size) => {
  const totalvalue = size.hight * size.width * size.length;
  return totalvalue;
};

console.log(size.map(total))```

Body:
How to do the multiplication with array objects and get the all 3 outputs

const size = [
  { hight: 20, width: 23, length: 54 },
  { hight: 40, width: 43, length: 44 },
  { hight: 20, width: 23, length: 54 },
];
const total = (size) => {
  const totalvalue = size.hight * size.width * size.length;
};
console.log(total)


问:
indexPath is nil after didSelectRow in tableView
I want to pass the selected row to the next VC.
But it is always nil, no matter which row was clicked.
I'm happy for any hints.</p>
```<code> func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        self.performSegue(withIdentifier: "goToDetails", sender: self)

    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "goTo Details" {
            if let indexPath = collectionTableView.indexPathForSelectedRow{
            let destinationVC = segue.destination as! DetailsViewController
                destinationVC.IdentifierAlbum = dataArray[indexPath.row].album
                destinationVC.IdentifierArtist = dataArray[indexPath.row].artist
                destinationVC.IdentifierRow = indexPath.row
                print (indexPath.row)
            }

</code>```

答:
Use your IndexPath as your sender

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    self.performSegue(withIdentifier: "goTo Details", sender: indexPath)

}
</code>```

then on your prepare(for segue:) get the index path as follows

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "goTo Details",
       let destinationVC = segue.destination as? DetailsViewController,
       let indexPath = sender as? IndexPath {

        //Whatever you do with indexPath

    }
}
</code>```

Body:
I want to pass the selected row to the next VC.
But it is always nil, no matter which row was clicked.
I'm happy for any hints.

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        self.performSegue(withIdentifier: "goToDetails", sender: self)

    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "goTo Details" {
            if let indexPath = collectionTableView.indexPathForSelectedRow{
            let destinationVC = segue.destination as! DetailsViewController
                destinationVC.IdentifierAlbum = dataArray[indexPath.row].album
                destinationVC.IdentifierArtist = dataArray[indexPath.row].artist
                destinationVC.IdentifierRow = indexPath.row
                print (indexPath.row)
            }

Body:
Use your IndexPath as your sender

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    self.performSegue(withIdentifier: "goTo Details", sender: indexPath)

}

then on your prepare(for segue:) get the index path as follows

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "goTo Details",
       let destinationVC = segue.destination as? DetailsViewController,
       let indexPath = sender as? IndexPath {

        //Whatever you do with indexPath

    }
}


问:
Spring WebClient set Bearer auth token in header
Following scenario:

I have two Microservices A and B. Service A is a Bearer client that has an open api and receives requests from clients that have to be authorized by keycloak. Now I want to send an authorized Request from Service A to Service B, which is also a bearer client.

I thought about adding the functionality as a filter function during the webclient builder process like

@Bean
WebClient webClient() {
    return WebClient.builder()
            .filter(authHeader())
            .build();
}

private ExchangeFilterFunction authHeader(String token) {
    return (request, next) -> next.exchange(ClientRequest.from(request).headers((headers) -> {
        headers.setBearerAuth(token);
    }).build());
}
```
<p>This is an example I found in another question. It seems to to be the right way to me but can I provide the "String token" parameter at that stage of configuration?</p>
<p>I'm just switching from <code>RestTemplate</code> to <code>WebClient</code>, so sorry I this is a dump question.</p>
<p>EDIT:
I am able to set the header manually while building a new <code>WebClient</code>.</p>
<pre class="lang-java prettyprint-override"><code>return WebClient.builder()
        .defaultHeader("Authorization", "Bearer "+ context.getTokenString())
        .build();
</code>```

As I know from the RestTemplate, it can be used as a Singleton. There also exists a KeyCloakRestTemplate which injects the header automatically.

WebClient is immutable, so when I inject it, I can't just use it and add the header afterwards.
In addition, I can't set this header on startup as I have to wait for a request to take the bearer header and pass it in. So I guess there is not other way than doing it this way?

答:
Or simply set it during the process of sending:</p>
```<code>webClient.get()
    .uri(url)
    .headers(h -> h.setBearerAuth(token))
    .retrieve();
</code>```

Body:
Following scenario:

I have two Microservices A and B. Service A is a Bearer client that has an open api and receives requests from clients that have to be authorized by keycloak. Now I want to send an authorized Request from Service A to Service B, which is also a bearer client.

I thought about adding the functionality as a filter function during the webclient builder process like

@Bean
WebClient webClient() {
    return WebClient.builder()
            .filter(authHeader())
            .build();
}

private ExchangeFilterFunction authHeader(String token) {
    return (request, next) -> next.exchange(ClientRequest.from(request).headers((headers) -> {
        headers.setBearerAuth(token);
    }).build());
}

This is an example I found in another question. It seems to to be the right way to me but can I provide the "String token" parameter at that stage of configuration?

I'm just switching from RestTemplate to WebClient, so sorry I this is a dump question.

EDIT:
I am able to set the header manually while building a new WebClient.

return WebClient.builder()
        .defaultHeader("Authorization", "Bearer "+ context.getTokenString())
        .build();

As I know from the RestTemplate, it can be used as a Singleton. There also exists a KeyCloakRestTemplate which injects the header automatically.

WebClient is immutable, so when I inject it, I can't just use it and add the header afterwards.
In addition, I can't set this header on startup as I have to wait for a request to take the bearer header and pass it in. So I guess there is not other way than doing it this way?

Body:
Or simply set it during the process of sending:

webClient.get()
    .uri(url)
    .headers(h -> h.setBearerAuth(token))
    .retrieve();


问:
How does Asynchronous Javascript Execution happen? and when not to use return statement?
```<code>// synchronous Javascript
var result = db.get('select * from table1');
console.log('I am syncronous');

// asynchronous Javascript
db.get('select * from table1', function(result){
    // do something with the result
});
console.log('I am asynchronous')
</code>```

I know in synchronous code, console.log() executes after result is fetched from db, whereas in asynchronous code console.log() executes before the db.get() fetches the result.

Now my question is, how does the execution happen behind the scenes for asynchronous code and why is it non-blocking?

I have searched the Ecmascript 5 standard to understand how asynchronous code works but could not find the word asynchronous in the entire standard.

And from nodebeginner.org I also found out that we should not use a return statement as it blocks the event loop. But nodejs api and third party modules contain return statements everywhere. So when should a return statement be used and when shouldn't it?

Can somebody throw some light on this?

答:
First of all, passing a function as a parameter is telling the function that you're calling that you would like it to call this function some time in the future.  When exactly in the future it will get called depends upon the nature of what the function is doing.

If the function is doing some networking and the function is configured to be non-blocking or asychronous, then the function will execute, the networking operation will be started and the function you called will return right away and the rest of your inline javascript code after that function will execute.  If you return a value from that function, it will return right away, long before the function you passed as a parameter has been called (the networking operation has not yet completed).

Meanwhile, the networking operation is going in the background.  It's sending the request, listening for the response, then gathering the response.  When the networking request has completed and the response has been collected, THEN and only then does the original function you called call the function you passed as a parameter.  This may be only a few milliseconds later or it may be as long as minutes later - depending upon how long the networking operation took to complete.

What's important to understand is that in your example, the db.get() function call has long since completed and the code sequentially after it has also executed.  What has not completed is the internal anonymous function that you passed as a parameter to that function.  That's being held in a javascript function closure until later when the networking function finishes.

It's my opinion that one thing that confuses a lot of people is that the anonymous function is declared inside of your call to db.get and appears to be part of that and appears that when db.get() is done, this would be done too, but that is not the case.  Perhaps that would look less like that if it was represented this way:

```<code>function getCompletionfunction(result) {
    // do something with the result of db.get
}

// asynchronous Javascript
db.get('select * from table1', getCompletionFunction);
</code>```

Then, maybe it would be more obvious that the db.get will return immediately and the getCompletionFunction will get called some time in the future.  I'm not suggesting you write it this way, but just showing this form as a means of illustrating what is really happening.

Here's a sequence worth understanding:

```<code>console.log("a");
db.get('select * from table1', function(result){
    console.log("b");
});
console.log("c");
</code>```

What you would see in the debugger console is this:

```<code>a
c
b
</code>```

"a" happens first.  Then, db.get() starts its operation and then immediately returns.  Thus, "c" happens next.  Then, when the db.get() operation actually completes some time in the future, "b" happens.

For some reading on how async handling works in a browser, see How does JavaScript handle AJAX responses in the background?

Body:
// synchronous Javascript
var result = db.get('select * from table1');
console.log('I am syncronous');

// asynchronous Javascript
db.get('select * from table1', function(result){
    // do something with the result
});
console.log('I am asynchronous')

I know in synchronous code, console.log() executes after result is fetched from db, whereas in asynchronous code console.log() executes before the db.get() fetches the result.

Now my question is, how does the execution happen behind the scenes for asynchronous code and why is it non-blocking?

I have searched the Ecmascript 5 standard to understand how asynchronous code works but could not find the word asynchronous in the entire standard.

And from nodebeginner.org I also found out that we should not use a return statement as it blocks the event loop. But nodejs api and third party modules contain return statements everywhere. So when should a return statement be used and when shouldn't it?

Can somebody throw some light on this?

Body:
First of all, passing a function as a parameter is telling the function that you're calling that you would like it to call this function some time in the future.  When exactly in the future it will get called depends upon the nature of what the function is doing.

If the function is doing some networking and the function is configured to be non-blocking or asychronous, then the function will execute, the networking operation will be started and the function you called will return right away and the rest of your inline javascript code after that function will execute.  If you return a value from that function, it will return right away, long before the function you passed as a parameter has been called (the networking operation has not yet completed).

Meanwhile, the networking operation is going in the background.  It's sending the request, listening for the response, then gathering the response.  When the networking request has completed and the response has been collected, THEN and only then does the original function you called call the function you passed as a parameter.  This may be only a few milliseconds later or it may be as long as minutes later - depending upon how long the networking operation took to complete.

What's important to understand is that in your example, the db.get() function call has long since completed and the code sequentially after it has also executed.  What has not completed is the internal anonymous function that you passed as a parameter to that function.  That's being held in a javascript function closure until later when the networking function finishes.

It's my opinion that one thing that confuses a lot of people is that the anonymous function is declared inside of your call to db.get and appears to be part of that and appears that when db.get() is done, this would be done too, but that is not the case.  Perhaps that would look less like that if it was represented this way:

function getCompletionfunction(result) {
    // do something with the result of db.get
}

// asynchronous Javascript
db.get('select * from table1', getCompletionFunction);

Then, maybe it would be more obvious that the db.get will return immediately and the getCompletionFunction will get called some time in the future.  I'm not suggesting you write it this way, but just showing this form as a means of illustrating what is really happening.

Here's a sequence worth understanding:

console.log("a");
db.get('select * from table1', function(result){
    console.log("b");
});
console.log("c");

What you would see in the debugger console is this:

a
c
b

"a" happens first.  Then, db.get() starts its operation and then immediately returns.  Thus, "c" happens next.  Then, when the db.get() operation actually completes some time in the future, "b" happens.

For some reading on how async handling works in a browser, see How does JavaScript handle AJAX responses in the background?


问:
Cannot convert input [00:00:00.020000] of type <class 'datetime.time'> to Timestamp
My input data has a high resolution of datetime with seconds in fraction. For example, it should be
1900-01-01 17:40:14.410000 instead of 1900-01-01 17:40:14.

Apparently this format has not been recognized by the pandas or python. How should I successfully convert this to pandas recognized time stamp style.

答:
I'm not sure if I understand it correctly but pandas do have the style in the Timestamp class,
myTime = pandas.Timestamp("1900-01-01 17:40:14.410000") which you can access the attributes and methods of.

myTime.year should output >>> 1900
myTime.time() should output >>> 17:40:14.410000 so on and so forth.


问:
visual basic error BC30456 'Form1' is not a member of 'WindowsApplication1'
Hello I am trying to do an exercise and keep getting this error when compiling.

Visual Basic error BC30456 'Form1' is not a member of 'WindowsApplication1'

I'm not sure how to fix it.

Below is my code:

Public Class frmCentsConverter
    Private Sub txtAmount_TextChanged(sender As Object, e As EventArgs) Handles txtAmount.TextChanged
        If IsNumeric(txtAmount.Text) Then
            Dim NumberofCents As Integer

            NumberofCents = CInt(txtAmount.Text)
            lblDollars.Text = CStr(NumberofCents \ 100)
            lblCents.Text = CStr(NumberofCents Mod 100)
        End If
    End Sub

    Private Sub lblTitle_Click(sender As Object, e As EventArgs) Handles lblTitle.Click

    End Sub
End Class
```

答:
This is how I fixed it.

Right click on the Name of your project and then click properties.

Locate the Target framework under the Applications tab.

Change it to ".NET Framework 4.5" (mine was on 4.5.2).

Click/accept/whatever it is to confirm your selection from the popup box.

Build/Rebuild solution.
This worked for me in VB.net 2015.
Good Luck!


问:
Vue.js <keep-alive> in template for slot not working
I'm working with a component that was built out called 'Stepper' it's a basic component that has the steps at the top to guide the user through a process. In this stepper we have a dynamic number of slots that are produced and we pass a component in to fill that slot.

Stepper.vue

...

    <slot :name="`${step.name}`" />

...
```
<p>Parent.vue</p>
<pre class="lang-html prettyprint-override"><code>...
<Stepper :items="steps"
  <template v-for="step in steps" v-slot:[step.name] :key="step.name">
    <keep-alive>
      <component :is="step.component" />
    </keep-alive>
  </template>
</Stepper>
...

<script lang="ts">
...
import Stepper from "@/components/Stepper.vue";
import Component1 from "@/components/Component1.vue";
import Component2 from "@/components/Component2.vue";

export default defineComponent({
  name: "ParentComponent",
  components: {
    Stepper,
    Component1,
    Component2,
  },
  setup() {
    const steps = ref([
      {
        name: "step1",
        label: "Step 1",
        component: "Component1",
      },
      {
        name: "step2",
        label: "Step 2",
        component: "Component2",
      },
    ]);

    return {
      steps,
    }
  }
</script>
</code>```

All in all everything is working. The component for each step displays, the steps increment so on and so forth. The issue we're having is that the <keep-alive> is not working. Every time you go back or forth in the steps the component re-renders and we're seeing the onMounted hook called. Granted we can pre-populate the form with some 'saved' data if needed but would be nice if we could get the <keep-alive> to work. We've also tried adding the :include="[COMPONENT_NAMES]" to the <keep-alive> as well, to no avail.

Edit: Updated code snippet with more details.

答:
The <keep-alive> is caching the dynamic component, but the v-if directive inside Stepper.vue removes the div.stepper-pane and its <slot> (thus destroying the current component before mounting the new one) based on currentItem.name, which leads to the behavior you're seeing.

One way to fix this is to refactor Stepper.vue, moving the list rendering into the default slot. To me, this makes sense because Stepper.vue only ever renders one step/slot at a time.

<Stepper :currentItem="currentItem">
  <keep-alive>
    <component :is="currentItem.component" />
  </keep-alive>
</Stepper>
```
<pre class="lang-html prettyprint-override"><code><!-- Stepper.vue -->
<div class="stepper-pane">
  <slot />
</div>
</code>```

demo

Body:
I'm working with a component that was built out called 'Stepper' it's a basic component that has the steps at the top to guide the user through a process. In this stepper we have a dynamic number of slots that are produced and we pass a component in to fill that slot.

Stepper.vue

...

    <slot :name="`${step.name}`" />

...

Parent.vue

...
<Stepper :items="steps"
  <template v-for="step in steps" v-slot:[step.name] :key="step.name">
    <keep-alive>
      <component :is="step.component" />
    </keep-alive>
  </template>
</Stepper>
...

All in all everything is working. The component for each step displays, the steps increment so on and so forth. The issue we're having is that the <keep-alive> is not working. Every time you go back or forth in the steps the component re-renders and we're seeing the onMounted hook called. Granted we can pre-populate the form with some 'saved' data if needed but would be nice if we could get the <keep-alive> to work. We've also tried adding the :include="[COMPONENT_NAMES]" to the <keep-alive> as well, to no avail.

Edit: Updated code snippet with more details.

Body:
The <keep-alive> is caching the dynamic component, but the v-if directive inside Stepper.vue removes the div.stepper-pane and its <slot> (thus destroying the current component before mounting the new one) based on currentItem.name, which leads to the behavior you're seeing.

One way to fix this is to refactor Stepper.vue, moving the list rendering into the default slot. To me, this makes sense because Stepper.vue only ever renders one step/slot at a time.

<!-- ParentComponent.vue -->
<Stepper :currentItem="currentItem">
  <keep-alive>
    <component :is="currentItem.component" />
  </keep-alive>
</Stepper>

<!-- Stepper.vue -->
<div class="stepper-pane">
  <slot />
</div>

demo


问:
What is the meaning of this makefile syntax %IDLINC%
I am trying to build a library for IDL however I am running into a lot of troubles. I believe understanding this line of syntax could help lead me to solve my bigger problems.

From what I know. The source code is written in fortran (I think?). There is the where the syntax first appears:

```<code>FOPTIONS_SHARED_win64_mingw=-I%IDLINC% -fno-second-underscore -static
</code>```

I believe this FOPTIONS variable plays in a role in the building of a shared library file (.dll). What does this line mean? In particular, what exactly is %IDLINC% ?(double percent signs) I see it appear quite a bit in the warning messages.

And here is a little snippet of the compile/link code from the makefile which uses the FOPTIONS variable:

```<code>all.help:
@more $(HELPDIR)/Help.all

all: all.$(OS).$(ENV)

all..:
echo "Missing OS and ENV variables"

all.linux32.intel32: all.build
all.linux32.gnu32: all.build
all.linux32.pgi32: all.build
all.linux64.intel32: all.build
all.linux64.intel64: all.build
all.linux64.gnu32: all.build
all.linux64.gnu64: all.build
all.linux64.pgi64: all.build
all.linux64.gfortran64: all.build
all.win32.cygwin32: all.build
all.win64.cygwin64: all.build
all.win32.mingw: all.build
all.win64.mingw: all.build
all.mach.gnu32: all.build
all.sunos.sparc32: all.build
all.sunos.sparc64: all.build
all.sunos.gnu32: all.build
all.sunos.gnu64: all.build

all.build: version.fortran ntime_max
    @cd $(SOURCEDIR); \
cp wrappers_$(WRAPPER_$(OS)_$(ENV)).inc wrappers.inc;\
echo "Building non-sharable object \
onera_desp_lib_$(LIBNAME_$(OS)_$(ENV)).$(NONSHAREDEXT_$(OS))"; \
$(FC_$(OS)_$(ENV)) $(FOPTIONS_NONSHARED_$(OS)_$(ENV)) *.f;\
$(AR) $(AROPTIONS_$(OS)) liboneradesp_$(LIBNAME_$(OS)_$(ENV)).$(NONSHAREDEXT_$(OS)) *.o;\
$(RANLIB) liboneradesp_$(LIBNAME_$(OS)_$(ENV)).$(NONSHAREDEXT_$(OS));\
echo "non-sharable object built";\
echo "";\
echo "Building sharable object \
onera_desp_lib_$(LIBNAME_$(OS)_$(ENV)).$(SHAREDEXT_$(OS))"; \
$(FC_$(OS)_$(ENV)) $(FOPTIONS_SHARED_$(OS)_$(ENV)) $(PIC_$(OS)_$(ENV)) -o
onera_desp_lib_$(LIBNAME_$(OS)_$(ENV)).$(SHAREDEXT_$(OS)) \
*.f $(LDOPTIONS_$(OS)_$(ENV));\
echo "sharable object built";\
echo "";\
echo "Building sequence achieved";
</code>```

Any help would be greatly appreicated! I am a complete beginner with Makefiles.

答:
%IDLINC% isn't makefile syntax, it's MS-DOS syntax. Variable substitution to be precise. The reason you see this in the warnings is because Make prints each command after its own pass of substitutions. Then it passes the command to the shell (MS-DOS) for actual execution, at which point IDLINC is substituted by that shell.

Since prefixed by -I in -I%IDLINC% I assume the variable is meant to hold the path to the IDL headers.

Body:
I am trying to build a library for IDL however I am running into a lot of troubles. I believe understanding this line of syntax could help lead me to solve my bigger problems.

From what I know. The source code is written in fortran (I think?). There is the where the syntax first appears:

FOPTIONS_SHARED_win64_mingw=-I%IDLINC% -fno-second-underscore -static

I believe this FOPTIONS variable plays in a role in the building of a shared library file (.dll). What does this line mean? In particular, what exactly is %IDLINC% ?(double percent signs) I see it appear quite a bit in the warning messages.

And here is a little snippet of the compile/link code from the makefile which uses the FOPTIONS variable:

all.help:
@more $(HELPDIR)/Help.all

all: all.$(OS).$(ENV)

all..:
echo "Missing OS and ENV variables"

all.linux32.intel32: all.build
all.linux32.gnu32: all.build
all.linux32.pgi32: all.build
all.linux64.intel32: all.build
all.linux64.intel64: all.build
all.linux64.gnu32: all.build
all.linux64.gnu64: all.build
all.linux64.pgi64: all.build
all.linux64.gfortran64: all.build
all.win32.cygwin32: all.build
all.win64.cygwin64: all.build
all.win32.mingw: all.build
all.win64.mingw: all.build
all.mach.gnu32: all.build
all.sunos.sparc32: all.build
all.sunos.sparc64: all.build
all.sunos.gnu32: all.build
all.sunos.gnu64: all.build

all.build: version.fortran ntime_max
    @cd $(SOURCEDIR); \
cp wrappers_$(WRAPPER_$(OS)_$(ENV)).inc wrappers.inc;\
echo "Building non-sharable object \
onera_desp_lib_$(LIBNAME_$(OS)_$(ENV)).$(NONSHAREDEXT_$(OS))"; \
$(FC_$(OS)_$(ENV)) $(FOPTIONS_NONSHARED_$(OS)_$(ENV)) *.f;\
$(AR) $(AROPTIONS_$(OS)) liboneradesp_$(LIBNAME_$(OS)_$(ENV)).$(NONSHAREDEXT_$(OS)) *.o;\
$(RANLIB) liboneradesp_$(LIBNAME_$(OS)_$(ENV)).$(NONSHAREDEXT_$(OS));\
echo "non-sharable object built";\
echo "";\
echo "Building sharable object \
onera_desp_lib_$(LIBNAME_$(OS)_$(ENV)).$(SHAREDEXT_$(OS))"; \
$(FC_$(OS)_$(ENV)) $(FOPTIONS_SHARED_$(OS)_$(ENV)) $(PIC_$(OS)_$(ENV)) -o
onera_desp_lib_$(LIBNAME_$(OS)_$(ENV)).$(SHAREDEXT_$(OS)) \
*.f $(LDOPTIONS_$(OS)_$(ENV));\
echo "sharable object built";\
echo "";\
echo "Building sequence achieved";

Any help would be greatly appreicated! I am a complete beginner with Makefiles.