问:
Match a pandas Data frame (df1) row value to another Data frame (df2) column and update a rows of different column in Data frame (Df1)
I have 2 data frame 1st (DF1) look like below.

```<code>    JID      JRSubUsageLabel_16 SUB_USAGE_16
22  6223    JR_BOne_CY16              NaN
26  6510    JR_S_CY16                 NaN
59  11932   JR_B_CY16                 NaN
70  14242   JR_B_CY16                NaN
</code>```

2nd Data Frame (df2) looks like this

```<code>             JID    JR1_B_CY16  JR_CY16
1           1457    NaN             NaN
2           1530    NaN             NaN
3           1535    5               NaN
4           2035    NaN             NaN
5           6223    5               NaN
6           6510    1.0             6
39         11932    1.0             NaN
40         12021    NaN             NaN
41         12056    NaN             NaN
42         14234    2               1.0
</code>```

I want to update my DF1 data frame base on the "JID" column and JR1SubUsageLabel_16 column value. JID is the matching column in both data frames. In DF1 "JR1SubUsageLabel_16" column values become DF2 columns. So, the DF2  one of the columns matches the DF1 "JR1SubUsageLabel_16" column values too. It should look like below.

```<code>    JID      JRLabel_16           SUB_USAGE_16
22  6223    JR1_B_CY16            5
26  6510    JR1_S_CY16            6
59  11932   JR1_B_CY16            1
70  14242   JR1_B_CY16            2
</code>```

I was trying to update this using lambda and mapping couldn't figure exactly how to update this. Could anyone help me??

Thanks in advance

答:
One way is merge:

```<code>s = df2.melt('JID',value_name='SUB_USAGE_16',var_name='JR1SubUsageLabel_16')
df1.drop('SUB_USAGE_16', axis=1).merge(s, on = ['JID','JR1SubUsageLabel_16'], how='left')
</code>```

Output:

```<code>     JID JR1SubUsageLabel_16  SUB_USAGE_16
0   6223     JR1_BioOne_CY16           5.0
1   6510   JR1_Springer_CY16           6.0
2  11932     JR1_BioOne_CY16           1.0
3  14242     JR1_BioOne_CY16           NaN
</code>```

Body:
I have 2 data frame 1st (DF1) look like below.

    JID      JRSubUsageLabel_16 SUB_USAGE_16
22  6223    JR_BOne_CY16              NaN
26  6510    JR_S_CY16                 NaN
59  11932   JR_B_CY16                 NaN
70  14242   JR_B_CY16                NaN

2nd Data Frame (df2) looks like this

             JID    JR1_B_CY16  JR_CY16
1           1457    NaN             NaN
2           1530    NaN             NaN
3           1535    5               NaN
4           2035    NaN             NaN
5           6223    5               NaN
6           6510    1.0             6
39         11932    1.0             NaN
40         12021    NaN             NaN
41         12056    NaN             NaN
42         14234    2               1.0

I want to update my DF1 data frame base on the "JID" column and JR1SubUsageLabel_16 column value. JID is the matching column in both data frames. In DF1 "JR1SubUsageLabel_16" column values become DF2 columns. So, the DF2  one of the columns matches the DF1 "JR1SubUsageLabel_16" column values too. It should look like below.

    JID      JRLabel_16           SUB_USAGE_16
22  6223    JR1_B_CY16            5
26  6510    JR1_S_CY16            6
59  11932   JR1_B_CY16            1
70  14242   JR1_B_CY16            2

I was trying to update this using lambda and mapping couldn't figure exactly how to update this. Could anyone help me??

Thanks in advance

Body:
One way is merge:

s = df2.melt('JID',value_name='SUB_USAGE_16',var_name='JR1SubUsageLabel_16')
df1.drop('SUB_USAGE_16', axis=1).merge(s, on = ['JID','JR1SubUsageLabel_16'], how='left')

Output:

     JID JR1SubUsageLabel_16  SUB_USAGE_16
0   6223     JR1_BioOne_CY16           5.0
1   6510   JR1_Springer_CY16           6.0
2  11932     JR1_BioOne_CY16           1.0
3  14242     JR1_BioOne_CY16           NaN


来源: stackexchange

问:
How to create multiple tables from one module in MVC view?
I need to create multiple tables from one module in mvc view , I created 2 header and 2 foreach  but when i run the view its not seperated and second set of columns header not appeared only one set of header columns at the beginning of view , How to seperate the view and show multiple tables include header and columns ?

This is my View code :

```<code>@model IEnumerable<AljawdahNewSite.Models.Orders_Tables>
@{
    ViewBag.Title = "Details1";
    Layout = "~/Views/Shared/_LayoutPatients.cshtml";
    var ids = new List<int>() { 1, 2, 3, 4 };
}
</code>```

Then this is first table :

```<code>@if (ids.Contains(Model.First().labCashView.DEPTID.GetValueOrDefault()))
{
 <div class="tab-content">
     <div class="tab-pane container active p-0" style="margin-left:15px">
         <hr />
         <dl class="horizontal" style="border:solid">
             <dt style="width: 20%;display: inline-block;color:blue;">@Html.DisplayNameFor(model => model.labCashView.Patient_Name)</dt>
             <dd style="width: 25%;display: inline-block;margin: 0px;margin-left:-50px">@Html.DisplayFor(model => model.FirstOrDefault().labCashView.Patient_Name)</dd>
             <dt style="width: 22%;display: inline-block;color:blue;">@Html.DisplayNameFor(model => model.labCashView.Customer_Name)</dt>
             <dd style="width: 25%;display: inline-block;margin: 0px;margin-left:0px">@Html.DisplayFor(model => model.FirstOrDefault().labCashView.Customer_Name)</dd>
             <dt style="width: 20%;display: inline-block;color:blue;">@Html.DisplayNameFor(model => model.labCashView.Patient_No)</dt>
             <dd style="width: 25%;display: inline-block;margin: 0px;margin-left:-50px">@Html.DisplayFor(model => model.FirstOrDefault().labCashView.Patient_No)</dd>
             <dt style="width: 22%;display: inline-block;margin-left:0px;color:blue;">@Html.DisplayNameFor(model => model.labCashView.Collection_Date)</dt>
             <dd style="width: 25%;display: inline-block;margin: 0px;margin-left:0px">@Html.DisplayFor(model => model.FirstOrDefault().labCashView.Collection_Date)</dd>
             <dt style="width: 20%;display: inline-block;color:blue;">@Html.DisplayNameFor(model => model.labCashView.SEX)</dt>
             <dd style="width: 20%;display: inline-block;margin: 0px;margin-left:-50px">@Html.DisplayFor(model => model.FirstOrDefault().labCashView.SEX)</dd>
             <dt style="width: 22%;display: inline-block;margin-left:60px;color:blue;">@Html.DisplayNameFor(model => model.labCashView.Receiving_Date)</dt>
             <dd style="width: 25%;display: inline-block;margin: 0px;margin-left:0px">@Html.DisplayFor(model => model.FirstOrDefault().labCashView.Receiving_Date)</dd>
             <dt style="width: 20%;display: inline-block;color:blue;">@Html.DisplayNameFor(model => model.labCashView.AGE)</dt>
             <dd style="width: 20%;display: inline-block;margin: 0px;margin-left:-50px">@Html.DisplayFor(model => model.FirstOrDefault().labCashView.AGE)</dd>
             <dt style="width: 22%;display: inline-block;margin-left:60px;color:blue;">@Html.DisplayNameFor(model => model.labCashView.Report_Date)</dt>
             <dd style="width: 25%;display: inline-block;margin: 0px;margin-left:0px">@Html.DisplayFor(model => model.FirstOrDefault().labCashView.Report_Date)</dd>
             <dt style="width: 20%;display: inline-block;color:blue;">@Html.DisplayNameFor(model => model.labCashView.order_number)</dt>
             <dd style="width: 25%;display: inline-block;margin: 0px;margin-left:-50px">@Html.DisplayFor(model => model.FirstOrDefault().labCashView.order_number)</dd>
         </dl>

         <table id="menu" class="table table-bordered table-striped">
             <tr>

                 <td> test name    </td>
                 <td> result  </td>
                 <td> From Range   </td>
                 <td> To Range </td>
                 <td> Other Range    </td>
                 <td> Report Date  </td>

             </tr>
             <tbody>
             @foreach (var item in Model.Where(x => ids.Contains(x.labCashView.DEPTID.GetValueOrDefault())))
             {
                     <tr>

                         <td>@item.labCashView.Test_Name</td>
                         <td>@item.labCashView.Result</td>
                         <td>@item.labCashView.Low_Range</td>
                         <td>@item.labCashView.High_Range</td>
                         <td style="width:20%">@item.labCashView.Text_Range</td>
                         <td>@item.labCashView.Report_Date.Value.ToShortDateString()</td>

                     </tr>

             }
                 </tbody>

         </table>
         <hr />

     </div>
 </div>

}
</code>```

And second table :

```<code>     @if (Model.First().labCashView.DEPTID == 6)
 {   <div class="tab-content">
         <div class="tab-pane container fade p-0" style="margin-left:15px">
             <hr />

                 <dl class="horizontal" style="border:solid">
                     <dt style="width: 20%;display: inline-block;color:blue;">@Html.DisplayNameFor(model => model.labCashView.Patient_Name)</dt>
                     <dd style="width: 25%;display: inline-block;margin: 0px;margin-left:-50px">@Html.DisplayFor(model => model.FirstOrDefault().labCashView.Patient_Name)</dd>
                     <dt style="width: 22%;display: inline-block;color:blue;">@Html.DisplayNameFor(model => model.labCashView.Customer_Name)</dt>
                     <dd style="width: 25%;display: inline-block;margin: 0px;margin-left:0px">@Html.DisplayFor(model => model.FirstOrDefault().labCashView.Customer_Name)</dd>
                     <dt style="width: 20%;display: inline-block;color:blue;">@Html.DisplayNameFor(model => model.labCashView.Patient_No)</dt>
                     <dd style="width: 25%;display: inline-block;margin: 0px;margin-left:-50px">@Html.DisplayFor(model => model.FirstOrDefault().labCashView.Patient_No)</dd>
                     <dt style="width: 22%;display: inline-block;margin-left:0px;color:blue;">@Html.DisplayNameFor(model => model.labCashView.Collection_Date)</dt>
                     <dd style="width: 25%;display: inline-block;margin: 0px;margin-left:0px">@Html.DisplayFor(model => model.FirstOrDefault().labCashView.Collection_Date)</dd>
                     <dt style="width: 20%;display: inline-block;color:blue;">@Html.DisplayNameFor(model => model.labCashView.SEX)</dt>
                     <dd style="width: 20%;display: inline-block;margin: 0px;margin-left:-50px">@Html.DisplayFor(model => model.FirstOrDefault().labCashView.SEX)</dd>
                     <dt style="width: 22%;display: inline-block;margin-left:60px;color:blue;">@Html.DisplayNameFor(model => model.labCashView.Receiving_Date)</dt>
                     <dd style="width: 25%;display: inline-block;margin: 0px;margin-left:0px">@Html.DisplayFor(model => model.FirstOrDefault().labCashView.Receiving_Date)</dd>
                     <dt style="width: 20%;display: inline-block;color:blue;">@Html.DisplayNameFor(model => model.labCashView.AGE)</dt>
                     <dd style="width: 20%;display: inline-block;margin: 0px;margin-left:-50px">@Html.DisplayFor(model => model.FirstOrDefault().labCashView.AGE)</dd>
                     <dt style="width: 22%;display: inline-block;margin-left:60px;color:blue;">@Html.DisplayNameFor(model => model.labCashView.Report_Date)</dt>
                     <dd style="width: 25%;display: inline-block;margin: 0px;margin-left:0px">@Html.DisplayFor(model => model.FirstOrDefault().labCashView.Report_Date)</dd>
                     <dt style="width: 20%;display: inline-block;color:blue;">@Html.DisplayNameFor(model => model.labCashView.order_number)</dt>
                     <dd style="width: 25%;display: inline-block;margin: 0px;margin-left:-50px">@Html.DisplayFor(model => model.FirstOrDefault().labCashView.order_number)</dd>
                 </dl>

             <table id="menu1" class="table table-bordered table-striped">
                 <tr>

                     <td> test name    </td>
                     <td> result  </td>
                     <td> From Range   </td>
                     <td> To Range </td>
                     <td> Other Range    </td>
                     <td> Report Date  </td>

                 </tr>
                 <tbody>
                     @foreach (var item in Model.Where(x => x.labCashView.DEPTID == 6))
                     {
                         <tr>

                             <td>@item.labCashView.TEXT</td>
                             <td>@item.labCashView.TEST_RESULT</td>
                             <td>@item.labCashView.UNIT</td>
                             <td>@item.labCashView.Text_Range</td>
                             <td>@item.labCashView.Report_Date.Value.ToShortDateString()</td>

                         </tr>
                     }
                 </tbody>

             </table>
             <hr />

         </div>
    </div>

 }
</code>```

when run the view in browser its appear one header and one table second header and second foreach not appeared  :

First table appeared correct like the image :

How to separate 2 tables and show each header and data in view each in one page ?

答:
1- Create the class :

```<code>public class TablesModel
    {
        public IEnumerable<Model1> model1 { get; set; }

        public IEnumerable<Model2> model2 { get; set; }
    }
</code>```

2- create the controller if you want to make relation with id use .Where()and to use relation with another table you can use .Include():

```<code>public ActionResult Index()
        {
            var tables = new TablesModel
            {
                model1 =db.Model1.ToList(),
                model2 =db.Model2.ToList(),

            };
            return View(tables);
</code>```

3- create empty view for controller and use like the following code :

```<code><div class="tab-content">

        <h5 class="text-uppercase p-2 text-center">model list</h5>
        <table class="table table-bordered table-striped">
            <thead class="thead-dark text-white">
                <tr>
                    <th>@Html.DisplayNameFor(m => Model.model1.FirstOrDefault().Name)</th>
                    <th>@Html.DisplayNameFor(m => Model.model1.FirstOrDefault().Age)</th>

                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model.model1 )
                {
                    <tr>
                        <td>@item.Name</td>
                        <td>@item.Age</td>

                    </tr>
                }
            </tbody>
        </table>
    </div>

<div class="tab-content">

        <h5 class="text-uppercase p-2 text-center">model list</h5>
        <table class="table table-bordered table-striped">
            <thead class="thead-dark text-white">
                <tr>
                    <th>@Html.DisplayNameFor(m => Model.model2.FirstOrDefault().Address)</th>
                    <th>@Html.DisplayNameFor(m => Model.model2.FirstOrDefault().Mobile)</th>

                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model.model2 )
                {
                    <tr>
                        <td>@item.Address</td>
                        <td>@item.Mobile</td>

                    </tr>
                }
            </tbody>
        </table>
    </div>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to create multiple tables from one module in mvc view , I created 2 header and 2 foreach  but when i run the view its not seperated and second set of columns header not appeared only one set of header columns at the beginning of view , How to seperate the view and show multiple tables include header and columns ?

This is my View code :

@model IEnumerable<AljawdahNewSite.Models.Orders_Tables>
@{
    ViewBag.Title = "Details1";
    Layout = "~/Views/Shared/_LayoutPatients.cshtml";
    var ids = new List<int>() { 1, 2, 3, 4 };
}

Then this is first table :

@if (ids.Contains(Model.First().labCashView.DEPTID.GetValueOrDefault()))
{

@Html.DisplayNameFor(model => model.labCashView.Patient_Name)

@Html.DisplayFor(model => model.FirstOrDefault().labCashView.Patient_Name)

@Html.DisplayNameFor(model => model.labCashView.Customer_Name)

@Html.DisplayFor(model => model.FirstOrDefault().labCashView.Customer_Name)

@Html.DisplayNameFor(model => model.labCashView.Patient_No)

@Html.DisplayFor(model => model.FirstOrDefault().labCashView.Patient_No)

@Html.DisplayNameFor(model => model.labCashView.Collection_Date)

@Html.DisplayFor(model => model.FirstOrDefault().labCashView.Collection_Date)

@Html.DisplayNameFor(model => model.labCashView.SEX)

@Html.DisplayFor(model => model.FirstOrDefault().labCashView.SEX)

@Html.DisplayNameFor(model => model.labCashView.Receiving_Date)

@Html.DisplayFor(model => model.FirstOrDefault().labCashView.Receiving_Date)

@Html.DisplayNameFor(model => model.labCashView.AGE)

@Html.DisplayFor(model => model.FirstOrDefault().labCashView.AGE)

@Html.DisplayNameFor(model => model.labCashView.Report_Date)

@Html.DisplayFor(model => model.FirstOrDefault().labCashView.Report_Date)

@Html.DisplayNameFor(model => model.labCashView.order_number)

@Html.DisplayFor(model => model.FirstOrDefault().labCashView.order_number)

                  test name
                  result
                  From Range
                  To Range
                  Other Range
                  Report Date

             @foreach (var item in Model.Where(x => ids.Contains(x.labCashView.DEPTID.GetValueOrDefault())))
             {

                         @item.labCashView.Test_Name
                         @item.labCashView.Result
                         @item.labCashView.Low_Range
                         @item.labCashView.High_Range
                         @item.labCashView.Text_Range
                         @item.labCashView.Report_Date.Value.ToShortDateString()

             }

}

And second table :

     @if (Model.First().labCashView.DEPTID == 6)
 {

@Html.DisplayNameFor(model => model.labCashView.Patient_Name)

@Html.DisplayFor(model => model.FirstOrDefault().labCashView.Patient_Name)

@Html.DisplayNameFor(model => model.labCashView.Customer_Name)

@Html.DisplayFor(model => model.FirstOrDefault().labCashView.Customer_Name)

@Html.DisplayNameFor(model => model.labCashView.Patient_No)

@Html.DisplayFor(model => model.FirstOrDefault().labCashView.Patient_No)

@Html.DisplayNameFor(model => model.labCashView.Collection_Date)

@Html.DisplayFor(model => model.FirstOrDefault().labCashView.Collection_Date)

@Html.DisplayNameFor(model => model.labCashView.SEX)

@Html.DisplayFor(model => model.FirstOrDefault().labCashView.SEX)

@Html.DisplayNameFor(model => model.labCashView.Receiving_Date)

@Html.DisplayFor(model => model.FirstOrDefault().labCashView.Receiving_Date)

@Html.DisplayNameFor(model => model.labCashView.AGE)

@Html.DisplayFor(model => model.FirstOrDefault().labCashView.AGE)

@Html.DisplayNameFor(model => model.labCashView.Report_Date)

@Html.DisplayFor(model => model.FirstOrDefault().labCashView.Report_Date)

@Html.DisplayNameFor(model => model.labCashView.order_number)

@Html.DisplayFor(model => model.FirstOrDefault().labCashView.order_number)

                      test name
                      result
                      From Range
                      To Range
                      Other Range
                      Report Date

                     @foreach (var item in Model.Where(x => x.labCashView.DEPTID == 6))
                     {

                             @item.labCashView.TEXT
                             @item.labCashView.TEST_RESULT
                             @item.labCashView.UNIT
                             @item.labCashView.Text_Range
                             @item.labCashView.Report_Date.Value.ToShortDateString()

                     }

 }

when run the view in browser its appear one header and one table second header and second foreach not appeared  :

First table appeared correct like the image :

How to separate 2 tables and show each header and data in view each in one page ?

Body:
1- Create the class :

public class TablesModel
    {
        public IEnumerable<Model1> model1 { get; set; }

        public IEnumerable<Model2> model2 { get; set; }
    }

2- create the controller if you want to make relation with id use .Where()and to use relation with another table you can use .Include():

public ActionResult Index()
        {
            var tables = new TablesModel
            {
                model1 =db.Model1.ToList(),
                model2 =db.Model2.ToList(),

            };
            return View(tables);

3- create empty view for controller and use like the following code :

<div class="tab-content">

        <h5 class="text-uppercase p-2 text-center">model list</h5>
        <table class="table table-bordered table-striped">
            <thead class="thead-dark text-white">
                <tr>
                    <th>@Html.DisplayNameFor(m => Model.model1.FirstOrDefault().Name)</th>
                    <th>@Html.DisplayNameFor(m => Model.model1.FirstOrDefault().Age)</th>

                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model.model1 )
                {
                    <tr>
                        <td>@item.Name</td>
                        <td>@item.Age</td>

                    </tr>
                }
            </tbody>
        </table>
    </div>

<div class="tab-content">

        <h5 class="text-uppercase p-2 text-center">model list</h5>
        <table class="table table-bordered table-striped">
            <thead class="thead-dark text-white">
                <tr>
                    <th>@Html.DisplayNameFor(m => Model.model2.FirstOrDefault().Address)</th>
                    <th>@Html.DisplayNameFor(m => Model.model2.FirstOrDefault().Mobile)</th>

                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model.model2 )
                {
                    <tr>
                        <td>@item.Address</td>
                        <td>@item.Mobile</td>

                    </tr>
                }
            </tbody>
        </table>
    </div>


问:
How to get NSDate day, month and year in integer format?
I want to get the day, month and year components of NSDate in integer form i.e. if the date is 1/2/1988 then I should get 1, 2 and 1988 separately as an integer. How can I do this in iOS? I found the similar question but the method descriptionWithCalendarFormat: gives a warning and seems to be deprecated by now.

答:
Here you are,

```<code>NSDate *currentDate = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:currentDate]; // Get necessary date components

 [components month]; //gives you month
 [components day]; //gives you day
 [components year]; // gives you year
</code>```

You can use NSDateComponents for that as above.

Please visit this page for details.

ContentLicense: CC BY-SA 3.0

Body:
Here you are,

NSDate *currentDate = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:currentDate]; // Get necessary date components

 [components month]; //gives you month
 [components day]; //gives you day
 [components year]; // gives you year

You can use NSDateComponents for that as above.

Please visit this page for details.


问:
Do conditions have to be wrapped in individual {} when used with $or or $and in MongoDB?
Will this:

```<code>db.restaurants.find( {borough: "Bronx", $or: [ {cuisine: "American"}, {cuisine: "Chinese"}  ] } )
</code>```

and this:

```<code>db.restaurants.find( {borough: "Bronx", $or: [ {cuisine: "American", cuisine: "Chinese"}]} )
</code>```

be considered same?

Does individual bracketing matter in $or or $and?

答:
You can't do this :

```<code>{ cuisine: "American", cuisine: "Chinese" }
</code>```

It's not a limitation by MongoDB, even in programming languages it's mostly the same thing. Think of it this way, we're actually providing objects to MongoDB queries. So if you attempt to create an object like above - it would always pick cuisine: "Chinese" cause it's the second one with same key cuisine. That means an object ideally won't hold two keys with same name(same reason why arrays do exists - multiple items/objects in an array can hold same key name). Eventually you'll end-up with :

```<code>{cuisine: "American"}, {cuisine: "Chinese"} // two objects
</code>```

But in MongoDB, you might not need to use $or & $and - if working on same key name :

$or to $in :

```<code>{ cuisine: { $in : ["American", "Chinese"] } } // or operation
</code>```

$and to $all :

```<code>{ cuisine: { $all : ["American", "Chinese"] } } // and operation
</code>```

Test : mongoplayground

Body:
Will this:

db.restaurants.find( {borough: "Bronx", $or: [ {cuisine: "American"}, {cuisine: "Chinese"}  ] } )

and this:

db.restaurants.find( {borough: "Bronx", $or: [ {cuisine: "American", cuisine: "Chinese"}]} )

be considered same?

Does individual bracketing matter in $or or $and?

Body:
You can't do this :

{ cuisine: "American", cuisine: "Chinese" }

It's not a limitation by MongoDB, even in programming languages it's mostly the same thing. Think of it this way, we're actually providing objects to MongoDB queries. So if you attempt to create an object like above - it would always pick cuisine: "Chinese" cause it's the second one with same key cuisine. That means an object ideally won't hold two keys with same name(same reason why arrays do exists - multiple items/objects in an array can hold same key name). Eventually you'll end-up with :

{cuisine: "American"}, {cuisine: "Chinese"} // two objects

But in MongoDB, you might not need to use $or & $and - if working on same key name :

$or to $in :

{ cuisine: { $in : ["American", "Chinese"] } } // or operation

$and to $all :

{ cuisine: { $all : ["American", "Chinese"] } } // and operation

Test : mongoplayground


问:
Refer AWS Account number inside IAM policy
For the sake of the automation, I want my IAM policies to be generic.

I am aware that ${aws:username} fetches username of the policy to whom it is applied to.

Is it possible to do the same for AWS Account number arn:aws:iam::1234567890:user/${aws:username} with something like this  arn:aws:iam::${aws:accountnumber}:user/${aws:username} inside an IAM policy.

Edited:
Allowed variables are listed in the document linked below.
https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_variables.html

答:
The best way to get account number that I found is via STS. Here's Java code that I use to get the account number that works with credentials from AssumeRole as well,</p>

```<code>String awsRegion = Regions.US_EAST_1;
AWSCredentials cred = new BasicAWSCredentials("access_key_id", "secret_key_id");
// AWSCredentials cred = BasicSessionCredentials(sessionCredentials.getAccessKeyId(),sessionCredentials.getSecretAccessKey(), sessionCredentials.getSessionToken());

AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder.standard()
        .withCredentials(new AWSStaticCredentialsProvider(cred))
        .withRegion(awsRegion)
        .build();
String awsAccountNumber = stsClient.getCallerIdentity(new GetCallerIdentityRequest())
        .getAccount();
</code>```

Body:
The best way to get account number that I found is via STS. Here's Java code that I use to get the account number that works with credentials from AssumeRole as well,

String awsRegion = Regions.US_EAST_1;
AWSCredentials cred = new BasicAWSCredentials("access_key_id", "secret_key_id");
// AWSCredentials cred = BasicSessionCredentials(sessionCredentials.getAccessKeyId(),sessionCredentials.getSecretAccessKey(), sessionCredentials.getSessionToken());

AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder.standard()
        .withCredentials(new AWSStaticCredentialsProvider(cred))
        .withRegion(awsRegion)
        .build();
String awsAccountNumber = stsClient.getCallerIdentity(new GetCallerIdentityRequest())
        .getAccount();


问:
Highcharts instance created in which Angular life cycle hook
I am currently using Angular 7+ with Highcharts API.

I integrated Highcharts using the following Official Github Link.

There is a callbackFunction in Highcharts which we can use to get the chart instance .
However, i am yet to figure out 2 things:

When does the actual instance of chart gets created along with the options, like in which lifecycle hook in Angular? Or is it independent of the lifecycle hooks.

I saw a developer's example in which he used the callbackFunction while inside the ngOnInit lifecycle hook and it worked ( i.e we got a chart instance from the callback ). However the same did not work for ngOnChanges hook.

So my point was that, suppose there is an @Input property related to graph data which is to be rendered by the Highcharts.chart ( like say appending a new series ), then i would have to use ngOnChanges method in order to detect changes in input property and ngOnChanges would be called before ngOnInit as per this . How would i get the chart instance then ? and how would i do an addSeries then ?

Why does addSeries work only on button click and not in ngOnInit ? Uncomment line number 59 inside hello.component.ts to see it.

Link to the code.

Please see hello.component.ts for any details.

答:
Demo
Here you just need to update chartoptions
If you want update data

```<code>ngOnChanges(){
    console.log(this.newData);
    this.chartOptions.series[0]=this.newData;
  }
</code>```

If you want add new series

```<code>ngOnChanges(){
    console.log('Inside ngOnchanges');
    this.chartOptions.series.push(this.newData)
  }
</code>```

Highchart is created after you set chartoptions of Highchart

You can define callback ngOnchange or ngOnInit.In both it works. But you missed that your this.chartCreated.addSeries(this.newData) is not working there because it is async function so outside of callback you may not define chartCreated. If you put this code in callback function you will see that it will add new series. Your first series created with  chartoptions.

It works with onclick because before click your callback has already defined your chartCreated That is why click works.

As a final you don't need to create extra variable ,you can use chartoptions to update or add new series.

Body:
Demo
Here you just need to update chartoptions
If you want update data

ngOnChanges(){
    console.log(this.newData);
    this.chartOptions.series[0]=this.newData;
  }

If you want add new series

ngOnChanges(){
    console.log('Inside ngOnchanges');
    this.chartOptions.series.push(this.newData)
  }

Highchart is created after you set chartoptions of Highchart

You can define callback ngOnchange or ngOnInit.In both it works. But you missed that your this.chartCreated.addSeries(this.newData) is not working there because it is async function so outside of callback you may not define chartCreated. If you put this code in callback function you will see that it will add new series. Your first series created with  chartoptions.

It works with onclick because before click your callback has already defined your chartCreated That is why click works.

As a final you don't need to create extra variable ,you can use chartoptions to update or add new series.


问:
Fetch id of clicked element using .live()
As per suggestions i changed my code to below

```<code><dl id="accRegion">
<#list command.instruments as instrType>
<dt ><a class="red">${instrType}</a></dt>
<dd >
    <#list command.logDates as logDate>
        <div id="${instrType}"><a class="orange">${logDate}</a></dt>
    </#list>
</dd>
</#list>
</code>```

but it still gets me the id of first element instead of the clicked one. Also, this dl is an accordion.

Here is the generated html fragment

```<code><dl id="accRegion">
<dt ><a class="red">Stocks</a></dt>
<dd >
        <div id="Stocks"><a class="orange">2011-05-31</a></dt>
</dd>
<dt ><a class="red">Futures</a></dt>

<dd >
        <div id="Futures"><a class="orange">2011-05-31</a></dt>
</dd>
</code>```

Trying below method

```<code>    $("#accRegion div").live('click',function(){
    alert($(this).attr("id"));
});
</code>```

答:
Try this:</p>

```<code>$("#accRegion dd dt").live('click',function(e){
    alert($(e.currentTarget).attr("id"));
});
</code>```

Body:
As per suggestions i changed my code to below

<#list command.instruments as instrType>

${instrType}

    <#list command.logDates as logDate>

${logDate}

    </#list>

</#list>

but it still gets me the id of first element instead of the clicked one. Also, this dl is an accordion.

Here is the generated html fragment

Stocks

2011-05-31

Futures

2011-05-31

Trying below method

    $("#accRegion div").live('click',function(){
    alert($(this).attr("id"));
});

Body:
Try this:

$("#accRegion dd dt").live('click',function(e){
    alert($(e.currentTarget).attr("id"));
});


问:
ActiveRecord create: pass in an array of attributes
I would like to know if there is a Rails way to create multiple records by passing in an array of attributes.

For instance, instead of

```<code>MyModel.create!(attr_1: some_attr, attr_2: 1)
MyModel.create!(attr_1: some_attr, attr_2: 2)
MyModel.create!(attr_1: some_attr, attr_2: 3)
MyModel.create!(attr_1: some_attr, attr_2: 4)
</code>```

I would like to do something like:

```<code>MyModel.create!(attr_1: some_attr, attr_2: [1,2,3,4])
</code>```

But it does not work. Is there a similar way to achieve this without looping?

答:
At the time the question was asked ActiveRecord did not have any built-in features to efficiently insert multiple records at once. As of today Rails 6 is the current stable release and it comes with Model#insert_all! which is a method for bulk inserting.

You'll find the documentation for it here https://edgeapi.rubyonrails.org/classes/ActiveRecord/Persistence/ClassMethods.html#method-i-insert_all-21

It is worth to mention that Rails 6 also implements Model#upsert_all! which efficiently inserts or updates in case the the record exists.

Body:
I would like to know if there is a Rails way to create multiple records by passing in an array of attributes.

For instance, instead of

MyModel.create!(attr_1: some_attr, attr_2: 1)
MyModel.create!(attr_1: some_attr, attr_2: 2)
MyModel.create!(attr_1: some_attr, attr_2: 3)
MyModel.create!(attr_1: some_attr, attr_2: 4)

I would like to do something like:

MyModel.create!(attr_1: some_attr, attr_2: [1,2,3,4])

But it does not work. Is there a similar way to achieve this without looping?


问:
NaNs produced in qtukey output
The following code is not generating output for few values of n. Getting the following message: "In stats::qtukey(p = 0.5, nmeans = n, df = Inf) : NaNs produced."

Any possible fix?

```<code>min_Ptukey <- function(par, nmeans){
  abs(.5 - stats::ptukey(q = par, nmeans = nmeans, df = Inf))
}

d <- function(n) {
if (n  < 100) {
  stats::qtukey(p = .5, nmeans = n, df = Inf)
}else{
  stats::optimise(f = min_Ptukey, interval = c(1,20), nmeans=n)$minimum
}
}

const<-data.frame(rep(NULL,2))
for(n in 2:75)
{
const<-rbind(const,c(n,d(n)))
}
colnames(const) <- c("n","d")
print(const,digits=18)
</code>```

答:
As highlighted in the comments by @akrun and @ben-bolker the qtukey algorithm is breaking down and producing the NaNs you're seeing.  Need to change one of the three parameters you're feeding it.

any of these three will work

qtukey(p=0.506, nmeans=37, df=Inf)
qtukey(p=0.50, nmeans=36, df=Inf)
qtukey(p=0.50, nmeans=37, df=2:280)
```

there may be another implemetation but note that the doco for qtukey says qtukey will be accurate to the 4th decimal place.

Title: NaNs produced in qtukey output

Body:
The following code is not generating output for few values of n. Getting the following message: "In stats::qtukey(p = 0.5, nmeans = n, df = Inf) : NaNs produced."

Any possible fix?

min_Ptukey <- function(par, nmeans){
  abs(.5 - stats::ptukey(q = par, nmeans = nmeans, df = Inf))
}

d <- function(n) {
if (n  < 100) {
  stats::qtukey(p = .5, nmeans = n, df = Inf)
}else{
  stats::optimise(f = min_Ptukey, interval = c(1,20), nmeans=n)$minimum
}
}

const<-data.frame(rep(NULL,2))
for(n in 2:75)
{
const<-rbind(const,c(n,d(n)))
}
colnames(const) <- c("n","d")
print(const,digits=18)

Body:
As highlighted in the comments by @akrun and @ben-bolker the qtukey algorithm is breaking down and producing the NaNs you're seeing.  Need to change one of the three parameters you're feeding it.

any of these three will work

qtukey(p=0.506, nmeans=37, df=Inf)
qtukey(p=0.50, nmeans=36, df=Inf)
qtukey(p=0.50, nmeans=37, df=2:280)

there may be another implemetation but note that the doco for qtukey says qtukey will be accurate to the 4th decimal place.


问:
Makefile: Rule dependent on directory of target
I am trying to create a Makefile to create object files in a directory based on the source file. For example I have DirA/file.c and DirB/file.c and I want to create a recipe for creating DirA/file.o and DirB/file.o.

```<code>rootdir/
|-- Makefile
|-- DirA
|    |-- source.c
|    +-- source.o
+-- DirB
    |-- file.c
    +-- file.o
</code>```

I would assume the recipe would be similar to the following:

```<code>MAKEFLAGS += --no-builtin-rules
DirA_Files=$(wildcard DirA/*.c)
DirB_Files=$(wildcard DirB/*.c)

.PHONY: all a_files b_files
all: a_files b_files
    @echo Done with all!
    @echo built $(patsubst %.c,%.o,$(DirA_Files)) $(patsubst %.c,%.o,$(DirB_Files))

a_files: $(patsubst %.c,%.o,$(DirA_Files))
b_files: $(patsubst %.c,%.o,$(DirB_Files))

DirA/%.o DirB/%.o : DirA/%.c DirB/%.c
    # Complex recipe that I'd rather not state twice in the Makefile
    @echo "Building $@ because $? changed"
    @touch $@
</code>```

But I do not want the object files in DirA to be dependent on the source files of DirB, which is what the above recipe implies.

I have also tried

```<code>DirA/%.o : DirA/%.c
DirB/%.o : DirB/%.c
DirA/%.o DirB/%.o :
    # Complex recipe that I'd rather not state twice in the Makefile
    @echo "Building $@ because $? changed"
    @touch $@
</code>```

But then the $? variable is always blank.

How could I create a single recipe that would also allow me to build a_files and b_files independently

答:
You can't combine pattern rules quite that easily. But this situation is what defined recipes were made for:</p>

```<code>define complex-rule
# Complex recipe that I'd rather not state twice in the Makefile
@echo "Building $@ because $? changed"
@touch $@
endef

DirA/%.o : DirA/%.c
        $(complex-rule)

DirB/%.o : DirB/%.c
        $(complex-rule)
</code>```

Body:
I am trying to create a Makefile to create object files in a directory based on the source file. For example I have DirA/file.c and DirB/file.c and I want to create a recipe for creating DirA/file.o and DirB/file.o.

rootdir/
|-- Makefile
|-- DirA
|    |-- source.c
|    +-- source.o
+-- DirB
    |-- file.c
    +-- file.o

I would assume the recipe would be similar to the following:

MAKEFLAGS += --no-builtin-rules
DirA_Files=$(wildcard DirA/*.c)
DirB_Files=$(wildcard DirB/*.c)

.PHONY: all a_files b_files
all: a_files b_files
    @echo Done with all!
    @echo built $(patsubst %.c,%.o,$(DirA_Files)) $(patsubst %.c,%.o,$(DirB_Files))

a_files: $(patsubst %.c,%.o,$(DirA_Files))
b_files: $(patsubst %.c,%.o,$(DirB_Files))

DirA/%.o DirB/%.o : DirA/%.c DirB/%.c
    # Complex recipe that I'd rather not state twice in the Makefile
    @echo "Building $@ because $? changed"
    @touch $@

But I do not want the object files in DirA to be dependent on the source files of DirB, which is what the above recipe implies.

I have also tried

DirA/%.o : DirA/%.c
DirB/%.o : DirB/%.c
DirA/%.o DirB/%.o :
    # Complex recipe that I'd rather not state twice in the Makefile
    @echo "Building $@ because $? changed"
    @touch $@

But then the $? variable is always blank.

How could I create a single recipe that would also allow me to build a_files and b_files independently

Body:
You can't combine pattern rules quite that easily. But this situation is what defined recipes were made for:

define complex-rule
# Complex recipe that I'd rather not state twice in the Makefile
@echo "Building $@ because $? changed"
@touch $@
endef

DirA/%.o : DirA/%.c
        $(complex-rule)

DirB/%.o : DirB/%.c
        $(complex-rule)


问:
VSCode: Turn auto scrolling permanently ON
In Visual Studio Code, is there any way to force the auto-scrolling option of the Output panel permanently enabled?
At the moment I have to click on the lock button every time I build my project to disable the scroll lock or better to say enable the auto-scrolling feature and this is so annoying.

I took a look at the settings but couldn't find any relevant parameter there.

Any ideas?

答:
An option to turn off the smart scroll feature was included in one of the recent updates (probably in the March 2020 update, I didn't find it in the changelog), see more: issue #69480

Since then, I've been able to "save" the scroll state, try this:

Go to File > Preferences > Settings (or Ctrl + ,)

In Features > Output, disable Smart Scroll option (or search output.smartScroll.enabled)

Tested with VSCode version 1.45.1 and CodeRunner 0.10.0


问:
Mac OS replace multiline with one character using sed
I hope this is not duplicate, I read some questions, but I am still struggling to achieve this.

Let say i have this text:

```<code>{
  "root": {
    "2020-05": []
  }
}
{
  "root2": {
    "result": "error",
    "message": "You can't access this resource as it requires 'view' access for the website id = 206."
  }
}
</code>```

How would I get the following result:

```<code>{
  "root": {
    "2020-05": []
  },
  "root2": {
    "result": "error",
    "message": "You can't access this resource as it requires 'view' access for the website id = 206."
  }
}
</code>```

I need to replace

```<code>{
}
</code>```

with just this

```<code>,
</code>```

Or better I need to replace this

```<code>  }
}
{
</code>```

with just this:

```<code>  },
</code>```

What is the best way to achieve this using sed?

I am not sure about the regex part, I tried this /^{}$/ and this $}^${^.

Thanks

答:
With jq, it's just

```<code>jq -s add tmp.json
</code>```

The -s option reads both objects in the stream into a single array, then the add filter combines the two objects into one.

A demonstration:

```<code>$ jq -s add <<EOF
> {
>   "root": {
>     "2020-05": []
>   }
> }
> {
>   "root2": {
>     "result": "error",
>     "message": "You can't access this resource as it requires 'view' access for the website id = 206."
>   }
> }
> EOF
{
  "root": {
    "2020-05": []
  },
  "root2": {
    "result": "error",
    "message": "You can't access this resource as it requires 'view' access for the website id = 206."
  }
}
</code>```

Body:
I hope this is not duplicate, I read some questions, but I am still struggling to achieve this.

Let say i have this text:

{
  "root": {
    "2020-05": []
  }
}
{
  "root2": {
    "result": "error",
    "message": "You can't access this resource as it requires 'view' access for the website id = 206."
  }
}

How would I get the following result:

{
  "root": {
    "2020-05": []
  },
  "root2": {
    "result": "error",
    "message": "You can't access this resource as it requires 'view' access for the website id = 206."
  }
}

I need to replace

{
}

with just this

,

Or better I need to replace this

  }
}
{

with just this:

  },

What is the best way to achieve this using sed?

I am not sure about the regex part, I tried this /^{}$/ and this $}^${^.

Thanks

Body:
With jq, it's just

jq -s add tmp.json

The -s option reads both objects in the stream into a single array, then the add filter combines the two objects into one.

A demonstration:

$ jq -s add <<EOF
> {
>   "root": {
>     "2020-05": []
>   }
> }
> {
>   "root2": {
>     "result": "error",
>     "message": "You can't access this resource as it requires 'view' access for the website id = 206."
>   }
> }
> EOF
{
  "root": {
    "2020-05": []
  },
  "root2": {
    "result": "error",
    "message": "You can't access this resource as it requires 'view' access for the website id = 206."
  }
}


问:
ZSH: Run shell script from nodejs w/child process exec > command not found (beginner)
I am trying to run a script from node w/exec and I get /bin/sh: require_brew: command not found in the terminal.
The goal is to run through a list of packages in node and then install them via a shell script.
The command I am trying to run looks like this util/sh/requirers.sh && require_brew fzf.

When I run only the command in the terminal it returns zsh: command not found.
I am not sure what do in order to make it run.

答:
The solution was to add a single period . before the script like so:
. util/sh/requirers.sh && require_brew


问:
How do you request device connection string in azure using python and iotHub library?
I am wondering how can you get device connection string from IotHub using python in azure? any ideas? the device object produced by IoTHubRegisterManager.Create_device_with_sas(...) doesn't seem to contain the property connection string.</p>

答:
You can get a device connection string from the device registry. However, it is not recommended that you do that on a device. The reason being is that you will need the IoT hub connection string to authenticate with your hub so that you can read the device registry. If your device is doing that and it is compromised then the perpetrator now has your IoT hub connection string and could cause all kinds of mayhem. You should specifically provide each device instance with its connection string.
Alternatively, you could research the Azure DPS service which will provide you with device authentication details in a secure manner.</p>


问:
ASP.NET AJAX Toolkit - CalendarExtender is reset on Postback
I have an ASP.NET page that has two input elements:

A TextBox that is ReadOnly. This TextBox is the TargetControl of a CalendarExtender

A DropDownList with AutoPostBack=true

Here is the code:

```<code><table border="0" cellpadding="0" cellspacing="0">
  <tr><td colspan="2">Date:</td></tr>
  <tr><td colspan="2">
    <asp:TextBox ID="dateTextBox" runat="server" ReadOnly="true" />
    <ajax:CalendarExtender ID="datePicker" runat="server" Format="MM/dd/yyyy" OnLoad="datePicker_Load" TargetControlID="dateTextBox" />
  </td></tr>

  <tr><td colspan="2">Select an Option:</td></tr>
  <tr>
    <td>Name: </td>
    <td><asp:DropDownList ID="optionsDropDownList" runat="server" AutoPostBack="true"
      OnLoad="optionsDropDownList_Load"
      OnSelectedIndexChanged="optionsDropDownList_SelectedIndexChanged"
      DataTextField="Name" DataValueField="ID" />
  </td></tr>

  <tr><td><asp:Button ID="saveButton" runat="server" Text="Save" OnClick="saveButton_Click" /></td></tr>
</table>
</code>```

When the DropDownList posts back, the date selected by the user with the datePicker is reset to the current date. In addition, if I look at the Text property of dateTextBox, it is equal to string.Empty.

How do I preserve the date that the user selected on a PostBack?

答:
```<code>protected void Page_Load(object sender, EventArgs e)
{
    txt_sdate.Text = Request[txt_sdate.UniqueID];
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have an ASP.NET page that has two input elements:

A TextBox that is ReadOnly. This TextBox is the TargetControl of a CalendarExtender

A DropDownList with AutoPostBack=true

Here is the code:

Date:

    <asp:TextBox ID="dateTextBox" runat="server" ReadOnly="true" />
    <ajax:CalendarExtender ID="datePicker" runat="server" Format="MM/dd/yyyy" OnLoad="datePicker_Load" TargetControlID="dateTextBox" />

Select an Option:

    Name:
    <asp:DropDownList ID="optionsDropDownList" runat="server" AutoPostBack="true"
      OnLoad="optionsDropDownList_Load"
      OnSelectedIndexChanged="optionsDropDownList_SelectedIndexChanged"
      DataTextField="Name" DataValueField="ID" />

<asp:Button ID="saveButton" runat="server" Text="Save" OnClick="saveButton_Click" />

When the DropDownList posts back, the date selected by the user with the datePicker is reset to the current date. In addition, if I look at the Text property of dateTextBox, it is equal to string.Empty.

How do I preserve the date that the user selected on a PostBack?


问:
Questions regarding efficiency
So while working through a course on Udemy over C++ one of the challenges was to check a string to see whether it was a palindrome or not. I completed the task successfully but went about it a different way than the instructor. I understand there are a multitude of ways to complete a task but I am wondering which is more efficient and why? It may seem stupid to be wondering about this while reteaching myself coding but I feel this is something I should be keeping in mind.

```<code>//Instructors code//

# include<iostream>
using namespace std;

/*program for reverse a string and check a string is a palidrome

*/
int main()
{
    string str="MADAM";
    string rev="";
    int len=(int)str.length();
    rev.resize(len);
    for(int i=0, j=len-1; i<len; i++, j--)
    {
        rev[i]=str[j];
    }
    rev[len]='\0';
    if(str.compare(rev)==0)
        cout<<"palindrome"<<endl;
    else
        cout<<"not a pallindrome"<<endl;
    return 0;
}
</code>```

My Approach

```<code>#include <iostream>
using namespace std;

int main(){
    string str1="test";
//    cout << "Enter a string to check if it is a Palindrome: ";
//    getline(cin,str1);

    string str2;

    string::reverse_iterator it;
    for(it=str1.rbegin(); it!= str1.rend(); it++)
    {
        str2.push_back(*it);

    }
    if(!str1.compare(str2))
        cout << "\nPalindrome";
    else
        cout << "\nNot a Palindrome";
    return 0;
}
</code>```

Thank you in advance.

答:
The simplest and most efficient way (no copying required) would be something like this:</p>

```<code>inline bool is_palindrome(const std::string& u) {
    return std::equal(u.begin(), std::next(u.begin(), u.length() / 2), u.rbegin());
}
</code>```

Title: Questions regarding efficiency

Body:
So while working through a course on Udemy over C++ one of the challenges was to check a string to see whether it was a palindrome or not. I completed the task successfully but went about it a different way than the instructor. I understand there are a multitude of ways to complete a task but I am wondering which is more efficient and why? It may seem stupid to be wondering about this while reteaching myself coding but I feel this is something I should be keeping in mind.

//Instructors code//

# include<iostream>
using namespace std;

/*program for reverse a string and check a string is a palidrome

*/
int main()
{
    string str="MADAM";
    string rev="";
    int len=(int)str.length();
    rev.resize(len);
    for(int i=0, j=len-1; i<len; i++, j--)
    {
        rev[i]=str[j];
    }
    rev[len]='\0';
    if(str.compare(rev)==0)
        cout<<"palindrome"<<endl;
    else
        cout<<"not a pallindrome"<<endl;
    return 0;
}

My Approach

#include <iostream>
using namespace std;

int main(){
    string str1="test";
//    cout << "Enter a string to check if it is a Palindrome: ";
//    getline(cin,str1);

    string str2;

    string::reverse_iterator it;
    for(it=str1.rbegin(); it!= str1.rend(); it++)
    {
        str2.push_back(*it);

    }
    if(!str1.compare(str2))
        cout << "\nPalindrome";
    else
        cout << "\nNot a Palindrome";
    return 0;
}

Thank you in advance.

Body:
The simplest and most efficient way (no copying required) would be something like this:

inline bool is_palindrome(const std::string& u) {
    return std::equal(u.begin(), std::next(u.begin(), u.length() / 2), u.rbegin());
}


问:
How to configure SWD pins using registers in STM32?
Info: I create Blink using registers in STM32. This works, except that after the firmware the SWD connector stops working for me. The reason most likely is that the SWD is on the same port along with the LED. When configuring the port and the LED pin, I probably reset the SWD settings.

Code:

```<code>#include "main.h"

void SystemClock_Config(void);

int main(void)
{
  HAL_Init();
  SystemClock_Config();

  __HAL_RCC_GPIOA_CLK_ENABLE();
  // Set PA8 to OUTPUT mode
  GPIOA->MODER = 0x00010000;
  // Set PUSH-PULL mode
  GPIOA->OTYPER = 0x00000000;
  // Set pin speed
  GPIOA->OSPEEDR = 0x64010000;
  // Set not pull
  GPIOA->PUPDR = 0x64000000;
  // Set pin bit
  GPIOA->BSRR = 0x00000100;

  static int pin_state = 0;

  while (1)
  {
      // LED blink
      if(pin_state == 0) {
        // Bit set
        GPIOA->BSRR = 0x00000100;
        pin_state = 1;
      } else {
        // Bit clear
        GPIOA->BSRR = 0x01000000;
        pin_state = 0;
      }

      HAL_Delay(3000);

  }
}

void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the CPU, AHB and APB busses clocks
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  /** Initializes the CPU, AHB and APB busses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
  {
    Error_Handler();
  }
}

void Error_Handler(void) {}

#ifdef  USE_FULL_ASSERT
void assert_failed(char *file, uint32_t line) {}
#endif
</code>```

In the STM32F334K8Tx datasheet, I did not find much information about setting registers for SWD contacts (which mode, setting the clock, pull-up, and more).

Question: how can this be done? Or where can I find information?

答:
How to avoid such problems

Firstly, I agree to the other answers in that you really should use some kind of function or macro to perform elementary register operations that you'll need quite often (like setting up GPIO pins). Then your code is just less prone to fairly simple programming mistakes such as in the question sample code.

What is needed

The actual problem about the sample code is that it doesn't only modify certain bits of the registers (e.g., to enable the LED pin as an output), but instead the entire GPIO bank register, which controls another 15 or 7 pins (plus the LED pin the program really wanted to address).

In STM32 (like in any ARM), virtually all register and memory locations are addressed as 32-bit variables.
Most port registers control more than a single resource (or more than a single aspect about a resource, resp.).
Instead, a bunch of similar resources (or parameters) are collected in a 32-bit register.

In order to modify a part of a register while retaining the contents of the other parts, the controller software must

read out the entire port register value (32 bit) into a CPU register (or RAM),

manipulate this register, usually by ANDing/ORing bits or groups of bits ("masks") out of it/into it,

write back the entire CPU register value (with its modifications) into the port register.

How to do this

If you take functions like the sample of @P__J__,

```<code>#define BITMASK(nbits)   ((1 << nbits) - 1)

void GPIO_SetMode(GPIO_TypeDef *gpio, unsigned pin, unsigned mode)
{
    gpio -> MODER &= ~(BITMASK(2) << (2 * pin));
    gpio -> MODER |= ((mode & BITMASK(2)) << (2 * pin));
}
</code>```

the compiler will translate the &= into some assembler instructions that perform steps (1.)-(3.) - and afterwards the |= in the same way.

The sample of @YvonBlais,

```<code>// Set PA8 to OUTPUT mode
GPIOA->MODER |= GPIO_MODER_MODER8_1; // Ref.: 9.4.1
</code>```

does the same (with less generality!) for a single register and modification.
It doesn't contain the &= part because it doesn't care to reset the target bits first but uses (with less generality...) the initialisation state of the MCU.

Both propositions should work in your case with more or less elegance/simplicity.

How not to do this / what actually happened to your controller

In contrast, the bug in the original sample is

```<code>// Set PA8 to OUTPUT mode
GPIOA->MODER = 0x00010000;
</code>```

This assigns the desired '01' pattern to bits [16:17] of the register (configuring pin 8 to output - see the
reference manual,
sec. 9.4.1).
However, at the same time it assigns '00' to [0:1], [2:3], ..., [14:15], [18:19], ..., and [30:31], which configures all other PAxy pins to Input mode.
As you can verify in the
datasheet,
(Table 14 / page 42), this also affects pins PA13/PA14, which used to be in Alternate Function (AF0) mode to support the SWD interface.

How to flash the corrected program

There is one way to overide the (erroneous) software settings in order to flash another binary:
The SWD adapter must pull the reset pin of the controller before/while it does the SWD programming.

All SWD programming tools allow this, but usually one must select the correct tool configuration ("Connect under reset" or similar) for this to work.

Body:
Info: I create Blink using registers in STM32. This works, except that after the firmware the SWD connector stops working for me. The reason most likely is that the SWD is on the same port along with the LED. When configuring the port and the LED pin, I probably reset the SWD settings.

Code:

#include "main.h"

void SystemClock_Config(void);

int main(void)
{
  HAL_Init();
  SystemClock_Config();

  __HAL_RCC_GPIOA_CLK_ENABLE();
  // Set PA8 to OUTPUT mode
  GPIOA->MODER = 0x00010000;
  // Set PUSH-PULL mode
  GPIOA->OTYPER = 0x00000000;
  // Set pin speed
  GPIOA->OSPEEDR = 0x64010000;
  // Set not pull
  GPIOA->PUPDR = 0x64000000;
  // Set pin bit
  GPIOA->BSRR = 0x00000100;

  static int pin_state = 0;

  while (1)
  {
      // LED blink
      if(pin_state == 0) {
        // Bit set
        GPIOA->BSRR = 0x00000100;
        pin_state = 1;
      } else {
        // Bit clear
        GPIOA->BSRR = 0x01000000;
        pin_state = 0;
      }

      HAL_Delay(3000);

  }
}

void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the CPU, AHB and APB busses clocks
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  /** Initializes the CPU, AHB and APB busses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
  {
    Error_Handler();
  }
}

void Error_Handler(void) {}

#ifdef  USE_FULL_ASSERT
void assert_failed(char *file, uint32_t line) {}
#endif

In the STM32F334K8Tx datasheet, I did not find much information about setting registers for SWD contacts (which mode, setting the clock, pull-up, and more).

Question: how can this be done? Or where can I find information?

Body:
How to avoid such problems

Firstly, I agree to the other answers in that you really should use some kind of function or macro to perform elementary register operations that you'll need quite often (like setting up GPIO pins). Then your code is just less prone to fairly simple programming mistakes such as in the question sample code.

What is needed

The actual problem about the sample code is that it doesn't only modify certain bits of the registers (e.g., to enable the LED pin as an output), but instead the entire GPIO bank register, which controls another 15 or 7 pins (plus the LED pin the program really wanted to address).

In STM32 (like in any ARM), virtually all register and memory locations are addressed as 32-bit variables.
Most port registers control more than a single resource (or more than a single aspect about a resource, resp.).
Instead, a bunch of similar resources (or parameters) are collected in a 32-bit register.

In order to modify a part of a register while retaining the contents of the other parts, the controller software must

read out the entire port register value (32 bit) into a CPU register (or RAM),

manipulate this register, usually by ANDing/ORing bits or groups of bits ("masks") out of it/into it,

write back the entire CPU register value (with its modifications) into the port register.

How to do this

If you take functions like the sample of @P__J__,

#define BITMASK(nbits)   ((1 << nbits) - 1)

void GPIO_SetMode(GPIO_TypeDef *gpio, unsigned pin, unsigned mode)
{
    gpio -> MODER &= ~(BITMASK(2) << (2 * pin));
    gpio -> MODER |= ((mode & BITMASK(2)) << (2 * pin));
}

the compiler will translate the &= into some assembler instructions that perform steps (1.)-(3.) - and afterwards the |= in the same way.

The sample of @YvonBlais,

// Set PA8 to OUTPUT mode
GPIOA->MODER |= GPIO_MODER_MODER8_1; // Ref.: 9.4.1

does the same (with less generality!) for a single register and modification.
It doesn't contain the &= part because it doesn't care to reset the target bits first but uses (with less generality...) the initialisation state of the MCU.

Both propositions should work in your case with more or less elegance/simplicity.

How not to do this / what actually happened to your controller

In contrast, the bug in the original sample is

// Set PA8 to OUTPUT mode
GPIOA->MODER = 0x00010000;

This assigns the desired '01' pattern to bits [16:17] of the register (configuring pin 8 to output - see the
reference manual,
sec. 9.4.1).
However, at the same time it assigns '00' to [0:1], [2:3], ..., [14:15], [18:19], ..., and [30:31], which configures all other PAxy pins to Input mode.
As you can verify in the
datasheet,
(Table 14 / page 42), this also affects pins PA13/PA14, which used to be in Alternate Function (AF0) mode to support the SWD interface.

How to flash the corrected program

There is one way to overide the (erroneous) software settings in order to flash another binary:
The SWD adapter must pull the reset pin of the controller before/while it does the SWD programming.

All SWD programming tools allow this, but usually one must select the correct tool configuration ("Connect under reset" or similar) for this to work.


问:
Share post to LinkedIn using Custom URL and specify image
I am able to successfully share a post to LinkedIn using their Custom URL API:

https://developer.linkedin.com/docs/share-on-linkedin

I can specify title, summary etc. but not an image. LinkedIn automatically grabs the image via an og:image tag from the linked page.

og:images are normally above 200x200 pixels, but LinkedIn is cropping (not resizing) the image to about 180 x 110.

Wordpress generally uses a 512x512 site icon, which a lot of plugins now pickup and add by default as the og:image icon. (ie. JetPack)

How to get around this issue without adding a very small [non-square] og:image to my site/pages?

答:
To set the preview screen for LinkedIn sharing, set your og: tags...

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

Source: LinkedIn Developer Docs: Making Your Website Shareable on LinkedIn.

Here's an example where it works for me:


问:
What is the difference between min-content and max-content in a CSS Grid row?
While I can see a difference between min-content and max-content values for the column size, when the text breaks with min-content and stretches as much as possible with max-content values, I don't see that effect in a row. Either the row size is defined with min-content or max-content, it seems not to take any effect. Is there any other practical use of min-content and max-content for the rows in a grid layout?

ul{
  list-style-type: none;
  width: 400px;
  height: 200px;
  padding: 0;
  display: grid;
  grid-gap: 5px;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: min-content max-content;
  box-shadow: 2px 2px 6px grey;
}

li:nth-child(1){
  background-color: #b9e2ff;
}

li:nth-child(2){
  background-color: #ffa733;
}

li:nth-child(3){
  background-color: #8b33ff;
}

li:nth-child(4){
  background-color: #ff3333;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>hello world hello world hello world hello world</li>
  <li>hello</li>
  <li>hello</li>
  <li>hello world hello world hello world hello world</li>
</ul></code>```

答:
You won't really see a difference since in most of the case, the width is first defined based on the text then the height will get computed later.

You may see a difference if you have a vertical text where the logic is inverted:

ul{
  list-style-type: none;
  width: 400px;
  height: 200px;
  padding: 0;
  display: grid;
  grid-gap: 5px;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: min-content max-content;
  box-shadow: 2px 2px 6px grey;
}
li {
    writing-mode: vertical-lr;
}
li:nth-child(1){
  background-color: #b9e2ff;
}

li:nth-child(2){
  background-color: #ffa733;
}

li:nth-child(3){
  background-color: #8b33ff;
}

li:nth-child(4){
  background-color: #ff3333;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>hello world hello world hello world hello world</li>
  <li>hello</li>
  <li>hello</li>
  <li>hello world hello world hello world hello world</li>
</ul></code>```

Body:
While I can see a difference between min-content and max-content values for the column size, when the text breaks with min-content and stretches as much as possible with max-content values, I don't see that effect in a row. Either the row size is defined with min-content or max-content, it seems not to take any effect. Is there any other practical use of min-content and max-content for the rows in a grid layout?

ul{
  list-style-type: none;
  width: 400px;
  height: 200px;
  padding: 0;
  display: grid;
  grid-gap: 5px;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: min-content max-content;
  box-shadow: 2px 2px 6px grey;
}

li:nth-child(1){
  background-color: #b9e2ff;
}

li:nth-child(2){
  background-color: #ffa733;
}

li:nth-child(3){
  background-color: #8b33ff;
}

li:nth-child(4){
  background-color: #ff3333;
}

hello world hello world hello world hello world

hello

hello

hello world hello world hello world hello world

Body:
You won't really see a difference since in most of the case, the width is first defined based on the text then the height will get computed later.

You may see a difference if you have a vertical text where the logic is inverted:

ul{
  list-style-type: none;
  width: 400px;
  height: 200px;
  padding: 0;
  display: grid;
  grid-gap: 5px;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: min-content max-content;
  box-shadow: 2px 2px 6px grey;
}
li {
    writing-mode: vertical-lr;
}
li:nth-child(1){
  background-color: #b9e2ff;
}

li:nth-child(2){
  background-color: #ffa733;
}

li:nth-child(3){
  background-color: #8b33ff;
}

li:nth-child(4){
  background-color: #ff3333;
}

<ul>
  <li>hello world hello world hello world hello world</li>
  <li>hello</li>
  <li>hello</li>
  <li>hello world hello world hello world hello world</li>
</ul>


问:
How to remove check constraint?
I am having difficult to remove CHECK using Alter in sql. Can anyone help me please?</p>

```<code>CREATE TABLE MyProject_COST (
    ID int(4) NOT NULL UNIQUE,
    detail varchar2(25) NOT NULL,
    cost int(6) CONSTRAINT cost_project CHECK(cost>=500)
);

ALTER TABLE MyProject_COST ALTER COLUMN Cost int(6)
</code>```

答:
Oracle does have an alter table ... drop constraint syntax for this.

But since you created an anonymous constraint, so this is tricky - because you don't know the name of the constraint.

One option is to use dynamic SQL to retrieve the constraint name, and drop it with an execute immediate command:

```<code>declare
    c_name varchar2(255 char);
begin

    select c.constraint_name into c_name
    from all_constraints c
    join all_cons_columns cc
        on  cc.table_name = c.table_name
        and cc.constraint_name = c.constraint_name
    where
        cc.table_name = 'MYPROJECT_COST'
        and cc.column_name ='COST'
        and c.constraint_type = 'C' ;

    if c_name is not null then
        execute immediate
            'alter table myproject_cost drop constraint "' || c_name || '"';
    end if;
end;
/
</code>```

Demo on DB Fiddle:

```<code>create table myproject_cost (
        id int not null unique,
        detail varchar2(25) not null,
        cost int check(cost >= 500)
    );

insert into MyProject_COST(id, detail, cost) values(1, 'foo', 0);
-- ORA-02290: check constraint (FIDDLE_XUVVCZVSYWWROHKPBFUF.SYS_C0030623) violated

declare
    c_name varchar2(255 char);
begin

    select c.constraint_name into c_name
    from all_constraints c
    join all_cons_columns cc
        on  cc.table_name = c.table_name
        and cc.constraint_name = c.constraint_name
    where
        cc.table_name = 'MYPROJECT_COST'
        and cc.column_name ='COST'
        and c.constraint_type = 'C' ;

    if c_name is not null then
        execute immediate
            'alter table myproject_cost drop constraint "' || c_name || '"';
    end if;
end;
/
-- 1 rows affected

insert into MyProject_COST(id, detail, cost) values(1, 'foo', 0);
-- 1 rows affected
</code>```

Title: How to remove check constraint?

Body:
I am having difficult to remove CHECK using Alter in sql. Can anyone help me please?

CREATE TABLE MyProject_COST (
    ID int(4) NOT NULL UNIQUE,
    detail varchar2(25) NOT NULL,
    cost int(6) CONSTRAINT cost_project CHECK(cost>=500)
);

ALTER TABLE MyProject_COST ALTER COLUMN Cost int(6)

Body:
Oracle does have an alter table ... drop constraint syntax for this.

But since you created an anonymous constraint, so this is tricky - because you don't know the name of the constraint.

One option is to use dynamic SQL to retrieve the constraint name, and drop it with an execute immediate command:

declare
    c_name varchar2(255 char);
begin

    select c.constraint_name into c_name
    from all_constraints c
    join all_cons_columns cc
        on  cc.table_name = c.table_name
        and cc.constraint_name = c.constraint_name
    where
        cc.table_name = 'MYPROJECT_COST'
        and cc.column_name ='COST'
        and c.constraint_type = 'C' ;

    if c_name is not null then
        execute immediate
            'alter table myproject_cost drop constraint "' || c_name || '"';
    end if;
end;
/

Demo on DB Fiddle:

create table myproject_cost (
        id int not null unique,
        detail varchar2(25) not null,
        cost int check(cost >= 500)
    );

insert into MyProject_COST(id, detail, cost) values(1, 'foo', 0);
-- ORA-02290: check constraint (FIDDLE_XUVVCZVSYWWROHKPBFUF.SYS_C0030623) violated

declare
    c_name varchar2(255 char);
begin

    select c.constraint_name into c_name
    from all_constraints c
    join all_cons_columns cc
        on  cc.table_name = c.table_name
        and cc.constraint_name = c.constraint_name
    where
        cc.table_name = 'MYPROJECT_COST'
        and cc.column_name ='COST'
        and c.constraint_type = 'C' ;

    if c_name is not null then
        execute immediate
            'alter table myproject_cost drop constraint "' || c_name || '"';
    end if;
end;
/
-- 1 rows affected

insert into MyProject_COST(id, detail, cost) values(1, 'foo', 0);
-- 1 rows affected


问:
accessing sqlite file in android
I have a sqlite file. I want to use it in my application.
Can anyone share proper example as how I can do that.

I was not sure if .sqlite file can be used so I have also made .db file.

答:
Please check below

http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

http://www.screaming-penguin.com/node/7742

http://www.higherpass.com/Android/Tutorials/Accessing-Data-With-Android-Cursors/

Title: accessing sqlite file in android


问:
How to update a clicked element using useState
kinda new to React and I am looking to use useState but only to be applied to the clicked element. For example:

```<code>const [backgroundColor, setBackgroundColor] = useState({background: "green"});
</code>```

in my function I have something like this:

```<code>function updateBackground(){
let updateColor = {background: "blue"};
setBackgroundColor(updateColor);
}
</code>```

then in my return JSX code I have

```<code>{subButtons.map(function(subButton, index){
   return (<div key={index} onClick={updateBackground} style={backgroundColor}>{subButton}</div>)
 })}
</code>```

but this will apply this function to all generated elements of the .map method.

How can I update my code to be applied to the clicked only element?

Thank you.

答:
You are attempting to manage the discrete state of multiple children in the parent.  @Denis Stukalov answered the question by suggesting keeping a corresponding array of state per child. This can work, but I find that it rarely scales well in the real world.

I would suggest keeping track of the state inside the button itself.

const BackgroundButton = (props) => {
  const [backgroundColor, setBackgroundColor] = React.useState({background: 'green'});
  const updateBackground = () => setBackgroundColor({background: 'blue'});
  return

};

const App = () => ['button1', 'button2', 'button3'].map(
  (subButton, index) => (
    <BackgroundButton key={index}>{subButton}</BackgroundButton>
  )
);
```

See this in action in this CodePen.

Body:
kinda new to React and I am looking to use useState but only to be applied to the clicked element. For example:

const [backgroundColor, setBackgroundColor] = useState({background: "green"});

in my function I have something like this:

function updateBackground(){
let updateColor = {background: "blue"};
setBackgroundColor(updateColor);
}

then in my return JSX code I have

{subButtons.map(function(subButton, index){
   return (
{subButton}
)
 })}

but this will apply this function to all generated elements of the .map method.

How can I update my code to be applied to the clicked only element?

Thank you.

Body:
You are attempting to manage the discrete state of multiple children in the parent.  @Denis Stukalov answered the question by suggesting keeping a corresponding array of state per child. This can work, but I find that it rarely scales well in the real world.

I would suggest keeping track of the state inside the button itself.

const BackgroundButton = (props) => {
  const [backgroundColor, setBackgroundColor] = React.useState({background: 'green'});
  const updateBackground = () => setBackgroundColor({background: 'blue'});
  return <div onClick={updateBackground} style={backgroundColor} {...props} />
};

const App = () => ['button1', 'button2', 'button3'].map(
  (subButton, index) => (
    <BackgroundButton key={index}>{subButton}</BackgroundButton>
  )
);

See this in action in this CodePen.


问:
undefined is not an object (evaluating 'Context._context') - React Native
I am trying to wrap one of my navigators with User Context that I created. I have achieved this before in other projects but I am encountering an issue. I Tried following this solution but it doesn't seem to be the same issue I am encountering. I can't exactly tell what is wrong here.

App.js Code :

```<code>import React, { useContext, useEffect } from "react";
import { View, Text, AsyncStorage, Button } from "react-native";
import { createStackNavigator } from "@react-navigation/stack";
import HomeScreen from "./src/screens/HomeScreen";
import LoginScreen from "./src/screens/login";
import CalendarScreen from "./src/screens/Calendar";
import SignUpScreen from "./src/screens/signUp";
import { scale, vs } from "react-native-size-matters";
import { createDrawerNavigator } from "@react-navigation/drawer";
import { createMaterialBottomTabNavigator } from "@react-navigation/material-bottom-tabs";
import { Icon } from "react-native-elements";
import UserContext, { UserProvider } from "./src/screens/Context/UserContext";
import { NavigationContainer } from "@react-navigation/native";

const Tab = createMaterialBottomTabNavigator();
const Stack = createStackNavigator();
const Drawer = createDrawerNavigator();

const signedIn = true; //this is for testing
const drawer_style = {
  backgroundColor: "#202B35",
  activeTintColor: "#000",

  width: 200,
};

const drawer_item_style = {
  activeTintColor: "orange",
  inactiveTintColor: "#fff",

  itemStyle: { marginVertical: vs(10) },
};

const non_user_stack = () => {
  <Stack.Navigator>
    <Stack.Screen
      name="Sign in - Cal "
      component={LoginScreen}
      options={({ navigation }) => ({
        headerShown: true,
        headerTintColor: "orange",

        headerStyle: {
          backgroundColor: "#202B35",
        },
      })}
    />

    <Stack.Screen
      name="Sign up - Cal "
      component={SignUpScreen}
      options={({ navigation }) => ({
        headerShown: true,
        headerTintColor: "orange",

        headerStyle: {
          backgroundColor: "#202B35",
        },
      })}
    />
  </Stack.Navigator>;
};

const UserMenu = () => {
  return (
    <NavigationContainer>
      <Drawer.Navigator
        initialRouteName="Home"
        drawerStyle={drawer_style}
        drawerContentOptions={drawer_item_style}
        drawerType="front"
      >
        <Drawer.Screen name="Home" component={MyStack} />
      </Drawer.Navigator>
    </NavigationContainer>
  );
};
const MyStack = () => {

  return(

    <Stack.Navigator>
      <Stack.Screen
        name="Cal"
        component={BottomNav}
        options={({ navigation }) => ({
          headerShown: true,
          headerTintColor: "orange",

          headerStyle: {
            backgroundColor: "#202B35",
          },
          headerLeft: (props) => (
            <Icon
              size={25}
              name={"ios-menu"}
              iconStyle={{
                fontSize: scale(30),
                color: "orange",
                margin: 5,
                marginLeft: 10,
              }}
              type="ionicon"
              color="orange"
              onPress={() => {
                navigation.toggleDrawer();
              }}
            />
          ),
        })}
      />
    </Stack.Navigator>
  )
};

export default App = () => {

  const { isSignedIn, check_and_set_signin_status } = useContext(UserContext); //<-- causes crash

  return (
      isSignedIn === "false" ? (
       <UserProvider>
         <UserMenu />
       </UserProvider>
    ) : (
      <non_user_stack></non_user_stack>
    );
  );

};
</code>```

UserContext.js :

```<code>import React, { useState, useEffect } from "react";
import * as Permissions from "expo-permissions";
import axios from "axios";
import { AsyncStorage } from "react-native";
//import registerForPushNotificationsAsync from "../Hooks/registerForPushNotifications";
import Constants from "expo-constants";

const UserContext = React.createContext();

const IS_SIGNEDIN = "is_signed_in";

export const UserProvider = ({ children }) => {
  const [isSignedIn, setSignIn] = useState(null);
  const [didAuthenticate, setAuthenticated] = useState(null);

  //Check if this user already signed in before and didnt log out since their last session
  //used for conditional rendering
  const check_and_set_signin_status = async () => {
    const signed_in = await AsyncStorage.getItem(IS_SIGNEDIN);

    if (signed_in == null || signed_in == "false") {
      await AsyncStorage.setItem(IS_SIGNEDIN, "false");
      setSignIn("false");
    } else {
      setSignIn("true");
    }

  };

  return (
    <UserContext.Provider
      value={{
        isSignedIn, // well use this for conditional rendering

        check_and_set_signin_status,
      }}
    >
      {children}
    </UserContext.Provider>
  );
};
</code>```

The Error :

答:
there is some mistake in your code

you are not exporting UserContext but you are importing UserContext
in App.js file

you are trying to use useContext and provider in same file but you
have to useContext inside of Provider child component

you are non_user_stack with first letter capital but you have to
make first letter capital

UserContext.js : you have to export UserContext in this file

```<code>import React, { useState, useEffect } from "react";
import { Text } from 'react-native'
import * as Permissions from "expo-permissions";
import axios from "axios";
import { AsyncStorage } from "react-native";
//import registerForPushNotificationsAsync from "../Hooks/registerForPushNotifications";
import Constants from "expo-constants";

const UserContext = React.createContext();
export default UserContext;
const IS_SIGNEDIN = "is_signed_in";

export const UserProvider = ({ children }) => {
  const [isSignedIn, setSignIn] = useState(null);
  const [didAuthenticate, setAuthenticated] = useState(null);
  const check_and_set_signin_status = async () => {
    const signed_in = await AsyncStorage.getItem(IS_SIGNEDIN);

    if (signed_in == null || signed_in == "false") {
      await AsyncStorage.setItem(IS_SIGNEDIN, "false");
      setSignIn("false");
    } else {
      setSignIn("true");
    }

  };

  return (
    <UserContext.Provider
      value={{
        isSignedIn, // well use this for conditional rendering

        check_and_set_signin_status,
      }}
    >
      {children}
    </UserContext.Provider>
  );
};
</code>```

App.js Code :

```<code>const App = () => {
 const { isSignedIn, check_and_set_signin_status } = useContext(UserContext); //<-- causes crash
  console.log( isSignedIn, check_and_set_signin_status ,"useContext")
  return isSignedIn === "false" ? (
    <UserMenu />
  ) : (
    <Non_user_stack></Non_user_stack>
  );
};

const jsx = () => (
  <UserProvider>
    <App />
  </UserProvider>
);

export default jsx;
</code>```

Body:
I am trying to wrap one of my navigators with User Context that I created. I have achieved this before in other projects but I am encountering an issue. I Tried following this solution but it doesn't seem to be the same issue I am encountering. I can't exactly tell what is wrong here.

App.js Code :

import React, { useContext, useEffect } from "react";
import { View, Text, AsyncStorage, Button } from "react-native";
import { createStackNavigator } from "@react-navigation/stack";
import HomeScreen from "./src/screens/HomeScreen";
import LoginScreen from "./src/screens/login";
import CalendarScreen from "./src/screens/Calendar";
import SignUpScreen from "./src/screens/signUp";
import { scale, vs } from "react-native-size-matters";
import { createDrawerNavigator } from "@react-navigation/drawer";
import { createMaterialBottomTabNavigator } from "@react-navigation/material-bottom-tabs";
import { Icon } from "react-native-elements";
import UserContext, { UserProvider } from "./src/screens/Context/UserContext";
import { NavigationContainer } from "@react-navigation/native";

const Tab = createMaterialBottomTabNavigator();
const Stack = createStackNavigator();
const Drawer = createDrawerNavigator();

const signedIn = true; //this is for testing
const drawer_style = {
  backgroundColor: "#202B35",
  activeTintColor: "#000",

  width: 200,
};

const drawer_item_style = {
  activeTintColor: "orange",
  inactiveTintColor: "#fff",

  itemStyle: { marginVertical: vs(10) },
};

const non_user_stack = () => {
  <Stack.Navigator>
    <Stack.Screen
      name="Sign in - Cal "
      component={LoginScreen}
      options={({ navigation }) => ({
        headerShown: true,
        headerTintColor: "orange",

        headerStyle: {
          backgroundColor: "#202B35",
        },
      })}
    />

    <Stack.Screen
      name="Sign up - Cal "
      component={SignUpScreen}
      options={({ navigation }) => ({
        headerShown: true,
        headerTintColor: "orange",

        headerStyle: {
          backgroundColor: "#202B35",
        },
      })}
    />
  </Stack.Navigator>;
};

const UserMenu = () => {
  return (
    <NavigationContainer>
      <Drawer.Navigator
        initialRouteName="Home"
        drawerStyle={drawer_style}
        drawerContentOptions={drawer_item_style}
        drawerType="front"
      >
        <Drawer.Screen name="Home" component={MyStack} />
      </Drawer.Navigator>
    </NavigationContainer>
  );
};
const MyStack = () => {

  return(

    <Stack.Navigator>
      <Stack.Screen
        name="Cal"
        component={BottomNav}
        options={({ navigation }) => ({
          headerShown: true,
          headerTintColor: "orange",

          headerStyle: {
            backgroundColor: "#202B35",
          },
          headerLeft: (props) => (
            <Icon
              size={25}
              name={"ios-menu"}
              iconStyle={{
                fontSize: scale(30),
                color: "orange",
                margin: 5,
                marginLeft: 10,
              }}
              type="ionicon"
              color="orange"
              onPress={() => {
                navigation.toggleDrawer();
              }}
            />
          ),
        })}
      />
    </Stack.Navigator>
  )
};

export default App = () => {

  const { isSignedIn, check_and_set_signin_status } = useContext(UserContext); //<-- causes crash

  return (
      isSignedIn === "false" ? (
       <UserProvider>
         <UserMenu />
       </UserProvider>
    ) : (
      <non_user_stack></non_user_stack>
    );
  );

};

UserContext.js :

import React, { useState, useEffect } from "react";
import * as Permissions from "expo-permissions";
import axios from "axios";
import { AsyncStorage } from "react-native";
//import registerForPushNotificationsAsync from "../Hooks/registerForPushNotifications";
import Constants from "expo-constants";

const UserContext = React.createContext();

const IS_SIGNEDIN = "is_signed_in";

export const UserProvider = ({ children }) => {
  const [isSignedIn, setSignIn] = useState(null);
  const [didAuthenticate, setAuthenticated] = useState(null);

  //Check if this user already signed in before and didnt log out since their last session
  //used for conditional rendering
  const check_and_set_signin_status = async () => {
    const signed_in = await AsyncStorage.getItem(IS_SIGNEDIN);

    if (signed_in == null || signed_in == "false") {
      await AsyncStorage.setItem(IS_SIGNEDIN, "false");
      setSignIn("false");
    } else {
      setSignIn("true");
    }

  };

  return (
    <UserContext.Provider
      value={{
        isSignedIn, // well use this for conditional rendering

        check_and_set_signin_status,
      }}
    >
      {children}
    </UserContext.Provider>
  );
};

The Error :

Body:
there is some mistake in your code

you are not exporting UserContext but you are importing UserContext
in App.js file

you are trying to use useContext and provider in same file but you
have to useContext inside of Provider child component

you are non_user_stack with first letter capital but you have to
make first letter capital

UserContext.js : you have to export UserContext in this file

import React, { useState, useEffect } from "react";
import { Text } from 'react-native'
import * as Permissions from "expo-permissions";
import axios from "axios";
import { AsyncStorage } from "react-native";
//import registerForPushNotificationsAsync from "../Hooks/registerForPushNotifications";
import Constants from "expo-constants";

const UserContext = React.createContext();
export default UserContext;
const IS_SIGNEDIN = "is_signed_in";

export const UserProvider = ({ children }) => {
  const [isSignedIn, setSignIn] = useState(null);
  const [didAuthenticate, setAuthenticated] = useState(null);
  const check_and_set_signin_status = async () => {
    const signed_in = await AsyncStorage.getItem(IS_SIGNEDIN);

    if (signed_in == null || signed_in == "false") {
      await AsyncStorage.setItem(IS_SIGNEDIN, "false");
      setSignIn("false");
    } else {
      setSignIn("true");
    }

  };

  return (
    <UserContext.Provider
      value={{
        isSignedIn, // well use this for conditional rendering

        check_and_set_signin_status,
      }}
    >
      {children}
    </UserContext.Provider>
  );
};

App.js Code :

const App = () => {
 const { isSignedIn, check_and_set_signin_status } = useContext(UserContext); //<-- causes crash
  console.log( isSignedIn, check_and_set_signin_status ,"useContext")
  return isSignedIn === "false" ? (
    <UserMenu />
  ) : (
    <Non_user_stack></Non_user_stack>
  );
};

const jsx = () => (
  <UserProvider>
    <App />
  </UserProvider>
);

export default jsx;


问:
Print whole HTML page including pdf file inside iframe
I've got an assignment to embed relatively small pdf file inside html page and print the entire html pade including the pdf file inside the iframe.
Here is the structure of my html page:

Here is my code:

@media print{
 body * {display:block;}
    .toPrint{display:block; border:0; width:100%; min-height:500px}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <button onclick="window.print()">Print</button>

 <h3>MUST BE PRINTED</h3>
    <p> MUST BE PRINTED</p>
    <iframe class="toPrint" src="https://nett.umich.edu/sites/default/files/docs/pdf_files_scan_create_reducefilesize.pdf" style="width:100%; height:97vh;"></iframe>
 <h3>MUST BE PRINTED</h3>
    <p> MUST BE PRINTED</p>
</body></code>```

Currently I'm printing the page using css @media query. But unfortunately this media query prints the pdf's first page only.

What can I do print the entire pdf file?

答:
Here is a simpler solution using javascript.

```<code><body>
        <h3 id='first_h3'>MUST BE PRINTED</h3>
        <p id ='first_paragraph'> MUST BE PRINTED</p>
        <div id="pdfRenderer"></div>
        <h3 id='second_h3'>MUST BE PRINTED</h3>
        <p id='second_paragraph'> MUST BE PRINTED</p>

<input type="submit" value="Print All"
  onclick="javascript:printPage()"
 />

</body>

<script>

 pages =[] // initiate an empty list here

function printPage() {

var first_h3 = document.getElementById('first_h3');
// get the first h3 tag and
// then push its innerHTML into the list
   pages.push(first_h3.innerHTML);

var first_paragraph = document.getElementById('first_paragraph');
// get the first paragraph and
// then push its innerHTML into the list
   pages.push(first_paragraph.innerHTML);

var pdfRenderer = document.getElementById('pdfRenderer');
// get the pdfRenderer and
// then push its innerHTML into the list
   pages.push(pdfRenderer.contentWindow.document.body.innerHTML);

var second_h3 = document.getElementById('second_h3');
// get the second h3 tag and
// then push its innerHTML into the list
   pages.push(second_h3.innerHTML);

var second_paragraph = document.getElementById('second_paragraph');
// get the second paragraph and
// then push its innerHTML into the list
   pages.push(second_paragraph.innerHTML);

if (pages && pages.length) {

// this if statement, just checks to ensure our list is not empty before running the code.

// here is the magic, we now set the parent window to be equal to all the concatenated innerHTML
window.content.document.body.innerHTML = pages;
// then we print this new window that contains all the different parts in the exact order we pushed them into the list.
window.print();
}
else {
// do nothing
}

}
</script>
</code>```

With this solution avoid the problem of the iframe being cut off if it exceeds one page. Secondly, you get only one print dialogue box even if you have multiple iframes.

Body:
I've got an assignment to embed relatively small pdf file inside html page and print the entire html pade including the pdf file inside the iframe.
Here is the structure of my html page:

Here is my code:

@media print{
 body * {display:block;}
    .toPrint{display:block; border:0; width:100%; min-height:500px}

    <button onclick="window.print()">Print</button>

MUST BE PRINTED

 MUST BE PRINTED

MUST BE PRINTED

 MUST BE PRINTED

Currently I'm printing the page using css @media query. But unfortunately this media query prints the pdf's first page only.

What can I do print the entire pdf file?

Body:
Here is a simpler solution using javascript.

<body>
        <h3 id='first_h3'>MUST BE PRINTED</h3>
        <p id ='first_paragraph'> MUST BE PRINTED</p>
        <div id="pdfRenderer"></div>
        <h3 id='second_h3'>MUST BE PRINTED</h3>
        <p id='second_paragraph'> MUST BE PRINTED</p>

<input type="submit" value="Print All"
  onclick="javascript:printPage()"
 />

</body>

<script>

 pages =[] // initiate an empty list here

function printPage() {

var first_h3 = document.getElementById('first_h3');
// get the first h3 tag and
// then push its innerHTML into the list
   pages.push(first_h3.innerHTML);

var first_paragraph = document.getElementById('first_paragraph');
// get the first paragraph and
// then push its innerHTML into the list
   pages.push(first_paragraph.innerHTML);

var pdfRenderer = document.getElementById('pdfRenderer');
// get the pdfRenderer and
// then push its innerHTML into the list
   pages.push(pdfRenderer.contentWindow.document.body.innerHTML);

var second_h3 = document.getElementById('second_h3');
// get the second h3 tag and
// then push its innerHTML into the list
   pages.push(second_h3.innerHTML);

var second_paragraph = document.getElementById('second_paragraph');
// get the second paragraph and
// then push its innerHTML into the list
   pages.push(second_paragraph.innerHTML);

if (pages && pages.length) {

// this if statement, just checks to ensure our list is not empty before running the code.

// here is the magic, we now set the parent window to be equal to all the concatenated innerHTML
window.content.document.body.innerHTML = pages;
// then we print this new window that contains all the different parts in the exact order we pushed them into the list.
window.print();
}
else {
// do nothing
}

}
</script>

With this solution avoid the problem of the iframe being cut off if it exceeds one page. Secondly, you get only one print dialogue box even if you have multiple iframes.