问:
Uncaught (in promise) Error: Unexpected null value at Object.throw_ [as throw] (errors.dart:266:49) at Object.nullCheck (operations.dart:528:63)
Im Trying to use Shared Services (api_cache_manager packege) for storing login info and i'm attaching the images which will give you breif explanation of errors

This is the Error im getting
Im tring to use the api_cache_manager for getting the login details through my API as im getting full response from the api
enter image description here
This is my Shared services Class
Below is the Code for my LoginResponseModel

```<code>LoginResponseModel loginResponseJson(String str) =>
    LoginResponseModel.fromJson(json.decode(str));

class LoginResponseModel {
  late final String message;
  late final Data data;

  LoginResponseModel.fromJson(Map<String, dynamic> json) {
    message = json["message"];
    data = Data.fromJson(json["data"]);
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};

    _data['message'] = message;
    _data['data'] = data.toJson();

    return _data;
  }
}

class Data {
  late final String fullName;
  late final String email;
  late final String userId;
  late final String token;

  Data({
    required this.fullName,
    required this.email,
    required this.userId,
    required this.token,
  });

  Data.fromJson(Map<String, dynamic> json) {
    fullName = json["fullName"];
    email = json["email"];
    userId = json["userId"];
    token = json["token"];
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};

    _data['fullName'] = fullName;
    _data['email'] = email;
    _data['userId'] = userId;
    _data['token'] = token;
    return _data;
  }
}

</code>```

I have tried some of the solutions but it cant work as it shows the error again and again,
I'am running the flutter app on web

Body:
Im Trying to use Shared Services (api_cache_manager packege) for storing login info and i'm attaching the images which will give you breif explanation of errors

This is the Error im getting
Im tring to use the api_cache_manager for getting the login details through my API as im getting full response from the api
enter image description here
This is my Shared services Class
Below is the Code for my LoginResponseModel

LoginResponseModel loginResponseJson(String str) =>
    LoginResponseModel.fromJson(json.decode(str));

class LoginResponseModel {
  late final String message;
  late final Data data;

  LoginResponseModel.fromJson(Map<String, dynamic> json) {
    message = json["message"];
    data = Data.fromJson(json["data"]);
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};

    _data['message'] = message;
    _data['data'] = data.toJson();

    return _data;
  }
}

class Data {
  late final String fullName;
  late final String email;
  late final String userId;
  late final String token;

  Data({
    required this.fullName,
    required this.email,
    required this.userId,
    required this.token,
  });

  Data.fromJson(Map<String, dynamic> json) {
    fullName = json["fullName"];
    email = json["email"];
    userId = json["userId"];
    token = json["token"];
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};

    _data['fullName'] = fullName;
    _data['email'] = email;
    _data['userId'] = userId;
    _data['token'] = token;
    return _data;
  }
}

I have tried some of the solutions but it cant work as it shows the error again and again,
I'am running the flutter app on web


来源: stackexchange

问:
Store delegates C#
I have complex model which I build as collection in many of my endpoints. To make it more readable I decided to create easy builder to map specific properties.

So the response model I have is as below:

```<code>public class ResponseModel
{
   public string Prop1 {get; set;}
   public int Prop2 {get; set;}
   public decimal? Prop3{get; set;}
   //.. and so on
}
</code>```

Most of times I create above ResponseModel based on result returned from another web service like below:

```<code>public class ServiceResponse
{
   public string Prop1 {get; set;}
   public int Prop2 {get; set;}
   public decimal? Prop3{get; set;}
   //.. and so on
}
</code>```

So initial propose was to simply use LINQ and return result from endpoint as below:

```<code>return serviceResponse.Select(x => new ResponseModel
{
   Prop1 = x.Prop1
   Prop2 = x.Prop2 + some value
   Prop3 = x.Prop3 + some another value
}
</code>```

After some time it appeared that most of properties are similar and only for some there is manipulation needed which is not common for all others.
I came up with below class:

```<code>public class ResponseBuilder
    {
        private List<ServiceResponse> _response;

        private Func<ServiceResponse, string> _prop1;
        private Func<ServiceResponse, int> _prop2;
        private Func<ServiceResponse, decimal?> _prop3;

        public ResponseBuilder(List<ServiceResponse> serviceResponse)
        {
            _response = serviceResponse;
            //Default mappings
            _prop2 = item => item.Prop2;
        }

        public ResponseBuilder MapProp1(Func<ServiceResponse, string> fun) { _prop1 = fun; return this; }
        public ResponseBuilder MapProp2(Func<ServiceResponse, int> fun) { _prop2 = fun; return this; }
        public ResponseBuilder MapProp3(Func<ServiceResponse, decimal?> fun) { _prop3 = fun; return this; }

        //Other map or filter methods

        public List<ResponseModel> Build()
        {
            return _response.Select(x => new ResponseModel
            {
                Prop1 = _prop1(x),
                Prop2 = _prop2(x),
                Prop3 = _prop3(x)
                //and so on
            }).ToList();
        }
    }
</code>```

This is working well however I dont like having so much fields.
Is there an option without using reflection/casting to store these func in some collection? Or the thing what I did is not proper way to go and there are other common solutoins for such cases?

ContentLicense: CC BY-SA 4.0

Title: Store delegates C#

Body:
I have complex model which I build as collection in many of my endpoints. To make it more readable I decided to create easy builder to map specific properties.

So the response model I have is as below:

public class ResponseModel
{
   public string Prop1 {get; set;}
   public int Prop2 {get; set;}
   public decimal? Prop3{get; set;}
   //.. and so on
}

Most of times I create above ResponseModel based on result returned from another web service like below:

public class ServiceResponse
{
   public string Prop1 {get; set;}
   public int Prop2 {get; set;}
   public decimal? Prop3{get; set;}
   //.. and so on
}

So initial propose was to simply use LINQ and return result from endpoint as below:

return serviceResponse.Select(x => new ResponseModel
{
   Prop1 = x.Prop1
   Prop2 = x.Prop2 + some value
   Prop3 = x.Prop3 + some another value
}

After some time it appeared that most of properties are similar and only for some there is manipulation needed which is not common for all others.
I came up with below class:

public class ResponseBuilder
    {
        private List<ServiceResponse> _response;

        private Func<ServiceResponse, string> _prop1;
        private Func<ServiceResponse, int> _prop2;
        private Func<ServiceResponse, decimal?> _prop3;

        public ResponseBuilder(List<ServiceResponse> serviceResponse)
        {
            _response = serviceResponse;
            //Default mappings
            _prop2 = item => item.Prop2;
        }

        public ResponseBuilder MapProp1(Func<ServiceResponse, string> fun) { _prop1 = fun; return this; }
        public ResponseBuilder MapProp2(Func<ServiceResponse, int> fun) { _prop2 = fun; return this; }
        public ResponseBuilder MapProp3(Func<ServiceResponse, decimal?> fun) { _prop3 = fun; return this; }

        //Other map or filter methods

        public List<ResponseModel> Build()
        {
            return _response.Select(x => new ResponseModel
            {
                Prop1 = _prop1(x),
                Prop2 = _prop2(x),
                Prop3 = _prop3(x)
                //and so on
            }).ToList();
        }
    }

This is working well however I dont like having so much fields.
Is there an option without using reflection/casting to store these func in some collection? Or the thing what I did is not proper way to go and there are other common solutoins for such cases?


问:
Is there an option to define a total sum over uniformly distributed parameter in GAMS?
I am trying to compare some results of my model with a certain parameter to the results with a uniformly distributed parameter (parameter is the number of passengers traveling from node i to node j).
To make the objective function values comparable, I would like to ensure the same number of passengers (total number of passengers). Is there any way in GAMS to set the sum over the uniformly distributed parameter equal to a certain value?</p>


问:
How to use ValueResolver in another ValueResolver or chain ValueResolver with Symfony
I'm using Symfony 6.2 with php 8.1.

Since the update of SF 6.2 i had to remove SensioFrameworkExtraBundle and migrate my code from ParamConverter to new custom ValueResolver.

However, i'm facing a lack a feature from this migration or i miss something :(

With a custom ParamConverter, i could resolve a parameter and rewrite the new content in the Request. This allow me to chain any ParamConverter.
The new way with custom ValueResolver does not rewrite the content in the Request.
Of course i can force to rewrite the content or create a new attribute in the Request but i feel it's wrong or not proper way.

My use case :

The resolver for TranslationKey need the resolver result of TranslationDomain and TranslationLanguage.
basically i would like to chain these resolver or group them like we can do in form Constraint.

services.yaml

App\Service\\ranslation\Request\ValueResolver\TranslationLanguageValueResolver:
  tags:
    - { name: controller.argument_value_resolver, priority: 103 }

App\Service\Translation\Request\ValueResolver\\TranslationDomainValueResolver:
  tags:
    - { name: controller.argument_value_resolver, priority: 102 }

App\Service\Translation\Request\ValueResolver\TranslationKeyValueResolver:
  tags:
    - { name: controller.argument_value_resolver, priority: 101 }
```
<p>My controller :</p>
<pre class="lang-php prettyprint-override"><code>public function edit (Request             $request,
   TranslationLanguage $translationLanguage,
   TranslationDomain   $translationDomain,
   TranslationKey      $translationKey,
   TranslationHelper   $translationHelper,
   Translation         $translation): Response
{
    [some code]
}
</code>```

TranslationKeyValueResolver :

public function resolve (Request $request, ArgumentMetadata $argument): iterable
{
    $argumentType = $argument->getType();
 if (!$argumentType || !($argumentType === TranslationKey::class)) {
        return [];
   }

   $translationLanguage = $request->get('translationLanguage'); //=> does not return the object since it's not chained
    [some code]

    return [new TranslationKey($translationKey)];
}
```
<p>Before :</p>
<pre class="lang-php prettyprint-override"><code>    public function apply(Request $request, ParamConverter $configuration)
    {
        [some code]

        $request->attributes->set($configuration->getName(), new TranslationLanguage($languages));

        return true;
    }
</code>```

After :

public function resolve (Request $request, ArgumentMetadata $argument): iterable
{
    $argumentType = $argument->getType();
 if (!$argumentType || !($argumentType === TranslationLanguage::class)) {
        return [];
   }

    [some code]

 return [new TranslationLanguage($languages)];
}
```
<p>So, i tried to create a new attribute in Request with the new value, but it feel terribly wrong since it suppose all resolver has been executed before and in order. But it's working.</p>
<p>I though to revolve again TranslationLangage and TranslationDomain in TranslationKeyValueResolver but i don't know how, neither what tag i should set in that case ? Custom tag ?</p>
<pre class="lang-yaml prettyprint-override"><code>App\Service\Translation\Request\ValueResolver\TranslationKeyValueResolver:
  tags:
    - { name: controller.argument_value_resolver, priority: 101 }
    - { name: another_tag_to_resolve_argument_from_resolver, priority: 101 } ??
</code>```

Any idea please ?

Radyium
Thanks

Body:
I'm using Symfony 6.2 with php 8.1.

Since the update of SF 6.2 i had to remove SensioFrameworkExtraBundle and migrate my code from ParamConverter to new custom ValueResolver.

However, i'm facing a lack a feature from this migration or i miss something :(

With a custom ParamConverter, i could resolve a parameter and rewrite the new content in the Request. This allow me to chain any ParamConverter.
The new way with custom ValueResolver does not rewrite the content in the Request.
Of course i can force to rewrite the content or create a new attribute in the Request but i feel it's wrong or not proper way.

My use case :

The resolver for TranslationKey need the resolver result of TranslationDomain and TranslationLanguage.
basically i would like to chain these resolver or group them like we can do in form Constraint.

services.yaml

App\Service\\ranslation\Request\ValueResolver\TranslationLanguageValueResolver:
  tags:
    - { name: controller.argument_value_resolver, priority: 103 }

App\Service\Translation\Request\ValueResolver\\TranslationDomainValueResolver:
  tags:
    - { name: controller.argument_value_resolver, priority: 102 }

App\Service\Translation\Request\ValueResolver\TranslationKeyValueResolver:
  tags:
    - { name: controller.argument_value_resolver, priority: 101 }

My controller :

public function edit (Request             $request,
   TranslationLanguage $translationLanguage,
   TranslationDomain   $translationDomain,
   TranslationKey      $translationKey,
   TranslationHelper   $translationHelper,
   Translation         $translation): Response
{
    [some code]
}

TranslationKeyValueResolver :

public function resolve (Request $request, ArgumentMetadata $argument): iterable
{
    $argumentType = $argument->getType();
 if (!$argumentType || !($argumentType === TranslationKey::class)) {
        return [];
   }

   $translationLanguage = $request->get('translationLanguage'); //=> does not return the object since it's not chained
    [some code]

    return [new TranslationKey($translationKey)];
}

Before :

    public function apply(Request $request, ParamConverter $configuration)
    {
        [some code]

        $request->attributes->set($configuration->getName(), new TranslationLanguage($languages));

        return true;
    }

After :

public function resolve (Request $request, ArgumentMetadata $argument): iterable
{
    $argumentType = $argument->getType();
 if (!$argumentType || !($argumentType === TranslationLanguage::class)) {
        return [];
   }

    [some code]

 return [new TranslationLanguage($languages)];
}

So, i tried to create a new attribute in Request with the new value, but it feel terribly wrong since it suppose all resolver has been executed before and in order. But it's working.

I though to revolve again TranslationLangage and TranslationDomain in TranslationKeyValueResolver but i don't know how, neither what tag i should set in that case ? Custom tag ?

App\Service\Translation\Request\ValueResolver\TranslationKeyValueResolver:
  tags:
    - { name: controller.argument_value_resolver, priority: 101 }
    - { name: another_tag_to_resolve_argument_from_resolver, priority: 101 } ??

Any idea please ?

Radyium
Thanks


问:
Pandas nunique() and value_counts()
I'm doing a udemy course about Pandas, one exercise asks you to select the number of jobs mentioned once in the dataframe in the year 2013
(the dataframe contains employeename, year , salaries, job title, etc .. )
I used

```<code>sal[sal["Year"]==2013]["JobTitle"].nunique(dropna="True")
</code>```

the output was 1051
the solution used value_counts()==1

```<code>sum(sal[sal['Year']==2013]['JobTitle'].value_counts() == 1)
</code>```

the output is 202
If I got the basics right, I think the sum value_counts()==1 is the same as unique but I got different outputs
any help please and thanks!

```<code>sal[sal["Year"]==2013]["JobTitle"].nunique(dropna="True")
</code>```

Title: Pandas nunique() and value_counts()

Body:
I'm doing a udemy course about Pandas, one exercise asks you to select the number of jobs mentioned once in the dataframe in the year 2013
(the dataframe contains employeename, year , salaries, job title, etc .. )
I used

sal[sal["Year"]==2013]["JobTitle"].nunique(dropna="True")

the output was 1051
the solution used value_counts()==1

sum(sal[sal['Year']==2013]['JobTitle'].value_counts() == 1)

the output is 202
If I got the basics right, I think the sum value_counts()==1 is the same as unique but I got different outputs
any help please and thanks!

sal[sal["Year"]==2013]["JobTitle"].nunique(dropna="True")


问:
glassDialog.setCanceledOnTouchOutside(true) not work for Android
I have a class that extends : DialogFragment() so I need to make it close if I touch outside. I have tried this solutions but its not working. Please help me find the way to close it by clicking outside the window

How to dismiss a DialogFragment when pressing outside the dialog?

My code

```<code>override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    _binding = MyFragmentDialogBinding.inflate(
        LayoutInflater.from(requireContext()),
        activity?.window?.decorView as ViewGroup,
        false
    )
    val glassDialog = GlassDialog(requireActivity(), binding.root)
    glassDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    glassDialog.setCanceledOnTouchOutside(true)
    glassDialog.setCancelable(true)
    return glassDialog
}
</code>```

Body:
I have a class that extends : DialogFragment() so I need to make it close if I touch outside. I have tried this solutions but its not working. Please help me find the way to close it by clicking outside the window

How to dismiss a DialogFragment when pressing outside the dialog?

My code

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    _binding = MyFragmentDialogBinding.inflate(
        LayoutInflater.from(requireContext()),
        activity?.window?.decorView as ViewGroup,
        false
    )
    val glassDialog = GlassDialog(requireActivity(), binding.root)
    glassDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    glassDialog.setCanceledOnTouchOutside(true)
    glassDialog.setCancelable(true)
    return glassDialog
}


问:
How do I prevent a user from sharing their token?
Let's say I have implemented an authentication system to access a given resource. The user enters their username and password, maybe even a 2fa code and then they are given an access token that they send along with each request for that resource. Then when the user tries to access that resource the backend checks if that token is present, then valid and if it is both of these things it returns a response with no error.

How do I make sure that the user does not send their token out for anyone to use? If they do, then anyone will be able to access all of the content that this user can access as long as the token they have remains valid, without the need for them to know that user's password. I saw 1 company check if the IP address of the request if the same as the IP address used to generate a token, but that doesn't scale very well and if the user is using a mobile device and change networks their IP address will change and the token will be no longer valid.

Also with that approach a user might create a token while connected to a VPN and then tell the people that the user will share their token with, to connect to that same VPN when they're using that user's token. I saw many replies to that question, but none of them seem to given an actual answer.

The token I refer to here might be a JWT, or anything else - that's not really relevant in this case.

To be clear, I'm not strictly tring to prevent a third party to steal a user's token and then use it (that too of course), but rather I'm trying to prevent a user from willingly sharing their token with others.


问:
What is using disk space in my Aurora Postgres DB and how do I clear it?
The snapshots of my Aurora PostgreSQL 11.13 instance are 2054 GiB and the total pg_database_size of all databases therein is only 1902 GiB. What is causing the size discrepancy?

Observed: I note that the size continues to grow week over week even though the table sizes are generally not growing (they haven't been fully vacuumed and thus have plenty of free tuple space). I also noted that when I deleted or inserted millions of records that the snapshot sizes increase faster  while, again, table size remains constant.

Theories:

Could this be some kind of log for logical replication (WAL?) but I have those configuration settings turned off. I've confirmed that configuration is mostly the same as default settings.

Perhaps what I need to clear is in the rdsadmin database that is managed exclusively by Aurora?

I have some manual snapshots from ~2 years ago; in another S.O. question I read that these may prevent data from being removed in the live database?

Database has not been restarted in a few months; could this be the result of temporary files building up?


问:
Requesting Console input from a UserInputHandler that is running on a separate thread
I am working on a Chat application for a school project. According to the instructions,
the client should run 2 separate threads. One that checks for user input in the console (In my case the CLI class), and the other should handle incoming server messages (ServerResponseHandler class).

Example of the CLI run method:

```<code>@Override
public void run() {
    Scanner scanner = new Scanner(System.in);
    while (true) {
        String userInput = scanner.nextLine();
        //Handle input
    }
}
</code>```

Example of ResponseHandler.class

```<code>void onMessageReceived() {
    // Display incoming message to UI
    // Request user input;
    // Send input to Server;
}
</code>```

Now in some cases I want the ResponseHandler to be able to request user input, and handle it in a separate way, but the CLI is already blocking the input on the scanner.NextLine()

How can i best approach this problem?

Body:
I am working on a Chat application for a school project. According to the instructions,
the client should run 2 separate threads. One that checks for user input in the console (In my case the CLI class), and the other should handle incoming server messages (ServerResponseHandler class).

Example of the CLI run method:

@Override
public void run() {
    Scanner scanner = new Scanner(System.in);
    while (true) {
        String userInput = scanner.nextLine();
        //Handle input
    }
}

Example of ResponseHandler.class

void onMessageReceived() {
    // Display incoming message to UI
    // Request user input;
    // Send input to Server;
}

Now in some cases I want the ResponseHandler to be able to request user input, and handle it in a separate way, but the CLI is already blocking the input on the scanner.NextLine()

How can i best approach this problem?


问:
How can I implement a pagination Node.js code to front-end
In my web application , I'm using a database and this database includes project details. Using Node.js, I'm able to paginate those project objects. But I couldn't implement it with front-end side. (I'm using handlebars view engine.)

This is my node.js code and database implementation.

```<code>router.get("/proje_kutuphanesi", async function (req, res) {

  try {

    let sql = "select * from proje_detaylari"
    const allDB = (await db_projeler.execute(sql));
    const projeler_db = allDB[0];

    const page = parseInt(req.query.page) ;
    const limit = parseInt(req.query.limit) ;

    const startIndex = (page-1)*limit ;
    const endIndex = page*limit ;

    const results = {};

      if(endIndex<projeler_db.length){
        results.next = {

          page: page+1,
          limit : limit

        }

      }

    if(startIndex>0) {

      results.previous = {

        page:  page-1,
        limit : limit

      }

    }

    results.results = projeler_db.slice(startIndex,endIndex) ;

 //res.json(results);

    res.render("proje_kütüphanesi", {

      projeler: results

    });

  } catch (error) {

    console.log(error);

  }

});
</code>```

So I need a front-end design with handlebars and anchor tags.  It is like

previous 1 2 3 4 5 6 next

I appericiate for your help, struggling for hours.

Body:
In my web application , I'm using a database and this database includes project details. Using Node.js, I'm able to paginate those project objects. But I couldn't implement it with front-end side. (I'm using handlebars view engine.)

This is my node.js code and database implementation.

router.get("/proje_kutuphanesi", async function (req, res) {

  try {

    let sql = "select * from proje_detaylari"
    const allDB = (await db_projeler.execute(sql));
    const projeler_db = allDB[0];

    const page = parseInt(req.query.page) ;
    const limit = parseInt(req.query.limit) ;

    const startIndex = (page-1)*limit ;
    const endIndex = page*limit ;

    const results = {};

      if(endIndex<projeler_db.length){
        results.next = {

          page: page+1,
          limit : limit

        }

      }

    if(startIndex>0) {

      results.previous = {

        page:  page-1,
        limit : limit

      }

    }

    results.results = projeler_db.slice(startIndex,endIndex) ;

 //res.json(results);

    res.render("proje_kütüphanesi", {

      projeler: results

    });

  } catch (error) {

    console.log(error);

  }

});

So I need a front-end design with handlebars and anchor tags.  It is like

previous 1 2 3 4 5 6 next

I appericiate for your help, struggling for hours.


问:
JavaScript reffer to C# item in foreach loop (ascx view)
I need to reffer to item inside c# foreach loop using JavaScript in old MVC ascx view.

I have code just like below:

```<code>
          <%foreach (var item in items)
            {%>
             console.log(item);
          <%}%>
</code>```

Let's say I want to console.log the item from items collection -> how can I achieve so?

Body:
I need to reffer to item inside c# foreach loop using JavaScript in old MVC ascx view.

I have code just like below:

          <%foreach (var item in items)
            {%>
             console.log(item);
          <%}%>

Let's say I want to console.log the item from items collection -> how can I achieve so?


问:
How to use object dynamically based on input?
I have 3 objects:

```<code>let Obj1 = {Obj1};
let Obj2 = {Obj2};
let Obj3 = {Obj3};
</code>```

and I need to perform some action on them:

```<code>Obj1.indexOf(value) === - 1 ? do_something() : do_something_else();
</code>```

But I want to choose the object to perform this operation on based on an input.

The input is a string describing the object name = "obj1", "obj2", "obj3".

Currently I am using if-else conditions to choose which object to perform the operation on:

```<code>if (input === "obj1") {
    Obj1.indexOf(value) === - 1 ? do_something() : do_something_else();
} else if (input === "obj2") {
    Obj2.indexOf(value) === - 1 ? do_something() : do_something_else();
} else if (input === "obj3") {
    Obj3.indexOf(value) === - 1 ? do_something() : do_something_else();
}
</code>```

Is there a way to do it more dynamically?

Body:
I have 3 objects:

let Obj1 = {Obj1};
let Obj2 = {Obj2};
let Obj3 = {Obj3};

and I need to perform some action on them:

Obj1.indexOf(value) === - 1 ? do_something() : do_something_else();

But I want to choose the object to perform this operation on based on an input.

The input is a string describing the object name = "obj1", "obj2", "obj3".

Currently I am using if-else conditions to choose which object to perform the operation on:

if (input === "obj1") {
    Obj1.indexOf(value) === - 1 ? do_something() : do_something_else();
} else if (input === "obj2") {
    Obj2.indexOf(value) === - 1 ? do_something() : do_something_else();
} else if (input === "obj3") {
    Obj3.indexOf(value) === - 1 ? do_something() : do_something_else();
}

Is there a way to do it more dynamically?


问:
Laravel API show, update, delete method not working
```<code><?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreCustomerDetailsRequest;
use App\Models\CustomerDetails;
use Illuminate\Http\Request;

class CustomerDetailsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $CustomerDetails = CustomerDetails::where('CustomerDetailsIsActive', '=', '1')->get();

        return response()->json([
            'status' => true,
            'message' => "CustomerDetails Get successfully!",
            'CustomerDetails' => $CustomerDetails,
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreCustomerDetailsRequest $request)
    {
        $CustomerDetails = CustomerDetails::create($request->all());

        return response()->json([
            'status' => true,
            'message' => "CustomerDetails Created successfully!",
            'CustomerDetails' => $CustomerDetails,
        ], 200);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\CustomerDetails  $CustomerDetails
     * @return \Illuminate\Http\Response
     */
    public function show(CustomerDetails $CustomerDetails)
    {

        return response()->json([
            'status' => true,
            'message' => "CustomerDetails Get successfully!",
            'CustomerDetails' => $CustomerDetails->where('CustomerDetailsIsActive', '=', '1')->where('CustomerDetailsID', '=', $CustomerDetails->CustomerDetailsID)->first(),
        ], 200);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\CustomerDetails  $CustomerDetails
     * @return \Illuminate\Http\Response
     */
    public function edit(CustomerDetails $CustomerDetails)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\CustomerDetails  $CustomerDetails
     * @return \Illuminate\Http\Response
     */
    public function update(StoreCustomerDetailsRequest $request, CustomerDetails $CustomerDetails)
    {

        return response()->json([
            'status' => true,
            'message' => "CustomerDetails Updated successfully!",
            'CustomerDetails' => $CustomerDetails,
        ], 200);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\CustomerDetails  $CustomerDetails
     * @return \Illuminate\Http\Response
     */
    public function destroy(CustomerDetails $CustomerDetails)
    {
        $CustomerDetails->CustomerDetailsIsActive = '0';
        $CustomerDetails->save();
        return response()->json([
            'status' => true,
            'message' => "CustomerDetails Deleted successfully!",
        ], 200);
    }
}
</code>```

The controller code

```<code><?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class CustomerDetails extends Model
{
    use HasFactory;
    protected $primaryKey = 'CustomerDetailsID';
    public $timestamps = false;
    protected $fillable = ['CustomerID', 'CustomerDetailsGenderID','CustomerDetailsCategoryID', 'CustomerDetailsAge','CustomerDetailsName', 'CustomerDetailsDateOfBirth', 'CustomerDetailsRelationshipID', 'CustomerDetailsRelationName', 'CustomerDetailsPAN', 'CustomerDetailsAadharNumber', 'CustomerDetailsPhoneNumber', 'CustomerDetailsDoorNo', 'CustomerDetailsStreet', 'CustomerDetailsDistrict', 'CustomerDetailsTaluk', 'CustomerDetailsState', 'CustomerDetailsPinCode'];
}
</code>```

The model code

```<code><?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreCustomerDetailsRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules()
    {
        return [
            "CustomerID" => "required",
            "CustomerDetailsCategoryID" => "required",
            "CustomerDetailsGenderID" => "required",
            "CustomerDetailsName" => "required",
            "CustomerDetailsAge" => "required",
            "CustomerDetailsDateOfBirth" => "required",
            "CustomerDetailsRelationshipID" => "required",
            "CustomerDetailsRelationName" => "required",
            "CustomerDetailsPAN" => "required",
            "CustomerDetailsAadharNumber" => "required",
            "CustomerDetailsPhoneNumber" => "required",
            "CustomerDetailsDoorNo" => "required",
            "CustomerDetailsStreet" => "required",
            "CustomerDetailsDistrict" => "required",
            "CustomerDetailsTaluk" => "required",
            "CustomerDetailsState" => "required",
            "CustomerDetailsPinCode" => "required",
        ];
    }
}
</code>```

The request code

```<code><?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create("customer_details", function (Blueprint $table) {
            $table->id("CustomerDetailsID");
            $table->integer("CustomerID");
            $table->integer("CustomerDetailsGenderID");
            $table->integer("CustomerDetailsCategoryID");
            $table->integer("CustomerDetailsRelationshipID");
            $table->integer("CustomerDetailsAge");
            $table->date("CustomerDetailsDateOfBirth");
            $table->string("CustomerDetailsRelationName");
            $table->string("CustomerDetailsName");
            $table->string("CustomerDetailsPAN");
            $table->string("CustomerDetailsAadharNumber");
            $table->string("CustomerDetailsPhoneNumber");
            $table->string("CustomerDetailsDoorNo");
            $table->string("CustomerDetailsStreet");
            $table->string("CustomerDetailsDistrict");
            $table->string("CustomerDetailsTaluk");
            $table->string("CustomerDetailsState");
            $table->string("CustomerDetailsPinCode");
            $table->boolean("CustomerDetailsIsActive")->default(1);
            $table->timestamp("CustomerDetailsCreatedAt")->useCurrent();
            $table->timestamp("CustomerDetailsUpdatedAt")->useCurrent()->useCurrentOnUpdate();
            $table->index(["CustomerDetailsGenderID"]);
            $table->index(["CustomerDetailsCategoryID"]);
            $table->index(["CustomerDetailsRelationshipID"]);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists("customer_details");
    }
};
</code>```

The DB
I use postman to test the API
When I call this controller Get only works, other methods not working
I tired to change CustomerDetails to Customer model. That one also nor working using CustomerDetailsController
Other API working fine. How to fix this issue. The Customer is master model Customer Details are transaction model

Body:
<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreCustomerDetailsRequest;
use App\Models\CustomerDetails;
use Illuminate\Http\Request;

class CustomerDetailsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $CustomerDetails = CustomerDetails::where('CustomerDetailsIsActive', '=', '1')->get();

        return response()->json([
            'status' => true,
            'message' => "CustomerDetails Get successfully!",
            'CustomerDetails' => $CustomerDetails,
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreCustomerDetailsRequest $request)
    {
        $CustomerDetails = CustomerDetails::create($request->all());

        return response()->json([
            'status' => true,
            'message' => "CustomerDetails Created successfully!",
            'CustomerDetails' => $CustomerDetails,
        ], 200);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\CustomerDetails  $CustomerDetails
     * @return \Illuminate\Http\Response
     */
    public function show(CustomerDetails $CustomerDetails)
    {

        return response()->json([
            'status' => true,
            'message' => "CustomerDetails Get successfully!",
            'CustomerDetails' => $CustomerDetails->where('CustomerDetailsIsActive', '=', '1')->where('CustomerDetailsID', '=', $CustomerDetails->CustomerDetailsID)->first(),
        ], 200);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\CustomerDetails  $CustomerDetails
     * @return \Illuminate\Http\Response
     */
    public function edit(CustomerDetails $CustomerDetails)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\CustomerDetails  $CustomerDetails
     * @return \Illuminate\Http\Response
     */
    public function update(StoreCustomerDetailsRequest $request, CustomerDetails $CustomerDetails)
    {

        return response()->json([
            'status' => true,
            'message' => "CustomerDetails Updated successfully!",
            'CustomerDetails' => $CustomerDetails,
        ], 200);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\CustomerDetails  $CustomerDetails
     * @return \Illuminate\Http\Response
     */
    public function destroy(CustomerDetails $CustomerDetails)
    {
        $CustomerDetails->CustomerDetailsIsActive = '0';
        $CustomerDetails->save();
        return response()->json([
            'status' => true,
            'message' => "CustomerDetails Deleted successfully!",
        ], 200);
    }
}

The controller code

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class CustomerDetails extends Model
{
    use HasFactory;
    protected $primaryKey = 'CustomerDetailsID';
    public $timestamps = false;
    protected $fillable = ['CustomerID', 'CustomerDetailsGenderID','CustomerDetailsCategoryID', 'CustomerDetailsAge','CustomerDetailsName', 'CustomerDetailsDateOfBirth', 'CustomerDetailsRelationshipID', 'CustomerDetailsRelationName', 'CustomerDetailsPAN', 'CustomerDetailsAadharNumber', 'CustomerDetailsPhoneNumber', 'CustomerDetailsDoorNo', 'CustomerDetailsStreet', 'CustomerDetailsDistrict', 'CustomerDetailsTaluk', 'CustomerDetailsState', 'CustomerDetailsPinCode'];
}

The model code

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreCustomerDetailsRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules()
    {
        return [
            "CustomerID" => "required",
            "CustomerDetailsCategoryID" => "required",
            "CustomerDetailsGenderID" => "required",
            "CustomerDetailsName" => "required",
            "CustomerDetailsAge" => "required",
            "CustomerDetailsDateOfBirth" => "required",
            "CustomerDetailsRelationshipID" => "required",
            "CustomerDetailsRelationName" => "required",
            "CustomerDetailsPAN" => "required",
            "CustomerDetailsAadharNumber" => "required",
            "CustomerDetailsPhoneNumber" => "required",
            "CustomerDetailsDoorNo" => "required",
            "CustomerDetailsStreet" => "required",
            "CustomerDetailsDistrict" => "required",
            "CustomerDetailsTaluk" => "required",
            "CustomerDetailsState" => "required",
            "CustomerDetailsPinCode" => "required",
        ];
    }
}

The request code

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create("customer_details", function (Blueprint $table) {
            $table->id("CustomerDetailsID");
            $table->integer("CustomerID");
            $table->integer("CustomerDetailsGenderID");
            $table->integer("CustomerDetailsCategoryID");
            $table->integer("CustomerDetailsRelationshipID");
            $table->integer("CustomerDetailsAge");
            $table->date("CustomerDetailsDateOfBirth");
            $table->string("CustomerDetailsRelationName");
            $table->string("CustomerDetailsName");
            $table->string("CustomerDetailsPAN");
            $table->string("CustomerDetailsAadharNumber");
            $table->string("CustomerDetailsPhoneNumber");
            $table->string("CustomerDetailsDoorNo");
            $table->string("CustomerDetailsStreet");
            $table->string("CustomerDetailsDistrict");
            $table->string("CustomerDetailsTaluk");
            $table->string("CustomerDetailsState");
            $table->string("CustomerDetailsPinCode");
            $table->boolean("CustomerDetailsIsActive")->default(1);
            $table->timestamp("CustomerDetailsCreatedAt")->useCurrent();
            $table->timestamp("CustomerDetailsUpdatedAt")->useCurrent()->useCurrentOnUpdate();
            $table->index(["CustomerDetailsGenderID"]);
            $table->index(["CustomerDetailsCategoryID"]);
            $table->index(["CustomerDetailsRelationshipID"]);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists("customer_details");
    }
};

The DB
I use postman to test the API
When I call this controller Get only works, other methods not working
I tired to change CustomerDetails to Customer model. That one also nor working using CustomerDetailsController
Other API working fine. How to fix this issue. The Customer is master model Customer Details are transaction model


问:
How do I add Acf for popup inside a slider repeater
I am having logo's slider repeater. Inside the repeater each logo should display a popup with div card. How do I add php repeater for both slider and popup.

How do I add php repeater for both slider and popup. Please suggest me the code for both.

Thank you in advance.


问:
Azure Pricing Calculator for Databricks: DBUs are not matching
I am using the Azure Pricing Calculator and try to asses my Databricks costs.

I have a Datatbricks service up and running which I use to asses my calculation. In the Cluster Summary (in databricks), it shows me, that 5-8 DBU/h will be consumed. In the pricing calculator, the predefined DBU/h are significantly lower (1.5 DBU/h). Why are the two numbers different?
I checked:

Region

Tier

Cluster Type


问:
How to reject-unsupported-caps in Selenium Grid hub and node
I am testing different configurations for selenium grid 4 and  in the official documentation is said that reject-unsupported-caps = true will "Allow the Distributor to reject a request immediately if the Grid does not support the requested capability."

To test the configuration locally I have hub and node with the following configurations:

```<code>#hubConfig.toml
[server]
port = 4444

[distributor]
healthcheck-interval = 10
reject-unsuported-caps = true

[logging]
structured-logs = true
log-file = "log/hubLog.log"
log-encoding = "UTF-8"
log-level = "CONFIG"
</code>```
```<code>#nodeConfig.toml
[server]
port = 6666

[node]
detect-drivers = true
max-sessions = 2
heartbeat-period = 10
session-timeout = 300
hub = "http://localhost:4444"

[logging]
structured-logs = true
log-file = "log/nodeLog.log"
log-encoding = "UTF-8"
log-level = "CONFIG"
</code>```

I am executing single test class maven/java/TestNG containing 3 tests. Two with correct capabilities(chrome,firefox) and one in safari. Example for the second test is below

```<code>@Test
public void test2() throws InterruptedException {
    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability(BROWSER_NAME,"safari");
    RemoteWebDriver remoteWebDriver = new RemoteWebDriver(gridURL,caps);
    remoteWebDriver.get("http://www.google.com");
    Thread.sleep(sleepTime);
    remoteWebDriver.quit();
}
</code>```

My expectation is that this test should be rejected immediately, but it fails after session timeout.

```<code>org.openqa.selenium.SessionNotCreatedException: Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure
</code>```

Body:
I am testing different configurations for selenium grid 4 and  in the official documentation is said that reject-unsupported-caps = true will "Allow the Distributor to reject a request immediately if the Grid does not support the requested capability."

To test the configuration locally I have hub and node with the following configurations:

#hubConfig.toml
[server]
port = 4444

[distributor]
healthcheck-interval = 10
reject-unsuported-caps = true

[logging]
structured-logs = true
log-file = "log/hubLog.log"
log-encoding = "UTF-8"
log-level = "CONFIG"

#nodeConfig.toml
[server]
port = 6666

[node]
detect-drivers = true
max-sessions = 2
heartbeat-period = 10
session-timeout = 300
hub = "http://localhost:4444"

[logging]
structured-logs = true
log-file = "log/nodeLog.log"
log-encoding = "UTF-8"
log-level = "CONFIG"

I am executing single test class maven/java/TestNG containing 3 tests. Two with correct capabilities(chrome,firefox) and one in safari. Example for the second test is below

@Test
public void test2() throws InterruptedException {
    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability(BROWSER_NAME,"safari");
    RemoteWebDriver remoteWebDriver = new RemoteWebDriver(gridURL,caps);
    remoteWebDriver.get("http://www.google.com");
    Thread.sleep(sleepTime);
    remoteWebDriver.quit();
}

My expectation is that this test should be rejected immediately, but it fails after session timeout.

org.openqa.selenium.SessionNotCreatedException: Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure


问:
Grouping a dataframe keeping certain values while changing others based on date
I am facing an issue trying to transform my dataframe in a certain way.

Here's what I currently have

Identifier
Identifier2
Date
Variable A
Variable B
Variable C

IdentityA
A123
1st Jan 2022
Active
N/A
N/A

IdentityA
A124
3rd Mar 2022
Active
Inactive
Active

IdentityA
A125
5th Dec 2022
Active
N/A
N/A

IdentityB
A166
3rd Jan 2022
N/A
Inactive
N/A

I want to transform my dataset based on these few criteria

I want to keep the variables as it is for the most current/latest entry of the identifier

If any of the previous entry of the same identifier has either "Active" or "Inactive", they should be marked "Inactive" in the final column

I'm not too concerned about the identifier2 and date for now

There will be a varying number of rows for each identifier so the code has to be able to account for that

The result dataset should look like this

Identifier
Variable A
Variable B
Variable C

IdentityA
Active
Inactive
Inactive

IdentityB
N/A
Inactive
N/A

Would appreciate any help, thanks!

I tried groupby at first, but that's all I could do. I didn't really know how I should "aggregate" the rest of the data while keeping the latest value as it is.


问:
c# Quartz.NET injected IServiceProvider is always disposed
I have an application in .NET 7 that is supposed to use Quartz to run scheduled jobs. The problem is that if I try to use the DI and the IServiceProvider interface, I always get an exception indicating that the object has been disposed. In the beginning I used the Microsoft BackgrouService and everything worked fine, as soon as I switched to the IJob interface I started having this kind of errors.
This is my job class:

```<code>[UsedImplicitly]
public class EventHubLogProcessorJob : IJob
{
    // Omit some code for brevity

    private readonly ConcurrentQueue<ClientEvent> _clientEvents = new();
    private readonly ConcurrentDictionary<string, int> _eventsPerPartition = new();

    private readonly ILogger<EventHubLogProcessorJob> _logger;
    private readonly IServiceProvider _serviceProvider;

    public EventHubLogProcessorJob(ILogger<EventHubLogProcessorJob> logger,
        IServiceProvider serviceProvider)
    {
        Guard.Against.Null(logger);
        Guard.Against.Null(serviceProvider);

        _logger = logger;
        _serviceProvider = serviceProvider;
    }

    public async Task Execute(IJobExecutionContext context)
    {
        try
        {
            var storageClient = new BlobContainerClient(StorageConnectionString, BlobContainerName);

            var processor = new EventProcessorClient(
                storageClient, ConsumerGroup, EventHubConnectionString, EventProcessorClientOptions);

            processor.ProcessEventAsync += OnProcessEvent;
            processor.ProcessErrorAsync += OnProcessError;

            await processor.StartProcessingAsync(context.CancellationToken);
        }
        catch (TaskCanceledException e)
        {
            _logger.LogError(e.Demystify(), "Task was canceled");
        }
        catch (Exception e)
        {
            _logger.LogError(e.Demystify(), "An unhandled exception has occurred");
        }
    }

    private Task OnProcessError(ProcessErrorEventArgs errorEventArgs)
    {
        _logger.LogError(errorEventArgs.Exception, "OnProcess error");

        return Task.CompletedTask;
    }

    private async Task OnProcessEvent(ProcessEventArgs eventArgs)
    {
        try
        {
            if (eventArgs.Data?.EventBody is null ||
                eventArgs.Data.EventBody.ToString().Contains(Constants.EventType.Failure))
            {
                return;
            }

            var logAudit = JsonSerializer.Deserialize<LogAuditRoot>(eventArgs.Data.EventBody.ToString(),
                SerializerOptions);

            if (logAudit.Tags.Contains(Constants.Tag.Stage, StringComparer.InvariantCultureIgnoreCase))
            {
                return;
            }

            var clientEvent = logAudit.ClientEvent;

            if (clientEvent.ClientId == Guid.Empty || string.IsNullOrEmpty(clientEvent.ClientName))
            {
                return;
            }

            _clientEvents.Enqueue(clientEvent);

            var partitionId = eventArgs.Partition.PartitionId;

            // Initialize or increment the count for the current partition.
            if (!_eventsPerPartition.TryAdd(partitionId, 0))
            {
                ++_eventsPerPartition[partitionId];
            }

            if (_eventsPerPartition[partitionId] >= 100)
            {
                await eventArgs.UpdateCheckpointAsync().ConfigureAwait(false);
                await InsertDataIntoDatabaseAsync();

                _clientEvents.Clear();
                _eventsPerPartition[partitionId] = 0;
            }
        }
        catch (Exception e)
        {
            _logger.LogError(e, "ProcessEventHandler exception");
        }
    }

    private async Task InsertDataIntoDatabaseAsync()
    {
        // Here i get the exception that the object has been disposed
        using var scope = _serviceProvider.CreateScope();

        var repository = scope.ServiceProvider.GetRequiredService<IRepository>();

        _logger.LogInformation("Count: {Count}", _clientEvents.Count.ToString());

        foreach (var clientEvent in _clientEvents)
        {
            var activity = clientEvent.ToEntity();

            repository.Insert(activity);

            await repository.SaveChangesAsync();
        }
    }
}
</code>```

The Exception:

System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'IServiceProvider'.
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ThrowHelper.ThrowObjectDisposedException()
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.CreateScope(IServiceProvider provider)

This is the code where I configure Quartz:

```<code>var host = Host.CreateDefaultBuilder(args)
    .UseWindowsService(options => { options.ServiceName = "ClientLogProcessor"; })
    .UseSerilog((context, services, configuration) =>
    {
        configuration
            .ReadFrom.Configuration(context.Configuration)
            .ReadFrom.Services(services)
            .Enrich.FromLogContext()
            .Enrich.WithExceptionDetails();
    })
    .ConfigureLogging(builder => builder.AddSerilog())
    .ConfigureAppConfiguration((context, builder) =>
    {
        var environment = context.HostingEnvironment.EnvironmentName;

        builder.AddJsonFile($"appsettings.{environment}.json");
    })
    .ConfigureServices((context, services) =>
    {
        services.AddWindowsService();
        services.AddScoped<IRepository, Repository>();
        services.AddDbContext<DataContext>(options =>
        {
            options.UseSqlServer(context.Configuration.GetConnectionString("Database"));
        });

        //services.AddHostedService<EventHubLogProcessorJob>();

        services.AddQuartz(configurator =>
        {
            configurator.UseMicrosoftDependencyInjectionJobFactory();

            const string eventHubJobKey = nameof(EventHubLogProcessorJob);

            configurator.AddJob<EventHubLogProcessorJob>(options => options.WithIdentity(eventHubJobKey));

            configurator.AddTrigger(options => options.ForJob(eventHubJobKey).StartNow());
        });

        services.AddQuartzHostedService();
    })
    .Build();
</code>```

How come this problem occurs with Quartz, while if I implement the Microsoft BackgrouService not?
How can I fix this? I hope I was clear.
A thousand thanks

Body:
I have an application in .NET 7 that is supposed to use Quartz to run scheduled jobs. The problem is that if I try to use the DI and the IServiceProvider interface, I always get an exception indicating that the object has been disposed. In the beginning I used the Microsoft BackgrouService and everything worked fine, as soon as I switched to the IJob interface I started having this kind of errors.
This is my job class:

[UsedImplicitly]
public class EventHubLogProcessorJob : IJob
{
    // Omit some code for brevity

    private readonly ConcurrentQueue<ClientEvent> _clientEvents = new();
    private readonly ConcurrentDictionary<string, int> _eventsPerPartition = new();

    private readonly ILogger<EventHubLogProcessorJob> _logger;
    private readonly IServiceProvider _serviceProvider;

    public EventHubLogProcessorJob(ILogger<EventHubLogProcessorJob> logger,
        IServiceProvider serviceProvider)
    {
        Guard.Against.Null(logger);
        Guard.Against.Null(serviceProvider);

        _logger = logger;
        _serviceProvider = serviceProvider;
    }

    public async Task Execute(IJobExecutionContext context)
    {
        try
        {
            var storageClient = new BlobContainerClient(StorageConnectionString, BlobContainerName);

            var processor = new EventProcessorClient(
                storageClient, ConsumerGroup, EventHubConnectionString, EventProcessorClientOptions);

            processor.ProcessEventAsync += OnProcessEvent;
            processor.ProcessErrorAsync += OnProcessError;

            await processor.StartProcessingAsync(context.CancellationToken);
        }
        catch (TaskCanceledException e)
        {
            _logger.LogError(e.Demystify(), "Task was canceled");
        }
        catch (Exception e)
        {
            _logger.LogError(e.Demystify(), "An unhandled exception has occurred");
        }
    }

    private Task OnProcessError(ProcessErrorEventArgs errorEventArgs)
    {
        _logger.LogError(errorEventArgs.Exception, "OnProcess error");

        return Task.CompletedTask;
    }

    private async Task OnProcessEvent(ProcessEventArgs eventArgs)
    {
        try
        {
            if (eventArgs.Data?.EventBody is null ||
                eventArgs.Data.EventBody.ToString().Contains(Constants.EventType.Failure))
            {
                return;
            }

            var logAudit = JsonSerializer.Deserialize<LogAuditRoot>(eventArgs.Data.EventBody.ToString(),
                SerializerOptions);

            if (logAudit.Tags.Contains(Constants.Tag.Stage, StringComparer.InvariantCultureIgnoreCase))
            {
                return;
            }

            var clientEvent = logAudit.ClientEvent;

            if (clientEvent.ClientId == Guid.Empty || string.IsNullOrEmpty(clientEvent.ClientName))
            {
                return;
            }

            _clientEvents.Enqueue(clientEvent);

            var partitionId = eventArgs.Partition.PartitionId;

            // Initialize or increment the count for the current partition.
            if (!_eventsPerPartition.TryAdd(partitionId, 0))
            {
                ++_eventsPerPartition[partitionId];
            }

            if (_eventsPerPartition[partitionId] >= 100)
            {
                await eventArgs.UpdateCheckpointAsync().ConfigureAwait(false);
                await InsertDataIntoDatabaseAsync();

                _clientEvents.Clear();
                _eventsPerPartition[partitionId] = 0;
            }
        }
        catch (Exception e)
        {
            _logger.LogError(e, "ProcessEventHandler exception");
        }
    }

    private async Task InsertDataIntoDatabaseAsync()
    {
        // Here i get the exception that the object has been disposed
        using var scope = _serviceProvider.CreateScope();

        var repository = scope.ServiceProvider.GetRequiredService<IRepository>();

        _logger.LogInformation("Count: {Count}", _clientEvents.Count.ToString());

        foreach (var clientEvent in _clientEvents)
        {
            var activity = clientEvent.ToEntity();

            repository.Insert(activity);

            await repository.SaveChangesAsync();
        }
    }
}

The Exception:

System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'IServiceProvider'.
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ThrowHelper.ThrowObjectDisposedException()
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.CreateScope(IServiceProvider provider)

This is the code where I configure Quartz:

var host = Host.CreateDefaultBuilder(args)
    .UseWindowsService(options => { options.ServiceName = "ClientLogProcessor"; })
    .UseSerilog((context, services, configuration) =>
    {
        configuration
            .ReadFrom.Configuration(context.Configuration)
            .ReadFrom.Services(services)
            .Enrich.FromLogContext()
            .Enrich.WithExceptionDetails();
    })
    .ConfigureLogging(builder => builder.AddSerilog())
    .ConfigureAppConfiguration((context, builder) =>
    {
        var environment = context.HostingEnvironment.EnvironmentName;

        builder.AddJsonFile($"appsettings.{environment}.json");
    })
    .ConfigureServices((context, services) =>
    {
        services.AddWindowsService();
        services.AddScoped<IRepository, Repository>();
        services.AddDbContext<DataContext>(options =>
        {
            options.UseSqlServer(context.Configuration.GetConnectionString("Database"));
        });

        //services.AddHostedService<EventHubLogProcessorJob>();

        services.AddQuartz(configurator =>
        {
            configurator.UseMicrosoftDependencyInjectionJobFactory();

            const string eventHubJobKey = nameof(EventHubLogProcessorJob);

            configurator.AddJob<EventHubLogProcessorJob>(options => options.WithIdentity(eventHubJobKey));

            configurator.AddTrigger(options => options.ForJob(eventHubJobKey).StartNow());
        });

        services.AddQuartzHostedService();
    })
    .Build();

How come this problem occurs with Quartz, while if I implement the Microsoft BackgrouService not?
How can I fix this? I hope I was clear.
A thousand thanks


问:
Add a shaper line under any selected text in word
I'm having trouble when I want to put a shaper line under any selected text, the length of the shaper line is equal to the length of the selected text.

For left-aligned and justify-aligned paragraphs, this works fine, but in case of right-aligned or center-aligned, it doesn't work correctly, the shaper line will be extended to the left by a distance equal to the indent.
Is there any way to solve this problem please?
Illustrated for cases

```<code>float LeftPt, RightPt, TopPt, LineSpace;
LeftPt = wApp.Selection.Characters.First.Information[WdInformation.wdHorizontalPositionRelativeToPage];
RightPt = wApp.Selection.Characters.Last.Information[WdInformation.wdHorizontalPositionRelativeToPage] +
                (float)wApp.Selection.Characters.Last.CharacterWidth;
TopPt = wApp.Selection.Information[WdInformation.wdVerticalPositionRelativeToPage];
LineSpace = wApp.Selection.Paragraphs.LineSpacing + 3;
Shape LineSp = wApp.ActiveDocument.Shapes.AddLine(LeftPt, TopPt + LineSpace, RightPt, TopPt + LineSpace);
</code>```

Body:
I'm having trouble when I want to put a shaper line under any selected text, the length of the shaper line is equal to the length of the selected text.

For left-aligned and justify-aligned paragraphs, this works fine, but in case of right-aligned or center-aligned, it doesn't work correctly, the shaper line will be extended to the left by a distance equal to the indent.
Is there any way to solve this problem please?
Illustrated for cases

float LeftPt, RightPt, TopPt, LineSpace;
LeftPt = wApp.Selection.Characters.First.Information[WdInformation.wdHorizontalPositionRelativeToPage];
RightPt = wApp.Selection.Characters.Last.Information[WdInformation.wdHorizontalPositionRelativeToPage] +
                (float)wApp.Selection.Characters.Last.CharacterWidth;
TopPt = wApp.Selection.Information[WdInformation.wdVerticalPositionRelativeToPage];
LineSpace = wApp.Selection.Paragraphs.LineSpacing + 3;
Shape LineSp = wApp.ActiveDocument.Shapes.AddLine(LeftPt, TopPt + LineSpace, RightPt, TopPt + LineSpace);


问:
Going Live With Shopidy Checkout UI Extension
I'm working on a checkout UI Extension that is supposed to render a custom components in shopify plus checkout.
Everything is going fine in development as soon as I work in a development store were UI extension preview is activated.

Then, I deploy extension with the CLI, create a version and activate it in the partner portal, upload app to fly.io and try use it on shopify plus live store with unlocked checkout.liquid... And I'm stuck here !

The extension doesn't render in checkout and the theme builder do not show the app in the checkout app so I cannot put it in a dynamic zone.

What am I doing wrong ?

Thanks for your help in advance


问:
R error message when calling agricolae package that usually work very well
When I called the agricolae package by :
library(agricolae)

I got this error message :
Error: package or namespace load failed for ‘agricolae’:
l'objet ‘faststack’ n'est pas exporté par 'namespace:fastmap'
In addition: Warning message:
le package ‘agricolae’ a été compilé avec la version R 4.0.5

I

Then I tryed to remove and install again the agricolae package using:
remove.packages("agricolae")
install.packages("agricolae")

And I tryed to call the package again, but I got the same error message
How to fix the problem , please?


问:
C++ lifetime model: Difference between constructing a span<T> over a buffer, and using placement-new to initialize pointers in it?
I'm having trouble understanding what the difference is between using span<T> to create a view over some memory area/buffer as a struct of type T, or using placement-new to initialize a pointer type.

Functionally, they both allow you to write something like foos[0], and to read/write to the underlying memory area.

If I understand it correctly, the placement-new starts the "lifetime" of the pointers in the memory area/buffer -- but functionally, I don't notice any difference in effects between the two.

Below shows an example of what I mean:

https://godbolt.org/z/ndYb4bo1K

//              BUFFER
// |==================================|
// | Page | Page | Page | Page | Page |
// |==================================|
// ^                                  ^
// 0 bytes                            (4096 * 5) bytes

#include <cstddef>
#include <cstdio>
#include
#include <cassert>

struct alignas(4096) Page { int id; };
alignas(4096) std::byte buffer[4096 * 5];

// Using placement-new to initialize Page pointers in the buffer
Page* page_ptrs = new (buffer) Page;

// Using span<T> to create a view of Pages over the buffer
auto pages = std::span<Page>(reinterpret_cast<Page*>(buffer), 5);

int main()
{
    // Get first and second page using page_ptrs
    Page* first_page = &page_ptrs[0];
    Page* second_page = &page_ptrs[1];

    first_page->id = 1;
    second_page->id = 2;

    // Get first and second page using pages
    Page first_page_2 = pages[0];
    Page second_page_2 = pages[1];

    printf("first_page.id = %d, second_page.id = %d \n", first_page->id, second_page->id);
    printf("first_page_2.id = %d, second_page_2.id = %d \n", first_page_2.id, second_page_2.id);

    assert(first_page->id == first_page_2.id);
    assert(second_page->id == second_page_2.id);

    // Update the page ID's using the span<T>
    pages[0].id = 3;
    pages[1].id = 4;
    assert(first_page->id == 3);
    assert(second_page->id == 4);
}
```


问:
How to save the status of a GridLayout on android
I was practicing with the android development and I had a doubt: is there any way to save the state of the elements inside a GridLayout when I rotate the phone using the "onSaveInstanceState" method?
Here is my little code

```<code>public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Game g = new Game(findViewById(R.id.grid),(Button) findViewById(R.id.resetBtn));
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
    }

}
</code>```

Inside my Game class I have this

```<code>public class Game {
    private final GridLayout grid;
    private final Button resetBtn;

    public Game(GridLayout grid,Button resetBtn) {
        this.grid = grid;
        this.resetBtn = resetBtn;
        setButtons();
        startGame();
    }
    ///
}
</code>```

Inside the setButtons() method I change the status for every button inside the grid.

Body:
I was practicing with the android development and I had a doubt: is there any way to save the state of the elements inside a GridLayout when I rotate the phone using the "onSaveInstanceState" method?
Here is my little code

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Game g = new Game(findViewById(R.id.grid),(Button) findViewById(R.id.resetBtn));
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
    }

}

Inside my Game class I have this

public class Game {
    private final GridLayout grid;
    private final Button resetBtn;

    public Game(GridLayout grid,Button resetBtn) {
        this.grid = grid;
        this.resetBtn = resetBtn;
        setButtons();
        startGame();
    }
    ///
}

Inside the setButtons() method I change the status for every button inside the grid.


问:
How to use matplotlib to draw multiple cylinders in one drawing?
enter image description here
I saw such a formal presentation of results in a paper.

I tried to use matplotlib to achieve the same effect, but failed. This is my code.

```<code>x1 = [
        [350, 100, 80, 1000],
        [200, 600, 150, 800],
        [600, 150, 100, 500],
        [450, 800, 75, 1000],
        [680, 400, 120, 500],
        [850, 600, 70, 750],
        [150, 250, 80, 1000],
        [750, 800, 100, 1000]
]

threats = np.asarray(x1)

def create3DEnvironment(threats):
    fig = plt.figure()

    ax = fig.add_subplot(projection='3d')

    counts = len(threats)

    us = np.linspace(0, 2 * np.pi, 20)
    for i in range(0, counts):
        x = threats[i, 0]
        y = threats[i, 1]
        r = threats[i, 2]
        h = threats[i, 3]

        zs = np.linspace(0, h, 30)
        us, zs = np.meshgrid(us, zs)
        xs = r * np.cos(us) + x
        ys = r * np.sin(us) + y
        ax.plot_surface(xs, ys, zs, cmap='Blues', alpha=0.8)
    plt.show()
</code>```

The error message is as follows

```<code>numpy.core._exceptions._ArrayMemoryError: Unable to allocate 14.8 MiB for an array with shape (3, 648002) and data type float64
</code>```

I'm not sure what's going on.

Could someone please provide me with any ways or information?

I much appreciate your time and help.

Body:
enter image description here
I saw such a formal presentation of results in a paper.

I tried to use matplotlib to achieve the same effect, but failed. This is my code.

x1 = [
        [350, 100, 80, 1000],
        [200, 600, 150, 800],
        [600, 150, 100, 500],
        [450, 800, 75, 1000],
        [680, 400, 120, 500],
        [850, 600, 70, 750],
        [150, 250, 80, 1000],
        [750, 800, 100, 1000]
]

threats = np.asarray(x1)

def create3DEnvironment(threats):
    fig = plt.figure()

    ax = fig.add_subplot(projection='3d')

    counts = len(threats)

    us = np.linspace(0, 2 * np.pi, 20)
    for i in range(0, counts):
        x = threats[i, 0]
        y = threats[i, 1]
        r = threats[i, 2]
        h = threats[i, 3]

        zs = np.linspace(0, h, 30)
        us, zs = np.meshgrid(us, zs)
        xs = r * np.cos(us) + x
        ys = r * np.sin(us) + y
        ax.plot_surface(xs, ys, zs, cmap='Blues', alpha=0.8)
    plt.show()

The error message is as follows

numpy.core._exceptions._ArrayMemoryError: Unable to allocate 14.8 MiB for an array with shape (3, 648002) and data type float64

I'm not sure what's going on.

Could someone please provide me with any ways or information?

I much appreciate your time and help.


问:
Pandas rolling average that takes missing points into account
I would like to calculate a moving average on a dataframe that contains missing "points"

For the following example, we can see that the period of 09:00:02 has an average of 1.0, where i would expect it to have the value of 0.5 because i would like to treat missing points (such as 09:00:01) as zeroes.

```<code>In [1]: import pandas as pd
   ...: import numpy as np

In [2]: df_time = pd.DataFrame({'B': [1, 1, 2, np.nan, 4]},
   ...:                        index = [pd.Timestamp('20130101 09:00:00'),
   ...:                                 pd.Timestamp('20130101 09:00:02'),
   ...:                                 pd.Timestamp('20130101 09:00:03'),
   ...:                                 pd.Timestamp('20130101 09:00:05'),
   ...:                                 pd.Timestamp('20130101 09:00:06')])
   ...:

In [3]: print(df_time)
   ...:
                       B
2013-01-01 09:00:00  1.0
2013-01-01 09:00:02  1.0
2013-01-01 09:00:03  2.0
2013-01-01 09:00:05  NaN
2013-01-01 09:00:06  4.0

In [4]: rolling = df_time.rolling('2s').mean()

In [5]: print(rolling)
                       B
2013-01-01 09:00:00  1.0
2013-01-01 09:00:02  1.0
2013-01-01 09:00:03  1.5
2013-01-01 09:00:05  NaN
2013-01-01 09:00:06  4.0
</code>```

Is there an option to do that with pandas rolling?

Of course there is the option to fill the missing dates with reindex - but i am looking for a "native" rolling option, assuming it can also be more efficient

Body:
I would like to calculate a moving average on a dataframe that contains missing "points"

For the following example, we can see that the period of 09:00:02 has an average of 1.0, where i would expect it to have the value of 0.5 because i would like to treat missing points (such as 09:00:01) as zeroes.

In [1]: import pandas as pd
   ...: import numpy as np

In [2]: df_time = pd.DataFrame({'B': [1, 1, 2, np.nan, 4]},
   ...:                        index = [pd.Timestamp('20130101 09:00:00'),
   ...:                                 pd.Timestamp('20130101 09:00:02'),
   ...:                                 pd.Timestamp('20130101 09:00:03'),
   ...:                                 pd.Timestamp('20130101 09:00:05'),
   ...:                                 pd.Timestamp('20130101 09:00:06')])
   ...:

In [3]: print(df_time)
   ...:
                       B
2013-01-01 09:00:00  1.0
2013-01-01 09:00:02  1.0
2013-01-01 09:00:03  2.0
2013-01-01 09:00:05  NaN
2013-01-01 09:00:06  4.0

In [4]: rolling = df_time.rolling('2s').mean()

In [5]: print(rolling)
                       B
2013-01-01 09:00:00  1.0
2013-01-01 09:00:02  1.0
2013-01-01 09:00:03  1.5
2013-01-01 09:00:05  NaN
2013-01-01 09:00:06  4.0

Is there an option to do that with pandas rolling?

Of course there is the option to fill the missing dates with reindex - but i am looking for a "native" rolling option, assuming it can also be more efficient


问:
IIS 8 - Stop remote
I recently got a new laptop.  I added IIS manager and connected to a remote website. i need to be able to stop the website from IIS. I used to be able to do this on my old laptop.

I  was able to connect but i have no option under actions to Stop, start, or restart the site. I dont know what is wrong and can't figure it out. Hope someone can help! thank you in advance

Title: IIS 8 - Stop remote


问:
Cunfluent Kafka (Python) - Check partition leader
The topic I am consuming data is distributed in 3 brokers and 18 partitions. Each broker is the leader for 6 partitions. How can I list the leader of each partition on my Python application? (I am using confluent kafka library).

I need to do this because I have 3 different apps, one per broker and I want them to programmatically check and consume data from all partitions that the broker is the leader.

Currently I have hardcoded the partitions on each broker, but I want to change this so that in case a broker goes down, I will commence consuming those partitions from the other two brokers.

Ideally I would like to exted the following code to include the leader for each topic:

```<code>metadata = consumer.list_topics(topic, timeout=10)
if metadata.topics[topic].error is not None:
    raise confluent_kafka.KafkaException(metadata.topics[topic].error)

partitions = [TopicPartition(topic, p) for p in metadata.topics[topic].partitions]
committed = consumer.committed(partitions, timeout=10)
for partition in committed:
    # Get the partitions low and high watermark offsets.
    (lo, hi) = consumer.get_watermark_offsets(partition, timeout=10, cached=False)

if partition.offset == confluent_kafka.OFFSET_INVALID:
    offset = "-"
else:
    offset = "%d" % (partition.offset)

if hi < 0:
    lag = "no hwmark"  # Unlikely
elif partition.offset < 0:
    # No committed offset, show total message count as lag.
    # The actual message count may be lower due to compaction
    # and record deletions.
    lag = "%d" % (hi - lo)
else:
    lag = "%d" % (hi - partition.offset)

print("%-50s  %9s  %9s" % (
    "{} [{}]".format(partition.topic, partition.partition), offset, lag))
</code>```

EDIT:

Following code from How to describe a topic using kafka client in Python

I added the following:

```<code>adminClient = AdminClient({
    'bootstrap.servers': 'my_server'
    })

fs = adminClient.describe_configs([ConfigResource(confluent_kafka.admin.RESOURCE_TOPIC, "bets")],
                        request_timeout=100)
topic_configResource = adminClient.describe_configs([ConfigResource(confluent_kafka.admin.RESOURCE_TOPIC, "bets")])
for j in concurrent.futures.as_completed(iter(topic_configResource.values())):
    config_response = j.result(timeout=100)
</code>```

Which throws timeout exception

Breaking down the code in order to try to debug, if I only run

```<code>fs = adminClient.describe_configs([ConfigResource(confluent_kafka.admin.RESOURCE_TOPIC, "bets")],
                    request_timeout=100)
fs
</code>```

I get the following:

{ConfigResource(ResourceType.TOPIC,bets): <Future at 0x27f882fb100
state=running>}

After the requiest timeout I have set, I get the following:

{ConfigResource(ResourceType.TOPIC,bets): <Future at 0x27f882fb100 state=finished raised KafkaException>}

On a side note, using Conduktor provides ISR and leader information per briker, therefore those informations are available on the cluster.

Body:
The topic I am consuming data is distributed in 3 brokers and 18 partitions. Each broker is the leader for 6 partitions. How can I list the leader of each partition on my Python application? (I am using confluent kafka library).

I need to do this because I have 3 different apps, one per broker and I want them to programmatically check and consume data from all partitions that the broker is the leader.

Currently I have hardcoded the partitions on each broker, but I want to change this so that in case a broker goes down, I will commence consuming those partitions from the other two brokers.

Ideally I would like to exted the following code to include the leader for each topic:

metadata = consumer.list_topics(topic, timeout=10)
if metadata.topics[topic].error is not None:
    raise confluent_kafka.KafkaException(metadata.topics[topic].error)

partitions = [TopicPartition(topic, p) for p in metadata.topics[topic].partitions]
committed = consumer.committed(partitions, timeout=10)
for partition in committed:
    # Get the partitions low and high watermark offsets.
    (lo, hi) = consumer.get_watermark_offsets(partition, timeout=10, cached=False)

if partition.offset == confluent_kafka.OFFSET_INVALID:
    offset = "-"
else:
    offset = "%d" % (partition.offset)

if hi < 0:
    lag = "no hwmark"  # Unlikely
elif partition.offset < 0:
    # No committed offset, show total message count as lag.
    # The actual message count may be lower due to compaction
    # and record deletions.
    lag = "%d" % (hi - lo)
else:
    lag = "%d" % (hi - partition.offset)

print("%-50s  %9s  %9s" % (
    "{} [{}]".format(partition.topic, partition.partition), offset, lag))

EDIT:

Following code from How to describe a topic using kafka client in Python

I added the following:

adminClient = AdminClient({
    'bootstrap.servers': 'my_server'
    })

fs = adminClient.describe_configs([ConfigResource(confluent_kafka.admin.RESOURCE_TOPIC, "bets")],
                        request_timeout=100)
topic_configResource = adminClient.describe_configs([ConfigResource(confluent_kafka.admin.RESOURCE_TOPIC, "bets")])
for j in concurrent.futures.as_completed(iter(topic_configResource.values())):
    config_response = j.result(timeout=100)

Which throws timeout exception

Breaking down the code in order to try to debug, if I only run

fs = adminClient.describe_configs([ConfigResource(confluent_kafka.admin.RESOURCE_TOPIC, "bets")],
                    request_timeout=100)
fs

I get the following:

{ConfigResource(ResourceType.TOPIC,bets): <Future at 0x27f882fb100
state=running>}

After the requiest timeout I have set, I get the following:

{ConfigResource(ResourceType.TOPIC,bets): <Future at 0x27f882fb100 state=finished raised KafkaException>}

On a side note, using Conduktor provides ISR and leader information per briker, therefore those informations are available on the cluster.


问:
push the results of a ajax query into another object
I'm trying to push the results of an AJAX query into another object but can't seem to do it.

Below is my Javascript code:

$.ajax({
  type: 'POST',
  url: '/Orion/Services/Information.asmx/QueryWithParameters',
  data: params,
  contentType: 'application/json; charset=utf-8',
  dataType: 'json',
  success: function (response) {
    //console.table(response);
    var results1 = {};
    for (var i = 0; i < response.d.Rows.length; i++) {
      results1.push({response.d.Rows[i][0], response.d.Rows[i][1]});
    }
    console.table(results1);
  },
});

```


问:
How to type a property in a parent class with the children value type in typescript?
I have 3 class, for the simplification, it's class A, B and C.

C inherit from B and B inherit from A. They share a same property initialState. The class A only declare the property initialState, the class B define initialState with a value, and class C define an initialState, it should use it own value + the one inherited from class B.

Here is my simple example:

abstract class ClassA<T> {
    readonly initialState: T; // initialState takes type from the class generic
}

interface StateFromB {
    count: number;
}

type StateWithChildState<T> = T & StateFromB;

// Here I call classA with the Type from children (it will be classC) + state type of classB
abstract class ClassB<T> extends ClassA<StateWithChildState<T>> {
    initialState: StateWithChildState<T> = {
        count: 0
    } as const;
}

interface StateFromC {
    allItems: any[];
}

class ClassC extends ClassB<StateFromC> {

    initialState: StateWithChildState<StateFromC> = {
        ...super.initialState,
        allItems: []
    } as const;
}
```

But typescript throw an error in the initialState of classB
'T' could be instantiated with an arbitrary type which could be unrelated to '{ readonly count: 0; }'. I understand why I have this error, but I can't find how to solve it.

How can I have my initialState in classB and classC and fully typed ?

Body:
I have 3 class, for the simplification, it's class A, B and C.

C inherit from B and B inherit from A. They share a same property initialState. The class A only declare the property initialState, the class B define initialState with a value, and class C define an initialState, it should use it own value + the one inherited from class B.

Here is my simple example:

abstract class ClassA<T> {
    readonly initialState: T; // initialState takes type from the class generic
}

interface StateFromB {
    count: number;
}

type StateWithChildState<T> = T & StateFromB;

// Here I call classA with the Type from children (it will be classC) + state type of classB
abstract class ClassB<T> extends ClassA<StateWithChildState<T>> {
    initialState: StateWithChildState<T> = {
        count: 0
    } as const;
}

interface StateFromC {
    allItems: any[];
}

class ClassC extends ClassB<StateFromC> {

    initialState: StateWithChildState<StateFromC> = {
        ...super.initialState,
        allItems: []
    } as const;
}

But typescript throw an error in the initialState of classB
'T' could be instantiated with an arbitrary type which could be unrelated to '{ readonly count: 0; }'. I understand why I have this error, but I can't find how to solve it.

How can I have my initialState in classB and classC and fully typed ?


问:
Retrieving HTML table values using python - soup.find_all returns nothing
I am trying to get table values (id = 'ClientTypeBody') of a web page using request and BeautifulSoup. On first try, I just wanted to print all sub-elements of a div with a specific id, but it returns nothing. The following is my snippet:

```<code>    from bs4 import BeautifulSoup
    import requests

    response = requests.get('http://www.tsetmc.com/loader.aspx?ParTree=151311&i=7745894403636165#')
    soup = BeautifulSoup(response.text, 'lxml')
    print(soup.find_all(id = 'ClientTypeContent'))
</code>```

The following image shows the corresponding html source which I have opened in chrome:
HTML Content

I am a little bit newbie in this field! and sorry for possible ambiguity in the question. Thank you.

Getting table values with id ClientTypeBody.

Body:
I am trying to get table values (id = 'ClientTypeBody') of a web page using request and BeautifulSoup. On first try, I just wanted to print all sub-elements of a div with a specific id, but it returns nothing. The following is my snippet:

    from bs4 import BeautifulSoup
    import requests

    response = requests.get('http://www.tsetmc.com/loader.aspx?ParTree=151311&i=7745894403636165#')
    soup = BeautifulSoup(response.text, 'lxml')
    print(soup.find_all(id = 'ClientTypeContent'))

The following image shows the corresponding html source which I have opened in chrome:
HTML Content

I am a little bit newbie in this field! and sorry for possible ambiguity in the question. Thank you.

Getting table values with id ClientTypeBody.


问:
Why do I face this problem in responsive design?
I want my layout to stay like this when it's in mobile screens.
Instead, it goes like this when I scroll a bit
// Here is the navbar code,

```<code>

display: flex;
  align-items: center;
  justify-content: space-between;
  height: 50px;
  padding: 10px;
  position: sticky;
  top: 0;

</code>```

// This is the leftbar code

```<code>display: flex;
  flex-direction: column;
  margin-left: 10px;
  position: sticky;
  top: 70px;
  height: calc(90.383378016085791vh - 70px);
</code>```

// This is the home page code

```<code>  position: sticky;
  top: 70px;
  height: calc(90.383378016085791vh - 70px);
  overflow-y: scroll;
  scroll-behavior: smooth;
</code>```

// And this is the bottom barcode

```<code>position: sticky;
    bottom: 0;
    height: 50px;
    padding: 10px;
</code>```

I want the layout to be the same even if I scroll in mobile screens, where the left bar and home have their own individual scroll.

Body:
I want my layout to stay like this when it's in mobile screens.
Instead, it goes like this when I scroll a bit
// Here is the navbar code,

display: flex;
  align-items: center;
  justify-content: space-between;
  height: 50px;
  padding: 10px;
  position: sticky;
  top: 0;

// This is the leftbar code

display: flex;
  flex-direction: column;
  margin-left: 10px;
  position: sticky;
  top: 70px;
  height: calc(90.383378016085791vh - 70px);

// This is the home page code

  position: sticky;
  top: 70px;
  height: calc(90.383378016085791vh - 70px);
  overflow-y: scroll;
  scroll-behavior: smooth;

// And this is the bottom barcode

position: sticky;
    bottom: 0;
    height: 50px;
    padding: 10px;

I want the layout to be the same even if I scroll in mobile screens, where the left bar and home have their own individual scroll.


问:
Trying to make an efficient query while searching for a specific value and a range of dates in MYSQL
I have this query:

```<code> select * from sales_order a
join sales_order_item b
 on order_id = entity_id
 where b.agent_id = 09
 AND a.creation_date >= '2022-01-01'
AND a.creation_date <= '2022-12-01';
</code>```

sales_order is a table that contains the header information of an
order

sales_order_item is a table that contains the line information of each order

Take a look at this example

Sales_order has these columns (order_id, creation_date)

order_id
creation_date

34.......
2022-02-01

45.......
2022-04-12

56.......
2022-07-22

67.......
2022-08-05

Sales_order_item has these columns (entity_id, item,agent_id)

entity_id
item
agent_id

34.......
3242344213
09

34.......
3442344213
09

34.......
2342344213
09

45.......
3142344213
09

Both tables join by order_id and entity_id.

What would it be the best way to obtain all the order_ids from a specific agent_id and a given range of dates?

Desired result:

I want to obtain all the order_ids (not duplicates) that belong to the agent_id = 09 and between 2022-02-01 and 2022-05-20

order_id

34

45

What would it be the most performant way to solve this?

Body:
I have this query:

 select * from sales_order a
join sales_order_item b
 on order_id = entity_id
 where b.agent_id = 09
 AND a.creation_date >= '2022-01-01'
AND a.creation_date <= '2022-12-01';

sales_order is a table that contains the header information of an
order

sales_order_item is a table that contains the line information of each order

Take a look at this example

Sales_order has these columns (order_id, creation_date)

order_id
creation_date

34.......
2022-02-01

45.......
2022-04-12

56.......
2022-07-22

67.......
2022-08-05

Sales_order_item has these columns (entity_id, item,agent_id)

entity_id
item
agent_id

34.......
3242344213
09

34.......
3442344213
09

34.......
2342344213
09

45.......
3142344213
09

Both tables join by order_id and entity_id.

What would it be the best way to obtain all the order_ids from a specific agent_id and a given range of dates?

Desired result:

I want to obtain all the order_ids (not duplicates) that belong to the agent_id = 09 and between 2022-02-01 and 2022-05-20

order_id

34

45

What would it be the most performant way to solve this?


问:
How to disable refresh token using angular-auth-oidc-client and openiddict?
I am using angular-auth-oidc-client lib with openiddict as identity server:

openiddict config:

.AddServer(options =>
   {
       // Enable the authorization, logout, token and userinfo endpoints.
       options.SetAuthorizationEndpointUris(
                 openIddictConfig.AuthorizationEndpointUris)
               .SetLogoutEndpointUris(openIddictConfig.LogoutEndpointUris)
               .SetTokenEndpointUris(openIddictConfig.TokenEndpointUris)
               .SetAccessTokenLifetime(TimeSpan.FromSeconds(10))
               .SetIdentityTokenLifetime(TimeSpan.FromSeconds(10))
               .SetUserinfoEndpointUris(openIddictConfig.UserinfoEndpointUris);

       // Mark the "email", "profile" and "roles" scopes as supported scopes.
       options.RegisterScopes(Scopes.Email, Scopes.Profile, Scopes.Roles);
       options.SetAccessTokenLifetime(TimeSpan.FromSeconds(10))
               .SetIdentityTokenLifetime(TimeSpan.FromSeconds(10));
       // Note: this sample only uses the authorization code flow but you can enable
       // the other flows if you need to support implicit, password or client credentials.
       options.AllowAuthorizationCodeFlow().RequireProofKeyForCodeExchange();
       //options.AllowRefreshTokenFlow();

       // Register the signing and encryption credentials.
       options.AddDevelopmentEncryptionCertificate()
               .AddDevelopmentSigningCertificate();

       // Register the ASP.NET Core host and configure the ASP.NET Core-specific options.
       options.UseAspNetCore()
               .DisableTransportSecurityRequirement()
               .EnableAuthorizationEndpointPassthrough()
               .EnableLogoutEndpointPassthrough()
               .EnableTokenEndpointPassthrough()
               .EnableUserinfoEndpointPassthrough()
               .EnableStatusCodePagesIntegration();

       // Encryption and signing of tokens
       options
       //    .AddEphemeralEncryptionKey()
       //    .AddEphemeralSigningKey()
           .DisableAccessTokenEncryption();
   })

```
<p>Angular config:</p>
```getOpenIDConfiguration(): OpenIdConfiguration {
  return {
   authority: this.oidcConfig.authority,
   clientId: this.oidcConfig.clientId,
   redirectUrl: this.oidcConfig.redirectUrl,
   postLogoutRedirectUri: this.oidcConfig.postLogoutRedirectUri,
   scope: 'openid profile email ',
   responseType: 'code',
   silentRenew: false,
   useRefreshToken: false,
   logLevel: LogLevel.Debug,
  }
}
```

NB: with this configuration when the token lifetime is expired there is a refresh token.

All I need is to disable the refresh token and set the expired lifetime to the token finally how to implement an expired token handler and log out? Thank you guys for your help.

Body:
I am using angular-auth-oidc-client lib with openiddict as identity server:

openiddict config:

.AddServer(options =>
   {
       // Enable the authorization, logout, token and userinfo endpoints.
       options.SetAuthorizationEndpointUris(
                 openIddictConfig.AuthorizationEndpointUris)
               .SetLogoutEndpointUris(openIddictConfig.LogoutEndpointUris)
               .SetTokenEndpointUris(openIddictConfig.TokenEndpointUris)
               .SetAccessTokenLifetime(TimeSpan.FromSeconds(10))
               .SetIdentityTokenLifetime(TimeSpan.FromSeconds(10))
               .SetUserinfoEndpointUris(openIddictConfig.UserinfoEndpointUris);

       // Mark the "email", "profile" and "roles" scopes as supported scopes.
       options.RegisterScopes(Scopes.Email, Scopes.Profile, Scopes.Roles);
       options.SetAccessTokenLifetime(TimeSpan.FromSeconds(10))
               .SetIdentityTokenLifetime(TimeSpan.FromSeconds(10));
       // Note: this sample only uses the authorization code flow but you can enable
       // the other flows if you need to support implicit, password or client credentials.
       options.AllowAuthorizationCodeFlow().RequireProofKeyForCodeExchange();
       //options.AllowRefreshTokenFlow();

       // Register the signing and encryption credentials.
       options.AddDevelopmentEncryptionCertificate()
               .AddDevelopmentSigningCertificate();

       // Register the ASP.NET Core host and configure the ASP.NET Core-specific options.
       options.UseAspNetCore()
               .DisableTransportSecurityRequirement()
               .EnableAuthorizationEndpointPassthrough()
               .EnableLogoutEndpointPassthrough()
               .EnableTokenEndpointPassthrough()
               .EnableUserinfoEndpointPassthrough()
               .EnableStatusCodePagesIntegration();

       // Encryption and signing of tokens
       options
       //    .AddEphemeralEncryptionKey()
       //    .AddEphemeralSigningKey()
           .DisableAccessTokenEncryption();
   })

Angular config:

getOpenIDConfiguration(): OpenIdConfiguration {
  return {
   authority: this.oidcConfig.authority,
   clientId: this.oidcConfig.clientId,
   redirectUrl: this.oidcConfig.redirectUrl,
   postLogoutRedirectUri: this.oidcConfig.postLogoutRedirectUri,
   scope: 'openid profile email ',
   responseType: 'code',
   silentRenew: false,
   useRefreshToken: false,
   logLevel: LogLevel.Debug,
  }
}

NB: with this configuration when the token lifetime is expired there is a refresh token.

All I need is to disable the refresh token and set the expired lifetime to the token finally how to implement an expired token handler and log out? Thank you guys for your help.