问:
String was not recognized as a valid DateTime. Converting string to DateTime
I need to convert a string to a DateTime format in the following code. But I am encountering the following error. How can I solve this?

Unhandled Exception:

System.FormatException: String was not recognized as a valid DateTime.

```<code>public static int calculateAge(string dateOfBirth)
{
    // Implement code here
    int age = 0;
    DateTime s = DateTime.ParseExact(dateOfBirth, "D", null);
    age = Convert.ToInt32(DateTime.Now.Year - s.Year);
    if (DateTime.Now.DayOfYear < s.DayOfYear)
        age = age - 1;

    return age;
}
</code>```

答:
Correct code.</p>

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

namespace DateEx1              //DO NOT CHANGE the namespace name
{
    public class Program       //DO NOT CHANGE the class name
    {
        public static void Main(string[] args)    //DO NOT CHANGE the 'Main' method signature
        {

             Console.WriteLine("Enter the date of birth (dd-mm-yyyy) ");
             string dateOfBirth=Console.ReadLine();
            Console.WriteLine(calculateAge(dateOfBirth));

        }

        public static int calculateAge(string dateOfBirth)
        {
            //Implement code here
            //int age;
            DateTime s = DateTime.ParseExact(dateOfBirth, "dd-mm-yyyy",null);
            DateTime today = DateTime.Now;
            int year = DateTime.Now.Year;

            int length=dateOfBirth.Length;
            string dcs = dateOfBirth.Substring(6,4);
            string csd=dateOfBirth.Substring(3,2);
            int age2=int.Parse(csd);
            if(age2>=6)
            {
            int age=int.Parse(dcs);
            int age1=(year-1)-age;
            return age1;
            }
            else
            {
                 int age=int.Parse(dcs);
            int age3=(year)-age;
            return age3;
            }
        }

        }

    }
</code>```

Body:
I need to convert a string to a DateTime format in the following code. But I am encountering the following error. How can I solve this?

Unhandled Exception:

System.FormatException: String was not recognized as a valid DateTime.

public static int calculateAge(string dateOfBirth)
{
    // Implement code here
    int age = 0;
    DateTime s = DateTime.ParseExact(dateOfBirth, "D", null);
    age = Convert.ToInt32(DateTime.Now.Year - s.Year);
    if (DateTime.Now.DayOfYear < s.DayOfYear)
        age = age - 1;

    return age;
}

Body:
Correct code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DateEx1              //DO NOT CHANGE the namespace name
{
    public class Program       //DO NOT CHANGE the class name
    {
        public static void Main(string[] args)    //DO NOT CHANGE the 'Main' method signature
        {

             Console.WriteLine("Enter the date of birth (dd-mm-yyyy) ");
             string dateOfBirth=Console.ReadLine();
            Console.WriteLine(calculateAge(dateOfBirth));

        }

        public static int calculateAge(string dateOfBirth)
        {
            //Implement code here
            //int age;
            DateTime s = DateTime.ParseExact(dateOfBirth, "dd-mm-yyyy",null);
            DateTime today = DateTime.Now;
            int year = DateTime.Now.Year;

            int length=dateOfBirth.Length;
            string dcs = dateOfBirth.Substring(6,4);
            string csd=dateOfBirth.Substring(3,2);
            int age2=int.Parse(csd);
            if(age2>=6)
            {
            int age=int.Parse(dcs);
            int age1=(year-1)-age;
            return age1;
            }
            else
            {
                 int age=int.Parse(dcs);
            int age3=(year)-age;
            return age3;
            }
        }

        }

    }


来源: stackexchange

问:
Apache Flink checkpointing stuck
we are running a job that has a ListState of between 300GB and 400GB and sometimes the list can grow to few thousands. In our use case, every item must have its own TTL, therefore we we create a new Timer for every new item of this ListState with a RocksDB backend on S3.

This currently is about 140+ millions of timers (that will trigger at event.timestamp + 40days).

Our problem is that suddenly the checkpointing of the job gets stuck, or VERY slow (like 1% in few hours) until it eventually timeouts. It generally stops (flink dashboard shows 0/12 (0%) while the previous lines show 12/12 (100%)) on a piece of the code which is pretty simple :

```<code>[...]
    val myStream = env.addSource(someKafkaConsumer)
      .rebalance
      .map(new CounterMapFunction[ControlGroup]("source.kafkaconsumer"))
      .uid("src_kafka_stream")
      .name("some_name")

      myStream.process(new MonitoringProcessFunction()).uid("monitoring_uuid").name(monitoring_name)
        .getSideOutput(outputTag)
        .keyBy(_.name)
        .addSink(sink)
[...]

</code>```

Few more information :

AT_LEAST_ONCE checkpointing mode seems to get more easily stuck than EXACTLY_ONCE

Few months ago the state went up to 1.5TB of data and I think billions of timers without any issue.

RAM, CPU and Networking on the machines where run both taskmanagers look normal

state.backend.rocksdb.thread.num = 4

First incident happened right when we received a flood of events (about millions in minutes) but not on the previous one.

All of the events come from Kafka topics.

When in AT_LEAST_ONCE checkpointing mode, the job still runs and consumes normally.

It's the second times that it happens to us that the topology runs very fine with few millions of events per day and suddenly stops checkpointing. We have no idea what could cause this.

Anyone can think of what could suddenly cause the checkpointing to get stuck?

答:
A few thoughts:

If you have many timers all firing more-or-less simultaneously, this storm of timers will prevent anything else from happening -- the tasks will loop calling onTimer until there are no more timers to be fired, during which time their input queues will be ignored, and checkpoint barriers will not progress.

If this is the cause of your troubles, you might add some random jitter to your timers so that event storms don't turn into timer storms later on. Reorganizing things to use State TTL might be another option.

If you have a lot of timers on the heap, this can lead to very high GC overhead. This won't necessarily fail the job, but can make checkpointing unstable. In this case, moving the timers into RocksDB may help.

Also: since you are using RocksDB, switching from ListState to MapState, with time as the key, would let you remove single entries without having to reserialize the entire list after each update. (With RocksDB, each key/value pair in a MapState is a separate RocksDB object.) Making the cleanup more efficient in this way might be the best remedy.

ContentLicense: CC BY-SA 4.0

Title: Apache Flink checkpointing stuck

Body:
we are running a job that has a ListState of between 300GB and 400GB and sometimes the list can grow to few thousands. In our use case, every item must have its own TTL, therefore we we create a new Timer for every new item of this ListState with a RocksDB backend on S3.

This currently is about 140+ millions of timers (that will trigger at event.timestamp + 40days).

Our problem is that suddenly the checkpointing of the job gets stuck, or VERY slow (like 1% in few hours) until it eventually timeouts. It generally stops (flink dashboard shows 0/12 (0%) while the previous lines show 12/12 (100%)) on a piece of the code which is pretty simple :

[...]
    val myStream = env.addSource(someKafkaConsumer)
      .rebalance
      .map(new CounterMapFunction[ControlGroup]("source.kafkaconsumer"))
      .uid("src_kafka_stream")
      .name("some_name")

      myStream.process(new MonitoringProcessFunction()).uid("monitoring_uuid").name(monitoring_name)
        .getSideOutput(outputTag)
        .keyBy(_.name)
        .addSink(sink)
[...]

Few more information :

AT_LEAST_ONCE checkpointing mode seems to get more easily stuck than EXACTLY_ONCE

Few months ago the state went up to 1.5TB of data and I think billions of timers without any issue.

RAM, CPU and Networking on the machines where run both taskmanagers look normal

state.backend.rocksdb.thread.num = 4

First incident happened right when we received a flood of events (about millions in minutes) but not on the previous one.

All of the events come from Kafka topics.

When in AT_LEAST_ONCE checkpointing mode, the job still runs and consumes normally.

It's the second times that it happens to us that the topology runs very fine with few millions of events per day and suddenly stops checkpointing. We have no idea what could cause this.

Anyone can think of what could suddenly cause the checkpointing to get stuck?


问:
`Vector.erase()` does not work for vector of classes
I've made a class of gym pass that has expiration date (int expiration), price for the pass (float price) and name of its' holder (string data). It also has services (char services), where 0 is basic, 1 is with free showers and 2 is VIP room.

Here's the definition of class:

    class GymPass
    {
        int expiration; //the amount of days
        char services; //0 - basic, 1 - shower, 2 - VIP room
        float price = ((int)services - 47) * expiration;
        string data; //client's identifiable data
    public:

        GymPass()
        {
            cout << "this: " << this;
            expiration = 0;
            services = '0';
            price = 0;
            data = "Lorem ipsum";
        }
        Pass(int expiration, char services, string data)
        {
            this->expiration = expiration;
            this->services = services;
            this->data = data;
        }

        void Print()
        {
            cout << "Gym Pass: ";
            switch (services)
            {
            case '0':
            {
                cout << "Basic gym access, ";
            }
            case '1':
            {
                cout << "gym + shower room, ";
            }
            case '2':
            {
                cout << "Luxurious gym pass with VIP room, ";
            }
            default:
            {
                cout << "Error."; //this should never happen
            }
            }
            cout << "valid for: " << expiration << " days, price: " << price << " zl." << endl;
        }
        void NewPass()
        {
            cout << "Choose service type: \n0 - basic\n1 - showers included\n2 - vip room included";
            {
                char temp{};
                do
                {
                    cin >> temp;
                    if (!((int)temp > 47 & (int)temp < 51)) cout << endl << "Incorrect service type.";
                } while (!((int)temp > 47 & (int)temp < 51));
                this->services = temp;
            }
            cout << endl << "Input the expiration date of the Pass:";
            cin >> this->expiration;
            cout << endl << "Input your name: ";
            cin >> this->data;
        }
        friend bool operator==(const GymPass& lhs, const GymPass& rhs)
        {
            if (lhs.price != rhs.price) return false;
            if (!(lhs.data._Equal(rhs.data))) return false;
            if (lhs.services != rhs.services) return false;
            if (lhs.expiration != rhs.expiration) return false;
            return true;
        }
    };
```
<p>I also made a class that's basically a vector of my <code>GymPass</code> classes. I'm trying to make a void function to delete one gym pass, but the erase throws error:</p>
<p><code>no instance of overloaded function "std::vector<_Ty, _Alloc>::erase [with _Ty=GymPass, _Alloc=std::allocator<GymPass>]" matches the argument list</code></p>
<p>Like a good programmer, I've done hours of googling, but to no luck. Here's definition of gym class</p>
<pre class="lang-cpp prettyprint-override"><code>     class Gym
    {
        vector <GymPass> Clients;
    public:
        void add(GymPass pass)
        {
            Clients.push_back(pass);
        }
        void remove(GymPass pass)
        {
            for (int i = 0; i < Clients.size(); i++)
            {
                if (Clients[i] == pass) Clients.erase(i);
            }
        }
    };
</code>```

void remove is the delete function, where I get the error. How do I fix the error?

答:
You must read erase()  doc first: erase() expects an iterator

Then something like this must do the job:

```<code>for (auto it = Stali_Klienci.begin(); it != Stali_Klienci.end(); )
{
   if (*it == karnet) {
        it = c.erase(it);
   } else {
        ++it;
   }
}
</code>```

Body:
I've made a class of gym pass that has expiration date (int expiration), price for the pass (float price) and name of its' holder (string data). It also has services (char services), where 0 is basic, 1 is with free showers and 2 is VIP room.

Here's the definition of class:

    class GymPass
    {
        int expiration; //the amount of days
        char services; //0 - basic, 1 - shower, 2 - VIP room
        float price = ((int)services - 47) * expiration;
        string data; //client's identifiable data
    public:

        GymPass()
        {
            cout << "this: " << this;
            expiration = 0;
            services = '0';
            price = 0;
            data = "Lorem ipsum";
        }
        Pass(int expiration, char services, string data)
        {
            this->expiration = expiration;
            this->services = services;
            this->data = data;
        }

        void Print()
        {
            cout << "Gym Pass: ";
            switch (services)
            {
            case '0':
            {
                cout << "Basic gym access, ";
            }
            case '1':
            {
                cout << "gym + shower room, ";
            }
            case '2':
            {
                cout << "Luxurious gym pass with VIP room, ";
            }
            default:
            {
                cout << "Error."; //this should never happen
            }
            }
            cout << "valid for: " << expiration << " days, price: " << price << " zl." << endl;
        }
        void NewPass()
        {
            cout << "Choose service type: \n0 - basic\n1 - showers included\n2 - vip room included";
            {
                char temp{};
                do
                {
                    cin >> temp;
                    if (!((int)temp > 47 & (int)temp < 51)) cout << endl << "Incorrect service type.";
                } while (!((int)temp > 47 & (int)temp < 51));
                this->services = temp;
            }
            cout << endl << "Input the expiration date of the Pass:";
            cin >> this->expiration;
            cout << endl << "Input your name: ";
            cin >> this->data;
        }
        friend bool operator==(const GymPass& lhs, const GymPass& rhs)
        {
            if (lhs.price != rhs.price) return false;
            if (!(lhs.data._Equal(rhs.data))) return false;
            if (lhs.services != rhs.services) return false;
            if (lhs.expiration != rhs.expiration) return false;
            return true;
        }
    };

I also made a class that's basically a vector of my GymPass classes. I'm trying to make a void function to delete one gym pass, but the erase throws error:

no instance of overloaded function "std::vector<_Ty, _Alloc>::erase [with _Ty=GymPass, _Alloc=std::allocator<GymPass>]" matches the argument list

Like a good programmer, I've done hours of googling, but to no luck. Here's definition of gym class

     class Gym
    {
        vector <GymPass> Clients;
    public:
        void add(GymPass pass)
        {
            Clients.push_back(pass);
        }
        void remove(GymPass pass)
        {
            for (int i = 0; i < Clients.size(); i++)
            {
                if (Clients[i] == pass) Clients.erase(i);
            }
        }
    };

void remove is the delete function, where I get the error. How do I fix the error?

Body:
You must read erase()  doc first: erase() expects an iterator

Then something like this must do the job:

for (auto it = Stali_Klienci.begin(); it != Stali_Klienci.end(); )
{
   if (*it == karnet) {
        it = c.erase(it);
   } else {
        ++it;
   }
}


问:
What's the best way to get rid of nested ifs in code while checking for conditions?
I'm developing a BlackBerry app in Java and I have an Options class where all user settings are stored. The problem is I need to check some conditions in order to know how to react. As I keep adding more features, more GUI options are shown to the user, more settings are stored in the Options class and more conditions need to be checked for.

Take the following code for example:

```<code>private void doCallMonitoring(int callId){
    /*This is the part that I want to avoid. Having
      multiple nested ifs. Here's just two conditions
      but as I add more, it will get unmantainable
      very quickly.*/
    if(Options.isActive().booleanValue()){
        callTime = new Timer();
        TimerTask callTimeTask = new TimerTask(){
            public void run(){
                callTimeSeconds++;
        if((callTimeSeconds == Options.getSoftLimit().intValue()) && (Phone.getActiveCall().getStatus() == PhoneCall.STATUS_CONNECTED)){
                    injectDTMFTone(Phone.getActiveCall());
        }else if((callTimeSeconds >= Options.getHardLimit().intValue()) && (Phone.getActiveCall().getStatus() == PhoneCall.STATUS_CONNECTED)){
                    injectEndCall();
                }
             }
        };
        callTime.schedule(callTimeTask, 0,1000);
    }else{
    System.out.println("Service not active");
    }
}
</code>```

How I would want it to work is to verify all options with a single call and from there determine the curse of action. How can I achieve such a design?

答:
You can use "extract method" refactoring and have all those checks into a one "readable" condition.

See this related answer Is bit lengthy but the point is to replace constructs like this:

```<code>       }else if((callTimeSeconds >= Options.getHardLimit().intValue()) && (Phone.getActiveCall().getStatus() == PhoneCall.STATUS_CONNECTED)){
                injectEndCall();
            }
         }
</code>```

For something like this:

```<code>       ....
       }else if(shouldInjectEndCall() ){
                injectEndCall();
            }
         }
       ...
</code>```

Remember objects do have state and may use other object to help them do its work.

OwnerDisplayName: Cesar

ContentLicense: CC BY-SA 2.5

Body:
I'm developing a BlackBerry app in Java and I have an Options class where all user settings are stored. The problem is I need to check some conditions in order to know how to react. As I keep adding more features, more GUI options are shown to the user, more settings are stored in the Options class and more conditions need to be checked for.

Take the following code for example:

private void doCallMonitoring(int callId){
    /*This is the part that I want to avoid. Having
      multiple nested ifs. Here's just two conditions
      but as I add more, it will get unmantainable
      very quickly.*/
    if(Options.isActive().booleanValue()){
        callTime = new Timer();
        TimerTask callTimeTask = new TimerTask(){
            public void run(){
                callTimeSeconds++;
        if((callTimeSeconds == Options.getSoftLimit().intValue()) && (Phone.getActiveCall().getStatus() == PhoneCall.STATUS_CONNECTED)){
                    injectDTMFTone(Phone.getActiveCall());
        }else if((callTimeSeconds >= Options.getHardLimit().intValue()) && (Phone.getActiveCall().getStatus() == PhoneCall.STATUS_CONNECTED)){
                    injectEndCall();
                }
             }
        };
        callTime.schedule(callTimeTask, 0,1000);
    }else{
    System.out.println("Service not active");
    }
}

How I would want it to work is to verify all options with a single call and from there determine the curse of action. How can I achieve such a design?

Body:
You can use "extract method" refactoring and have all those checks into a one "readable" condition.

See this related answer Is bit lengthy but the point is to replace constructs like this:

       }else if((callTimeSeconds >= Options.getHardLimit().intValue()) && (Phone.getActiveCall().getStatus() == PhoneCall.STATUS_CONNECTED)){
                injectEndCall();
            }
         }

For something like this:

       ....
       }else if(shouldInjectEndCall() ){
                injectEndCall();
            }
         }
       ...

Remember objects do have state and may use other object to help them do its work.

OwnerDisplayName: Oscar Reyes


问:
Hibernate L2 Caching for many-to-one associations
I am somewhat new to hibernate and am attempting to implement second level caching using ehCache.  I am running into a problem when attempting to use the L2 cache to retrieve a many-to-one association.  The association mapping in my foo.hbm.xml file looks like:

```<code><hibernate-mapping>
    <class name="com.test.Foo" table="FOO" >
        <id name="id" type="long">
            <column name="FOO_ID" precision="11" scale="0" />
            <generator class="assigned" />
        </id>

        <many-to-one name="bar" class="com.test.Bar" >
            <cache usage="read-only" />
            <column name="BAR_TY" not-null="true" />
            <column name="BAR_VAL" length="4" not-null="true" />
        </many-to-one>

    </class>
</hibernate-mapping>
</code>```

(This is a very shortened/modified version of my actual hbm.xml file, hopefully no errors in it)

Note that I am only caching "bar", not "foo".  However when I run a unit test with this mapping I get the following error:

SEVERE: Error parsing XML: XML InputStream(40) The content of element type "many-to-one" must match "(meta*,(column|formula)*)".

When I take out  it works fine, just no L2 caching.
Is it simply that the many-to-one relationship doesn't support caching?  And if so, any suggestions on how to get around this?

FYI I have another unit test that reads "bar" directly (i.e. not through an association) and it works correctly - the 2nd time I get a "bar" it gets it from the L2 cache, so I'm fairly confident I have the rest of the configuration done correctly.  And so sorry, still in the stone ages at work so no annotations etc.

答: Have you tried moving definition of bar into another, separate .hbm.xml and only referencing it from foo?

ContentLicense: CC BY-SA 3.0

Body:
I am somewhat new to hibernate and am attempting to implement second level caching using ehCache.  I am running into a problem when attempting to use the L2 cache to retrieve a many-to-one association.  The association mapping in my foo.hbm.xml file looks like:

<hibernate-mapping>
    <class name="com.test.Foo" table="FOO" >
        <id name="id" type="long">
            <column name="FOO_ID" precision="11" scale="0" />
            <generator class="assigned" />
        </id>

        <many-to-one name="bar" class="com.test.Bar" >
            <cache usage="read-only" />
            <column name="BAR_TY" not-null="true" />
            <column name="BAR_VAL" length="4" not-null="true" />
        </many-to-one>

    </class>
</hibernate-mapping>

(This is a very shortened/modified version of my actual hbm.xml file, hopefully no errors in it)

Note that I am only caching "bar", not "foo".  However when I run a unit test with this mapping I get the following error:

SEVERE: Error parsing XML: XML InputStream(40) The content of element type "many-to-one" must match "(meta*,(column|formula)*)".

When I take out  it works fine, just no L2 caching.
Is it simply that the many-to-one relationship doesn't support caching?  And if so, any suggestions on how to get around this?

FYI I have another unit test that reads "bar" directly (i.e. not through an association) and it works correctly - the 2nd time I get a "bar" it gets it from the L2 cache, so I'm fairly confident I have the rest of the configuration done correctly.  And so sorry, still in the stone ages at work so no annotations etc.


问:
Set random string variable in laravel InfyOm
Hi i use InfyOm (Laravel Genrator).
I want set random string to variable key on adding new record, but i dont know how i can do it.

Keys Controller

```<code>public function store(CreatekeysRequest $request)
{
    $input = $request->all();

    $keys = $this->keysRepository->create($input);

    Flash::success('Added');

    return redirect(route('keys.index'));
}
</code>```

i generate string on key model with mutator but key changed always when i edit record.

Keys model

```<code>public function setDomainAttribute($value) {
    $this->attributes['domain'] = $value;
    $key = $this->attributes['key'] = Str::random(16);
    Flash::success("Key generated for {$value}<br><b>{$key}");
}
</code>```

答:
I'm not familiar with InfyOm but I believe you can just use the standard Eloquent events like so:

<?php
// models/Key.php
class Key
{
    public static function boot()
    {
        parent::boot();
        self::creating(function($model) {
            $model->key = Str::random(16);
        });
    }
}
```

The above code will set the key property when you're creating a new Key model.

See https://laravel.com/docs/7.x/eloquent#events

Body:
Hi i use InfyOm (Laravel Genrator).
I want set random string to variable key on adding new record, but i dont know how i can do it.

Keys Controller

public function store(CreatekeysRequest $request)
{
    $input = $request->all();

    $keys = $this->keysRepository->create($input);

    Flash::success('Added');

    return redirect(route('keys.index'));
}

i generate string on key model with mutator but key changed always when i edit record.

Keys model

public function setDomainAttribute($value) {
    $this->attributes['domain'] = $value;
    $key = $this->attributes['key'] = Str::random(16);
    Flash::success("Key generated for {$value}
{$key}");
}

Body:
I'm not familiar with InfyOm but I believe you can just use the standard Eloquent events like so:

<?php
// models/Key.php
class Key
{
    public static function boot()
    {
        parent::boot();
        self::creating(function($model) {
            $model->key = Str::random(16);
        });
    }
}

The above code will set the key property when you're creating a new Key model.

See https://laravel.com/docs/7.x/eloquent#events


问:
How do i prompt user to re-enter input for previous waterfall step if he/she finds the input entered to be incorrect
The scenario is as follows:

In case the input provided by user seems incorrect in a waterfall step (e.g. incorrect name, incorrect date)
User would like to enter the last input again by saying “ (reenter)” or  (enter again) .

It’s like if there are three steps in waterfall dialog: Step1->Step2->Step3

After providing input for Step2, if user sees the input to be incorrect he would like to interrupt the flow by saying any of the words mentioned above to enter input for previous step.

I could not find a way to go back to previous waterfall step.

There are few solution available to go back to previous step but I was unable to replicate the same in python.

Link1:- Bot framework v4.0 how to execute the previous waterfall step in a dialog

Link2:- https://pauliom.com/2018/08/08/manipulating-waterfall-steps-botframework-v4/

I tried handling the scenario using interrupt but the issue persists as the next Turn continues from where the conversation left off.

答:
What you can use is Validators, check this article for more information or find below code snippets [c#] as a summary.
 I have also added a Python snippet in the end

When a user replies to your prompt the validation will be triggered.
If the validation returns false, a retry prompt will be sent to the user

There is no need to go back to the previous step if you implement validators

            AddDialog(new TextPrompt("TextPromptId", UserNameValidation));
            AddDialog(new NumberPrompt<int>("NumberPromptId", MobileNumberValidation));
            AddDialog(new ChoicePrompt("ChoicePromptId", ChoiceValidataion));
```

<p>Username Validator:</p>

<pre class="lang-cs prettyprint-override"><code>
    private Task<bool> UserNameValidation(PromptValidatorContext<string> promptContext, CancellationToken cancellationToken)
           {
               return Task.FromResult(true);
           }
</code>```

Choice Validator:

    private Task<bool> ChoiceValidataion(PromptValidatorContext<FoundChoice> promptContext, CancellationToken cancellationToken)
            {
                return Task.FromResult(true);
            }

```

<p>Mobile Phone Validator:</p>

<pre class="lang-cs prettyprint-override"><code>

    private async Task<bool> MobileNumberValidation(PromptValidatorContext<int> promptcontext, CancellationToken cancellationtoken)
            {
                if (!promptcontext.Recognized.Succeeded)
                {
                    await promptcontext.Context.SendActivityAsync("Hello, Please enter the valid mobile no",
                        cancellationToken: cancellationtoken);

                    return false;
                }

                int count = Convert.ToString(promptcontext.Recognized.Value).Length;
                if (count != 10)
                {
                    await promptcontext.Context.SendActivityAsync("Hello , you are missing some number !!!",
                        cancellationToken: cancellationtoken);
                    return false;
                }

                return true;
            }

</code>```

I am not a Python developer but you find a python sample in Here in the Python tab and the below snippet:

async def age_prompt_validator(prompt_context: PromptValidatorContext) -> bool:
    # This condition is our validation rule. You can also change the value at this point.
    return (
        prompt_context.recognized.succeeded
        and 0 < prompt_context.recognized.value < 150
    )
```

Hope that helps

Body:
What you can use is Validators, check this article for more information or find below code snippets [c#] as a summary.
 I have also added a Python snippet in the end

When a user replies to your prompt the validation will be triggered.
If the validation returns false, a retry prompt will be sent to the user

There is no need to go back to the previous step if you implement validators

            AddDialog(new TextPrompt("TextPromptId", UserNameValidation));
            AddDialog(new NumberPrompt<int>("NumberPromptId", MobileNumberValidation));
            AddDialog(new ChoicePrompt("ChoicePromptId", ChoiceValidataion));

Username Validator:

    private Task<bool> UserNameValidation(PromptValidatorContext<string> promptContext, CancellationToken cancellationToken)
           {
               return Task.FromResult(true);
           }

Choice Validator:

    private Task<bool> ChoiceValidataion(PromptValidatorContext<FoundChoice> promptContext, CancellationToken cancellationToken)
            {
                return Task.FromResult(true);
            }

Mobile Phone Validator:

    private async Task<bool> MobileNumberValidation(PromptValidatorContext<int> promptcontext, CancellationToken cancellationtoken)
            {
                if (!promptcontext.Recognized.Succeeded)
                {
                    await promptcontext.Context.SendActivityAsync("Hello, Please enter the valid mobile no",
                        cancellationToken: cancellationtoken);

                    return false;
                }

                int count = Convert.ToString(promptcontext.Recognized.Value).Length;
                if (count != 10)
                {
                    await promptcontext.Context.SendActivityAsync("Hello , you are missing some number !!!",
                        cancellationToken: cancellationtoken);
                    return false;
                }

                return true;
            }

I am not a Python developer but you find a python sample in Here in the Python tab and the below snippet:

async def age_prompt_validator(prompt_context: PromptValidatorContext) -> bool:
    # This condition is our validation rule. You can also change the value at this point.
    return (
        prompt_context.recognized.succeeded
        and 0 < prompt_context.recognized.value < 150
    )

Hope that helps


问:
Using Constructors in C# - getting multiple errors following an almost 2 year old course
I just started learning C#, having previously learned Python. I know how classes and constructors work in Python with init(self,...)

I'm following the Giraffe Academy / FreeCodeCamp tutorial on C#, and I am doing the exact same thing as him (I can't see any difference anyway). Still, I get errors when trying to create a constructor for a book Class. This is my code, and I get like 5 different errors from it:

```<code> namespace StuffThingy
    {
        class Book
        {
            public string title;
            public string author;
            public int pages;
        }
        public Book(string aTitle,string aAuthor, int aPages)
        {
            title = aTitle;
            author = aAuthor;
            pages = aPages;
        }
</code>```

It's like it doesn't recognize that I have just defined the public variables before using them in my constructor

答:
Try to put the Constructor INSIDE the class.</p>

```<code>namespace StuffThingy
{
    class Book
    {
        public string title;
        public string author;
        public int pages;

        public Book(string aTitle,string aAuthor, int aPages)
        {
            title = aTitle;
            author = aAuthor;
            pages = aPages;
        }
    }
}
</code>```

Body:
I just started learning C#, having previously learned Python. I know how classes and constructors work in Python with init(self,...)

I'm following the Giraffe Academy / FreeCodeCamp tutorial on C#, and I am doing the exact same thing as him (I can't see any difference anyway). Still, I get errors when trying to create a constructor for a book Class. This is my code, and I get like 5 different errors from it:

 namespace StuffThingy
    {
        class Book
        {
            public string title;
            public string author;
            public int pages;
        }
        public Book(string aTitle,string aAuthor, int aPages)
        {
            title = aTitle;
            author = aAuthor;
            pages = aPages;
        }

It's like it doesn't recognize that I have just defined the public variables before using them in my constructor

Body:
Try to put the Constructor INSIDE the class.

namespace StuffThingy
{
    class Book
    {
        public string title;
        public string author;
        public int pages;

        public Book(string aTitle,string aAuthor, int aPages)
        {
            title = aTitle;
            author = aAuthor;
            pages = aPages;
        }
    }
}


问:
Retrofit okhttp doesn't send any request
At my logcat I have such lines during server call:

```<code>Rejecting re-init on previously-failed class java.lang.Class<okhttp3.internal.platform.ConscryptPlatform$platformTrustManager$2>: java.lang.NoClassDefFoundError: Failed resolution of: Lorg/conscrypt/ConscryptHostnameVerifier;

Caused by: java.lang.ClassNotFoundException: Didn't find class "org.conscrypt.ConscryptHostnameVerifier" on path: DexPathList[[zip file "/data/app/package-JHk9QBF7PSIufoXeKqbmNA==/base.apk"],nativeLibraryDirectories=[/data/app/package-JHk9QBF7PSIufoXeKqbmNA==/lib/x86, /system/lib, /system/vendor/lib]]
</code>```

After some time I can see such message:

```<code>okhttp.OkHttpClient: <-- HTTP FAILED: java.net.SocketTimeoutException: timeout
</code>```

And I checked that internet works well on my device. App doesn't crashes but I can't send any request. For example everything was working well during all this week, and right now smth damaged :( How to fix this error?

UPDATE

My gradle app file:

```<code>buildscript {
    ext.kotlin_version = '1.3.71'
    repositories { jcenter() }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.72"
        classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version"
    }
}

apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlinx-serialization'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 29
    defaultConfig {
        applicationId "package"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 87
        versionName "1.0.0"
        testInstrumentationRunner "android.support.APICallRequests.runner.AndroidJUnitRunner"
    }
    buildTypes {
        debug {
            buildConfigField "String", "API_URL", 'url'
        }
        release {
            buildConfigField "String", "API_URL", 'url'
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.release
        }
    }

    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = "1.8"
    }

    lintOptions {
        checkReleaseBuilds false
        // Or, if you prefer, you can continue to check for errors in release builds,
        // but continue the build even when errors are found:
        abortOnError false
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation files('libs/mail.jar')
    implementation 'com.jakewharton.timber:timber:4.7.1'
    implementation 'org.apache.commons:commons-io:1.3.2'

    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    testImplementation 'junit:junit:4.13'

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    implementation 'androidx.cardview:cardview:1.0.0'

    // Retrofit
    implementation 'com.google.code.gson:gson:2.8.6'
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation 'com.squareup.retrofit2:converter-scalars:2.9.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:4.7.2'
    implementation 'org.jsoup:jsoup:1.13.1'

    implementation 'us.belka:androidtoggleswitch:1.2.2'
    implementation 'com.github.droidbond:LoadingButton:0.1.5'

    implementation 'io.github.tonnyl:whatsnew:0.1.1'
    implementation 'com.github.GrenderG:Toasty:1.3.1'
    implementation 'com.lsjwzh:materialloadingprogressbar:0.5.8-RELEASE'

    implementation 'com.daimajia.swipelayout:library:1.2.0@aar'

    implementation 'androidx.browser:browser:1.2.0'

    implementation 'com.google.firebase:firebase-analytics:17.4.2'
    implementation 'com.crashlytics.sdk.android:crashlytics:2.10.1'
    implementation 'com.google.firebase:firebase-messaging:20.2.0'
    implementation 'com.google.firebase:firebase-core:17.4.2'

    implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.3.72'
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.14.0" // JVM dependency
    implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.72'

    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.0"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.0"
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7"
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"

    implementation 'com.squareup.picasso:picasso:2.71828'
    implementation 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0'
}
</code>```

答: Looks like OkHttp need something like this: implementation 'org.conscrypt:conscrypt-android:2.4.0'. I'm not sure if it's newest version, but according to Github it is.

Body:
At my logcat I have such lines during server call:

Rejecting re-init on previously-failed class java.lang.Class<okhttp3.internal.platform.ConscryptPlatform$platformTrustManager$2>: java.lang.NoClassDefFoundError: Failed resolution of: Lorg/conscrypt/ConscryptHostnameVerifier;

Caused by: java.lang.ClassNotFoundException: Didn't find class "org.conscrypt.ConscryptHostnameVerifier" on path: DexPathList[[zip file "/data/app/package-JHk9QBF7PSIufoXeKqbmNA==/base.apk"],nativeLibraryDirectories=[/data/app/package-JHk9QBF7PSIufoXeKqbmNA==/lib/x86, /system/lib, /system/vendor/lib]]

After some time I can see such message:

okhttp.OkHttpClient: <-- HTTP FAILED: java.net.SocketTimeoutException: timeout

And I checked that internet works well on my device. App doesn't crashes but I can't send any request. For example everything was working well during all this week, and right now smth damaged :( How to fix this error?

UPDATE

My gradle app file:

buildscript {
    ext.kotlin_version = '1.3.71'
    repositories { jcenter() }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.72"
        classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version"
    }
}

apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlinx-serialization'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 29
    defaultConfig {
        applicationId "package"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 87
        versionName "1.0.0"
        testInstrumentationRunner "android.support.APICallRequests.runner.AndroidJUnitRunner"
    }
    buildTypes {
        debug {
            buildConfigField "String", "API_URL", 'url'
        }
        release {
            buildConfigField "String", "API_URL", 'url'
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.release
        }
    }

    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = "1.8"
    }

    lintOptions {
        checkReleaseBuilds false
        // Or, if you prefer, you can continue to check for errors in release builds,
        // but continue the build even when errors are found:
        abortOnError false
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation files('libs/mail.jar')
    implementation 'com.jakewharton.timber:timber:4.7.1'
    implementation 'org.apache.commons:commons-io:1.3.2'

    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    testImplementation 'junit:junit:4.13'

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    implementation 'androidx.cardview:cardview:1.0.0'

    // Retrofit
    implementation 'com.google.code.gson:gson:2.8.6'
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation 'com.squareup.retrofit2:converter-scalars:2.9.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:4.7.2'
    implementation 'org.jsoup:jsoup:1.13.1'

    implementation 'us.belka:androidtoggleswitch:1.2.2'
    implementation 'com.github.droidbond:LoadingButton:0.1.5'

    implementation 'io.github.tonnyl:whatsnew:0.1.1'
    implementation 'com.github.GrenderG:Toasty:1.3.1'
    implementation 'com.lsjwzh:materialloadingprogressbar:0.5.8-RELEASE'

    implementation 'com.daimajia.swipelayout:library:1.2.0@aar'

    implementation 'androidx.browser:browser:1.2.0'

    implementation 'com.google.firebase:firebase-analytics:17.4.2'
    implementation 'com.crashlytics.sdk.android:crashlytics:2.10.1'
    implementation 'com.google.firebase:firebase-messaging:20.2.0'
    implementation 'com.google.firebase:firebase-core:17.4.2'

    implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.3.72'
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.14.0" // JVM dependency
    implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.72'

    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.0"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.0"
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7"
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"

    implementation 'com.squareup.picasso:picasso:2.71828'
    implementation 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0'
}


问:
When use async/await on .net core web-api with repository pattern?
I'm trying to write a simple web api service with Users CRUD, i'm a bit confused about using async/await methods in repository pattern...
pattern flow is: CONTROLLER > BLOGIC > REPOSITORY
where i must use async/await methods ?
in all layers or only at the top (controller layer)?</p>

答:
async is "bubbling" up in your code structure, so obviously main source of asynchronous code  should be your repository layer, but to leverage it being asynchronous you will need to make all calling code to be asynchronous too (or just return Task<T> if caller just passes results without doing anything with them) otherwise you will need to block on asynchronous call which basically not only removes all possible gains from it but also in some cases can introduce issues.

Also please read this answer.


问:
The color of and <input type="color"> element on a page DOESN'T match its value attribute
I am working on a personnal exercise where I create a small app to allow users to update colors of different parts of an SVG using the <input type = "color"> element.

The SVG I am playing with is a simple cloud drawings with writing in it. You can modify 3 parts: cloud's stroke color, cloud's fill color and writing's color.

See it live:

live: https://argonathmos.github.io/SVGfun/

code: https://github.com/argonathmos/SVGfun

It is a simple UI with 3 areas:

A Random button that applies random colors to each parts of the
SVG.

Three <input type="color"> element for each part of the SVG to
modify each colors by hand.

A Download button that allows the
user to export the SVG with the custom colors applyied to it.

Here is what I notice that bothers me and don't know how to fix yet:

When I click "random", the SVG colors are updated, as well as the value of the <input type="color"> elements, as well as the color of the  element on the page (ie the little squares color matches the colors of the associated SVG section).

When I apply a color individually through the <input type="color"> element the color of the SVG is updated as well as the value of the <input type="color"> element, and so is the color of the input color element on the page (the little square).

But If I click "random" after having already selected a color from the color picker by hand:
The SVG colors are updated, the value attribute of the <input type="color"> elements as well, but the color of the  element on the page doesn't update its stays the same as the previously hand picked color. (ie the little square color DOESN'T match the color of the associated SVG section eventhough the value attribute of the  element does.)

答:
The problem appears to be, that you are using

```<code> strokeColorInput.setAttribute('value',strokeColor);
</code>```

to update the value of your color input fields. That is able to set the color for fields you did not already make an explicit choice in, but once you did, it doesn’t work as expected any more.

(This is probably a manifestation of the well-known attribute vs property problem/issue here, see What is the difference between properties and attributes in HTML?)

Make that

```<code> strokeColorInput.value = strokeColor;
</code>```

instead, and it appears to be working fine.

Body:
The problem appears to be, that you are using

 strokeColorInput.setAttribute('value',strokeColor);

to update the value of your color input fields. That is able to set the color for fields you did not already make an explicit choice in, but once you did, it doesn’t work as expected any more.

(This is probably a manifestation of the well-known attribute vs property problem/issue here, see What is the difference between properties and attributes in HTML?)

Make that

 strokeColorInput.value = strokeColor;

instead, and it appears to be working fine.


问:
ANTLR Tool version 4.5.3 used for code generation does not match the current runtime version 4.7.1
I'm getting an error in DataBindingMapperImpl.java for one specific data binding which results in the following error when building the project.

ANTLR Tool version 4.5.3 used for code generation does not match the current runtime version 4.7.1.

ANTLR Runtime version 4.5.3 used for parser compilation does not match the current runtime version 4.7.1

ANTLR Tool version 4.5.3 used for code generation does not match the current runtime version 4.7.1

ANTLR Runtime version 4.5.3 used for parser compilation does not match the current runtime version 4.7.1

/Users/casper/Documents/ARCore/Name/app/build/generated/source/kapt/nameDebug/com/company/name/DataBinderMapperImpl.java:10: error: cannot find symbol

```<code>import com.company.name.databinding.ActivitySplashScreenBindingImpl;

                                                ^

symbol:   class ActivitySplashScreenBindingImpl

> Task :app:kaptNameDebugKotlin FAILED
> Task :app:mergeExtDexNameDebug
location: package com.company.name.databinding
FAILURE: Build failed with an exception.
</code>```

followed by the error message below...

I followed the similar post here which resulted in this, which is the end of the error message above.

```<code>FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:kaptNameDebugKotlin'.
> A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution
> java.lang.reflect.InvocationTargetException (no error message)
</code>```

I have also tried

Clean Project and then Rebuild project

File -> Invalidate Caches / Restart

Turn Android Studio on and off

The layout file connected to the data binding looks like this

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:tools="http://schemas.android.com/tools"
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">

<data>
    <variable
        name="viewmodel"
        type="com.company.name.ui.splashScreen.viewModel.SplashScreenViewModel"/>
    <variable
        name="tryAgainBtnHandler"
        type="com.company.name.ui.splashScreen.viewModel.interfaces.TryAgainBtnHandler"/>
</data>

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.splashScreen.view.SplashScreenActivity">
</code>```

Solution

The error was caused by a mistake. I did set visibility by

```<code>android:visibility="@{viewmodel.errorContainerVisible ? View.VISIBLE : View.GONE}"
</code>```

and forgot to import

```<code><data>
    <import type="android.view.View"/>
</code>```

答:
I got the same error, in my case it was caused due to wrong imports in xml layout.I refactored and changed my package name but that didn't changed the same inside xml files.It showed me the same error.I went through all the fragments,activities and layouts to check if there was any wrong imports/missing imports.After clearing all the import and variable issues, the build was successful.</p>

```<code><data class="MainActivityBinding">

    <variable
        name="vm"
        type="com.abcd.efg.home.MapViewModel" />
</data>

<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.google.android.material.appbar.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/includeAppBar"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <FrameLayout
                android:id="@+id/toolbar_container"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <androidx.appcompat.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    android:background="@color/colorPrimary"
                    app:popupTheme="@style/AppTheme.PopupOverlay"
                    app:title="@string/app_name"
                    app:titleTextColor="@color/white" />
            </FrameLayout>

        </com.google.android.material.appbar.AppBarLayout>

        <fragment
            android:id="@+id/navigation"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:defaultNavHost="true"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/includeAppBar"
            app:navGraph="@navigation/nav_main" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/sideNV"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@color/drawerBackground"
        android:fitsSystemWindows="true"
        android:shadowColor="@color/white"
        app:headerLayout="@layout/nav_header_home"
        app:menu="@menu/activity_main_drawer" />

</androidx.drawerlayout.widget.DrawerLayout>
</code>```

Body:
I'm getting an error in DataBindingMapperImpl.java for one specific data binding which results in the following error when building the project.

ANTLR Tool version 4.5.3 used for code generation does not match the current runtime version 4.7.1.

ANTLR Runtime version 4.5.3 used for parser compilation does not match the current runtime version 4.7.1

ANTLR Tool version 4.5.3 used for code generation does not match the current runtime version 4.7.1

ANTLR Runtime version 4.5.3 used for parser compilation does not match the current runtime version 4.7.1

/Users/casper/Documents/ARCore/Name/app/build/generated/source/kapt/nameDebug/com/company/name/DataBinderMapperImpl.java:10: error: cannot find symbol

import com.company.name.databinding.ActivitySplashScreenBindingImpl;

                                                ^

symbol:   class ActivitySplashScreenBindingImpl

> Task :app:kaptNameDebugKotlin FAILED
> Task :app:mergeExtDexNameDebug
location: package com.company.name.databinding
FAILURE: Build failed with an exception.

followed by the error message below...

I followed the similar post here which resulted in this, which is the end of the error message above.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:kaptNameDebugKotlin'.
> A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution
> java.lang.reflect.InvocationTargetException (no error message)

I have also tried

Clean Project and then Rebuild project

File -> Invalidate Caches / Restart

Turn Android Studio on and off

The layout file connected to the data binding looks like this

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:tools="http://schemas.android.com/tools"
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">

<data>
    <variable
        name="viewmodel"
        type="com.company.name.ui.splashScreen.viewModel.SplashScreenViewModel"/>
    <variable
        name="tryAgainBtnHandler"
        type="com.company.name.ui.splashScreen.viewModel.interfaces.TryAgainBtnHandler"/>
</data>

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.splashScreen.view.SplashScreenActivity">

Solution

The error was caused by a mistake. I did set visibility by

android:visibility="@{viewmodel.errorContainerVisible ? View.VISIBLE : View.GONE}"

and forgot to import

<data>
    <import type="android.view.View"/>

Body:
I got the same error, in my case it was caused due to wrong imports in xml layout.I refactored and changed my package name but that didn't changed the same inside xml files.It showed me the same error.I went through all the fragments,activities and layouts to check if there was any wrong imports/missing imports.After clearing all the import and variable issues, the build was successful.

<data class="MainActivityBinding">

    <variable
        name="vm"
        type="com.abcd.efg.home.MapViewModel" />
</data>

<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.google.android.material.appbar.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/includeAppBar"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <FrameLayout
                android:id="@+id/toolbar_container"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <androidx.appcompat.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    android:background="@color/colorPrimary"
                    app:popupTheme="@style/AppTheme.PopupOverlay"
                    app:title="@string/app_name"
                    app:titleTextColor="@color/white" />
            </FrameLayout>

        </com.google.android.material.appbar.AppBarLayout>

        <fragment
            android:id="@+id/navigation"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:defaultNavHost="true"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/includeAppBar"
            app:navGraph="@navigation/nav_main" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/sideNV"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@color/drawerBackground"
        android:fitsSystemWindows="true"
        android:shadowColor="@color/white"
        app:headerLayout="@layout/nav_header_home"
        app:menu="@menu/activity_main_drawer" />

</androidx.drawerlayout.widget.DrawerLayout>


问:
JSON Data producing key error for nested data
I'm getting a key error when trying to access some nested JSON data, this is because i am struggling to print the SECOND set of data under ["updates"] , see code below:

```<code>for url in URLs:
    JSONdata = requests.get(url, cookies=cookies, verify=False) .json()
    notifications = JSONdata["notifications"]
    for JSONkey in notifications:
        outDiscards = JSONkey["updates"]["outDiscards"]["value"]["avg"]["float"]
        inDiscards = JSONkey["updates"]["inDiscards"]["value"]["avg"]["float"]
        name = JSONkey["path_elements"][1]
        interface = JSONkey["path_elements"][5]
        print(name, interface, outDiscards, inDiscards, sep=',')
</code>```

The JSON data looks like this and i am trying to access the AVG float for the key ["outDiscards]" (Scroll all the way to the bottom to find it):

```<code>{
 "notifications": [
  {
   "timestamp": "1590228300000000000",
   "path_elements": [
    "Devices",
    "ASDASDA23",
    "versioned-data",
    "interfaces",
    "data",
    "Ethernet6",
    "aggregate",
    "rates",
    "1m"
   ],
   "updates": {
    "alignmentErrors": {
     "key": "alignmentErrors",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    },
    "fcsErrors": {
     "key": "fcsErrors",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    },
    "frameTooLongs": {
     "key": "frameTooLongs",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    },
    "frameTooShorts": {
     "key": "frameTooShorts",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    },
    "inDiscards": {
     "key": "inDiscards",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    },
    "inErrors": {
     "key": "inErrors",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    },
    "outErrors": {
     "key": "outErrors",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    },
    "symbolErrors": {
     "key": "symbolErrors",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    }
   }
  },
  {
   "timestamp": "1590672660000000000",
   "path_elements": [
    "Devices",
    "ASDASDA23",
    "versioned-data",
    "interfaces",
    "data",
    "Ethernet6",
    "aggregate",
    "rates",
    "1m"
   ],
   "updates": {
    "inOctets": {
     "key": "inOctets",
     "value": {
      "avg": {
       "float": 2252589.403482577
      },
      "max": {
       "float": 3062029.5123118195
      },
      "min": {
       "float": 1716651.1165519762
      },
      "stddev": {
       "float": 486507.3457503787
      },
      "weight": {
       "float": 0.9999999999999999
      }
     }
    },
    "inUcastPkts": {
     "key": "inUcastPkts",
     "value": {
      "avg": {
       "float": 4924.985636262933
      },
      "max": {
       "float": 6405.247375228221
      },
      "min": {
       "float": 4027.16222744576
      },
      "stddev": {
       "float": 856.3274693923914
      },
      "weight": {
       "float": 0.9999999999999999
      }
     }
    },
    "outMulticastPkts": {
     "key": "outMulticastPkts",
     "value": {
      "avg": {
       "float": 0.03331537922781352
      },
      "max": {
       "float": 0.09996021185548479
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0.047115061840280935
      },
      "weight": {
       "float": 0.9999999999999999
      }
     }
    },
    "outOctets": {
     "key": "outOctets",
     "value": {
      "avg": {
       "float": 532952.2820988153
      },
      "max": {
       "float": 686277.7896707873
      },
      "min": {
       "float": 453320.58138715214
      },
      "stddev": {
       "float": 80364.91411229585
      },
      "weight": {
       "float": 0.9999999999999999
      }
     }
    },
    "outUcastPkts": {
     "key": "outUcastPkts",
     "value": {
      "avg": {
       "float": 4409.95750691497
      },
      "max": {
       "float": 5605.478585933741
      },
      "min": {
       "float": 3652.11719308749
      },
      "stddev": {
       "float": 677.6427171449172
      },
      "weight": {
       "float": 0.9999999999999999
      }
     }
    }
   }
  },
  {
   "timestamp": "1590444480000000000",
   "path_elements": [
    "Devices",
    "ASDASDA23",
    "versioned-data",
    "interfaces",
    "data",
    "Ethernet6",
    "aggregate",
    "rates",
    "1m"
   ],
   "updates": {
    "outDiscards": {
     "key": "outDiscards",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    }
   }
  },
</code>```

I keep getting a KeyError, this is because if i print out just ["updates"] it only goes up to "SymbolErrors" in the JSON data, because it closes out with ))), i don't know how to access the second part of the data

答:
The Outdiscards was variably changing place, i fixed this issue with the try and except method and accessing the correct indexes</p>

```<code>    inDiscards = JSONkey[0]["updates"]["inDiscards"]["value"]["avg"]["float"]
    name = JSONkey[1]["path_elements"][1]
    interface = JSONkey[1]["path_elements"][5]
    try:
        outDiscards = JSONkey[0]["updates"]["outDiscards"]["value"]["avg"]["float"]
        # print(inDiscards, outDiscards)
    except KeyError:
        outDiscards = JSONkey[2]["updates"]["outDiscards"]["value"]["avg"]["float"]
        # print(inDiscards, outDiscards)
</code>```

Body:
I'm getting a key error when trying to access some nested JSON data, this is because i am struggling to print the SECOND set of data under ["updates"] , see code below:

for url in URLs:
    JSONdata = requests.get(url, cookies=cookies, verify=False) .json()
    notifications = JSONdata["notifications"]
    for JSONkey in notifications:
        outDiscards = JSONkey["updates"]["outDiscards"]["value"]["avg"]["float"]
        inDiscards = JSONkey["updates"]["inDiscards"]["value"]["avg"]["float"]
        name = JSONkey["path_elements"][1]
        interface = JSONkey["path_elements"][5]
        print(name, interface, outDiscards, inDiscards, sep=',')

The JSON data looks like this and i am trying to access the AVG float for the key ["outDiscards]" (Scroll all the way to the bottom to find it):

{
 "notifications": [
  {
   "timestamp": "1590228300000000000",
   "path_elements": [
    "Devices",
    "ASDASDA23",
    "versioned-data",
    "interfaces",
    "data",
    "Ethernet6",
    "aggregate",
    "rates",
    "1m"
   ],
   "updates": {
    "alignmentErrors": {
     "key": "alignmentErrors",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    },
    "fcsErrors": {
     "key": "fcsErrors",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    },
    "frameTooLongs": {
     "key": "frameTooLongs",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    },
    "frameTooShorts": {
     "key": "frameTooShorts",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    },
    "inDiscards": {
     "key": "inDiscards",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    },
    "inErrors": {
     "key": "inErrors",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    },
    "outErrors": {
     "key": "outErrors",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    },
    "symbolErrors": {
     "key": "symbolErrors",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    }
   }
  },
  {
   "timestamp": "1590672660000000000",
   "path_elements": [
    "Devices",
    "ASDASDA23",
    "versioned-data",
    "interfaces",
    "data",
    "Ethernet6",
    "aggregate",
    "rates",
    "1m"
   ],
   "updates": {
    "inOctets": {
     "key": "inOctets",
     "value": {
      "avg": {
       "float": 2252589.403482577
      },
      "max": {
       "float": 3062029.5123118195
      },
      "min": {
       "float": 1716651.1165519762
      },
      "stddev": {
       "float": 486507.3457503787
      },
      "weight": {
       "float": 0.9999999999999999
      }
     }
    },
    "inUcastPkts": {
     "key": "inUcastPkts",
     "value": {
      "avg": {
       "float": 4924.985636262933
      },
      "max": {
       "float": 6405.247375228221
      },
      "min": {
       "float": 4027.16222744576
      },
      "stddev": {
       "float": 856.3274693923914
      },
      "weight": {
       "float": 0.9999999999999999
      }
     }
    },
    "outMulticastPkts": {
     "key": "outMulticastPkts",
     "value": {
      "avg": {
       "float": 0.03331537922781352
      },
      "max": {
       "float": 0.09996021185548479
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0.047115061840280935
      },
      "weight": {
       "float": 0.9999999999999999
      }
     }
    },
    "outOctets": {
     "key": "outOctets",
     "value": {
      "avg": {
       "float": 532952.2820988153
      },
      "max": {
       "float": 686277.7896707873
      },
      "min": {
       "float": 453320.58138715214
      },
      "stddev": {
       "float": 80364.91411229585
      },
      "weight": {
       "float": 0.9999999999999999
      }
     }
    },
    "outUcastPkts": {
     "key": "outUcastPkts",
     "value": {
      "avg": {
       "float": 4409.95750691497
      },
      "max": {
       "float": 5605.478585933741
      },
      "min": {
       "float": 3652.11719308749
      },
      "stddev": {
       "float": 677.6427171449172
      },
      "weight": {
       "float": 0.9999999999999999
      }
     }
    }
   }
  },
  {
   "timestamp": "1590444480000000000",
   "path_elements": [
    "Devices",
    "ASDASDA23",
    "versioned-data",
    "interfaces",
    "data",
    "Ethernet6",
    "aggregate",
    "rates",
    "1m"
   ],
   "updates": {
    "outDiscards": {
     "key": "outDiscards",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    }
   }
  },

I keep getting a KeyError, this is because if i print out just ["updates"] it only goes up to "SymbolErrors" in the JSON data, because it closes out with ))), i don't know how to access the second part of the data

Body:
The Outdiscards was variably changing place, i fixed this issue with the try and except method and accessing the correct indexes

    inDiscards = JSONkey[0]["updates"]["inDiscards"]["value"]["avg"]["float"]
    name = JSONkey[1]["path_elements"][1]
    interface = JSONkey[1]["path_elements"][5]
    try:
        outDiscards = JSONkey[0]["updates"]["outDiscards"]["value"]["avg"]["float"]
        # print(inDiscards, outDiscards)
    except KeyError:
        outDiscards = JSONkey[2]["updates"]["outDiscards"]["value"]["avg"]["float"]
        # print(inDiscards, outDiscards)


问:
Re-use variable outside of function?
How can I use return the $row array in the below example, so that I can re-use the variable outside of this function?

I manage to echo the information inside the function using $row['columnName'], but various combinations of global and $GLOBALS, return $xyz and getting variable scope to work for me has me a bit out of my depth. Any answers please?

```<code><?php
function getInfo() {

    $query = /* Some SQL Query */;

    $result = mysql_query($query);

    if($result == false)
    {
       user_error("Query failed: " . mysql_error() . "<br />\n$query");
    }
    elseif(mysql_num_rows($result) == 0)
    {
       echo "<p>Sorry, no rows were returned by your query.</p>\n";
    }
    else
    {
    while ($row = mysql_fetch_assoc($result)) {
        /* What goes here? */
        }
    }

}
?>
</code>```

答:
```<code>function getInfo() {

    $query = /* Some SQL Query */;

    $result = mysql_query($query);

    if($result == false)
    {
       user_error("Query failed: " . mysql_error() . "<br />\n$query");
    }
    elseif(mysql_num_rows($result) == 0)
    {
       echo "<p>Sorry, no rows were returned by your query.</p>\n";
    }
    else
    {

    $data = array();

    while ($row = mysql_fetch_assoc($result)) {

           $data[] = $row;
        }

     return $data;
    }

}
</code>```

Then you just do: $mydata = getInfo();

Title: Re-use variable outside of function?

Body:
How can I use return the $row array in the below example, so that I can re-use the variable outside of this function?

I manage to echo the information inside the function using $row['columnName'], but various combinations of global and $GLOBALS, return $xyz and getting variable scope to work for me has me a bit out of my depth. Any answers please?

<?php
function getInfo() {

    $query = /* Some SQL Query */;

    $result = mysql_query($query);

    if($result == false)
    {
       user_error("Query failed: " . mysql_error() . "
\n$query");
    }
    elseif(mysql_num_rows($result) == 0)
    {
       echo "
Sorry, no rows were returned by your query.
\n";
    }
    else
    {
    while ($row = mysql_fetch_assoc($result)) {
        /* What goes here? */
        }
    }

}
?>

Body:
function getInfo() {

    $query = /* Some SQL Query */;

    $result = mysql_query($query);

    if($result == false)
    {
       user_error("Query failed: " . mysql_error() . "<br />\n$query");
    }
    elseif(mysql_num_rows($result) == 0)
    {
       echo "<p>Sorry, no rows were returned by your query.</p>\n";
    }
    else
    {

    $data = array();

    while ($row = mysql_fetch_assoc($result)) {

           $data[] = $row;
        }

     return $data;
    }

}

Then you just do: $mydata = getInfo();


问:
How can I restart kafka-manager safely with out kill command?
my kafka-manager can't update consumer information and keeps the removed consumer groups list, so i try to restart kafka-manager. (i'm using kafka-manager 1.3.3.22 and kafka 2.12-2.1.1)

but README.md in kafka-manager and /bin/kafka-manager command doesn't appear to provide stop/restart.

is there any way to safely restart or terminate kafka-manager? without 'kill -9 PID' commend

答:
There is no restart command out of the box however, you can run Kafka Manager as a service.

Firstly, create the service file under /etc/systemd/system/kafka-manager.service
and add the following content:

```<code>[Unit]
Description=Kafka Manager
After=network.target

[Install]
WantedBy=multi-user.target

[Service]
ExecStart=/opt/kafka-manager-1.3.3.22/bin/kafka-manager
Type=simple
</code>```

In /opt/kafka-manager-1.3.3.22/conf/application.conf:

```<code>play.crypto.secret="some-secret"
play.http.requestHandler="play.http.DefaultHttpRequestHandler"
play.application.loader=loader.KafkaManagerLoader
pinned-dispatcher.type="PinnedDispatcher"
pinned-dispatcher.executor="thread-pool-executor"
kafka-manager.zkhosts="my-zookeeper-connection-string"
kafka-manager.base-zk-path="/a-chroot"
</code>```

In /opt/kafka-manager-1.3.3.22/conf/application.ini:

```<code>-Dapplication.home=/opt/kafka-manager-1.3.3.22
-Dpidfile.path=/opt/kafka-manager-1.3.3.22/kafka-manager.pid
-Dhttp.port=8080
</code>```

and finally run

```<code>systemctl daemon-reload
systemctl enable kafka-manager --now
</code>```

Start the service

```<code>systemctl start kafka-manager.service
</code>```

Stop the service

```<code>systemctl stop kafka-manager.service
</code>```

Restart the service

```<code>systemctl restart kafka-manager.service
</code>```

Body:
There is no restart command out of the box however, you can run Kafka Manager as a service.

Firstly, create the service file under /etc/systemd/system/kafka-manager.service
and add the following content:

[Unit]
Description=Kafka Manager
After=network.target

[Install]
WantedBy=multi-user.target

[Service]
ExecStart=/opt/kafka-manager-1.3.3.22/bin/kafka-manager
Type=simple

In /opt/kafka-manager-1.3.3.22/conf/application.conf:

play.crypto.secret="some-secret"
play.http.requestHandler="play.http.DefaultHttpRequestHandler"
play.application.loader=loader.KafkaManagerLoader
pinned-dispatcher.type="PinnedDispatcher"
pinned-dispatcher.executor="thread-pool-executor"
kafka-manager.zkhosts="my-zookeeper-connection-string"
kafka-manager.base-zk-path="/a-chroot"

In /opt/kafka-manager-1.3.3.22/conf/application.ini:

-Dapplication.home=/opt/kafka-manager-1.3.3.22
-Dpidfile.path=/opt/kafka-manager-1.3.3.22/kafka-manager.pid
-Dhttp.port=8080

and finally run

systemctl daemon-reload
systemctl enable kafka-manager --now

Start the service

systemctl start kafka-manager.service

Stop the service

systemctl stop kafka-manager.service

Restart the service

systemctl restart kafka-manager.service


问:
Encrypt/Decrypt failed(private key missing) with ownly generated certificate C#
I need to generate the RSA certificate(self signed certificate) with help of C# code. I have used the below code to create the certificate.

```<code>public bool CreateRSACertificate()
{
    RSA rsaKey = RSA.Create();
    CertificateRequest certRequest = new CertificateRequest("cn=MyApplication", rsaKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
    certRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
    certRequest.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(certRequest.PublicKey, false));

    X509Certificate2 certificate = certRequest.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(5));

    byte[] certData = certificate.Export(X509ContentType.Pfx, "TestPassword");
    X509Certificate2 cert = new X509Certificate2(certData, "TestPassword", X509KeyStorageFlags.Exportable);

    File.WriteAllBytes("MyCertificate.pfx", cert.Export(X509ContentType.Pfx, "TestPassword"));

    return true;
}
</code>```

And, after that I try to encrypt the data using the the certificate file which I created using the below code.

```<code>public bool EncryptAndDecryptFile()
{
    string data = "{data: 'mydate123@gmail.com'}";

    X509Certificate2 certificate = new X509Certificate2("MyCertificate.pfx", "TestPassword", X509KeyStorageFlags.Exportable);
    if (certificate.HasPrivateKey) {
        Console.WriteLine("Private key available "); // It's says like the private key was available
    }

    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
    rsa.FromXmlString(certificate.PublicKey.Key.ToXmlString(false));

    byte[] bytes = Encoding.ASCII.GetBytes(data);
    var encryptedData = rsa.Encrypt(bytes, false); //It seems the data encrypted. I'm not sure.But, I can able to see some encrypted data.

    using (certificate.GetRSAPrivateKey()) {

        RSACryptoServiceProvider drsa = new RSACryptoServiceProvider();
        drsa.FromXmlString(certificate.PrivateKey.ToXmlString(false));
        var decdata = drsa.Decrypt(encryptedData, false); // Here, I see some exception.

        someString = Encoding.ASCII.GetString(decdata);
    }
    Console.WriteLine("someString someString ::: " + someString);

    return true;
}
</code>```

While, running the above code I see the below error.

```<code>Unhandled exception. Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: Key not valid for use in specified state.
   at Internal.NativeCrypto.CapiHelper.ExportKeyBlob(Boolean includePrivateParameters, SafeKeyHandle safeKeyHandle)
   at System.Security.Cryptography.RSACryptoServiceProvider.ExportParameters(Boolean includePrivateParameters)
   at ConfigUtility.X509Certificate.ReadRSACertificate()
</code>```

To verify the certificate I have the below command,

```<code>certutil -dump MyCertificate.pfx
</code>```

So, the above utility gave me the below output,

```<code>================ Certificate 0 ================
================ Begin Nesting Level 1 ================
Element 0:
Serial Number: 054834637a713ecf
Issuer: CN=MyApplication
 NotBefore: 29-05-2020 13:49
 NotAfter: 29-05-2025 13:49
Subject: CN=MyApplication
Signature matches Public Key
Root Certificate: Subject matches Issuer
Cert Hash(sha1): 16e83e8a92a38b948adad03a86768e27115851d4
----------------  End Nesting Level 1  ----------------
  Provider = Microsoft Software Key Storage Provider
Private key is NOT plain text exportable
Encryption test passed
CertUtil: -dump command completed successfully.
</code>```

答:
In fact, you get exception in this line:

```<code>drsa.FromXmlString(certificate.PrivateKey.ToXmlString(false));
</code>```

the whole encryption and decryption code pieces are incorrect, you are messing things with old an deprecated RSACryptoServiceProvider and doing unnecessary operations. Here is how the method should look like:

```<code>public bool EncryptAndDecryptFile() {
    string data = "{data: 'mydate123@gmail.com'}";

    X509Certificate2 certificate = new X509Certificate2("MyCertificate.pfx", "TestPassword", X509KeyStorageFlags.Exportable);
    if (certificate.HasPrivateKey) {
        Console.WriteLine("Private key available "); // It's says like the private key was available
    }

    Byte[] encryptedData = new Byte[0];
    using (RSA pubKey = certificate.GetRSAPublicKey()) {
        byte[] bytes = Encoding.ASCII.GetBytes(data);
        encryptedData = rsa.Encrypt(bytes, RSAEncryptionPadding.OaepSHA256);
    }

    // assuming, encryptedData is not null
    String someString = String.Empty;
    using (RSA prKey = certificate.GetRSAPrivateKey()) {
        Byte[] decdata = prKey.Decrypt(encryptedData, RSAEncryptionPadding.OaepSHA256);

        someString = Encoding.ASCII.GetString(decdata);
    }

    return data.Equals(someString);
}
</code>```

Body:
I need to generate the RSA certificate(self signed certificate) with help of C# code. I have used the below code to create the certificate.

public bool CreateRSACertificate()
{
    RSA rsaKey = RSA.Create();
    CertificateRequest certRequest = new CertificateRequest("cn=MyApplication", rsaKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
    certRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
    certRequest.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(certRequest.PublicKey, false));

    X509Certificate2 certificate = certRequest.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(5));

    byte[] certData = certificate.Export(X509ContentType.Pfx, "TestPassword");
    X509Certificate2 cert = new X509Certificate2(certData, "TestPassword", X509KeyStorageFlags.Exportable);

    File.WriteAllBytes("MyCertificate.pfx", cert.Export(X509ContentType.Pfx, "TestPassword"));

    return true;
}

And, after that I try to encrypt the data using the the certificate file which I created using the below code.

public bool EncryptAndDecryptFile()
{
    string data = "{data: 'mydate123@gmail.com'}";

    X509Certificate2 certificate = new X509Certificate2("MyCertificate.pfx", "TestPassword", X509KeyStorageFlags.Exportable);
    if (certificate.HasPrivateKey) {
        Console.WriteLine("Private key available "); // It's says like the private key was available
    }

    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
    rsa.FromXmlString(certificate.PublicKey.Key.ToXmlString(false));

    byte[] bytes = Encoding.ASCII.GetBytes(data);
    var encryptedData = rsa.Encrypt(bytes, false); //It seems the data encrypted. I'm not sure.But, I can able to see some encrypted data.

    using (certificate.GetRSAPrivateKey()) {

        RSACryptoServiceProvider drsa = new RSACryptoServiceProvider();
        drsa.FromXmlString(certificate.PrivateKey.ToXmlString(false));
        var decdata = drsa.Decrypt(encryptedData, false); // Here, I see some exception.

        someString = Encoding.ASCII.GetString(decdata);
    }
    Console.WriteLine("someString someString ::: " + someString);

    return true;
}

While, running the above code I see the below error.

Unhandled exception. Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: Key not valid for use in specified state.
   at Internal.NativeCrypto.CapiHelper.ExportKeyBlob(Boolean includePrivateParameters, SafeKeyHandle safeKeyHandle)
   at System.Security.Cryptography.RSACryptoServiceProvider.ExportParameters(Boolean includePrivateParameters)
   at ConfigUtility.X509Certificate.ReadRSACertificate()

To verify the certificate I have the below command,

certutil -dump MyCertificate.pfx

So, the above utility gave me the below output,

================ Certificate 0 ================
================ Begin Nesting Level 1 ================
Element 0:
Serial Number: 054834637a713ecf
Issuer: CN=MyApplication
 NotBefore: 29-05-2020 13:49
 NotAfter: 29-05-2025 13:49
Subject: CN=MyApplication
Signature matches Public Key
Root Certificate: Subject matches Issuer
Cert Hash(sha1): 16e83e8a92a38b948adad03a86768e27115851d4
----------------  End Nesting Level 1  ----------------
  Provider = Microsoft Software Key Storage Provider
Private key is NOT plain text exportable
Encryption test passed
CertUtil: -dump command completed successfully.

Body:
In fact, you get exception in this line:

drsa.FromXmlString(certificate.PrivateKey.ToXmlString(false));

the whole encryption and decryption code pieces are incorrect, you are messing things with old an deprecated RSACryptoServiceProvider and doing unnecessary operations. Here is how the method should look like:

public bool EncryptAndDecryptFile() {
    string data = "{data: 'mydate123@gmail.com'}";

    X509Certificate2 certificate = new X509Certificate2("MyCertificate.pfx", "TestPassword", X509KeyStorageFlags.Exportable);
    if (certificate.HasPrivateKey) {
        Console.WriteLine("Private key available "); // It's says like the private key was available
    }

    Byte[] encryptedData = new Byte[0];
    using (RSA pubKey = certificate.GetRSAPublicKey()) {
        byte[] bytes = Encoding.ASCII.GetBytes(data);
        encryptedData = rsa.Encrypt(bytes, RSAEncryptionPadding.OaepSHA256);
    }

    // assuming, encryptedData is not null
    String someString = String.Empty;
    using (RSA prKey = certificate.GetRSAPrivateKey()) {
        Byte[] decdata = prKey.Decrypt(encryptedData, RSAEncryptionPadding.OaepSHA256);

        someString = Encoding.ASCII.GetString(decdata);
    }

    return data.Equals(someString);
}


问:
Add see more option to the server data in angular 8
I am facing an issue with my project.

I want to add see more option to a paragraph and that paragraph's data is coming from a server.

I know how to add see more option to HTML paragraph, but I don't know how to add see more option to the data that is coming from the server.

```<code><p>Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas
Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas
Jayesh Vyas Jayesh Vyas <span id="dots">...</span>
<span id="more">Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas
Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas
Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas
Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas
Jayesh Vyas Jayesh Vyas Jayesh Vyas .</span></p>
<button onclick="myFunction()" id="myBtn">Read more</button>
</code>```

JavaScript code

```<code><script>
function myFunction() {
  var dots = document.getElementById("dots");
  var moreText = document.getElementById("more");
  var btnText = document.getElementById("myBtn");

  if (dots.style.display === "none") {
    dots.style.display = "inline";
    btnText.innerHTML = "Read more";
    moreText.style.display = "none";
  } else {
    dots.style.display = "none";
    btnText.innerHTML = "Read less";
    moreText.style.display = "inline";
  }
}
</script>
</code>```

So you can see above I tried above code for a paragraph and it is working fine for me.

but in my project, the HTML component is as below.

```<code><div  class="col-12 col-lg-12" *ngFor="let post of rec?.attributes?.Postings | filter : searchText | filter:filterText; let i=index">
<div class="col-12 noRightPadding" style="overflow-wrap: break-word;white-space: pre-line;word-break:break-all;
">{{post?.attributes?.Message}} </div>
</div>
</code>```

you can see the paragraph is coming as post.attributes.Message and I don't have an idea how to add see more option for this if it exceeds more than two lines.

can anyone help me with this?

答:
Demo You can do it with if condition and create one more property for each element such as post?.attributes?.isMore as default false</p>

```<code>   <div  class="col-12 col-lg-12" >
        <div class="col-12 noRightPadding">
           {{ post?.attributes?.Message.length>100 ? post?.attributes?.Message.substring(0,10)+'...': post?.attributes?.Message}}
            <a *ngIf=" post?.attributes?.Message.length>10"(click)="post?.attributes?.isMore=!post?.attributes?.isMore">{{!post?.attributes?.isMore && post?.attributes?.Message.length>10 ? 'Read More' : 'Read Less' }}</a> </div>
      </div>
    </div>
</code>```

Body:
I am facing an issue with my project.

I want to add see more option to a paragraph and that paragraph's data is coming from a server.

I know how to add see more option to HTML paragraph, but I don't know how to add see more option to the data that is coming from the server.

Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas
Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas
Jayesh Vyas Jayesh Vyas ...
Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas
Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas
Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas
Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas
Jayesh Vyas Jayesh Vyas Jayesh Vyas .

<button onclick="myFunction()" id="myBtn">Read more</button>

JavaScript code

So you can see above I tried above code for a paragraph and it is working fine for me.

but in my project, the HTML component is as below.

{{post?.attributes?.Message}}

you can see the paragraph is coming as post.attributes.Message and I don't have an idea how to add see more option for this if it exceeds more than two lines.

can anyone help me with this?

Body:
Demo You can do it with if condition and create one more property for each element such as post?.attributes?.isMore as default false

   <div  class="col-12 col-lg-12" >
        <div class="col-12 noRightPadding">
           {{ post?.attributes?.Message.length>100 ? post?.attributes?.Message.substring(0,10)+'...': post?.attributes?.Message}}
            <a *ngIf=" post?.attributes?.Message.length>10"(click)="post?.attributes?.isMore=!post?.attributes?.isMore">{{!post?.attributes?.isMore && post?.attributes?.Message.length>10 ? 'Read More' : 'Read Less' }}</a> </div>
      </div>
    </div>