问:
Switch, case, try and catch in C# probelm
I am very new to C# programming. I wanted to catch the errors for example invalid input (not a number from 1-6) and print out a message stating the error. This is my code.

```<code>private static bool ManageStudents()
    {
        Console.Clear();
        Console.WriteLine("========================");
        Console.WriteLine(" Choose an option:");
        Console.WriteLine("  1. Add a new student");
        Console.WriteLine("  2. View all students");
        Console.WriteLine("  3. Search students");
        Console.WriteLine("  4. Delete students");
        Console.WriteLine("  5. Update students");
        Console.WriteLine("  6. Back to main menu");
        Console.WriteLine("========================");
        Console.Write("\r\nPlease choose: ");

        try
        {
            switch (Console.ReadLine())
            {
                case "1":
                    AddStudents();
                    return true;
                case "2":
                    ViewStudents();
                    return true;
                case "3":
                    SearchStudents();
                    return true;
                case "4":
                    DeleteStudents();
                    return true;
                case "5":
                    UpdateStudents();
                    return true;
                case "6":
                    return false;
                default:
                    return true;
            }
        }

        catch (Exception e)
        {
            Console.WriteLine("error message");
            Console.ReadLine();
            return true;
        }

    }
</code>```

When I run the program the message "error message" didn't appear after I enter an invalid character.

答:
Replace

```<code> default:
       return true;
</code>```

with

```<code> default:
       throw new Exception();
</code>```

Body:
I am very new to C# programming. I wanted to catch the errors for example invalid input (not a number from 1-6) and print out a message stating the error. This is my code.

private static bool ManageStudents()
    {
        Console.Clear();
        Console.WriteLine("========================");
        Console.WriteLine(" Choose an option:");
        Console.WriteLine("  1. Add a new student");
        Console.WriteLine("  2. View all students");
        Console.WriteLine("  3. Search students");
        Console.WriteLine("  4. Delete students");
        Console.WriteLine("  5. Update students");
        Console.WriteLine("  6. Back to main menu");
        Console.WriteLine("========================");
        Console.Write("\r\nPlease choose: ");

        try
        {
            switch (Console.ReadLine())
            {
                case "1":
                    AddStudents();
                    return true;
                case "2":
                    ViewStudents();
                    return true;
                case "3":
                    SearchStudents();
                    return true;
                case "4":
                    DeleteStudents();
                    return true;
                case "5":
                    UpdateStudents();
                    return true;
                case "6":
                    return false;
                default:
                    return true;
            }
        }

        catch (Exception e)
        {
            Console.WriteLine("error message");
            Console.ReadLine();
            return true;
        }

    }

When I run the program the message "error message" didn't appear after I enter an invalid character.

Body:
Replace

 default:
       return true;

with

 default:
       throw new Exception();


来源: stackexchange

答: default when used in a switch statement is just that - a case to default to if no match is found. If you want the try block to fail, you'll need to throw an exception within the default.

ContentLicense: CC BY-SA 4.0

Title: Switch, case, try and catch in C# probelm


问:
Python authorization
I need to write a script that is included in the personal account of my Internet provider and transmits information about the current balance.

At the moment I am stuck at the time of authorization. I found and edited such a script for myself:

```<code>import requests

url = 'https://bill.tomtel.ru/login.html'

USERNAME, PASSWORD, = 'mylogin', 'mypass'

resp = requests.get(url, auth=(USERNAME, PASSWORD))

r = requests.post(url)

print(r.content)
</code>```

But this does not help to pass authorization...

I can enter this link through a browser and go to a page of this type:

```<code>https://bill.tomtel.ru/fastcom/!w3_p_main.showform?FORMNAME=QFRAME&CONFIG=CONTRACT&SID=BLABLABLA&NLS=WR
</code>```

I can go through browser authorization through both links, but why can't I do this through a script?

Please help with this.

答:
Your browser probably has a session token/cookie stored and that is why you can access it through the browser. There are a couple issues here:

It looks like you need to login to the site first -- through a POST method, not a GET. The GET is what loads the page. But once you submit the form it's going to do a POST request.

Actually, using requests to login to a site is not as easy as it looks. Usually you have to find the url it's posting to (examine the developer toolbar to see the url), and you often have to pass information in addition to your username/password, such as a csrf token, a cookie, or something else.

I would suggest using a browser-automator for this, perhaps something like selenium Webdriver. It makes logging into a site much simpler than using HTTP in a raw request, as it emulates a browser. I would suggest this -- it's much simpler and faster!

Another thing to note: auth=(USERNAME, PASSWORD) is not quite the username/password in the form (it's something else) but I don't think understanding that is too relevant to what you're trying to do.

Here is the url and required form data to log in:

Title: Python authorization

Body:
I need to write a script that is included in the personal account of my Internet provider and transmits information about the current balance.

At the moment I am stuck at the time of authorization. I found and edited such a script for myself:

import requests

url = 'https://bill.tomtel.ru/login.html'

USERNAME, PASSWORD, = 'mylogin', 'mypass'

resp = requests.get(url, auth=(USERNAME, PASSWORD))

r = requests.post(url)

print(r.content)

But this does not help to pass authorization...

I can enter this link through a browser and go to a page of this type:

https://bill.tomtel.ru/fastcom/!w3_p_main.showform?FORMNAME=QFRAME&CONFIG=CONTRACT&SID=BLABLABLA&NLS=WR

I can go through browser authorization through both links, but why can't I do this through a script?

Please help with this.


问:
How to extend database schema for new requirements of mandatory and optional participation
I have an application for managing events in our institution. Recently a new program for the staff was started and i was asked to handle it in the same application. This new program for staff has two paths, Group 01 is for recently hired people and Group 02: is for experienced people.

So For every year there will be like 12-15 events. e.g.

```<code>EV-001 - Skill 01 --- Mandatory
EV-002 - Skill 02 --- Mandatory
...
EV-013 - Skill 13 --- Optional
EV-014 - Skill 14 --- Optional
</code>```

Program for Newly Hired staff will require them to participate in 5 specific events in a year, lets call mandatory events. These events can change over the years. That for Next year they can include different 5 events.

Program for Experienced staff will require them to participate in ANY 5 events in a year (from 1 to 14).

I already have Following tables

Employee Table

Events Table (event table has an "event tag" field which i initially planned to use)

Participation Table (for keeping records of participation in any event)

So the first issue is how to expand my database such that I can handle new requirements. As I mentioned that I was planning to use the "Event Tag" field in my Event Table to declare 2 types of events, Mandatory and Optional. and for group 01, I check if they have participated in 5 mandatory types of events and for Group 02, I check if they have participated in 5 events from Mandatory + Optional.
So the issue is that if a participant participate in "EV-002 - Skill 02" twice then his participation should only be counted once, not twice.

In the end, i need to display how many people participated in this program and how many finished it from each group and each batch.

So is there any flexible and simple solution to this problem?

I am using MS SQL with ASP.NET/C#

答:
After trying and discussing it some of the colleagues I have adopted a solution that might be helpful for others.

I created 5 new tables. First one is

```<b>Program Event Table</b>
(Columns)
 - Event  ID
 - Event Name
 - Description
 - More Fields
```

Second Is

```<b>Program Participants Group Table</b>
(Columns)
 - Group ID
 - Group Name
 - Description
 - Mandatory Events Required
 - Optional Events Required
 - More Fields
```

Third is

```<b>Program Events Group Table</b>
(Columns)
 - Event ID (FK)
 - Group ID (FK)
 - Mandatory (bit field)
 - Optional (bit field)
 - More items if required
```

The Fourth table is

```<b>Program Participants Table (listing the registered participants)</b>
(Columns)
 - Participant ID
 - Employee ID (FK)
 - Group ID  (FK)
 - Batch ID  (FK)
 - More items if required
```

and the final table is

```<b>Program Batch Table (For distinguishing between different batches)</b>
(Columns)
 - Batch ID
 - Batch Start Date
 - Batch End Date
 - More items if required
```

I filled the Program Events Group table with the the list of events related to the program and their requirement criteria for each group.
So If Event 01 -- Skill 01 is required for Group 01 and is optional for Group 02 then the Program Events Group table will have 2 entries.

```
Event 01, Group 01, 1, 0, ...
Event 01, Group 02, 0, 1, ...
```

But if Event 08 -- Skill 08 is option for Group 02 but is not required by Group 01 then it will have only 1 entry in the table.

```
Event 08, Group 02, 0, 1, ...
```

Now I added the Event ID  from the Program Event Table to the existing Event table, so if a new event belongs to this program then Program event ID will be added. So now the existing participation table is used and the existing event table is also used.

Body:
I have an application for managing events in our institution. Recently a new program for the staff was started and i was asked to handle it in the same application. This new program for staff has two paths, Group 01 is for recently hired people and Group 02: is for experienced people.

So For every year there will be like 12-15 events. e.g.

EV-001 - Skill 01 --- Mandatory
EV-002 - Skill 02 --- Mandatory
...
EV-013 - Skill 13 --- Optional
EV-014 - Skill 14 --- Optional

Program for Newly Hired staff will require them to participate in 5 specific events in a year, lets call mandatory events. These events can change over the years. That for Next year they can include different 5 events.

Program for Experienced staff will require them to participate in ANY 5 events in a year (from 1 to 14).

I already have Following tables

Employee Table

Events Table (event table has an "event tag" field which i initially planned to use)

Participation Table (for keeping records of participation in any event)

So the first issue is how to expand my database such that I can handle new requirements. As I mentioned that I was planning to use the "Event Tag" field in my Event Table to declare 2 types of events, Mandatory and Optional. and for group 01, I check if they have participated in 5 mandatory types of events and for Group 02, I check if they have participated in 5 events from Mandatory + Optional.
So the issue is that if a participant participate in "EV-002 - Skill 02" twice then his participation should only be counted once, not twice.

In the end, i need to display how many people participated in this program and how many finished it from each group and each batch.

So is there any flexible and simple solution to this problem?

I am using MS SQL with ASP.NET/C#

Body:
After trying and discussing it some of the colleagues I have adopted a solution that might be helpful for others.

I created 5 new tables. First one is

Program Event Table
(Columns)
 - Event  ID
 - Event Name
 - Description
 - More Fields

Second Is

Program Participants Group Table
(Columns)
 - Group ID
 - Group Name
 - Description
 - Mandatory Events Required
 - Optional Events Required
 - More Fields

Third is

Program Events Group Table
(Columns)
 - Event ID (FK)
 - Group ID (FK)
 - Mandatory (bit field)
 - Optional (bit field)
 - More items if required

The Fourth table is

Program Participants Table (listing the registered participants)
(Columns)
 - Participant ID
 - Employee ID (FK)
 - Group ID  (FK)
 - Batch ID  (FK)
 - More items if required

and the final table is

Program Batch Table (For distinguishing between different batches)
(Columns)
 - Batch ID
 - Batch Start Date
 - Batch End Date
 - More items if required

I filled the Program Events Group table with the the list of events related to the program and their requirement criteria for each group.
So If Event 01 -- Skill 01 is required for Group 01 and is optional for Group 02 then the Program Events Group table will have 2 entries.

Event 01, Group 01, 1, 0, ...
Event 01, Group 02, 0, 1, ...

But if Event 08 -- Skill 08 is option for Group 02 but is not required by Group 01 then it will have only 1 entry in the table.

Event 08, Group 02, 0, 1, ...

Now I added the Event ID  from the Program Event Table to the existing Event table, so if a new event belongs to this program then Program event ID will be added. So now the existing participation table is used and the existing event table is also used.


答:
```<code>  default:
        return true;
</code>```

<p>You are telling it to return true without an error. You should change that to </p>

```<code>  default:
        throw new Exception("Invalid Selection")
</code>```

Body:
  default:
        return true;

You are telling it to return true without an error. You should change that to

  default:
        throw new Exception("Invalid Selection")


问:
Need help on mail composer in xcode
I have warning on with error message below. Please help.

Assigning to 'id<MFMailComposeViewControllerDeelegate>' from incompatible type 'MyViewController'
and
Class 'MyViewController' does not implement the 'MFMailComposeViewControllerDelegate' protocol

The code is

```<code>-(void)displayComposerSheet

{

MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];

//below bold code is warning

    **picker.mailComposeDelegate = self;**

[picker setSubject:@"My first apps!"];

// Set up recipients
NSArray *toRecipients = [NSArray arrayWithObjects: nil];

[picker setToRecipients:toRecipients];

[picker setMessageBody:TextView.text isHTML:NO];

[self presentModalViewController:picker animated:YES];

[picker release];

}
</code>```

答:
The problem is as the error says: your class MyViewController doesn't conform to the MFMailComposeViewControllerDelegate protocol. Your interface line should look something like this:

```<code>@interface MyViewController : UIViewController <MFMailComposeViewControllerDelegate>
</code>```

And, of course, you should be sure to implement mailComposeController:didFinishWithResult:error: in your class.

ContentLicense: CC BY-SA 3.0

Title: Need help on mail composer in xcode

Body:
I have warning on with error message below. Please help.

Assigning to 'id<MFMailComposeViewControllerDeelegate>' from incompatible type 'MyViewController'
and
Class 'MyViewController' does not implement the 'MFMailComposeViewControllerDelegate' protocol

The code is

-(void)displayComposerSheet

{

MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];

//below bold code is warning

    **picker.mailComposeDelegate = self;**

[picker setSubject:@"My first apps!"];

// Set up recipients
NSArray *toRecipients = [NSArray arrayWithObjects: nil];

[picker setToRecipients:toRecipients];

[picker setMessageBody:TextView.text isHTML:NO];

[self presentModalViewController:picker animated:YES];

[picker release];

}

Body:
The problem is as the error says: your class MyViewController doesn't conform to the MFMailComposeViewControllerDelegate protocol. Your interface line should look something like this:

@interface MyViewController : UIViewController <MFMailComposeViewControllerDelegate>

And, of course, you should be sure to implement mailComposeController:didFinishWithResult:error: in your class.


问:
Software framework and application framework?
I was wondering what differences and relations are between software framework and application framework? The existence of articles for both concepts in Wikipedia confuses me.

Are they both some kind of libraries?

Thanks and regards!

答:
Application framework is a type of software framework.

No.Software framework and Application framework is not the same. Application framework is a type of software framework. Application frameworks are often used for  development of general GUI applications but some other frameworks like Enterprise architecture framework(Development of enterprise applications), Oracle ADF(Provide visual and declarative approaches to java EE development), and Cactus computing frameworks(Used for scientific computing with higher performance) can also be considered as software frameworks.

Since not all the application frameworks are software frameworks.


问:
how to pass image file from database to html in django project
I tried many solution to solve it. But I can't fix and resolve. I can't able to pass the image file of my users to my html page. But I can able to access and pass all elements from database of a specific user. When I try to access the Image file of a user, it just returns a file path of the image. Please help me to resolve it.

models.py

```<code>class registration(models.Model):

    First_Name =models.CharField(max_length=50)
    Last_name = models.CharField(max_length=50)
    Phone_number = models.BigIntegerField()
    Email_id = models.EmailField()
    Password = models.CharField(max_length=20)
    Conform_Password = models.CharField(max_length=20)
    Register_No = models.BigIntegerField(primary_key=True)
    profile_pic = models.ImageField(upload_to="Profile")

    def __str__(self):
        return self.First_Name
</code>```

views.py

```<code>def login(request, *args, **kwargs):

 if request.method == 'POST':
     user_Name=int(request.POST["stu_uname"])
     pass_word=request.POST["stu_pwd"]

     get_user_name = registration.objects.filter(Register_No = user_Name).exists()
     if get_user_name is True:
         check_pwd = registration.objects.values('Password').filter(Register_No = user_Name)
         for check in check_pwd:
             pwd = check['Password']
                     if pwd == pass_word:
             user_objects = get_objects(user_Name)
             return render(request, "stu_profile.html", {'userObj': user_objects})
         else:
             return HttpResponse("<h1> Password is incorrect</h1>")
     else:
         return HttpResponse("<h1> User name is incorrect </h1>")
 return redirect('student')
def get_objects(name):

 check_objects = registration.objects.values().filter(Register_No = name)
 for check in check_objects:
     values = check
 return values
</code>```

HTML PAGE

```<code>    <div class="pro_pic">

      <img src = "{{userObj.profile_pic}}"> #this image doesn't render.

      <div>
        <p> {{userObj.First_Name}} {{userObj.Last_name}} </p>
      </div>

    </div>
</code>```

Settings.py

```<code>MEDIA_ROOT = os.path.join(BASE_DIR, 'Pictures/')
MEDIA_URL = '/Pictures/'

</code>```

答:
I hope this works for you.

HTML PAGE

```<code>{% load static %}
{% static "img" as baseUrl %}

<div class="pro_pic">

      <img src = "{{userObj.profile_pic.url}}"> #this image doesn't render.

      <div>
        <p> {{userObj.First_Name}} {{userObj.Last_name}} </p>
      </div>

    </div>
</code>```

And {% static "< your image folder name in static folder > as baseurl" %}

Body:
I tried many solution to solve it. But I can't fix and resolve. I can't able to pass the image file of my users to my html page. But I can able to access and pass all elements from database of a specific user. When I try to access the Image file of a user, it just returns a file path of the image. Please help me to resolve it.

models.py

class registration(models.Model):

    First_Name =models.CharField(max_length=50)
    Last_name = models.CharField(max_length=50)
    Phone_number = models.BigIntegerField()
    Email_id = models.EmailField()
    Password = models.CharField(max_length=20)
    Conform_Password = models.CharField(max_length=20)
    Register_No = models.BigIntegerField(primary_key=True)
    profile_pic = models.ImageField(upload_to="Profile")

    def __str__(self):
        return self.First_Name

views.py

def login(request, *args, **kwargs):

 if request.method == 'POST':
     user_Name=int(request.POST["stu_uname"])
     pass_word=request.POST["stu_pwd"]

     get_user_name = registration.objects.filter(Register_No = user_Name).exists()
     if get_user_name is True:
         check_pwd = registration.objects.values('Password').filter(Register_No = user_Name)
         for check in check_pwd:
             pwd = check['Password']
                     if pwd == pass_word:
             user_objects = get_objects(user_Name)
             return render(request, "stu_profile.html", {'userObj': user_objects})
         else:
             return HttpResponse("
 Password is incorrect
")
     else:
         return HttpResponse("
 User name is incorrect
")
 return redirect('student')
def get_objects(name):

 check_objects = registration.objects.values().filter(Register_No = name)
 for check in check_objects:
     values = check
 return values

HTML PAGE

       #this image doesn't render.

 {{userObj.First_Name}} {{userObj.Last_name}}

Settings.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'Pictures/')
MEDIA_URL = '/Pictures/'

Body:
I hope this works for you.

HTML PAGE

{% load static %}
{% static "img" as baseUrl %}

<div class="pro_pic">

      <img src = "{{userObj.profile_pic.url}}"> #this image doesn't render.

      <div>
        <p> {{userObj.First_Name}} {{userObj.Last_name}} </p>
      </div>

    </div>

And {% static "< your image folder name in static folder > as baseurl" %}


问:
SMS delivery report for SMS_DELIVERED Intent not working
I have gone through several solutions provided in Stackoverflow.com for getting delivery reports for SMS on android device programmatically.  I have implemented (borrowed from one of the contributors on Stackoverflow.com) 2 Broadcast Receivers, one for PendingIntent = "SMS_SENT" and another for PendingIntent="SMS_DELIVERED". Upon running the app, the Text message is sent and I get the "SMS SENT" from sentReceiver but I do not get any response from the deliverReceiver. The same program apparently works for the contributors on Stackoverflow.com.  My device is Samsung Galaxy S5, 6.0.1 os.  I have tried code from several posting but all of them behave similarly. On the device there is no option to turn the delivery report on/off either. Appreciate some guidance.  Here is the code:

```<code>     public class DeliverReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent arg1) {

            System.out.println("+++ DeliverReceiver resultcode = "+getResultCode());
            switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(context, "SMS Delivered", LENGTH_SHORT).show();
                    break;
                case Activity.RESULT_CANCELED:
                    makeText(context, "SMS Not Delivered",
                            LENGTH_SHORT).show();
                    break;
            }

        }
    }

public class SentReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent arg1) {

            System.out.println("+++ SentReceiver resultcode = "+getResultCode());
            switch (getResultCode()) {
                case Activity.RESULT_OK:
                    makeText(context, "+++sms_sent+++", LENGTH_SHORT).show();
                    //startActivity(new Intent(SendSMS.this, ChooseOption.class));
                    //overridePendingTransition(R.anim.animation, R.anim.animation2);
                    break;
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    makeText(context, "Generic failure", LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NO_SERVICE:
                    makeText(context, "No service", LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NULL_PDU:
                    makeText(context, "Null PDU", LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_RADIO_OFF:
                    makeText(context, "Radio off", LENGTH_SHORT).show();
                    break;
            }

        }
    }

    public class MainActivity extends AppCompatActivity {
        private static final int MY_PERMISSIONS_REQUEST_SEND_SMS = 101;

        private BroadcastReceiver sendBroadcastReceiver = new SentReceiver();
        private BroadcastReceiver deliveryBroadcastReceiver = new DeliverReceiver();

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {

                ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission
                        .SEND_SMS}, MY_PERMISSIONS_REQUEST_SEND_SMS);

                if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.SEND_SMS)) {

                } else {

                    ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.SEND_SMS}, MY_PERMISSIONS_REQUEST_SEND_SMS);
               }
            }
            sendSMS("6785459898","+++ Testing SMS +++");
        }
        @Override
        protected void onPause() {
            // TODO Auto-generated method stub
            super.onPause();

            try {
                unregisterReceiver(sendBroadcastReceiver);
                unregisterReceiver(deliveryBroadcastReceiver);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        @Override
        protected void onDestroy() {
            // TODO Auto-generated method stub
            super.onDestroy();
            try {
                unregisterReceiver(sendBroadcastReceiver);
                unregisterReceiver(deliveryBroadcastReceiver);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

            private void sendSMS(String ph, String msg){
                String SENT = "SMS_SENT";
                String DELIVERED = "SMS_DELIVERED";

                PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), PendingIntent.FLAG_UPDATE_CURRENT);

                PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), PendingIntent.FLAG_UPDATE_CURRENT);

                registerReceiver(sendBroadcastReceiver, new IntentFilter(SENT));

                registerReceiver(deliveryBroadcastReceiver, new IntentFilter(DELIVERED));

                SmsManager sms = SmsManager.getDefault();
                sms.sendTextMessage(ph, null, msg, sentPI, deliveredPI);

            }

        }
</code>```

Here is the manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.WRITE_SMS"/>
<uses-permission android:name="android.permission.BROADCAST_SMS"/>

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>

            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
    <receiver android:name="com.android.internal.telephony.sendsms5.DeliverReceiver">
        <intent-filter>
            <action android:name="SMS_DELIVERED" />
        </intent-filter>
    </receiver>
    <receiver android:name="com.android.internal.telephony.sendsms5.SentReceiver">
        <intent-filter>
            <action android:name="SMS_SENT" />
        </intent-filter>
    </receiver>
 </application>
</code>```

答: Try removing the intent-filters, on some OS levels implicit intents in this case don't work

Body:
I have gone through several solutions provided in Stackoverflow.com for getting delivery reports for SMS on android device programmatically.  I have implemented (borrowed from one of the contributors on Stackoverflow.com) 2 Broadcast Receivers, one for PendingIntent = "SMS_SENT" and another for PendingIntent="SMS_DELIVERED". Upon running the app, the Text message is sent and I get the "SMS SENT" from sentReceiver but I do not get any response from the deliverReceiver. The same program apparently works for the contributors on Stackoverflow.com.  My device is Samsung Galaxy S5, 6.0.1 os.  I have tried code from several posting but all of them behave similarly. On the device there is no option to turn the delivery report on/off either. Appreciate some guidance.  Here is the code:

     public class DeliverReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent arg1) {

            System.out.println("+++ DeliverReceiver resultcode = "+getResultCode());
            switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(context, "SMS Delivered", LENGTH_SHORT).show();
                    break;
                case Activity.RESULT_CANCELED:
                    makeText(context, "SMS Not Delivered",
                            LENGTH_SHORT).show();
                    break;
            }

        }
    }

public class SentReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent arg1) {

            System.out.println("+++ SentReceiver resultcode = "+getResultCode());
            switch (getResultCode()) {
                case Activity.RESULT_OK:
                    makeText(context, "+++sms_sent+++", LENGTH_SHORT).show();
                    //startActivity(new Intent(SendSMS.this, ChooseOption.class));
                    //overridePendingTransition(R.anim.animation, R.anim.animation2);
                    break;
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    makeText(context, "Generic failure", LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NO_SERVICE:
                    makeText(context, "No service", LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NULL_PDU:
                    makeText(context, "Null PDU", LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_RADIO_OFF:
                    makeText(context, "Radio off", LENGTH_SHORT).show();
                    break;
            }

        }
    }

    public class MainActivity extends AppCompatActivity {
        private static final int MY_PERMISSIONS_REQUEST_SEND_SMS = 101;

        private BroadcastReceiver sendBroadcastReceiver = new SentReceiver();
        private BroadcastReceiver deliveryBroadcastReceiver = new DeliverReceiver();

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {

                ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission
                        .SEND_SMS}, MY_PERMISSIONS_REQUEST_SEND_SMS);

                if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.SEND_SMS)) {

                } else {

                    ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.SEND_SMS}, MY_PERMISSIONS_REQUEST_SEND_SMS);
               }
            }
            sendSMS("6785459898","+++ Testing SMS +++");
        }
        @Override
        protected void onPause() {
            // TODO Auto-generated method stub
            super.onPause();

            try {
                unregisterReceiver(sendBroadcastReceiver);
                unregisterReceiver(deliveryBroadcastReceiver);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        @Override
        protected void onDestroy() {
            // TODO Auto-generated method stub
            super.onDestroy();
            try {
                unregisterReceiver(sendBroadcastReceiver);
                unregisterReceiver(deliveryBroadcastReceiver);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

            private void sendSMS(String ph, String msg){
                String SENT = "SMS_SENT";
                String DELIVERED = "SMS_DELIVERED";

                PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), PendingIntent.FLAG_UPDATE_CURRENT);

                PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), PendingIntent.FLAG_UPDATE_CURRENT);

                registerReceiver(sendBroadcastReceiver, new IntentFilter(SENT));

                registerReceiver(deliveryBroadcastReceiver, new IntentFilter(DELIVERED));

                SmsManager sms = SmsManager.getDefault();
                sms.sendTextMessage(ph, null, msg, sentPI, deliveredPI);

            }

        }

Here is the manifest:

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.WRITE_SMS"/>
<uses-permission android:name="android.permission.BROADCAST_SMS"/>

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>

            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
    <receiver android:name="com.android.internal.telephony.sendsms5.DeliverReceiver">
        <intent-filter>
            <action android:name="SMS_DELIVERED" />
        </intent-filter>
    </receiver>
    <receiver android:name="com.android.internal.telephony.sendsms5.SentReceiver">
        <intent-filter>
            <action android:name="SMS_SENT" />
        </intent-filter>
    </receiver>
 </application>


问:
Programmatically set item selection in showOpenDialogSync
I am using Electron's showOpenDialogSync successfully, but I have a minor issue. I want users to be able to change the root directory for, say, a library from a set of libraries:

```<code>usr/project/library1/
usr/project/library2/
  subdir1/
  subdir2/
  subdir3/
usr/project/library3/
</code>```

Now the issue is, when I use the showOpenDialogSync dialog and pass it usr/project/library2/ as the default, it shows all the subdirectories. I would rather it show the dialog for usr/project with library2 highlighted, so I can quickly switch between libraries, without having to hit the back-button to select a different library.

I can, of course, switch the default path to just usr/project but it won't have library2 selected as the default selection (or I don't see how).

In short, how can I have the showOpenDialogSync show the path to the parent folder of the default selection, with the default selection selected instead of opening the full path of that default selection.

答:
Unfortunately, there is no such functionality provided in the Electron dialog API.

If there is a good case for your Electron app to have this feature, you may consider building the open dialog yourself. Of course, everything that the prebuilt dialogs give you is now yours to re-implement. Be aware that non-standard dialogs will throw off some users. Furthermore, should you also need a save dialog, you may end up re-implementing that as well for sake of uniformity.

Why doesn't Electron offer this option? Electron makes use of the file dialogs provided by the underlying operating system. That's why they look "native" in each operating system. It only passes through calls; its functionality cannot exceed that of the underlying dialogs.

It's possible that the file dialog of a specific OS is actually able to do what you want. Regarding Windows, the docs suggest that there is no way to select an existing item. For GTK, on the other hand, there is gtk_file_chooser_set_filename(), which (at least for save dialogs) allows to select an item. However, Electron's GTK save dialog implementation makes use of gtk_file_chooser_set_current_name(), which only allows to set a filename.

Whatever the functionality of the dialogs of a given OS may be, Electron would need to support those options in order for you to have a chance of using them.

Cross-platform frameworks like Electron offer a common abstraction of OS features like dialogs, so that developers building apps with Electron don't have to deal with the OS specifics for each OS that needs to be supported. On the flipside, that can also mean that only a common subset of functionality is available.

Body:
I am using Electron's showOpenDialogSync successfully, but I have a minor issue. I want users to be able to change the root directory for, say, a library from a set of libraries:

usr/project/library1/
usr/project/library2/
  subdir1/
  subdir2/
  subdir3/
usr/project/library3/

Now the issue is, when I use the showOpenDialogSync dialog and pass it usr/project/library2/ as the default, it shows all the subdirectories. I would rather it show the dialog for usr/project with library2 highlighted, so I can quickly switch between libraries, without having to hit the back-button to select a different library.

I can, of course, switch the default path to just usr/project but it won't have library2 selected as the default selection (or I don't see how).

In short, how can I have the showOpenDialogSync show the path to the parent folder of the default selection, with the default selection selected instead of opening the full path of that default selection.


问:
kubernetes - can't access the cluster with new user certificate
I want to create new user admin in kubernetes ,i do all the steps for creating and authorizing the certificates but when i want to access to api,i receive anuthorized error.
i do these steps to create user-admin:

1/ openssl genrsa -out user.key 2048

2/ openssl req -new -key user.key -out user.csr -subj "/CN=kube-user"

3/

```<code>cat <<EOF | kubectl apply -f -
apiVersion: certificates.k8s.io/v1beta1
kind: CertificateSigningRequest
metadata:
  name: user
spec:
  request: $(cat user.csr | base64 | tr -d '\n')
  usages:
  - digital signature
  - key encipherment
  - server auth
EOF
</code>```

4/ k certificate approve user

5/ k get csr user -o jsonpath='{.status.certificate}' | base64 --decode > user.crt

6/ kubectl config view -o jsonpath='{.clusters[0].cluster.certificate-authority-data}' --raw | base64 --decode - > ca.crt

7/

```<code>curl https://$Kube-Master-Ip:6443/api/v1 \
 --key user.key \
 --cert user.crt \
 --cacert ca.crt
</code>```

8/ and this is what i've receive:

```<code>{
"kind":"Status",
"apiVersion":"v1",
"metadata":{},
"status":"Failure",
"message":"Unauthorized",
"reason":"Unatuhorized",
"code":401
}
</code>```

document source: https://kubernetes.io/docs/tasks/tls/managing-tls-in-a-cluster/

答:
The step 2 command is wrong. The admin user should be part of system:masters group.</p>

```<code>openssl req -new -key user.key -out user.csr -subj "/CN=kube-user/O=system:masters"
</code>```

Body:
I want to create new user admin in kubernetes ,i do all the steps for creating and authorizing the certificates but when i want to access to api,i receive anuthorized error.
i do these steps to create user-admin:

1/ openssl genrsa -out user.key 2048

2/ openssl req -new -key user.key -out user.csr -subj "/CN=kube-user"

3/

cat <<EOF | kubectl apply -f -
apiVersion: certificates.k8s.io/v1beta1
kind: CertificateSigningRequest
metadata:
  name: user
spec:
  request: $(cat user.csr | base64 | tr -d '\n')
  usages:
  - digital signature
  - key encipherment
  - server auth
EOF

4/ k certificate approve user

5/ k get csr user -o jsonpath='{.status.certificate}' | base64 --decode > user.crt

6/ kubectl config view -o jsonpath='{.clusters[0].cluster.certificate-authority-data}' --raw | base64 --decode - > ca.crt

7/

curl https://$Kube-Master-Ip:6443/api/v1 \
 --key user.key \
 --cert user.crt \
 --cacert ca.crt

8/ and this is what i've receive:

{
"kind":"Status",
"apiVersion":"v1",
"metadata":{},
"status":"Failure",
"message":"Unauthorized",
"reason":"Unatuhorized",
"code":401
}

document source: https://kubernetes.io/docs/tasks/tls/managing-tls-in-a-cluster/

Body:
The step 2 command is wrong. The admin user should be part of system:masters group.

openssl req -new -key user.key -out user.csr -subj "/CN=kube-user/O=system:masters"


问:
how to customized hr,month,year in python date time module?
How can i customize hrs,days,months of date time module in python?
day of 5 hrs only, a month of 20 days only, and a year of 10 months only.
using date time module.</p>

答:
I agree with @TimPeters . This just doesn't fit in what datetime does.

For your needs, I would be inclined to start my own class from scratch, as that is pretty far from datetime.

That said...you could look into monkeypatching datetime...but I would recommend against it. It's a pretty complex beast, and changing something as fundamental as the number of hours in a day will blow away unknown assumptions within the code, and would certainly turn its unit tests upside down.

Build your own from scratch is my advice.


问:
Android sensor how to get the accuracy at anytime?
I know the onAccuracyChanged(Sensor sensor, int accuracy) callback, but it only happens when there's a change. How do I get the accuracy at anytime?

In Google Map, if you click on a POI where you're currently at, there's an option for you to Calibrate Compass, and in that screen they show you the current accuracy level.

In order words, after I calibrate my compass with figure 8, how do I check if my accuracy level indeed increases? I need a way something like sensor.getAccuracy() but I can't find that method.

答:
I found a solution for this at https://github.com/sky-map-team/stardroid/blob/master/app/src/main/java/com/google/android/stardroid/activities/CompassCalibrationActivity.java

```<code>  @Override
  public void onSensorChanged(SensorEvent event) {
    if (!accuracyReceived) {
      onAccuracyChanged(event.sensor, event.accuracy);
    }
  }
</code>```

Basically, it is calling the onAccuracyChanged() within onSensorChanged() at the initial stage to capture the current accuracy level at the beginning. Subsequently, onAccuracyChanged() will be called automatically by the system when there is a change to that. And, at anytime, you may also examine the value if event.accuracy in onSensorChanged() for any data received.

Body:
I found a solution for this at https://github.com/sky-map-team/stardroid/blob/master/app/src/main/java/com/google/android/stardroid/activities/CompassCalibrationActivity.java

  @Override
  public void onSensorChanged(SensorEvent event) {
    if (!accuracyReceived) {
      onAccuracyChanged(event.sensor, event.accuracy);
    }
  }

Basically, it is calling the onAccuracyChanged() within onSensorChanged() at the initial stage to capture the current accuracy level at the beginning. Subsequently, onAccuracyChanged() will be called automatically by the system when there is a change to that. And, at anytime, you may also examine the value if event.accuracy in onSensorChanged() for any data received.


问:
solace monitoring: looking for prometheus exporter
Is the a way to have a solace prometheus exporter?

For example let the prometheus mon server export its metrics as promehteus compatible web service?
Or to use something like the PushGateway for the metrics over topic?

答:
I mean time we created an exporter:
https://github.com/dabgmx/solace_exporter
https://hub.docker.com/r/dabgmx/solace-exporter</p>


问:
Countdown var to loop and display array
I'm very new to javascript and I'm trying to do something I thought would be very basic.

I've created a countdown timer and used "i" as my variable to hold a number from 0-5. And I have an array of "d" from d[0] to d[5] containing strings.

I'm trying to make the timer countdown pass the "i" value into an innerHTML method array value so I want it to display d[5]... d[4]...d[3]... etc.

What am I doing wrong!? Please Help!

```<code><html><head><script language="javascript" type="text/javascript">

var d=new Array():
    d[1]="One";
    d[2]="Two";
    d[3]="Three";
    d[4]="Four";
    d[5]="Five";

    var i=5;

    var i=setInterval("timer()",2000); //1000 will  run it every 1 second

    function timer() {
        i--;
        if (i <= 0)

 clearInterval(countD);
 return;
      }
 }

 document.getElementById(timer).innerHTML = d[i];

 </script>

 </head>
 <body>

 <h1>
 <p id="timer"></p>
 </h1>

 </body>
 </html>
</code>```

答:
I'm sorry to say but your code is quite a mess; here's one way to get your code to work, along with a working example:

```<code><html>
<head>
 <script language="javascript" type="text/javascript">
    var d=new Array();
    d[0]="One";
    d[1]="Two";
    d[2]="Three";
    d[3]="Four";
    d[4]="Five";

    var i=4;

    var myTimer =setInterval(timer,2000); //1000 will  run it every 1 second

    function timer() {
        document.getElementById("timer").innerHTML = d[i];
        i--;
        if (i < 0){
            clearInterval(myTimer);
        }
    }
 </script>
 </head>
 <body>
    <h1>
        <p id="timer"></p>
    </h1>
 </body>
 </html>
</code>```

The problems with your JavaScript

You've got two declarations for i, one after the other - one is set to 5 and the other to the setInterval timer

What is countD in clearInterval(countD);?

document.getElementById(timer).innerHTML = d[i]; is attempting to use the function timer as the argument to getElementById. It should be in quotes: document.getElementById("timer").innerHTML = d[i];

It is also being invoked only once since it's not inside the function that is being called by the timer.

var d=new Array(): should be terminated by a ;(semi-colon) and not a : (colon)

You have unmatched braces - your if statement doesn't have an opening brace ({) but it does have a closing one.

Note that while setInterval("timer()", 1000) is valid JavaScript, it depends on eval which should be avoided if possible. The alternate, preferred way to use this is setInterval(timer, 1000) i.e. passing the function and not a string.

Title: Countdown var to loop and display array

Body:
I'm sorry to say but your code is quite a mess; here's one way to get your code to work, along with a working example:

<html>
<head>
 <script language="javascript" type="text/javascript">
    var d=new Array();
    d[0]="One";
    d[1]="Two";
    d[2]="Three";
    d[3]="Four";
    d[4]="Five";

    var i=4;

    var myTimer =setInterval(timer,2000); //1000 will  run it every 1 second

    function timer() {
        document.getElementById("timer").innerHTML = d[i];
        i--;
        if (i < 0){
            clearInterval(myTimer);
        }
    }
 </script>
 </head>
 <body>
    <h1>
        <p id="timer"></p>
    </h1>
 </body>
 </html>

The problems with your JavaScript

You've got two declarations for i, one after the other - one is set to 5 and the other to the setInterval timer

What is countD in clearInterval(countD);?

document.getElementById(timer).innerHTML = d[i]; is attempting to use the function timer as the argument to getElementById. It should be in quotes: document.getElementById("timer").innerHTML = d[i];

It is also being invoked only once since it's not inside the function that is being called by the timer.

var d=new Array(): should be terminated by a ;(semi-colon) and not a : (colon)

You have unmatched braces - your if statement doesn't have an opening brace ({) but it does have a closing one.

Note that while setInterval("timer()", 1000) is valid JavaScript, it depends on eval which should be avoided if possible. The alternate, preferred way to use this is setInterval(timer, 1000) i.e. passing the function and not a string.


问:
Simple example of filtering items in a grid in Vaadin Flow 14
I want to suppress the display of some items in a Grid widget in Vaadin Flow 14.

For example, if the user enters a year in a IntegerField widget, I want the grid to show only items with an associated date before that year. Items with a date on or after that date should disappear. If the user changes the year number, the filtering should be re-applied with fewer or more items displayed appropriately in the grid.

I have seen filters on Grid discussed but cannot wrap my head around the various moving parts. Perhaps someone could show a simple example?

答:
Filtering grids is quite slick, and fairly easy once you get the hang of it.

First, understand that the Grid object is not actually filtered. The DataProvider backing the Grid is filtered. The Grid automatically updates its own display to match changes to the data provider.

Below is an entire example app. When it first appears, we see four items it the Grid widget. These items are simply java.time.LocalDate objects.

When the user enters a year number in the IntegerField, we apply a filter to the ListDataProvider object backing our grid. If the user clears the year number from that IntegerField, we clear all filters from our data provider.

Setting and clearing the filter(s) takes effect immediately. This point threw me, with me thinking that I must somehow “apply” the filters after calling setFilter or addFilter. But, no, the Grid automatically updates its display — with no further code on my part. The predicate test defined as part of your filter is automatically applied to each item in the ListDataProvider object’s data set. Those items that pass the test are displayed, while items that fail the test are suppressed from display.

The setting and clearing of filters is done in a value-change listener on the IntegerField widget. When a user enters a number (and leaves the field, such as by pressing Tab or Return), our listener object automatically is called, with an event object passed. Notice that we test for a null being retrieved from the IntegerField. A null means the user cleared the existing entry, leaving the field blank.

Where did we define our ListDataProvider object to back our Grid object? That data provider was instantiated automatically for us when we passed a List to the Grid::setItems method.

By the way, you can have a Grid automatically display columns using the JavaBeans-style naming conventions (getter/setter methods). But here in this example we defined our columns explicitly, their values generated by calling the LocalDate :: method references we pass.

```<code>package work.basil.example;

import com.vaadin.flow.component.AbstractField;
import com.vaadin.flow.component.dependency.CssImport;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.IntegerField;
import com.vaadin.flow.data.provider.ListDataProvider;
import com.vaadin.flow.router.Route;

import java.time.LocalDate;
import java.time.Month;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * The main view contains a button and a click listener.
 */
@Route ( "" )
//@PWA ( name = "Project Base for Vaadin", shortName = "Project Base" )
@CssImport ( "./styles/shared-styles.css" )
@CssImport ( value = "./styles/vaadin-text-field-styles.css", themeFor = "vaadin-text-field" )
public class MainView extends VerticalLayout
{
    private Grid < LocalDate > grid;
    private IntegerField yearField;

    public MainView ( )
    {
        yearField = new IntegerField( "Filter years before: " );
        yearField.addValueChangeListener(
                ( AbstractField.ComponentValueChangeEvent < IntegerField, Integer > event ) -> {
                    Integer year = event.getValue();
                    // If the user cleared the field, its value is null. In such a case, clear all filters.
                    // If the user entered a year number into this field, specify a filter.
                    if ( Objects.isNull( year ) )
                    {
                        ( ( ListDataProvider < LocalDate > ) grid.getDataProvider() ).clearFilters();
                    } else
                    {
                        ( ( ListDataProvider < LocalDate > ) grid.getDataProvider() ).setFilter( ( LocalDate localDate ) -> localDate.getYear() < year );
                    }
                }
        );

        grid = new Grid <>();
        List < LocalDate > dates = List.of(
                LocalDate.of( 2020 , Month.JANUARY , 23 ) ,
                LocalDate.of( 2019 , Month.FEBRUARY , 24 ) ,
                LocalDate.of( 2022 , Month.MARCH , 25 ) ,
                LocalDate.of( 2011 , Month.APRIL , 26 )
        );
        grid.setItems( new ArrayList < LocalDate >( dates ) );
        grid.addColumn( LocalDate :: toString );
        grid.addColumn( LocalDate :: getYear );
        grid.addColumn( LocalDate :: getDayOfWeek );

        this.add( yearField , grid );
    }
}
</code>```

You can install multiple filters by calling addFilter instead of setFilter. The predicates are effective combined as AND rather than as OR. So all the predicate tests must pass for an item to be displayed. Call clearFilters to remove any filters. Calling setFilter clears any existing filters and installs a single filter.

Body:
Filtering grids is quite slick, and fairly easy once you get the hang of it.

First, understand that the Grid object is not actually filtered. The DataProvider backing the Grid is filtered. The Grid automatically updates its own display to match changes to the data provider.

Below is an entire example app. When it first appears, we see four items it the Grid widget. These items are simply java.time.LocalDate objects.

When the user enters a year number in the IntegerField, we apply a filter to the ListDataProvider object backing our grid. If the user clears the year number from that IntegerField, we clear all filters from our data provider.

Setting and clearing the filter(s) takes effect immediately. This point threw me, with me thinking that I must somehow “apply” the filters after calling setFilter or addFilter. But, no, the Grid automatically updates its display — with no further code on my part. The predicate test defined as part of your filter is automatically applied to each item in the ListDataProvider object’s data set. Those items that pass the test are displayed, while items that fail the test are suppressed from display.

The setting and clearing of filters is done in a value-change listener on the IntegerField widget. When a user enters a number (and leaves the field, such as by pressing Tab or Return), our listener object automatically is called, with an event object passed. Notice that we test for a null being retrieved from the IntegerField. A null means the user cleared the existing entry, leaving the field blank.

Where did we define our ListDataProvider object to back our Grid object? That data provider was instantiated automatically for us when we passed a List to the Grid::setItems method.

By the way, you can have a Grid automatically display columns using the JavaBeans-style naming conventions (getter/setter methods). But here in this example we defined our columns explicitly, their values generated by calling the LocalDate :: method references we pass.

package work.basil.example;

import com.vaadin.flow.component.AbstractField;
import com.vaadin.flow.component.dependency.CssImport;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.IntegerField;
import com.vaadin.flow.data.provider.ListDataProvider;
import com.vaadin.flow.router.Route;

import java.time.LocalDate;
import java.time.Month;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * The main view contains a button and a click listener.
 */
@Route ( "" )
//@PWA ( name = "Project Base for Vaadin", shortName = "Project Base" )
@CssImport ( "./styles/shared-styles.css" )
@CssImport ( value = "./styles/vaadin-text-field-styles.css", themeFor = "vaadin-text-field" )
public class MainView extends VerticalLayout
{
    private Grid < LocalDate > grid;
    private IntegerField yearField;

    public MainView ( )
    {
        yearField = new IntegerField( "Filter years before: " );
        yearField.addValueChangeListener(
                ( AbstractField.ComponentValueChangeEvent < IntegerField, Integer > event ) -> {
                    Integer year = event.getValue();
                    // If the user cleared the field, its value is null. In such a case, clear all filters.
                    // If the user entered a year number into this field, specify a filter.
                    if ( Objects.isNull( year ) )
                    {
                        ( ( ListDataProvider < LocalDate > ) grid.getDataProvider() ).clearFilters();
                    } else
                    {
                        ( ( ListDataProvider < LocalDate > ) grid.getDataProvider() ).setFilter( ( LocalDate localDate ) -> localDate.getYear() < year );
                    }
                }
        );

        grid = new Grid <>();
        List < LocalDate > dates = List.of(
                LocalDate.of( 2020 , Month.JANUARY , 23 ) ,
                LocalDate.of( 2019 , Month.FEBRUARY , 24 ) ,
                LocalDate.of( 2022 , Month.MARCH , 25 ) ,
                LocalDate.of( 2011 , Month.APRIL , 26 )
        );
        grid.setItems( new ArrayList < LocalDate >( dates ) );
        grid.addColumn( LocalDate :: toString );
        grid.addColumn( LocalDate :: getYear );
        grid.addColumn( LocalDate :: getDayOfWeek );

        this.add( yearField , grid );
    }
}

You can install multiple filters by calling addFilter instead of setFilter. The predicates are effective combined as AND rather than as OR. So all the predicate tests must pass for an item to be displayed. Call clearFilters to remove any filters. Calling setFilter clears any existing filters and installs a single filter.


问:
datetime.timestamp returns different values in pandas apply and dataframe selection

Question

See code below demonstrating the issue. A simple pandas dataframe is created with one row and one column containing one datetime instance. As you can see, calling timestamp() on the datetime object returns 1581894000.0. Selecting the datetime object through the dataframe and calling timestamp() gives 1581897600.0. When using pandas apply function to call datetime.timestamp on each row of column 'date', the return value becomes 1581894000.0. I would expect to get the same timestamp value in all situations.

```<code>In[19]: d = datetime(2020, 2, 17)
In[20]: d.timestamp()
Out[20]: 1581894000.0 <----------------------------------+
In[21]: df = pd.DataFrame({'date': [d]})                 |
In[22]: df                                               |
Out[22]:                                                 |
        date                                             |
0 2020-02-17                                             |
In[23]: df['date'][0]                                    |
Out[23]: Timestamp('2020-02-17 00:00:00')                |
In[24]: df['date'][0].timestamp()                        |
Out[24]: 1581897600.0 <---------------------- These should be the same
In[25]: df['date'].apply(datetime.timestamp)             |
Out[25]:                                                 |
0    1.581894e+09                                        |
Name: date, dtype: float64                               |
In[26]: df['date'].apply(datetime.timestamp)[0]          |
Out[26]: 1581894000.0 <----------------------------------+
</code>```

Edit

Thanks to input from @ALollz, using to_datetime and Timestamp from pandas, as shown below seems to fix the problem.

```<code>In[15]: d = pd.to_datetime(datetime(2020,2,17))
In[16]: d.timestamp()
Out[16]: 1581897600.0
In[17]: df = pd.DataFrame({'date': [d]})
In[18]: df
Out[18]:
        date
0 2020-02-17
In[19]: df['date'][0]
Out[19]: Timestamp('2020-02-17 00:00:00')
In[20]: df['date'][0].timestamp()
Out[20]: 1581897600.0
In[21]: df['date'].apply(pd.Timestamp.timestamp)
Out[21]:
0    1.581898e+09
Name: date, dtype: float64
In[22]: df['date'].apply(pd.Timestamp.timestamp)[0]
Out[22]: 1581897600.0
</code>```

答:
The problem is timezone awareness. pandas doesn't always play well with the datetime module and some decisions diverge from the standard library, in this case how to deal with timezone unaware datetime objects.

This specific issue seems to have been a design choice based upon this open issue

Yah, for tz-naive we implement timestamp as if it were UTC. Among other things, this ensures that we get the same behavior regardless of where the code is running.

So to get a consistent answer you'd need a UTC localized timezone so that datetime.timestamp used that instead of your machine's local timezone.

```<code>from datetime import datetime
import pytz

my_date = datetime(2020, 2, 17)
my_date_aware = pytz.utc.localize(my_date)

# UTC aware is the same as pandas
datetime.timestamp(my_date_aware) - pd.to_datetime(my_date).timestamp()
#0

datetime.timestamp(my_date) - pd.to_datetime(my_date).timestamp()
#18000.0
</code>```

Body:
Question

See code below demonstrating the issue. A simple pandas dataframe is created with one row and one column containing one datetime instance. As you can see, calling timestamp() on the datetime object returns 1581894000.0. Selecting the datetime object through the dataframe and calling timestamp() gives 1581897600.0. When using pandas apply function to call datetime.timestamp on each row of column 'date', the return value becomes 1581894000.0. I would expect to get the same timestamp value in all situations.

In[19]: d = datetime(2020, 2, 17)
In[20]: d.timestamp()
Out[20]: 1581894000.0 <----------------------------------+
In[21]: df = pd.DataFrame({'date': [d]})                 |
In[22]: df                                               |
Out[22]:                                                 |
        date                                             |
0 2020-02-17                                             |
In[23]: df['date'][0]                                    |
Out[23]: Timestamp('2020-02-17 00:00:00')                |
In[24]: df['date'][0].timestamp()                        |
Out[24]: 1581897600.0 <---------------------- These should be the same
In[25]: df['date'].apply(datetime.timestamp)             |
Out[25]:                                                 |
0    1.581894e+09                                        |
Name: date, dtype: float64                               |
In[26]: df['date'].apply(datetime.timestamp)[0]          |
Out[26]: 1581894000.0 <----------------------------------+

Edit

Thanks to input from @ALollz, using to_datetime and Timestamp from pandas, as shown below seems to fix the problem.

In[15]: d = pd.to_datetime(datetime(2020,2,17))
In[16]: d.timestamp()
Out[16]: 1581897600.0
In[17]: df = pd.DataFrame({'date': [d]})
In[18]: df
Out[18]:
        date
0 2020-02-17
In[19]: df['date'][0]
Out[19]: Timestamp('2020-02-17 00:00:00')
In[20]: df['date'][0].timestamp()
Out[20]: 1581897600.0
In[21]: df['date'].apply(pd.Timestamp.timestamp)
Out[21]:
0    1.581898e+09
Name: date, dtype: float64
In[22]: df['date'].apply(pd.Timestamp.timestamp)[0]
Out[22]: 1581897600.0

Body:
The problem is timezone awareness. pandas doesn't always play well with the datetime module and some decisions diverge from the standard library, in this case how to deal with timezone unaware datetime objects.

This specific issue seems to have been a design choice based upon this open issue

Yah, for tz-naive we implement timestamp as if it were UTC. Among other things, this ensures that we get the same behavior regardless of where the code is running.

So to get a consistent answer you'd need a UTC localized timezone so that datetime.timestamp used that instead of your machine's local timezone.

from datetime import datetime
import pytz

my_date = datetime(2020, 2, 17)
my_date_aware = pytz.utc.localize(my_date)

# UTC aware is the same as pandas
datetime.timestamp(my_date_aware) - pd.to_datetime(my_date).timestamp()
#0

datetime.timestamp(my_date) - pd.to_datetime(my_date).timestamp()
#18000.0


问:
How to use loop to display looped information all at once? Functionality Issue
I am learning C++ and would like some help with functionality for my code below.
Quick summary/usage of my code: Program is to display randomized (x,y) coordinates and then print out the coordinates in a grid.

I got everything to work regarding randomizing (x,y) coordinates and then displaying their grid location.

The problem I am having is my code displays a separate grid for each coordinate instead of showing ALL coordinates on the same grid. [I attached a picture of my current output below].

I know this is a functionality issue.. but I am having trouble thinking of how to manipulate my loops so that the coordinates can be displayed first, followed by ONE grid with all the coordinates on it... I hope this makes sense.

Snippet of my code:

```<code>//Note: value of n and k is given by user earlier in the code
vector<vector<int> > vec( n , vector<int> (n));
cout << "\nGrid with city locations:\n";
for(i=0; i<k; i++) {
    //random select int coordinates (x,y) for each K(cities)
    x = rand() % n + 0;
    y = rand() % n + 0;
    arrCity[i] = i;

    //display coordinates for city 1..city2.. etc
    cout << "City " << arrCity[i] <<": (" << x << "," << y << ")" << endl;

    //display cities on grid
    for (int rows=0; rows < n; rows++) {
        for (int columns=0; columns < n; columns++) {
            if ((rows == y) && (columns == x)) {
                cout << "|" << (i);
            } else {
                cout << "|_";
            }

        }
        cout << "\n";
    }
    cout << "\n";
}
</code>```

Current Output:

As you can see there's a separate grid for each 'city coordinate'

答:
You need to store all city coordinates in order to display them on a single grid print.
In the code below I changed a few things in order to hopefully address your problem.

I have moved all city-related data into a structure

Then all cities are initialized before the grid output

When printing the grid, we have to search all cities if their coordinates match the current position, if so, we print the corresponding index.

Live Demo

```<code>#include <vector>
#include <iostream>

struct City
{
    int index;
    int x, y;

    City(int index_, int x_, int y_)
        : index(index_), x(x_), y(y_)
    { }
};

int main()
{
    int n = 10;
    int k = 6;

    std::vector<City> arrCity;
    arrCity.reserve(k);

    for(int i = 0; i < k; i++)
        arrCity.emplace_back(i, rand() % n, rand() % n);

    std::cout << "\nGrid with city locations:\n";

    for (int k = 0; k < arrCity.size(); k++)
        std::cout << "City " << arrCity[k].index << ": (" << arrCity[k].x << "," << arrCity[k].y << ")" << std::endl;

    //display cities on grid
    for (int i=0; i < n; i++) {
        for (int j=0; j < n; j++) {
            int w = -1;
            for (int k = 0; k < arrCity.size(); k++)
                if ((i == arrCity[k].y) && (j == arrCity[k].x))
                    w = k;

            if (w >= 0)
                std::cout << "|" << arrCity[w].index;
            else
                std::cout << "|_";
        }
        std::cout << "\n";
    }

    return 0;
}
</code>```

Body:
I am learning C++ and would like some help with functionality for my code below.
Quick summary/usage of my code: Program is to display randomized (x,y) coordinates and then print out the coordinates in a grid.

I got everything to work regarding randomizing (x,y) coordinates and then displaying their grid location.

The problem I am having is my code displays a separate grid for each coordinate instead of showing ALL coordinates on the same grid. [I attached a picture of my current output below].

I know this is a functionality issue.. but I am having trouble thinking of how to manipulate my loops so that the coordinates can be displayed first, followed by ONE grid with all the coordinates on it... I hope this makes sense.

Snippet of my code:

//Note: value of n and k is given by user earlier in the code
vector<vector<int> > vec( n , vector<int> (n));
cout << "\nGrid with city locations:\n";
for(i=0; i<k; i++) {
    //random select int coordinates (x,y) for each K(cities)
    x = rand() % n + 0;
    y = rand() % n + 0;
    arrCity[i] = i;

    //display coordinates for city 1..city2.. etc
    cout << "City " << arrCity[i] <<": (" << x << "," << y << ")" << endl;

    //display cities on grid
    for (int rows=0; rows < n; rows++) {
        for (int columns=0; columns < n; columns++) {
            if ((rows == y) && (columns == x)) {
                cout << "|" << (i);
            } else {
                cout << "|_";
            }

        }
        cout << "\n";
    }
    cout << "\n";
}

Current Output:

As you can see there's a separate grid for each 'city coordinate'

Body:
You need to store all city coordinates in order to display them on a single grid print.
In the code below I changed a few things in order to hopefully address your problem.

I have moved all city-related data into a structure

Then all cities are initialized before the grid output

When printing the grid, we have to search all cities if their coordinates match the current position, if so, we print the corresponding index.

Live Demo

#include <vector>
#include <iostream>

struct City
{
    int index;
    int x, y;

    City(int index_, int x_, int y_)
        : index(index_), x(x_), y(y_)
    { }
};

int main()
{
    int n = 10;
    int k = 6;

    std::vector<City> arrCity;
    arrCity.reserve(k);

    for(int i = 0; i < k; i++)
        arrCity.emplace_back(i, rand() % n, rand() % n);

    std::cout << "\nGrid with city locations:\n";

    for (int k = 0; k < arrCity.size(); k++)
        std::cout << "City " << arrCity[k].index << ": (" << arrCity[k].x << "," << arrCity[k].y << ")" << std::endl;

    //display cities on grid
    for (int i=0; i < n; i++) {
        for (int j=0; j < n; j++) {
            int w = -1;
            for (int k = 0; k < arrCity.size(); k++)
                if ((i == arrCity[k].y) && (j == arrCity[k].x))
                    w = k;

            if (w >= 0)
                std::cout << "|" << arrCity[w].index;
            else
                std::cout << "|_";
        }
        std::cout << "\n";
    }

    return 0;
}


问:
Elisp extend variable lifetime
I have a loop in which I create a local variable during each iteration. I then declare a lambda that uses the local variable sometime in the future.

```<code>      (dolist (entry (read-lines "~/.emacs-projects"))
         (let ((project (car (json-read-from-string entry)))) ;; <---- I NEED THIS ONE
             (widget-create 'link
                     :button-prefix ""
                     :button-suffix ""
                     :action (lambda (wid &rest ignore) (load-project project)) ;; HERE
                     (format "%s : %s\n" (car project) (cdr project)))))
</code>```

In the code above I create project and when :action triggers I want to use project as an argument to another function. Currently i am getting Symbol’s value as variable is void: project when the lambda is run which makes me think that the outer scope is not preserved.

How can I extend the lifetime of project so that I can access it in the lambda?

答:
You want to use the lexically scoped flavor of Emacs Lisp, which was one of the main novelties added to Emacs-24.  To do it, just add the following somewhere (usually inside a comment) on the first line of your Elisp file:

```<code>-*- lexical-binding:t -*-
</code>```

Hopefully, at some point in the future, the old dynamically-scoped dialect will not be the default any more.

Title: Elisp extend variable lifetime

Body:
I have a loop in which I create a local variable during each iteration. I then declare a lambda that uses the local variable sometime in the future.

      (dolist (entry (read-lines "~/.emacs-projects"))
         (let ((project (car (json-read-from-string entry)))) ;; <---- I NEED THIS ONE
             (widget-create 'link
                     :button-prefix ""
                     :button-suffix ""
                     :action (lambda (wid &rest ignore) (load-project project)) ;; HERE
                     (format "%s : %s\n" (car project) (cdr project)))))

In the code above I create project and when :action triggers I want to use project as an argument to another function. Currently i am getting Symbol’s value as variable is void: project when the lambda is run which makes me think that the outer scope is not preserved.

How can I extend the lifetime of project so that I can access it in the lambda?

Body:
You want to use the lexically scoped flavor of Emacs Lisp, which was one of the main novelties added to Emacs-24.  To do it, just add the following somewhere (usually inside a comment) on the first line of your Elisp file:

-*- lexical-binding:t -*-

Hopefully, at some point in the future, the old dynamically-scoped dialect will not be the default any more.


问:
how to generate a php image for src
I would like to use:

```<code>src="my_generated_image_from_php.jpg"
</code>```

instead of

src="my_php_image.php"

How do I do it?

my_php_image.php like:

```<code><?php
     ......
     Header('Content-type: image/png');
     imagepng($im2);
     imagedestroy($im2);
     ......
?>
</code>```

答:
You'll need to send an image header along with the image binary in your my_php_image.php file like so:

```<code>header("Content-Type: image/jpeg");
echo file_get_contents("my_generated_image_from_php.jpeg");
</code>```

Obviously, you'll need to make sure the relative path of the image is correct for it to work. Otherwise, just use an absolute path from the root directory.

If you do this, you'll be able to use the second option as the image source.

Title: how to generate a php image for src

Body:
I would like to use:

src="my_generated_image_from_php.jpg"

instead of

src="my_php_image.php"

How do I do it?

my_php_image.php like:

<?php
     ......
     Header('Content-type: image/png');
     imagepng($im2);
     imagedestroy($im2);
     ......
?>

Body:
You'll need to send an image header along with the image binary in your my_php_image.php file like so:

header("Content-Type: image/jpeg");
echo file_get_contents("my_generated_image_from_php.jpeg");

Obviously, you'll need to make sure the relative path of the image is correct for it to work. Otherwise, just use an absolute path from the root directory.

If you do this, you'll be able to use the second option as the image source.


问:
Can run a build pipeline failed when the code coverage below a certain parameter
I added a .net test build to run my unit test

```<code>steps:
- task: DotNetCoreCLI@2
  displayName: 'Test Public API Project '
  inputs:
    command: test
    projects: '**/DWP.CDA.API.Test.csproj'
    arguments: '--output publish_output --configuration $(BuildConfiguration) /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura /p:Threshold=80 /p:ThresholdStat=total /p:CoverletOutput=$(Build.SourcesDirectory)\TestResults\Coverage\ --collect "Code coverage"'
</code>```

How can I get a build pipeline failed when code line coverage below 80%?

答:
One option is to use the Build Quality Checks task. You can fail a build based on a number of different Code Coverage result options

Another path is that you could do something custom by getting the code coverage results from the rest API.

Body:
I added a .net test build to run my unit test

steps:
- task: DotNetCoreCLI@2
  displayName: 'Test Public API Project '
  inputs:
    command: test
    projects: '**/DWP.CDA.API.Test.csproj'
    arguments: '--output publish_output --configuration $(BuildConfiguration) /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura /p:Threshold=80 /p:ThresholdStat=total /p:CoverletOutput=$(Build.SourcesDirectory)\TestResults\Coverage\ --collect "Code coverage"'

How can I get a build pipeline failed when code line coverage below 80%?


问:
UDF for conditional generation of filename
I want to pass the filename dynamically based on the condition. I have written the below code but the filename is not getting passed . I think there might be some issue in the if condition.

```<code>DynamicConfiguration conf = (DynamicConfiguration) container.getTransformationParameters().get(StreamTransformationConstants.DYNAMIC_CONFIGURATION);
DynamicConfigurationKey key = DynamicConfigurationKey.create("http://sap.com/xi/XI/System","FileName");

//get current timestamp and reformat
Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");

//define filename
String filename = new String("");
if (orgid == "G"||"ZG"||"S")
{
filename = "N_" + df.format(date) + ".txt"  ;
}
if (orgid == "L")
{
filename = "D_" + df.format(date) + ".txt"  ;
}

if (orgid == "F"||"IV")
{
filename = "F_" + df.format(date) + ".txt"  ;
}

conf.put(key, filename);

return filename;
</code>```

Please let me know where I am getting wrong.

答:
Several things:

Don't use == to compare strings for equality. Use the equals() method instead. The == checks if both objects point to the same memory location whereas the String#equals() method evaluates to the comparison of values in the objects.

Don't initialize your String variables in this fashion: String filename = new String("");. This is a String Constructor Invocation. What you should be doing is: String filename = "";.

You can't check to see if a particular variable contains one of multiple possibilities in this fashion:

```<code>if (orgid == "G" || "ZG" || "S") {
</code>```

As mentioned earlier you need to use the String#equals() method and to compare against other possibilities you need to compare each string to the variable, for example:

```<code>if (orgid.equals("G") || orgid.equals("ZG") || orgid.equals("S")) {
</code>```

It's better to use switch statement instead for something like this, for example:

```<code>/* Using the String#toUpperCase() method ensures that
   we don't need to worry about what letter case happens
   to be in orgid.    */
switch (orgid.toUpperCase()) {
    case "G":
    case "ZG":
    case "S":
        filename = "N_" + df.format(date) + ".txt";
        break;
    case "L":
        filename = "D_" + df.format(date) + ".txt";
        break;
    case "F":
    case "IV":
        filename = "F_" + df.format(date) + ".txt";
        break;
    default:
        System.err.println("Can Not Establish A Proper File Name (missing prefix)!");
        return;
}
</code>```

Body:
I want to pass the filename dynamically based on the condition. I have written the below code but the filename is not getting passed . I think there might be some issue in the if condition.

DynamicConfiguration conf = (DynamicConfiguration) container.getTransformationParameters().get(StreamTransformationConstants.DYNAMIC_CONFIGURATION);
DynamicConfigurationKey key = DynamicConfigurationKey.create("http://sap.com/xi/XI/System","FileName");

//get current timestamp and reformat
Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");

//define filename
String filename = new String("");
if (orgid == "G"||"ZG"||"S")
{
filename = "N_" + df.format(date) + ".txt"  ;
}
if (orgid == "L")
{
filename = "D_" + df.format(date) + ".txt"  ;
}

if (orgid == "F"||"IV")
{
filename = "F_" + df.format(date) + ".txt"  ;
}

conf.put(key, filename);

return filename;

Please let me know where I am getting wrong.

Body:
Several things:

Don't use == to compare strings for equality. Use the equals() method instead. The == checks if both objects point to the same memory location whereas the String#equals() method evaluates to the comparison of values in the objects.

Don't initialize your String variables in this fashion: String filename = new String("");. This is a String Constructor Invocation. What you should be doing is: String filename = "";.

You can't check to see if a particular variable contains one of multiple possibilities in this fashion:

if (orgid == "G" || "ZG" || "S") {

As mentioned earlier you need to use the String#equals() method and to compare against other possibilities you need to compare each string to the variable, for example:

if (orgid.equals("G") || orgid.equals("ZG") || orgid.equals("S")) {

It's better to use switch statement instead for something like this, for example:

/* Using the String#toUpperCase() method ensures that
   we don't need to worry about what letter case happens
   to be in orgid.    */
switch (orgid.toUpperCase()) {
    case "G":
    case "ZG":
    case "S":
        filename = "N_" + df.format(date) + ".txt";
        break;
    case "L":
        filename = "D_" + df.format(date) + ".txt";
        break;
    case "F":
    case "IV":
        filename = "F_" + df.format(date) + ".txt";
        break;
    default:
        System.err.println("Can Not Establish A Proper File Name (missing prefix)!");
        return;
}


问:
Promise { <state>: "pending" } - Should we use .then after async / await? Confused
I have just started learning JavaScript and am building an application using React.
I am struggling with an issue and would appreciate your help. I did come across similar questions but wasn't convinced with the answers and they didnt help me.
Please find my issue below . I am hiding the real name of the variables , components .

myService.js

```<code>export const findThisById = async Id=> {
  const response = await fetch(`${URL}/${Id}`);
  const json = await response.json();
  return json;
};
</code>```

myContainer.js // This is the parent component which has many chil component

```<code>        .......
     import {findThisById} from "../myService"

            findThis= async Id=> {
            const xyz= await findThisById(Id);
            return xyz;

         <Component1 findThis = {this.findThis}/>
        ......
</code>```

Component1.js

```<code>const Component1 = ({findThis}) => (

<Component2 findThis = {findThis} id = {Id} // Id is being passed successfully
   />

)
</code>```

Component2.js

```<code>    class Component2 extends React.Component {
      constructor(props) {
        super(props);
        console.log("Inside Constructor");
        const something = this.props.findThis(this.props.id);
        // course.then(data => console.log(data) // This works, i get the right data
        )
        console.log(something ); // Using this i get Promise state pending
      }

 // I need to use this value "something" inside a <h1></h1>

}
</code>```

I have ommited all exports/imports but they work correctly
The network tab in the console also make a 200 request and the response sub tab shows the correct values.
Should i use .then when i call the function findThis? Why? I am using await for fetch and its response.
Please help me. Struggl

答:
As mentioned in one of the comments async / await is just syntactic sugar for promises, so generally speaking you can either await or .then the result of findThis. That said, since you are calling this inside of a constructor function you won't be able to use await since the constructor isn't an async function.

One way to get the result of the Promise to render in your component would be to set the result in the component state and then render from the state. As mentioned by @Emile Bergeron in a follow up comment, you probably don't want to call setState in your constructor but instead in componentDidMount. This is to avoid calling setState on a potentially unmounted component.

```<code>class Component2 extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      searchResult: ''
    }
  }

  componentDidMount() {
    this.props.findThis(this.props.id).then(searchResult => {
      this.setState({
        searchResult
      })
    });
  }

  render() {
    return <div>{this.state.searchResult}</div>
  }
}
</code>```

Body:
I have just started learning JavaScript and am building an application using React.
I am struggling with an issue and would appreciate your help. I did come across similar questions but wasn't convinced with the answers and they didnt help me.
Please find my issue below . I am hiding the real name of the variables , components .

myService.js

export const findThisById = async Id=> {
  const response = await fetch(`${URL}/${Id}`);
  const json = await response.json();
  return json;
};

myContainer.js // This is the parent component which has many chil component

        .......
     import {findThisById} from "../myService"

            findThis= async Id=> {
            const xyz= await findThisById(Id);
            return xyz;

         <Component1 findThis = {this.findThis}/>
        ......

Component1.js

const Component1 = ({findThis}) => (

<Component2 findThis = {findThis} id = {Id} // Id is being passed successfully
   />

)

Component2.js

    class Component2 extends React.Component {
      constructor(props) {
        super(props);
        console.log("Inside Constructor");
        const something = this.props.findThis(this.props.id);
        // course.then(data => console.log(data) // This works, i get the right data
        )
        console.log(something ); // Using this i get Promise state pending
      }

 // I need to use this value "something" inside a

}

I have ommited all exports/imports but they work correctly
The network tab in the console also make a 200 request and the response sub tab shows the correct values.
Should i use .then when i call the function findThis? Why? I am using await for fetch and its response.
Please help me. Struggl

Body:
As mentioned in one of the comments async / await is just syntactic sugar for promises, so generally speaking you can either await or .then the result of findThis. That said, since you are calling this inside of a constructor function you won't be able to use await since the constructor isn't an async function.

One way to get the result of the Promise to render in your component would be to set the result in the component state and then render from the state. As mentioned by @Emile Bergeron in a follow up comment, you probably don't want to call setState in your constructor but instead in componentDidMount. This is to avoid calling setState on a potentially unmounted component.

class Component2 extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      searchResult: ''
    }
  }

  componentDidMount() {
    this.props.findThis(this.props.id).then(searchResult => {
      this.setState({
        searchResult
      })
    });
  }

  render() {
    return <div>{this.state.searchResult}</div>
  }
}