问:
custom style rules on html and body tags with react jss, @global does not get applied
i am attempting to apply custom style rules to: all elements, html, and body tags using react jss, in a React TS library.

when the component inspected in storybook the '@global' rules non present

here is the relevant code section:

```<code>import React from 'react';
import jss from 'jss';
import { AppShellProps } from '../interfaces/AppShellProps';
import { StyledThemeContextProvider } from 'ui-context';

const globalStyles = {
    '@global': {
        '*': {
            margin: 0,
            padding: 0,
            boxSizing: 'border-box',
        },
        html: {
            fontSize: '16px',
            overflowY: 'hidden',
            overflowX: 'hidden',
        },
        body: {
            width: '100%',
            minHeight: '100vh',
        }
};

export const AppShell: React.FC<AppShellProps> = ({ ...props }) => {
    const { classes } = jss
        .createStyleSheet({
            shellMain: {
                border: '3px dashed purple',
            },
            ...globalStyles,
        })
        .attach();

    return (
        <main className={classes.shellMain}>
            <StyledThemeContextProvider themeName={props.themeName}>{props.children}</StyledThemeContextProvider>
        </main>
    );
};
</code>```

and here is the result of the inspection:

Q: how would it be possible to achieve to apply the globalStyle style rules. and stay close to the react jss implementation? or simply just what do i do wrong :)

答:
as it turns out i had left the jss import when i was experimenting, i replaced

import jss from 'jss';

with:

import { createUseStyles } from 'react-jss';

and the classes is implemented like such:

```<code>export const AppShell: React.FC<AppShellProps> = ({ ...props }) => {
    const classes = createUseStyles({
        shellMain: {
            border: '3px dashed purple',
        },
        ...globalStyles,
    }).apply({});

    return (
        <main className={classes.shellMain}>
            <StyledThemeContextProvider themeName={props.themeName}>{props.children}</StyledThemeContextProvider>
        </main>
    );
};
</code>```

this implementation results in global style rules get applied:

Body:
i am attempting to apply custom style rules to: all elements, html, and body tags using react jss, in a React TS library.

when the component inspected in storybook the '@global' rules non present

here is the relevant code section:

import React from 'react';
import jss from 'jss';
import { AppShellProps } from '../interfaces/AppShellProps';
import { StyledThemeContextProvider } from 'ui-context';

const globalStyles = {
    '@global': {
        '*': {
            margin: 0,
            padding: 0,
            boxSizing: 'border-box',
        },
        html: {
            fontSize: '16px',
            overflowY: 'hidden',
            overflowX: 'hidden',
        },
        body: {
            width: '100%',
            minHeight: '100vh',
        }
};

export const AppShell: React.FC<AppShellProps> = ({ ...props }) => {
    const { classes } = jss
        .createStyleSheet({
            shellMain: {
                border: '3px dashed purple',
            },
            ...globalStyles,
        })
        .attach();

    return (

    );
};

and here is the result of the inspection:

Q: how would it be possible to achieve to apply the globalStyle style rules. and stay close to the react jss implementation? or simply just what do i do wrong :)

Body:
as it turns out i had left the jss import when i was experimenting, i replaced

import jss from 'jss';

with:

import { createUseStyles } from 'react-jss';

and the classes is implemented like such:

export const AppShell: React.FC<AppShellProps> = ({ ...props }) => {
    const classes = createUseStyles({
        shellMain: {
            border: '3px dashed purple',
        },
        ...globalStyles,
    }).apply({});

    return (
        <main className={classes.shellMain}>
            <StyledThemeContextProvider themeName={props.themeName}>{props.children}</StyledThemeContextProvider>
        </main>
    );
};

this implementation results in global style rules get applied:


来源: stackexchange

问:
smart paging with datagrid
How do I configure my datagrid to use paging such that it won't pull ALL the rows from the database, but rather only the rows for the current page.

BTW, should I be using a datagrid still or is there a newer control?

答:
When I've implemented paging like this in the past, you can push the responsability on to SQL to do the paging assuming you tell it to the page number and size. This is dependant on the type of database your running.

Doing it on SQL Server 2000 is a litle complex but if your using that, I might have resources that I can dig out

Paging in SQL Server 2005 / 2008 is very easy.

As for how do you tell the DB, that depends on how your binding to your grid, and how your pulling your data.

OwnerDisplayName: Blankman

ContentLicense: CC BY-SA 2.5

Title: smart paging with datagrid

OwnerDisplayName: Josh


问:
Node exporter: Server resource & Disk space stopped showing data
Grafana and Node Exporter Version details are as follows,

```<code>Grafana - v8.1.4 (6855cdff7c)
Node Exporter - v1.0.1.linux-amd64
</code>```

Problem: On grafana for 1 Node Exporter for Prometheus Dashboard EN v20201010 dashboard suddenly not showing data for Server resource overview and Disk Space used Basic sections. Refer to the below screenshot.

It was working till last week, there is no change on Prometheus and Grafana's side. Node exporter service is running fine in all the servers and I can see the metrics from the http://server-1:9100/metrics link. this looks like Prometheus scraping data correctly.

What could be the problem? Some pointers to solve this will be helpful.

答: It was an issue with the system's time. Have noticed that server's time was not in sync with our domain server.Therefore fixed by running ntpdate -s domain-server, Now able to view the metrics on Grafana Dashboard.

ContentLicense: CC BY-SA 4.0

Body:
Grafana and Node Exporter Version details are as follows,

Grafana - v8.1.4 (6855cdff7c)
Node Exporter - v1.0.1.linux-amd64

Problem: On grafana for 1 Node Exporter for Prometheus Dashboard EN v20201010 dashboard suddenly not showing data for Server resource overview and Disk Space used Basic sections. Refer to the below screenshot.

It was working till last week, there is no change on Prometheus and Grafana's side. Node exporter service is running fine in all the servers and I can see the metrics from the http://server-1:9100/metrics link. this looks like Prometheus scraping data correctly.

What could be the problem? Some pointers to solve this will be helpful.


问:
How program interpreter locates the full path of dynamic libraries to be loaded?
I was trying out dynamic linking of libraries. This is a toy program I wrote:

```<code>// prog.c

#include<stdio.h>

int sum(int, int);
int diff(int, int);

int main(int argc, char* argv[]) {
    int a = 10, b = 5;

    printf("Sum: %d\n", sum(a, b));
    printf("Diff: %d\n", diff(a, b));
}
</code>```
```<code>// sum.c

int sum(int a, int b) {
    return a + b;
}
</code>```
```<code>// diff.c

int diff(int a, int b) {
    return a - b;
}
</code>```

Compiled using these commands:

```<code>$ gcc -fPIC -c sum.c diff.c
$ gcc -shared -o libdtest.so sum.o diff.o
$ gcc prog.c -L. -l dtest
</code>```

When I tried to run this, it says ./a.out: error while loading shared libraries: libdtest.so: cannot open shared object file: No such file or directory. The file libdtest.so is still in my folder. What is the mistake here?

I used readelf to read a.out file. There, in the dynamic section, linked libraries were libdtest.so and libc.so.6 . But I couldn't find any reference to their full paths. How does program interpreter locate those files and load them?

答:
The dynamic library loader have a fixed set of paths that it uses to search for libraries. If you have a custom library which isn't in that set then the library won't be found and you get an error.

Unfortunately the linker doesn't automatically add the path to the libraries it links with by default to the finished executable. Instead you must specify a special option to add the path: -rpath.

You can't use -rpath directly with the gcc front-end program, it's a linker-specific option. You need to use the -Wl option:

```<code>$ gcc prog.c -L. -l dtest -Wl,-rpath=$PWD
</code>```

If the library is or will be installed in some directory other than $PWD, then you need to provide the actual (full) path to the installation directory.

Other possible solution includes adding the path to the set the dynamic loader uses (not recommended for uncommon paths), or setting the LD_LIBRARY_PATH environment variable (which is not recommended at all).

Body:
I was trying out dynamic linking of libraries. This is a toy program I wrote:

// prog.c

#include<stdio.h>

int sum(int, int);
int diff(int, int);

int main(int argc, char* argv[]) {
    int a = 10, b = 5;

    printf("Sum: %d\n", sum(a, b));
    printf("Diff: %d\n", diff(a, b));
}

// sum.c

int sum(int a, int b) {
    return a + b;
}

// diff.c

int diff(int a, int b) {
    return a - b;
}

Compiled using these commands:

$ gcc -fPIC -c sum.c diff.c
$ gcc -shared -o libdtest.so sum.o diff.o
$ gcc prog.c -L. -l dtest

When I tried to run this, it says ./a.out: error while loading shared libraries: libdtest.so: cannot open shared object file: No such file or directory. The file libdtest.so is still in my folder. What is the mistake here?

I used readelf to read a.out file. There, in the dynamic section, linked libraries were libdtest.so and libc.so.6 . But I couldn't find any reference to their full paths. How does program interpreter locate those files and load them?

Body:
The dynamic library loader have a fixed set of paths that it uses to search for libraries. If you have a custom library which isn't in that set then the library won't be found and you get an error.

Unfortunately the linker doesn't automatically add the path to the libraries it links with by default to the finished executable. Instead you must specify a special option to add the path: -rpath.

You can't use -rpath directly with the gcc front-end program, it's a linker-specific option. You need to use the -Wl option:

$ gcc prog.c -L. -l dtest -Wl,-rpath=$PWD

If the library is or will be installed in some directory other than $PWD, then you need to provide the actual (full) path to the installation directory.

Other possible solution includes adding the path to the set the dynamic loader uses (not recommended for uncommon paths), or setting the LD_LIBRARY_PATH environment variable (which is not recommended at all).


问:
Angular Material: Reseting reactiveform shows validation error
I am using angular5 reactivemodule to show a form in my application. I had also used required validator which will subsequently make the field in red color and show an error msg to the user.

It is working as expected but when I reset the form using

this.form.reset()

the form shows me a validation error that the specific field is required.
I also used form.markAsPristine() or form.markAsUntouched() to make it work but the problem persist after applying multiple combination of possible pairs.

example.html

```<code><form [formGroup]="checkForm" (ngSubmit)="submitForm()">
  <mat-form-field>
    <input matInput formControlName="name" placeholder="name" />
    <mat-error *ngIf="checkForm.get('name').errors?.required">
      Name is required.
    </mat-error>
  </mat-form-field>
  <mat-form-field>
    <input matInput formControlName="email" placeholder="email" />
    <mat-error *ngIf="checkForm.get('email').errors?.required">
      Name is required.
    </mat-error>
  </mat-form-field>
  <button [disabled]="checkForm.invalid" type="submit">add</button>
</form>
</code>```

example.ts

```<code>checkForm  = this.formBuilder.group({
  'name': ['', Validators.required],
  'email': ['', Validators.required]
});

submitForm() {
   this.checkForm.reset();
   // this.checkForm.markAsPristine();
   this.checkForm.markAsUntouched();
}
</code>```

Any help is appreciated.

答: Adding type="reset" to Reset button worked for me instead of using formGroupDirective.resetform().

ContentLicense: CC BY-SA 3.0

Body:
I am using angular5 reactivemodule to show a form in my application. I had also used required validator which will subsequently make the field in red color and show an error msg to the user.

It is working as expected but when I reset the form using

this.form.reset()

the form shows me a validation error that the specific field is required.
I also used form.markAsPristine() or form.markAsUntouched() to make it work but the problem persist after applying multiple combination of possible pairs.

example.html

<form [formGroup]="checkForm" (ngSubmit)="submitForm()">
  <mat-form-field>
    <input matInput formControlName="name" placeholder="name" />
    <mat-error *ngIf="checkForm.get('name').errors?.required">
      Name is required.
    </mat-error>
  </mat-form-field>
  <mat-form-field>
    <input matInput formControlName="email" placeholder="email" />
    <mat-error *ngIf="checkForm.get('email').errors?.required">
      Name is required.
    </mat-error>
  </mat-form-field>
  <button [disabled]="checkForm.invalid" type="submit">add</button>
</form>

example.ts

checkForm  = this.formBuilder.group({
  'name': ['', Validators.required],
  'email': ['', Validators.required]
});

submitForm() {
   this.checkForm.reset();
   // this.checkForm.markAsPristine();
   this.checkForm.markAsUntouched();
}

Any help is appreciated.


问:
Object: Do not delete existing keys
Hi have the following code snipped. (Javascript create Object by array
The problem is, this will delete my existing key, but i want to keep and update them. Only if the key not exists, then should add it.

function setValueToLightGroup(Group, keys, value) {
  let c=Group;
  keys = keys.split('.');

  for (var i=0; i<keys.length-1; ++i) c = c[keys[i]] = {};
  c[keys[i]] = value;
}

setValueToLightGroup(LightGroups[`FlurEG`], 'autoOff.timers.startTimer', 300);
setValueToLightGroup(LightGroups[`FlurEG`], 'autoOff.enabled', true);
setValueToLightGroup(LightGroups[`FlurEG`], 'power', true);```

答:
The general problem is that you overwrite the previous value of c[keys[i]] in every iteration of the for loop with {}. If you want to keep the previous contents, please only overwrite the contents if the key does not exist.

```<code>for (let i = 0; i < keys.length - 1; i++) {
  if (!(keys[i] in c)) { // <-- this check avoids that value is overwritten
    c[keys[i]] = {};
  }
  c = c[keys[i]];
}
</code>```

As noted in the comments, an alternative would be using ??= for the assignment. It performs the assignment if the left hand side is undefined.

Title: Object: Do not delete existing keys

Body:
The general problem is that you overwrite the previous value of c[keys[i]] in every iteration of the for loop with {}. If you want to keep the previous contents, please only overwrite the contents if the key does not exist.

for (let i = 0; i < keys.length - 1; i++) {
  if (!(keys[i] in c)) { // <-- this check avoids that value is overwritten
    c[keys[i]] = {};
  }
  c = c[keys[i]];
}

As noted in the comments, an alternative would be using ??= for the assignment. It performs the assignment if the left hand side is undefined.


问:
To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function
I have this code

```<code>import ReactDOM from "react-dom";
import React, { useState, useEffect } from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

function ParamsExample() {
  return (
    <Router>
      <div>
        <h2>Accounts</h2>
        <Link to="/">Netflix</Link>
        <Route path="/" component={Miliko} />
      </div>
    </Router>
  );
}

const Miliko = ({ match }) => {
  const [data, setData] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isError, setIsError] = useState(false);

  useEffect(() => {
    (async function() {
      setIsError(false);
      setIsLoading(true);
      try {
        const Res = await fetch("https://foo0022.firebaseio.com/New.json");
        const ResObj = await Res.json();
        const ResArr = await Object.values(ResObj).flat();
        setData(ResArr);
      } catch (error) {
        setIsError(true);
      }
      setIsLoading(false);
    })();
    console.log(data);
  }, [match]);
  return <div>{`${isLoading}${isError}`}</div>;
};

function App() {
  return (
    <div className="App">
      <ParamsExample />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
</code>```

I created three links that open the Miliko component. but when I quickly click on the links I get this error:

To fix, cancel all subscriptions and asynchronous tasks in a useEffect
cleanup function.

答:
you can wrap any action as a callback inside checkUnmount</p>
```<code>const useUnmounted = () => {
  const mountedRef = useRef(true);

  useEffect(
    () => () => {
      mountedRef.current = false;
    },
    [],
  );

  const checkUnmount = useCallback(
    (cb = () => {}) => {
      try {
        if (!mountedRef.current) throw new Error('Component is unmounted');
        cb();
      } catch (error) {
        console.log({ error });
      }
    },
    [mountedRef.current],
  );

  return [checkUnmount, mountedRef.current];
};
</code>```

Body:
I have this code

import ReactDOM from "react-dom";
import React, { useState, useEffect } from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

function ParamsExample() {
  return (
    <Router>

Accounts

        <Link to="/">Netflix</Link>
        <Route path="/" component={Miliko} />

    </Router>
  );
}

const Miliko = ({ match }) => {
  const [data, setData] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isError, setIsError] = useState(false);

  useEffect(() => {
    (async function() {
      setIsError(false);
      setIsLoading(true);
      try {
        const Res = await fetch("https://foo0022.firebaseio.com/New.json");
        const ResObj = await Res.json();
        const ResArr = await Object.values(ResObj).flat();
        setData(ResArr);
      } catch (error) {
        setIsError(true);
      }
      setIsLoading(false);
    })();
    console.log(data);
  }, [match]);
  return
{`${isLoading}${isError}`}
;
};

function App() {
  return (

      <ParamsExample />

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

I created three links that open the Miliko component. but when I quickly click on the links I get this error:

To fix, cancel all subscriptions and asynchronous tasks in a useEffect
cleanup function.

Body:
you can wrap any action as a callback inside checkUnmount

const useUnmounted = () => {
  const mountedRef = useRef(true);

  useEffect(
    () => () => {
      mountedRef.current = false;
    },
    [],
  );

  const checkUnmount = useCallback(
    (cb = () => {}) => {
      try {
        if (!mountedRef.current) throw new Error('Component is unmounted');
        cb();
      } catch (error) {
        console.log({ error });
      }
    },
    [mountedRef.current],
  );

  return [checkUnmount, mountedRef.current];
};


问:
Expression in Polars select context that refers to earlier alias
Is there a way to allow an expression in Polars to refer to a previous aliased expression? For example, this code that defines two new columns errors because the second new column refers to the first:

import polars as pl

df = pl.DataFrame(dict(x=[0, 0, 1]))

df.select([
  (pl.col('x') + 1).alias('y'),
  (pl.col('y') * 2).alias('z')],
)
# pyo3_runtime.PanicException: called `Result::unwrap()` on an `Err` value:
# NotFound("Unable to get field named \"y\". Valid fields: [\"x\"]")
```

The error makes it obvious that the failure is caused by the first alias not being visible to the second expression. Is there a straightforward way to make this work?

答:
All polars expressions within a context are executed in parallel. So they cannot refer to a column that does not yet exist.

A context is:

df.with_columns

df.select

df.groupby(..).agg

This means you need to enforce sequential execution for expressions that reference to other expression outputs.

In your case I would do:

(df.with_column(
       (pl.col('x') + 1).alias('y')
    ).select([
       pl.col('y'),
      (pl.col('y') * 2).alias('z')
]))
```

Body:
Is there a way to allow an expression in Polars to refer to a previous aliased expression? For example, this code that defines two new columns errors because the second new column refers to the first:

import polars as pl

df = pl.DataFrame(dict(x=[0, 0, 1]))

df.select([
  (pl.col('x') + 1).alias('y'),
  (pl.col('y') * 2).alias('z')],
)
# pyo3_runtime.PanicException: called `Result::unwrap()` on an `Err` value:
# NotFound("Unable to get field named \"y\". Valid fields: [\"x\"]")

The error makes it obvious that the failure is caused by the first alias not being visible to the second expression. Is there a straightforward way to make this work?


问:
Filters in ASP.NET Core MVC
In ASP.NET MVC, I was using a controller for ActionExecuting, ActionExecuted, OnException, Dispose etc. which was derived from the System.Web.Mvc.Controller

But after changing the application to .NET Core that derives from Microsoft.AspNetCore.Mvc.Controller, I'm getting below errors.

'MyBaseController.OnActionExecuting(ActionExecutingContext)': cannot change access modifiers when overriding 'public' inherited member 'Controller.OnActionExecuting(ActionExecutingContext)'

'MMBaseController.OnActionExecuted(ActionExecutedContext)': cannot change access modifiers when overriding 'public' inherited member 'Controller.OnActionExecuted(ActionExecutedContext)'

```<code>public class MyBaseController : Controller
{
    protected override void OnActionExecuting(ActionExecutedContext filterContext)
    {
        string controller = Convert.ToString(filterContext.RequestContext.RouteData.Values["controller"]);
        string action = Convert.ToString(filterContext.RequestContext.RouteData.Values["action"]);
        if (!filterContext.HttpContext.Request.IsAuthenticated)
        {
            SmartLogger.Info("UnAuthenticated Request");

            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
            {
                SmartLogger.Info("UnAuthenticated Ajax Request");
            }
        }
    }
}
</code>```

'ActionExecutedContext' does not contain a definition for 'RequestContext' and no accessible extension method 'RequestContext' accepting a first argument of type 'ActionExecutedContext' could be found (are you missing a using directive or an assembly reference?)

Now I tried below method, still not able to use filterContext.HttpContext.Request.IsAuthenticated and filterContext.HttpContext.Request.IsAjaxRequest(), getting below error:

```<code>public class CustomFilter : ActionFilterAttribute, IActionFilter
{
    public override void OnActionExecuting(ActionExecutedContext filterContext)
    {
        string controller = Convert.ToString(filterContext.RouteData.Values["controller"]);
        string action = Convert.ToString(filterContext.RouteData.Values["action"]);
        if (!filterContext.HttpContext.Request.IsAuthenticated)
        {
            SmartLogger.Info("UnAuthenticated Request");

            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                SmartLogger.Info("UnAuthenticated Ajax Request");
            }
            TempData["CurrentSessionErrorMessage"] = "Ajax Authentication Failed";
        }
    }
}
</code>```

'HttpRequest' does not contain a definition for 'IsAuthenticated' and no accessible extension method 'IsAuthenticated' accepting a first argument of type 'HttpRequest' could be found (are you missing a using directive or an assembly reference?)

'HttpRequest' does not contain a definition for 'IsAjaxRequest' and no accessible extension method 'IsAjaxRequest' accepting a first argument of type 'HttpRequest' could be found (are you missing a using directive or an assembly reference?)

Do we need to have entire code changes for this implementation in .NET Core.

答:
Generally speaking, we will not define filter in the controller in Asp.Net Core, we usually create a class inheritance Filter. For example

```<code>public class SampleActionFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        // Do something before the action executes.
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        // Do something after the action executes.
    }
}
</code>```

then you can use [SampleActionFilter] attribute on you controller.

you can read this document about filter in Asp.Net core.

Title: Filters in ASP.NET Core MVC

Body:
In ASP.NET MVC, I was using a controller for ActionExecuting, ActionExecuted, OnException, Dispose etc. which was derived from the System.Web.Mvc.Controller

But after changing the application to .NET Core that derives from Microsoft.AspNetCore.Mvc.Controller, I'm getting below errors.

'MyBaseController.OnActionExecuting(ActionExecutingContext)': cannot change access modifiers when overriding 'public' inherited member 'Controller.OnActionExecuting(ActionExecutingContext)'

'MMBaseController.OnActionExecuted(ActionExecutedContext)': cannot change access modifiers when overriding 'public' inherited member 'Controller.OnActionExecuted(ActionExecutedContext)'

public class MyBaseController : Controller
{
    protected override void OnActionExecuting(ActionExecutedContext filterContext)
    {
        string controller = Convert.ToString(filterContext.RequestContext.RouteData.Values["controller"]);
        string action = Convert.ToString(filterContext.RequestContext.RouteData.Values["action"]);
        if (!filterContext.HttpContext.Request.IsAuthenticated)
        {
            SmartLogger.Info("UnAuthenticated Request");

            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
            {
                SmartLogger.Info("UnAuthenticated Ajax Request");
            }
        }
    }
}

'ActionExecutedContext' does not contain a definition for 'RequestContext' and no accessible extension method 'RequestContext' accepting a first argument of type 'ActionExecutedContext' could be found (are you missing a using directive or an assembly reference?)

Now I tried below method, still not able to use filterContext.HttpContext.Request.IsAuthenticated and filterContext.HttpContext.Request.IsAjaxRequest(), getting below error:

public class CustomFilter : ActionFilterAttribute, IActionFilter
{
    public override void OnActionExecuting(ActionExecutedContext filterContext)
    {
        string controller = Convert.ToString(filterContext.RouteData.Values["controller"]);
        string action = Convert.ToString(filterContext.RouteData.Values["action"]);
        if (!filterContext.HttpContext.Request.IsAuthenticated)
        {
            SmartLogger.Info("UnAuthenticated Request");

            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                SmartLogger.Info("UnAuthenticated Ajax Request");
            }
            TempData["CurrentSessionErrorMessage"] = "Ajax Authentication Failed";
        }
    }
}

'HttpRequest' does not contain a definition for 'IsAuthenticated' and no accessible extension method 'IsAuthenticated' accepting a first argument of type 'HttpRequest' could be found (are you missing a using directive or an assembly reference?)

'HttpRequest' does not contain a definition for 'IsAjaxRequest' and no accessible extension method 'IsAjaxRequest' accepting a first argument of type 'HttpRequest' could be found (are you missing a using directive or an assembly reference?)

Do we need to have entire code changes for this implementation in .NET Core.

Body:
Generally speaking, we will not define filter in the controller in Asp.Net Core, we usually create a class inheritance Filter. For example

public class SampleActionFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        // Do something before the action executes.
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        // Do something after the action executes.
    }
}

then you can use [SampleActionFilter] attribute on you controller.

you can read this document about filter in Asp.Net core.


问:
Why does v-progress-circular (v2.5.0+) no longer display
Since vuetify@2.5.0 the v-progress-circular—visible class is not applied on any progress components - meaning that just a dot is being displayed.

Is there anything I need to change from my existing pre 2.5.0 codebase to make it work?

My html code works on versions pre 2.5.0 ...

```<code><v-progress-circular indeterminate color="muted"></v-progress-circular>
</code>```

If I inspect the code, vuetify generates the following:

```<code><div data-v-7ba5bd90="" role="progressbar" aria-valuemin="0" aria-valuemax="100" class="v-progress-circular v-progress-circular--indeterminate muted--text" style="height: 32px; width: 32px;">
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="22.857142857142858 22.857142857142858 45.714285714285715 45.714285714285715" style="transform: rotate(0deg);">
    <circle fill="transparent" cx="45.714285714285715" cy="45.714285714285715" r="20" stroke-width="5.714285714285714" stroke-dasharray="125.664" stroke-dashoffset="125.66370614359172px" class="v-progress-circular__overlay"></circle>
  </svg>
  <div class="v-progress-circular__info"></div>
</div>
</code>```

As you can see, the classlist for the wrapping div should also contain

```<code>v-progress-circular--visible
</code>```

But it doesn't. When I add that manually in the devtools the circular progress components spins in the expected way. Without it, it just renders as a dot.

In vuetify versions pre 2.5.0 it adds the v-progress-circular--visible class fine.

Has a bug crept in when upgrading to 2.5.0 - on the documentation site I can see the spinners spinning fine ...

答:
It must have occurred during migration between the different versions.

When I inserted a debugger statement in the vuetify directives/intersect file

https://github.com/vuetifyjs/vuetify/blob/0eec92f0/packages/vuetify/src/directives/intersect/index.ts#L30

to see what's going on, the problem magically disappeared. Perhaps it was some sort of webpacker caching thing going on?

Body:
Since vuetify@2.5.0 the v-progress-circular—visible class is not applied on any progress components - meaning that just a dot is being displayed.

Is there anything I need to change from my existing pre 2.5.0 codebase to make it work?

My html code works on versions pre 2.5.0 ...

<v-progress-circular indeterminate color="muted"></v-progress-circular>

If I inspect the code, vuetify generates the following:

  <svg xmlns="http://www.w3.org/2000/svg" viewBox="22.857142857142858 22.857142857142858 45.714285714285715 45.714285714285715" style="transform: rotate(0deg);">
    <circle fill="transparent" cx="45.714285714285715" cy="45.714285714285715" r="20" stroke-width="5.714285714285714" stroke-dasharray="125.664" stroke-dashoffset="125.66370614359172px" class="v-progress-circular__overlay"></circle>
  </svg>

As you can see, the classlist for the wrapping div should also contain

v-progress-circular--visible

But it doesn't. When I add that manually in the devtools the circular progress components spins in the expected way. Without it, it just renders as a dot.

In vuetify versions pre 2.5.0 it adds the v-progress-circular--visible class fine.

Has a bug crept in when upgrading to 2.5.0 - on the documentation site I can see the spinners spinning fine ...


问:
Can I migrate a partitioned table to a non-partitioned table in Oracle with the CREATE TABLE statement?
I have an Oracle 11g partitioned table with 10 partitions for ten years of data, each on its own tablespace partitioned by range. Each year-partition contains 12 monthly-partitions.

I would like to convert this table to a non-partitioned table, before migrating all the database to Postgresql 10.7 with ora2pg.

I've read that I could first backup this table by expdp and then import it using PARTITIONS_OPTIONS parameter option of impdp.

But is it also possible to use this following statement as a strict equivalent ?

```<code>CREATE TABLE IF NOT EXISTS non_partitioned_table AS SELECT * FROM partitioned_table
</code>```

I would not lose any data, but what about the indexes ?

Is there other differences between these two procedures ?

答:
Syntax you posted doesn't exist in Oracle (there's no if not exists clause there).

Therefore, you'd

```<code>create table non_partitioned_table as select * from partitioned_table;
</code>```

If object whose name is non_partitioned_table already exists, that command would fail.

No indexes would be created automatically - you'd have to create them manually, but - you'd do that in PostgreSQL anyway, wouldn't you? Why bother in Oracle as you won't be using that table for anything (except migration purposes); right?

Body:
I have an Oracle 11g partitioned table with 10 partitions for ten years of data, each on its own tablespace partitioned by range. Each year-partition contains 12 monthly-partitions.

I would like to convert this table to a non-partitioned table, before migrating all the database to Postgresql 10.7 with ora2pg.

I've read that I could first backup this table by expdp and then import it using PARTITIONS_OPTIONS parameter option of impdp.

But is it also possible to use this following statement as a strict equivalent ?

CREATE TABLE IF NOT EXISTS non_partitioned_table AS SELECT * FROM partitioned_table

I would not lose any data, but what about the indexes ?

Is there other differences between these two procedures ?

Body:
Syntax you posted doesn't exist in Oracle (there's no if not exists clause there).

Therefore, you'd

create table non_partitioned_table as select * from partitioned_table;

If object whose name is non_partitioned_table already exists, that command would fail.

No indexes would be created automatically - you'd have to create them manually, but - you'd do that in PostgreSQL anyway, wouldn't you? Why bother in Oracle as you won't be using that table for anything (except migration purposes); right?


问:
How to use module in kotlin Mutliplatform moblie
Hey I am learning Kotlin Multiplatform mobile. I starting learning from the doc. I successfully run the module in android and ios platform, without any problem. Now I want to implement this in real project. I successfully created the module inside my pre-existing android directory. According to this Make your cross-platform application work on iOS we can only use module inside the android directory. I work as android developer and my other team have ios developer. So the problem is we have different system for android and ios. So how can I share this module to the Ios team. Please guide me how to achieve this. I read somewhere ios need XCFramework. But I am not sure, how can I achieved this. Can someone guide me step wise? Thanks</p>

答:
In general, Kotlin Multiplatform Mobile provides you with an ability to build frameworks for iOS. It can be delivered in several ways:

Simple ModuleName.framework file ready to be imported into your teammate's app,

CocoaPods integration, providing your teammate with the ability to rebuild this framework from sources and to use third-party libraries from Kotlin code,

Universal (fat) framework and XCFramework. These two are designed to provide the framework user with the ability to build the result app for different CPU architectures. This would be helpful when publishing the app.

If your aim is to just show the iOS team an example of Kotlin Multiplatform Mobile power, I think it would be enough to declare the framework, build it by executing the appropriate gradle task and share the result file.

If they would also like to put some code into the iOS-specific part of your module, adding the CocoaPods integration will be a good idea.


问:
How to sign binaries during publishing a single file dotnet core app?
I would like to sign binaries that go inside a single-file published .net core application. This is because I would like the libraries, when unpacked into %temp%\.net\%app_name%\%random_dir%, to be digitally signed. Here's my shortened version of the project file.

```<code><Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net5.0</TargetFramework>
    <PublishSingleFile>true</PublishSingleFile>
    <SelfContained>true</SelfContained>
    <RuntimeIdentifier>win-x86</RuntimeIdentifier>
    <PublishTrimmed>false</PublishTrimmed>
    <PublishReadyToRun>false</PublishReadyToRun>
    <Configuration>Release</Configuration>
    <IncludeAllContentForSelfExtract>true</IncludeAllContentForSelfExtract>
  </PropertyGroup>

  <Target Name="SignPrePublishedFiles" AfterTargets="ComputeAndCopyFilesToPublishDirectory">
    <ItemGroup>
      <FileToSign Include="$(OutDir)Foo.*.dll" />
    </ItemGroup>
    <Exec Command="jsign ~~~params removed for brevity~~~ %(FileToSign.Identity)" />
  </Target>

</Project>
</code>```

The SignPrePublishedFiles target signs required files in the $(OutDir) dir, but the published app contains unsigned binaries. I think this is because the incorrect  timing of: AfterTargets="ComputeAndCopyFilesToPublishDirectory" or incorrect folder, I assumed $(OutDir) is used for publishing. Here, I use jsign because the build runs on Linux, but the signing is done for Windows binaries.

How do you sign your published files, specifically those inside the single-file app?

答:
You can sign the output dll and apphost wrapper for a project while it's in obj/ - this is what eventually gets published. Try something like this:

  <Target Name="SignIntermediates" BeforeTargets="GetCopyToOutputDirectoryItems">
    <ItemGroup>
      <FileToSign Include="$(IntermediateOutputPath)$(TargetFileName)" />
      <FileToSign Condition="'$(TargetExt)' == '.dll' And '$(OutputType)' == 'WinExe'" Include="$(IntermediateOutputPath)apphost.exe" />
    </ItemGroup>

    <Exec Command="jsign ~~~params removed for brevity~~~ %(FileToSign.Identity)" />
  </Target>
```

GetCopyToOutputDirectoryItems is the last public target before apphost.exe is copied and renamed to $(TargetName).exe.

Body:
I would like to sign binaries that go inside a single-file published .net core application. This is because I would like the libraries, when unpacked into %temp%\.net\%app_name%\%random_dir%, to be digitally signed. Here's my shortened version of the project file.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net5.0</TargetFramework>
    <PublishSingleFile>true</PublishSingleFile>
    <SelfContained>true</SelfContained>
    <RuntimeIdentifier>win-x86</RuntimeIdentifier>
    <PublishTrimmed>false</PublishTrimmed>
    <PublishReadyToRun>false</PublishReadyToRun>
    <Configuration>Release</Configuration>
    <IncludeAllContentForSelfExtract>true</IncludeAllContentForSelfExtract>
  </PropertyGroup>

  <Target Name="SignPrePublishedFiles" AfterTargets="ComputeAndCopyFilesToPublishDirectory">
    <ItemGroup>
      <FileToSign Include="$(OutDir)Foo.*.dll" />
    </ItemGroup>
    <Exec Command="jsign ~~~params removed for brevity~~~ %(FileToSign.Identity)" />
  </Target>

</Project>

The SignPrePublishedFiles target signs required files in the $(OutDir) dir, but the published app contains unsigned binaries. I think this is because the incorrect  timing of: AfterTargets="ComputeAndCopyFilesToPublishDirectory" or incorrect folder, I assumed $(OutDir) is used for publishing. Here, I use jsign because the build runs on Linux, but the signing is done for Windows binaries.

How do you sign your published files, specifically those inside the single-file app?

Body:
You can sign the output dll and apphost wrapper for a project while it's in obj/ - this is what eventually gets published. Try something like this:

  <Target Name="SignIntermediates" BeforeTargets="GetCopyToOutputDirectoryItems">
    <ItemGroup>
      <FileToSign Include="$(IntermediateOutputPath)$(TargetFileName)" />
      <FileToSign Condition="'$(TargetExt)' == '.dll' And '$(OutputType)' == 'WinExe'" Include="$(IntermediateOutputPath)apphost.exe" />
    </ItemGroup>

    <Exec Command="jsign ~~~params removed for brevity~~~ %(FileToSign.Identity)" />
  </Target>

GetCopyToOutputDirectoryItems is the last public target before apphost.exe is copied and renamed to $(TargetName).exe.


问:
Integer expression expected
I want to read my files line by line every 5 seconds. This time I just tried one-line bash command to do this.
And bash command is:

```<code>let X=1;while [ $X -lt 20 ];do cat XXX.file |head -$X|tail -1;X=$X+1;sleep 5;done
</code>```

However I got the error like:

```<code>-bash: [: 1+1: integer expression expected
</code>```

What's the problem?
btw, why can't we do $X < 20? (Instead we have to do -lt, less than?)

thx

答:
The sum X=$X+1 should be X=$(expr $X + 1 ).

You can also use < for the comparison, but you have to write (("$X" < "20")) with the double parenthesis instead of [ $X -lt 20 ].

Title: Integer expression expected

Body:
I want to read my files line by line every 5 seconds. This time I just tried one-line bash command to do this.
And bash command is:

let X=1;while [ $X -lt 20 ];do cat XXX.file |head -$X|tail -1;X=$X+1;sleep 5;done

However I got the error like:

-bash: [: 1+1: integer expression expected

What's the problem?
btw, why can't we do $X < 20? (Instead we have to do -lt, less than?)

thx


问:
How to fix Bad state: field does not exist within the DocumentSnapshotPlatform Firebase Flutter FutureBuilder
I'm getting an error in a FutureBuilder while trying to retrieve data from the Firestore database.  The error message is:

The following StateError was thrown building
FutureBuilder<DocumentSnapshot<Object?>>(dirty, state:
_FutureBuilderState<DocumentSnapshot<Object?>>#9feea): Bad state: field does not exist within the DocumentSnapshotPlatform

The relevant error-causing widget was:
FutureBuilder<DocumentSnapshot<Object?>>
FutureBuilder:file:///Users/cy/AndroidStudioProjects/improve_practice_app/lib/app/community/tabs/profile_tab.dart:47:24

I reviewed different SO threads and and still have no idea what to do to fix my code.  Firebase is definitely working properly and I don't see any missing fields.  Any help will be appreciated.  Thanks.

```<code>class ProfileTab extends StatefulWidget {
  const ProfileTab({
    Key? key,
  }) : super(key: key);

  @override
  State<ProfileTab> createState() => _ProfileTabState();
}

class _ProfileTabState extends State<ProfileTab> {
  final currentUser = Auth().currentUser?.uid;

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: CustomScrollView(slivers: <Widget>[
      SliverToBoxAdapter(
          child: FutureBuilder<DocumentSnapshot<Map<String, dynamic>>>(
              future: Auth().usersReference.doc(currentUser).get(),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return const AdaptiveCircularProgress();
                }
                AppUser appUser = AppUser.fromDocument(snapshot.data);
                return UserProfileHeaderContainer(headerContent: []);
              }))
    ]));
  }
}

class AppUser {
  AppUser({
    this.bio,
    this.displayName,
    this.followers,
    this.following,
    this.photoUrl,
    this.userID,
    this.userCart,
    this.userName,
  });

  final String? bio;
  final String? displayName;
  final List? followers;
  final List? following;
  final String? photoUrl;
  final List? userCart;
  final String? userID;
  final String? userName;

  factory AppUser.fromDocument(DocumentSnapshot? doc) {
    return AppUser(
      bio: doc?[FirebaseString.bio],
      displayName: doc?[FirebaseString.displayName],
      followers: doc?[FirebaseString.followers],
      following: doc?[FirebaseString.following],
      photoUrl: doc?[FirebaseString.photoUrl],
      userCart: doc?[FirebaseString.userCart],
      userID: doc?[FirebaseString.userID],
      userName: doc?[FirebaseString.userName],
    );
  }

  Map<String, dynamic> toJson() => {
    FirebaseString.bio: bio,
    FirebaseString.displayName: displayName,
    FirebaseString.followers: followers,
    FirebaseString.following: following,
    FirebaseString.photoUrl: photoUrl,
    FirebaseString.uid: userID,
    FirebaseString.userCart: userCart,
    FirebaseString.userName: userName,
  };

}
</code>```

答:
You are parsing it wrong. You need to do something like.</p>
```<code>factory AppUser.fromDocument(DocumentSnapshot<Map<String, dynamic>> doc) {

// it's the data map which has all the info
final map = doc.data()

return AppUser(
  bio: map[FirebaseString.bio],
  ....,
  ....,
  );
}
</code>```

Body:
I'm getting an error in a FutureBuilder while trying to retrieve data from the Firestore database.  The error message is:

The following StateError was thrown building
FutureBuilder<DocumentSnapshot<Object?>>(dirty, state:
_FutureBuilderState<DocumentSnapshot<Object?>>#9feea): Bad state: field does not exist within the DocumentSnapshotPlatform

The relevant error-causing widget was:
FutureBuilder<DocumentSnapshot<Object?>>
FutureBuilder:file:///Users/cy/AndroidStudioProjects/improve_practice_app/lib/app/community/tabs/profile_tab.dart:47:24

I reviewed different SO threads and and still have no idea what to do to fix my code.  Firebase is definitely working properly and I don't see any missing fields.  Any help will be appreciated.  Thanks.

class ProfileTab extends StatefulWidget {
  const ProfileTab({
    Key? key,
  }) : super(key: key);

  @override
  State<ProfileTab> createState() => _ProfileTabState();
}

class _ProfileTabState extends State<ProfileTab> {
  final currentUser = Auth().currentUser?.uid;

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: CustomScrollView(slivers: <Widget>[
      SliverToBoxAdapter(
          child: FutureBuilder<DocumentSnapshot<Map<String, dynamic>>>(
              future: Auth().usersReference.doc(currentUser).get(),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return const AdaptiveCircularProgress();
                }
                AppUser appUser = AppUser.fromDocument(snapshot.data);
                return UserProfileHeaderContainer(headerContent: []);
              }))
    ]));
  }
}

class AppUser {
  AppUser({
    this.bio,
    this.displayName,
    this.followers,
    this.following,
    this.photoUrl,
    this.userID,
    this.userCart,
    this.userName,
  });

  final String? bio;
  final String? displayName;
  final List? followers;
  final List? following;
  final String? photoUrl;
  final List? userCart;
  final String? userID;
  final String? userName;

  factory AppUser.fromDocument(DocumentSnapshot? doc) {
    return AppUser(
      bio: doc?[FirebaseString.bio],
      displayName: doc?[FirebaseString.displayName],
      followers: doc?[FirebaseString.followers],
      following: doc?[FirebaseString.following],
      photoUrl: doc?[FirebaseString.photoUrl],
      userCart: doc?[FirebaseString.userCart],
      userID: doc?[FirebaseString.userID],
      userName: doc?[FirebaseString.userName],
    );
  }

  Map<String, dynamic> toJson() => {
    FirebaseString.bio: bio,
    FirebaseString.displayName: displayName,
    FirebaseString.followers: followers,
    FirebaseString.following: following,
    FirebaseString.photoUrl: photoUrl,
    FirebaseString.uid: userID,
    FirebaseString.userCart: userCart,
    FirebaseString.userName: userName,
  };

}

Body:
You are parsing it wrong. You need to do something like.

factory AppUser.fromDocument(DocumentSnapshot<Map<String, dynamic>> doc) {

// it's the data map which has all the info
final map = doc.data()

return AppUser(
  bio: map[FirebaseString.bio],
  ....,
  ....,
  );
}


问:
Proper separation of concerns between microservices
Let's assume I would like to create a blogging platform that would allow managing user accounts, therefore I came up with 2 microservices:

Blogging - managing posts, tags, etc.

Users - managing users, their roles, etc.

It's clear to me that Post contains the ID of the author (User) and User contains IDs of the Posts he wrote.

The problem is that when a client requests a Post, I would also like to return the name of the author and send it together to the client in a DTO (view model). I see 2 possible solutions for that:

Introduce the concept of the User (only ID and name) in a domain of the Blogging service. Every time a client requests a Post, all relevant data is fetched only from this microservice. Every time a user's name is modified in a Users microservice, this service is notified and updated author's names.

Keep the concerns completely separated. Every time a client asks for a Post, Blogging microservice is called to fetch Post and then Users microservice is called to fetch the author's name based on the ID.

So far I was leaning towards solution #1 as it would require only 1 call to the 1 microservice when Post is requested, but then let's say if the number of functions (microservices) starts growing and I keep adding small concepts from each of them only to limit the number of calls, I'm afraid I would end up in a spaghetti Blogging microservice... But then I also don't think the number of microservices will grow significantly ;)

Which way do you find better and why? Does any of the approaches break the microservices architecture principles and my concerns are justified?

答:
It really depends on the way your program is going to develop.

Solution #1 (editing the Blogging model)

Here you edit your model for the sake of the performance. Most of the time I don't think altering the model itself for the sake of performance is the right way. If you don't think the concept of an User inside the Blogging context is right, you shouldn't put it there. Another problem is that you would have to deal with eventual consistency between you bounded contexts (BC). If you think the concept of User inside Blogging is not a bad idea, it might be probably the way to go.

Solution #2 (querying the data separately)

Although this might not be performance friendly, I think this would be the easiest way at the beginning. You won't have to deal with eventual consistency (+dealing with synchronizing the data between BC) and you don't have to alter your model. But if you really care about performance and keeping your model clean, you might be interested in read model.

Another solution - read model

The concept of read model is about having at least two separate models: one for reading the data and for writing/editing the data. If we want to implement this concept for your problem, we would create a read model for the Blogging BC where Posts and Users could be merged together (something like in solution #1) and then queried. We can synchronize this data with the help of events, so when the Post or User changes, it would raise an event and save the changed data into your read model. This way you can merge/alter any data you want for better performance. It might be very similar to solution #1, but the main difference is that you don't edit your main model. You create new one just for the reading. It is probably the hardest solution, but if your project is large and performance heavy, this might be a way.

I wouldn't say any solution is the best or the worst for solving your problem. It always depends on the context.


问:
Looking for an efficient way of making a new data frame of totals across categories in R
Total R beginner here, looking for the quickest / most sensible way to do this:

I have a data frame that looks similar to this (but much longer):

dataframe:

date
a
b
c

1/1/2021
4
3
2

1/2/2021
2
2
1

1/3/2021
5
3
5

I am attempting to create a new data frame showing totals for a, b, and c (which go on for a while), and don't need the dates. I want to make a data frame that would look this:

letter
total

a
11

b
8

c
8

So far, the closest I have got to this is by writing a pipe like this:

```<code>dataframe <- totals %>%
   summarize(total_a = sum(a), total_b = sum(b), total_c = sum(c))
</code>```

which almost gives me what I want, a data frame that looks like this:
|a|b|c|
|:-:|:-:|:-:|
|11|8|8|

Is there a way (besides manually typing out a new data frame for totals) to quickly turn my totals table into the format I'm looking for? Or is there a better way to write the pipe that will give me the table I want? I want to use these totals to make a pie chart but am running into problems when I attempt to make a pie chart out of the table like I have it now. I really appreciate any help in advance and hope I was able to explain what I'm trying to do correctly.

答:
One efficient way is to use colSums from base R, where we get the sums of each column, excluding the date column (hence the reason for the -1 in df[,1]. Then, I use stack to put into long format. The [,2:1] is just changing the order of the column output, so that letter is first and total is second. I wrap this in setNames to rename the column names.

```<code>setNames(nm=c("letter", "total"),stack(colSums(df[,-1]))[,2:1])

  letter total
1      a    11
2      b     8
3      c     8
</code>```

Or with tidyverse, we can get the sum of every column, except for date. Then, we can put it into long format using pivot_longer.

```<code>df %>%
  summarise(across(-date, sum)) %>%
  pivot_longer(everything(), names_to = "letter", values_to = "total")
</code>```

Or another option using data.table:

```<code>library(data.table)
dt <- as.data.table(df)

melt(dt[,-1][, lapply(.SD, sum)], id.vars=integer(), variable.name = "letter", value.name = "total")
</code>```

Data

```<code>df <- structure(list(date = c("1/1/2021", "1/2/2021", "1/3/2021"),
                     a = c(4L, 2L, 5L), b = c(3L, 2L, 3L), c = c(2L, 1L, 5L)),
                class = "data.frame", row.names = c(NA, -3L))
</code>```

Body:
Total R beginner here, looking for the quickest / most sensible way to do this:

I have a data frame that looks similar to this (but much longer):

dataframe:

date
a
b
c

1/1/2021
4
3
2

1/2/2021
2
2
1

1/3/2021
5
3
5

I am attempting to create a new data frame showing totals for a, b, and c (which go on for a while), and don't need the dates. I want to make a data frame that would look this:

letter
total

a
11

b
8

c
8

So far, the closest I have got to this is by writing a pipe like this:

dataframe <- totals %>%
   summarize(total_a = sum(a), total_b = sum(b), total_c = sum(c))

which almost gives me what I want, a data frame that looks like this:
|a|b|c|
|:-:|:-:|:-:|
|11|8|8|

Is there a way (besides manually typing out a new data frame for totals) to quickly turn my totals table into the format I'm looking for? Or is there a better way to write the pipe that will give me the table I want? I want to use these totals to make a pie chart but am running into problems when I attempt to make a pie chart out of the table like I have it now. I really appreciate any help in advance and hope I was able to explain what I'm trying to do correctly.

Body:
One efficient way is to use colSums from base R, where we get the sums of each column, excluding the date column (hence the reason for the -1 in df[,1]. Then, I use stack to put into long format. The [,2:1] is just changing the order of the column output, so that letter is first and total is second. I wrap this in setNames to rename the column names.

setNames(nm=c("letter", "total"),stack(colSums(df[,-1]))[,2:1])

  letter total
1      a    11
2      b     8
3      c     8

Or with tidyverse, we can get the sum of every column, except for date. Then, we can put it into long format using pivot_longer.

df %>%
  summarise(across(-date, sum)) %>%
  pivot_longer(everything(), names_to = "letter", values_to = "total")

Or another option using data.table:

library(data.table)
dt <- as.data.table(df)

melt(dt[,-1][, lapply(.SD, sum)], id.vars=integer(), variable.name = "letter", value.name = "total")

Data

df <- structure(list(date = c("1/1/2021", "1/2/2021", "1/3/2021"),
                     a = c(4L, 2L, 5L), b = c(3L, 2L, 3L), c = c(2L, 1L, 5L)),
                class = "data.frame", row.names = c(NA, -3L))


问:
What is wrong in this Spring Security configuration? How can I make an endpoint accessible to users having different authorities?
I am working on a Spring Boot protecting my APIs using Spring Security and JWT tokens and I have the following iusse.

I have an API handling endpoint like this: http://localhost:8019/api/admin/user/54/wallet

I have 2 user types:

ADMIN USER: having ADMIN autority  defined into the JWT tokend.

CLIENT USER: having CLIENT autority  defined into the JWT tokend.

The previous API must be accessible by both the user types (I know that the /admin/ section in the URI is not the best...it will be refactored in the near future).

Then I have this class extending the Spring Boot WebSecurityConfigurerAdapter class and implementing my security configuration:

```<code>@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("customUserDetailsService")
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtConfig jwtConfig;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    private static final String[] USER_MATCHER = { "/api/user/email/**"};

    private static final String[] CLIENT_MATCHER = {

                                                        "/api/users/email/*",
                                                        //"/api/admin/**",
                                                        "/api/admin/user/{userID}/wallet"
                                                    };

    private static final String[] ADMIN_MATCHER = {
                                                        "/api/users/email/**",
                                                        "/api/admin/users",
                                                        "/api/admin/user/{userID}/wallet",
                                                        "/api/admin/**"

                                                   };

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception
    {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        /*
         * NOTE:
         * Using hasRole expects the authority names to start with 'ROLE_' prefix
         * Instead, we use hasAuthority as we can use the names as it is
         */
        http.csrf().disable()
                   .authorizeRequests()

                   .antMatchers(USER_MATCHER).hasAnyAuthority("USER")
                   .antMatchers(CLIENT_MATCHER).hasAnyAuthority("CLIENT")
                   .antMatchers(ADMIN_MATCHER).hasAnyAuthority("ADMIN")
                   //.antMatchers(CLIENT_MATCHER).hasAnyAuthority("CLIENT")
                   .antMatchers("/api/users/test").authenticated()
                   .antMatchers(HttpMethod.POST, jwtConfig.getUri()).permitAll()
                   .anyRequest().denyAll()
                   .and()
                   .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(
            new TokenVerificationFilter(authenticationManager(), jwtConfig, jwtTokenUtil),UsernamePasswordAuthenticationFilter.class);
    }

    /* To allow Pre-flight [OPTIONS] request from browser */
    @Override
    public void configure(WebSecurity web)
    {
        web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
        web.ignoring().antMatchers("/swagger-ui/**",
                                    "/webjars/**",
                                    "/v2/**",
                                    "/swagger-resources/**",
                                    "/swagger-ui.html");
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder()
    {
        return new BCryptPasswordEncoder();
    };

}
</code>```

The problem is that as it is defined in the previous configuration if I try to call the previous API (http://localhost:8019/api/admin/user/54/wallet) with a token related to an user having the CLIENT autority I am obtaining this error message:

```<code>{
    "timestamp": "2022-02-13T20:22:10.418+00:00",
    "status": 403,
    "error": "Forbidden",
    "message": "Forbidden",
    "path": "/api/admin/user/54/wallet"
}
</code>```

Viceversa if I try to call the previous API passing a token of an user having the AMDIN authority I obtain the expected API output.

It seems pretty strange to me because into the CLIENT_MATCHER I have defined this rule:

```<code>"/api/admin/user/{userID}/wallet"
</code>```

The strangest thing is that if I remove this line from the ADMIN_MATCHER:

```<code>"/api/admin/user/{userID}/wallet",
</code>```

that become something like:

```<code>private static final String[] ADMIN_MATCHER = {
                                                    "/api/users/email/**",
                                                    "/api/admin/users",
                                                    //"/api/admin/user/{userID}/wallet",
                                                    "/api/admin/**"
                                                    }
</code>```

Now the behavior is the complete opposite: using a JWT token of an user having the CLIENT authority I retrieve the expected output, but now using a JWT token of an user having the ADMIN authoruty I obtain this error message:

{
"timestamp": "2022-02-13T20:27:47.793+00:00",
"status": 403,
"error": "Forbidden",
"message": "Forbidden",
"path": "/api/admin/user/54/wallet"
}

and this seems pretty strange to me because the ADMIN_MATCHER contaisn this rule:

```<code>"/api/admin/**"
</code>```

that should meaning: access to all the API having an enptoint starting with "/api/admin/" folloed by anything else.

What is wrong in my Spring configuration? What am I missing? How can I fix it in such a way that this API could be accessible using a JWT token having ADMIN or CLIENT authority?

答:
The problem is the way you have written your rules. The rule that matches is the one that is used so if a request comes in and it finds "/api/user/email/**" it will find the first that matches, the one for USER.

What you should write is .antMatchers("/api/user/email/**").hasAnyAuthority("USER", "CLIENT", "ADMIN") to allow all of them access. That is your security rule, it will not go over all rules it will detect the one that matches first (which also means that ordering is very important for your rules!).

This applies to all your other rules as well BTW.

Body:
I am working on a Spring Boot protecting my APIs using Spring Security and JWT tokens and I have the following iusse.

I have an API handling endpoint like this: http://localhost:8019/api/admin/user/54/wallet

I have 2 user types:

ADMIN USER: having ADMIN autority  defined into the JWT tokend.

CLIENT USER: having CLIENT autority  defined into the JWT tokend.

The previous API must be accessible by both the user types (I know that the /admin/ section in the URI is not the best...it will be refactored in the near future).

Then I have this class extending the Spring Boot WebSecurityConfigurerAdapter class and implementing my security configuration:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("customUserDetailsService")
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtConfig jwtConfig;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    private static final String[] USER_MATCHER = { "/api/user/email/**"};

    private static final String[] CLIENT_MATCHER = {

                                                        "/api/users/email/*",
                                                        //"/api/admin/**",
                                                        "/api/admin/user/{userID}/wallet"
                                                    };

    private static final String[] ADMIN_MATCHER = {
                                                        "/api/users/email/**",
                                                        "/api/admin/users",
                                                        "/api/admin/user/{userID}/wallet",
                                                        "/api/admin/**"

                                                   };

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception
    {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        /*
         * NOTE:
         * Using hasRole expects the authority names to start with 'ROLE_' prefix
         * Instead, we use hasAuthority as we can use the names as it is
         */
        http.csrf().disable()
                   .authorizeRequests()

                   .antMatchers(USER_MATCHER).hasAnyAuthority("USER")
                   .antMatchers(CLIENT_MATCHER).hasAnyAuthority("CLIENT")
                   .antMatchers(ADMIN_MATCHER).hasAnyAuthority("ADMIN")
                   //.antMatchers(CLIENT_MATCHER).hasAnyAuthority("CLIENT")
                   .antMatchers("/api/users/test").authenticated()
                   .antMatchers(HttpMethod.POST, jwtConfig.getUri()).permitAll()
                   .anyRequest().denyAll()
                   .and()
                   .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(
            new TokenVerificationFilter(authenticationManager(), jwtConfig, jwtTokenUtil),UsernamePasswordAuthenticationFilter.class);
    }

    /* To allow Pre-flight [OPTIONS] request from browser */
    @Override
    public void configure(WebSecurity web)
    {
        web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
        web.ignoring().antMatchers("/swagger-ui/**",
                                    "/webjars/**",
                                    "/v2/**",
                                    "/swagger-resources/**",
                                    "/swagger-ui.html");
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder()
    {
        return new BCryptPasswordEncoder();
    };

}

The problem is that as it is defined in the previous configuration if I try to call the previous API (http://localhost:8019/api/admin/user/54/wallet) with a token related to an user having the CLIENT autority I am obtaining this error message:

{
    "timestamp": "2022-02-13T20:22:10.418+00:00",
    "status": 403,
    "error": "Forbidden",
    "message": "Forbidden",
    "path": "/api/admin/user/54/wallet"
}

Viceversa if I try to call the previous API passing a token of an user having the AMDIN authority I obtain the expected API output.

It seems pretty strange to me because into the CLIENT_MATCHER I have defined this rule:

"/api/admin/user/{userID}/wallet"

The strangest thing is that if I remove this line from the ADMIN_MATCHER:

"/api/admin/user/{userID}/wallet",

that become something like:

private static final String[] ADMIN_MATCHER = {
                                                    "/api/users/email/**",
                                                    "/api/admin/users",
                                                    //"/api/admin/user/{userID}/wallet",
                                                    "/api/admin/**"
                                                    }

Now the behavior is the complete opposite: using a JWT token of an user having the CLIENT authority I retrieve the expected output, but now using a JWT token of an user having the ADMIN authoruty I obtain this error message:

{
"timestamp": "2022-02-13T20:27:47.793+00:00",
"status": 403,
"error": "Forbidden",
"message": "Forbidden",
"path": "/api/admin/user/54/wallet"
}

and this seems pretty strange to me because the ADMIN_MATCHER contaisn this rule:

"/api/admin/**"

that should meaning: access to all the API having an enptoint starting with "/api/admin/" folloed by anything else.

What is wrong in my Spring configuration? What am I missing? How can I fix it in such a way that this API could be accessible using a JWT token having ADMIN or CLIENT authority?


问:
How to generate quality windows icons with images of capital letters inside using Python?
I want to get 26 files (for starters): A.ico, B.ico, ... Z.ico, where they are composed of 16x16 256-color image, and a 32x32 256-color image, where the color of the text is black, and the font is ... say Calibri, and the size - whatever fits best into the square. I would like to do this using Python Image Library if possible.

I know that I can probably get my icons through other means, but I would like to learn to use the PIL better, and would like to use it for the task at hand.

答: Start with a large blank image and draw the character on the center of it. Find the edges of the character and extract a square from the image that includes all of the character. Use the thumbnail function with the ANTIALIAS option to reduce it to the 16x16 or 32x32 size required. Then reduce the number of colors to 256: How to reduce color palette with PIL


问:
Need to access Firefox browser in remote machine connected using Open Connection in Robot Testcase
Problem statement is:
Execute Robothost Testcase -> used Open Connection keyword to connect to machineX. used Open Browser keyword to open Firefox of machineX.
But instead of opening firefox browser of machineX, browser from Robothost is opening from where testcase is getting executed.
But my testcase execution needs to be done on webpage opened in machineX only.

Since used Open Browser after connecting to remote machine, expecting browser of remote machine to be active. verified that connectivity to remote machine is active.

Below is sample code tried to open browser from machineX

```<code>*** Testcases ***
LaunchBrowser
    Open Connection    ${machineX}
    Sleep    5s
    Open Browser    ${base_url}
    Sleep    5s
    Input Text    //input[@id="normal_login_username"]    admin
    Input Text    //input[@id="normal_login_password"]    admin
    Click Element    //button
    Sleep    5s
    Capture page screenshot    filename=output5g.png
    Close Browser
</code>```

Any suggestions to handle this scenario

答:
This is not how the ssh library works, in order to execute something on the machine x you need to use ssh library keywords. The selenium library will be executed on your machine.
You can install robot framework on machine x and execute the test there. Otherwise you cannot use ssh library. You can trigger the test from your machine if you have to do this remotely.</p>

Body:
Problem statement is:
Execute Robothost Testcase -> used Open Connection keyword to connect to machineX. used Open Browser keyword to open Firefox of machineX.
But instead of opening firefox browser of machineX, browser from Robothost is opening from where testcase is getting executed.
But my testcase execution needs to be done on webpage opened in machineX only.

Since used Open Browser after connecting to remote machine, expecting browser of remote machine to be active. verified that connectivity to remote machine is active.

Below is sample code tried to open browser from machineX

*** Testcases ***
LaunchBrowser
    Open Connection    ${machineX}
    Sleep    5s
    Open Browser    ${base_url}
    Sleep    5s
    Input Text    //input[@id="normal_login_username"]    admin
    Input Text    //input[@id="normal_login_password"]    admin
    Click Element    //button
    Sleep    5s
    Capture page screenshot    filename=output5g.png
    Close Browser

Any suggestions to handle this scenario


问:
Possible to get queryset from list of queryset -Django
I wanted to take queryset from multiple models. I am trying to achieve multiple search with and condition.
views.py,

```<code>def list(self, request, *args, **kwargs):
        search_query = self.request.query_params.get('search')
        split_query = search_query.split()
        employment = None
        employee1 = []
        employment1 = []
        for query in split_query:
            print("hi", query)
        # query = self.request.query_params.get('search')
            employee = PositionFulfillment.objects.filter(
                Q(employment__employee__code__icontains=query) |
                Q(employment__employee__person__name__icontains=query) |
                Q(employment__employee__person__surname__icontains=query)
            )
            # emp = list(chain(employee))
            employee1.append(employee)
            print("employee", employee1)
            active_employee = PositionFulfillment.objects.filter(primary_flag=True, thru_date=None)
            if active_employee:
                employment = active_employee.filter(
                    Q(position__position_type__name__icontains=query) |
                    Q(employment__organization__name__icontains=query) |
                    Q(employment__status__status__employment_status__icontains=query)
                )
            employment1.append(employment)
        all_results = list(chain(map(lambda x: x, employee1), map(lambda y: y, employment1)))
        # all_results = list(chain(employee, employment))
        print("all_results", all_results)
        serializer = EmployeeSearchSerializer(all_results)

        return Response(serializer.data, status=status.HTTP_200_OK)
</code>```

I have got output like below,

```<code>all_results,
[<QuerySet [<PositionFulfillment: 27>, <PositionFulfillment: 29>, <PositionFulfillment: 30>]>, <QuerySet []>, <QuerySet []>, <QuerySet [<PositionFulfillment: 28>]>]

Expected output,
 [<PositionFulfillment: 27>, <PositionFulfillment: 29>, <PositionFulfillment: 30>]> ,<QuerySet [<PositionFulfillment: 28>]>]
</code>```

How can i achieve this???

答:
You can add conditions to the query instead of creating new queries:</p>
```<code>def list(self, request, *args, **kwargs):
        search_query = self.request.query_params.get('search')
        split_query = search_query.split()

        q = None  # this is filter
        for query in split_query:
            print("hi", query)
            if q is None:
                q = Q(employment__employee__code__icontains=query)
            else:
                q.add(Q(employment__employee__code__icontains=query), Q.OR)

            q.add(Q(employment__employee__person__name__icontains=query), Q.OR)
            q.add(Q(employment__employee__person__surname__icontains=query), Q.OR)

            # same for active_employee

        # make only one query based on all conditions in q
        all_results = PositionFulfillment.objects.filter(q)
        print("all_results", all_results)
        serializer = EmployeeSearchSerializer(all_results)

        return Response(serializer.data, status=status.HTTP_200_OK)
</code>```

Body:
I wanted to take queryset from multiple models. I am trying to achieve multiple search with and condition.
views.py,

def list(self, request, *args, **kwargs):
        search_query = self.request.query_params.get('search')
        split_query = search_query.split()
        employment = None
        employee1 = []
        employment1 = []
        for query in split_query:
            print("hi", query)
        # query = self.request.query_params.get('search')
            employee = PositionFulfillment.objects.filter(
                Q(employment__employee__code__icontains=query) |
                Q(employment__employee__person__name__icontains=query) |
                Q(employment__employee__person__surname__icontains=query)
            )
            # emp = list(chain(employee))
            employee1.append(employee)
            print("employee", employee1)
            active_employee = PositionFulfillment.objects.filter(primary_flag=True, thru_date=None)
            if active_employee:
                employment = active_employee.filter(
                    Q(position__position_type__name__icontains=query) |
                    Q(employment__organization__name__icontains=query) |
                    Q(employment__status__status__employment_status__icontains=query)
                )
            employment1.append(employment)
        all_results = list(chain(map(lambda x: x, employee1), map(lambda y: y, employment1)))
        # all_results = list(chain(employee, employment))
        print("all_results", all_results)
        serializer = EmployeeSearchSerializer(all_results)

        return Response(serializer.data, status=status.HTTP_200_OK)

I have got output like below,

all_results,
[<QuerySet [<PositionFulfillment: 27>, <PositionFulfillment: 29>, <PositionFulfillment: 30>]>, <QuerySet []>, <QuerySet []>, <QuerySet [<PositionFulfillment: 28>]>]

Expected output,
 [<PositionFulfillment: 27>, <PositionFulfillment: 29>, <PositionFulfillment: 30>]> ,<QuerySet [<PositionFulfillment: 28>]>]

How can i achieve this???

Body:
You can add conditions to the query instead of creating new queries:

def list(self, request, *args, **kwargs):
        search_query = self.request.query_params.get('search')
        split_query = search_query.split()

        q = None  # this is filter
        for query in split_query:
            print("hi", query)
            if q is None:
                q = Q(employment__employee__code__icontains=query)
            else:
                q.add(Q(employment__employee__code__icontains=query), Q.OR)

            q.add(Q(employment__employee__person__name__icontains=query), Q.OR)
            q.add(Q(employment__employee__person__surname__icontains=query), Q.OR)

            # same for active_employee

        # make only one query based on all conditions in q
        all_results = PositionFulfillment.objects.filter(q)
        print("all_results", all_results)
        serializer = EmployeeSearchSerializer(all_results)

        return Response(serializer.data, status=status.HTTP_200_OK)


问:
How to resolve "Missing PendingIntent mutability flag" lint warning in android api 30+?
As soon as I updated the target SDK to 30+ (Android R or later), a lint warning Missing PendingIntent mutability flag appeared on my PendingIntent.FLAG_UPDATE_CURRENT flag when I want to define PendingIntent.

How should I handle this lint with no effect on the app functionality?

答:
If your app is targeting Android 12 (targetSdkVersion = 31), and uses an older version of the WorkManager directly OR by any of the third-party libraries then you require to update it to the latest to resolve it.

```<code>dependencies {
    val work_version = "2.8.1"

    // (Java only)
    implementation("androidx.work:work-runtime:$work_version")

    // Kotlin + coroutines
    implementation("androidx.work:work-runtime-ktx:$work_version")

    // optional - RxJava2 support
    implementation("androidx.work:work-rxjava2:$work_version")
}
</code>```

Body:
If your app is targeting Android 12 (targetSdkVersion = 31), and uses an older version of the WorkManager directly OR by any of the third-party libraries then you require to update it to the latest to resolve it.

dependencies {
    val work_version = "2.8.1"

    // (Java only)
    implementation("androidx.work:work-runtime:$work_version")

    // Kotlin + coroutines
    implementation("androidx.work:work-runtime-ktx:$work_version")

    // optional - RxJava2 support
    implementation("androidx.work:work-rxjava2:$work_version")
}


问:
Using Generics in C# to compare conditionally
In my scenario, I have two types of objects. A plan and a tier. Each one shares certain values, while the tier has 3 additional values (Rate, Min, and Max).

I would like to make a generic method to conditionally evaluate whether or not the new object can be written to the database, based on the following conditions:

Creation:

A tier: ((o1.Rate!=o2.Rate) || ((o1.Start!=o2.Start) && (o1.End!=o2.End))) && (MinVal && MaxVal)

A tier or plan: (o1.Name!=o2.Name)

A tier or plan: Only one can have (Active == true), the rest must be false.

Is it possible to create a generic method for something like this? If so, are there any examples of something like this? Or does anyone have suggestions?

thanks!

MORE:
So I have a list of objects, and I need to compare a newly created one with each other object in the database before I actually write it to the database.

答:
I am really not sure what the question is... but if all this is some sort of "pre-check" before it gets created in the database I usually resort to a stored procedure in the database which takes alle relevant params for creation and return a primary key or when it fails an error code... in case of success then load with the primary key the created object from database...

The database is usually very efficient on such comparisons - and if I ever need to run multiple instances of the program in parallel and/or create objects independently from different programs the database solution takes care of it...

EDIT - as per comment/request:

I usually work with Oracle so I don't have any SQL Server Stored procedure at hand... but these links should provide some insight:

https://web.archive.org/web/20211020103538/https://www.4guysfromrolla.com/webtech/tips/t100901-1.shtml

http://www.developerfusion.com/samplechapter/91/stored-procedures/4/

http://msdn.microsoft.com/en-us/library/ms187926.aspx

http://msdn.microsoft.com/en-us/library/ms187004.aspx

http://msdn.microsoft.com/en-us/library/ms190778.aspx


问:
Finding Number of pages from the total number of digits used to number the pages
I am stuck in a problem where the user inputs the total number of digits used in numbering the pages and the program gives the total number of pages in the book.

(i.e. a book of 10 pages needs 11 digits to number because the numbers 1-9 are written with one digit and the number 10 is written with two digits; an 11 pages book requires 13 digits ...).

I tried it by using a while loop but it does not run as it exceeds the execution time.

My C code looks like this:

```<code>#include <stdio.h>

int main() {
    int n, pages = 9;
    scanf("%d", &n);

    if (n <= 9) {
        printf("%d",n);
    }
    else if (n % 2 == 0) {
        printf("Invalid input");
    }
    else {
        while (n < 9) {
            pages++;
            n -= 2;
        }
    }
    return 0;
}
</code>```

Can anyone please help me with this problem?

答:
Consider using successive tests like this:

if the number <= 9, the number of pages is number, else set pages = 9 and subtract 9 from number.

if the number <= 90 * 2, the number of pages is pages + number / 2, else set pages += 90 and subtract 90 * 2 from number.

if the number <= 900 * 3, the number of pages is pages + number / 3, else set pages += 900 and subtract 900 * 3 from number.

etc.

You can write a loop to solve the problem without making an assumption on the range of the type used to store number and pages.

```<code>int number_of_pages(int number_of_digits) {
    int n1 = 9, n2 = 1, pages = 0;
    while (number / n2 > n1) {
        pages += n1;
        number -= n1 * n2;
        n1 *= 10;
        n2 += 1;
    }
    return pages + number / n2;
}
</code>```

Body:
I am stuck in a problem where the user inputs the total number of digits used in numbering the pages and the program gives the total number of pages in the book.

(i.e. a book of 10 pages needs 11 digits to number because the numbers 1-9 are written with one digit and the number 10 is written with two digits; an 11 pages book requires 13 digits ...).

I tried it by using a while loop but it does not run as it exceeds the execution time.

My C code looks like this:

#include <stdio.h>

int main() {
    int n, pages = 9;
    scanf("%d", &n);

    if (n <= 9) {
        printf("%d",n);
    }
    else if (n % 2 == 0) {
        printf("Invalid input");
    }
    else {
        while (n < 9) {
            pages++;
            n -= 2;
        }
    }
    return 0;
}

Can anyone please help me with this problem?

Body:
Consider using successive tests like this:

if the number <= 9, the number of pages is number, else set pages = 9 and subtract 9 from number.

if the number <= 90 * 2, the number of pages is pages + number / 2, else set pages += 90 and subtract 90 * 2 from number.

if the number <= 900 * 3, the number of pages is pages + number / 3, else set pages += 900 and subtract 900 * 3 from number.

etc.

You can write a loop to solve the problem without making an assumption on the range of the type used to store number and pages.

int number_of_pages(int number_of_digits) {
    int n1 = 9, n2 = 1, pages = 0;
    while (number / n2 > n1) {
        pages += n1;
        number -= n1 * n2;
        n1 *= 10;
        n2 += 1;
    }
    return pages + number / n2;
}


问:
How to run "az deployment group" command with serviceprincipal
As part of automating alert creation in Loganalytic workspace,We are using AzureDevops Server and looking for a way to run az deployment group command in Azuredevops pipeline. We have a working pipeline to execute the  ADO tasks in Subscription-A like AzureCLI and AzureResourceGroupDeployment using the predefined serviceconnection configured with the service principal{SP-A} which is having required access on Subscripion A and it is working as expected.

Now we got the requirement to execute same pipeline to Subscription B, where the current used servicePrincipal SP-A does not have subscription level access. So we are blocked with the further steps as we are only allowed to get the specific access (like create or modify alert rule in LAW- Microsoft.Insights/ScheduledQueryRules/[Read, Write, Delete] )  for the SP-A to create the alert rules in Loganalyticworkspace of subscription B.

So we are looking for guidance on below things.

Is it possible to configure a service connection to Subscription B using the same SP-A that only has the Microsoft.Insights/ScheduledQueryRules/[Read, Write, Delete]  permission on the LAW, and not having any access to subscription B or resource group of LAW-B

If the above method will not work, is there any way to run az group deploy commands with service Pricipal credentails by adding in to the command as paramaters.

The working ADO tasks for subs A is as follows and looking for a solution if we can use same for Sub B

```<code>- task: AzureCLI@2
  displayName: "verify the deployment changes"
  inputs:
    azureSubscription: ${{ parameters.subscription }}
    scriptType: 'bash'
    scriptLocation: 'inlineScript'
    inlineScript: 'az deployment group what-if --resource-group ${{ parameters.resourceGroup }} --template-file $(System.DefaultWorkingDirectory)/template.json --parameters $(System.DefaultWorkingDirectory)/param.json'
- task: AzureResourceGroupDeployment@2
  inputs:
    azureSubscription: ${{ parameters.subscription }}
    action: 'Create Or Update Resource Group'
    resourceGroupName: ${{ parameters.resourceGroup }}
    location: ${{ parameters.region }}
    templateLocation: 'Linked artifact'
    csmFile: '$(System.DefaultWorkingDirectory)/template.json'
    csmParametersFile: '$(System.DefaultWorkingDirectory)/param.json'
    deploymentMode: 'Incremental'
</code>```

答:
Is it possible to configure a service connection to Subscription B
using the same SP-A that only has the
Microsoft.Insights/ScheduledQueryRules/[Read, Write, Delete]
permission on the LAW, and not having any access to subscription B or
resource group of LAW-B

It will be not possible as you will be creating custom role with only Microsoft.Insights/ScheduledQueryRules/* which is required for managing/creating Scheduled Query Alerts but for the service account to find the LAW and Deploy the Alerts using the resource group deployment will at least require read permission on subscription or resource group  and Microsoft/Resources/deployments/* to create deployments.

You can check these built-in roles for Azure Monitor.

Body:
As part of automating alert creation in Loganalytic workspace,We are using AzureDevops Server and looking for a way to run az deployment group command in Azuredevops pipeline. We have a working pipeline to execute the  ADO tasks in Subscription-A like AzureCLI and AzureResourceGroupDeployment using the predefined serviceconnection configured with the service principal{SP-A} which is having required access on Subscripion A and it is working as expected.

Now we got the requirement to execute same pipeline to Subscription B, where the current used servicePrincipal SP-A does not have subscription level access. So we are blocked with the further steps as we are only allowed to get the specific access (like create or modify alert rule in LAW- Microsoft.Insights/ScheduledQueryRules/[Read, Write, Delete] )  for the SP-A to create the alert rules in Loganalyticworkspace of subscription B.

So we are looking for guidance on below things.

Is it possible to configure a service connection to Subscription B using the same SP-A that only has the Microsoft.Insights/ScheduledQueryRules/[Read, Write, Delete]  permission on the LAW, and not having any access to subscription B or resource group of LAW-B

If the above method will not work, is there any way to run az group deploy commands with service Pricipal credentails by adding in to the command as paramaters.

The working ADO tasks for subs A is as follows and looking for a solution if we can use same for Sub B

- task: AzureCLI@2
  displayName: "verify the deployment changes"
  inputs:
    azureSubscription: ${{ parameters.subscription }}
    scriptType: 'bash'
    scriptLocation: 'inlineScript'
    inlineScript: 'az deployment group what-if --resource-group ${{ parameters.resourceGroup }} --template-file $(System.DefaultWorkingDirectory)/template.json --parameters $(System.DefaultWorkingDirectory)/param.json'
- task: AzureResourceGroupDeployment@2
  inputs:
    azureSubscription: ${{ parameters.subscription }}
    action: 'Create Or Update Resource Group'
    resourceGroupName: ${{ parameters.resourceGroup }}
    location: ${{ parameters.region }}
    templateLocation: 'Linked artifact'
    csmFile: '$(System.DefaultWorkingDirectory)/template.json'
    csmParametersFile: '$(System.DefaultWorkingDirectory)/param.json'
    deploymentMode: 'Incremental'


问:
Polars: Specify dtypes for all columns at once in read_csv
In Polars, how can one specify a single dtype for all columns in read_csv?

According to the docs, the dtypes argument to read_csv can take either a mapping (dict) in the form of {'column_name': dtype}, or a list of dtypes, one for each column.
However, it is not clear how to specify "I want all columns to be a single dtype".

If you wanted all columns to be Utf-8 for example and you knew the total number of columns, you could do:

pl.read_csv('sample.csv', dtypes=[pl.Utf8]*number_of_columns)
```
<p>However, this doesn't work if you don't know the total number of columns.
In Pandas, you could do something like:</p>
<pre class="lang-py prettyprint-override"><code>pd.read_csv('sample.csv', dtype=str)
</code>```

But this doesn't work in Polars.

答:
Reading all data in a csv to any other type than pl.Utf8 likely fails with a lot of null values. We can use expressions to declare how we want to deal with those null values.

If you read a csv with infer_schema_length=0, polars does not know the schema and will read all columns as pl.Utf8 as that is a super type of all polars types.

When read as Utf8 we can use expressions to cast all columns.

(pl.read_csv("test.csv", infer_schema_length=0)
   .with_columns(pl.all().cast(pl.Int32, strict=False))
```

Body:
In Polars, how can one specify a single dtype for all columns in read_csv?

According to the docs, the dtypes argument to read_csv can take either a mapping (dict) in the form of {'column_name': dtype}, or a list of dtypes, one for each column.
However, it is not clear how to specify "I want all columns to be a single dtype".

If you wanted all columns to be Utf-8 for example and you knew the total number of columns, you could do:

pl.read_csv('sample.csv', dtypes=[pl.Utf8]*number_of_columns)

However, this doesn't work if you don't know the total number of columns.
In Pandas, you could do something like:

pd.read_csv('sample.csv', dtype=str)

But this doesn't work in Polars.


问:
How to turn off grid lines in Flex Spark DataGrid
Just as the title says, how can I turn off horizontal and vertical grid lines in a Flex Spark DataGrid?</p>

答: Create a new skin based on the original one and edit it to your liking. </p>


问:
populating a dataframe with value_counts()
I am looking to make a data frame with two columns. One is a list of numbers, and the other the frequency of occurrence of the first column. So far I have: imported the data, here is an example: should be a 3x6 dataframe.

2 8 13 15 60 67 23

13 25 45 67 68 6

2 8 13 15 61 29
....... so on.
I have separated the columns of this data to its own series.
firstRowtoSeires = fullNumbersFormated.loc[:,'first']
from there I get the column but, it's not labeled first. It looks like the 'first' is at the bottom of series. It shows the index and the number corresponding with the index.
example.

0      5

1     18

2     10

3      2

4      4

5     11

6      8

........

Name: first, dtype: int64

But I am looking to add a row that has the frequency of the numbers in a third( or second ) column. And to get the formatting of the column right, so the labels is at the top.
I'v also tried: countsForFirstRow = firstRowtoSeires.value_counts()

38    6

45    4

36    4

47    4

34    4

48    4

29    4

33    4

And get this. While this is almost right, I am unable to sort the numbers, it only sorts on the value counts. I feel like I can do everything but what I want with the data. I want to be able to sort the numbers not the value count numbers. And eventually make a 12 column data frame with the first, second, third, forth, fifth, sixth set of numbers with the value counts. I have also made my main data a NumPy array but don't know how to sperate the columns to get value counts for that, so I have stuck with pandas, but not afraid to try anything.

first number is the unique number

frequency of number showing in series

```<code>   8     8

   3     7

  10     7

   2     6

   1     6

  12     6
</code>```

The first column being the index. the second(first) being the unique number in that column. and the third being the frequency that number shows.

答:
You can use:</p>
```<code>for c in df.columns:
    df[f'new_{c}'] = df[c].map(df[c].value_counts())
</code>```

Body:
I am looking to make a data frame with two columns. One is a list of numbers, and the other the frequency of occurrence of the first column. So far I have: imported the data, here is an example: should be a 3x6 dataframe.

2 8 13 15 60 67 23

13 25 45 67 68 6

2 8 13 15 61 29
....... so on.
I have separated the columns of this data to its own series.
firstRowtoSeires = fullNumbersFormated.loc[:,'first']
from there I get the column but, it's not labeled first. It looks like the 'first' is at the bottom of series. It shows the index and the number corresponding with the index.
example.

0      5

1     18

2     10

3      2

4      4

5     11

6      8

........

Name: first, dtype: int64

But I am looking to add a row that has the frequency of the numbers in a third( or second ) column. And to get the formatting of the column right, so the labels is at the top.
I'v also tried: countsForFirstRow = firstRowtoSeires.value_counts()

38    6

45    4

36    4

47    4

34    4

48    4

29    4

33    4

And get this. While this is almost right, I am unable to sort the numbers, it only sorts on the value counts. I feel like I can do everything but what I want with the data. I want to be able to sort the numbers not the value count numbers. And eventually make a 12 column data frame with the first, second, third, forth, fifth, sixth set of numbers with the value counts. I have also made my main data a NumPy array but don't know how to sperate the columns to get value counts for that, so I have stuck with pandas, but not afraid to try anything.

first number is the unique number

frequency of number showing in series

   8     8

   3     7

  10     7

   2     6

   1     6

  12     6

The first column being the index. the second(first) being the unique number in that column. and the third being the frequency that number shows.

Body:
You can use:

for c in df.columns:
    df[f'new_{c}'] = df[c].map(df[c].value_counts())