问:
Visual Studio 2022 error related to MKL, cant load Intel.Build.ICLTasks.v160.dll
My C# project works with Intel Math Kernal Library when using Visual studio 2019.
I just installed VS 2022 and tried to build the project using old toolset (v142).

It fails to build with this error:

```<code>Severity    Code    Description Project File    Line    Suppression State
Error   MSB4062 The "ICMessage" task could not be loaded from the assembly C:\Program Files %28x86%29\Microsoft Visual Studio\2019\Professional\Msbuild\Microsoft\VC\v160\Intel.Build.ICLTasks.v160.dll. Could not load file or assembly 'file:///C:\Program Files %28x86%29\Microsoft Visual Studio\2019\Professional\Msbuild\Microsoft\VC\v160\Intel.Build.ICLTasks.v160.dll' or one of its dependencies. The system cannot find the file specified. Confirm that the <UsingTask> declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask.    StreamsProcessor    C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Msbuild\Microsoft\VC\v160\Platforms\x64\PlatformToolsets\v142\ImportAfter\Intel.Libs.MKL.v142.targets  37
</code>```

This is the file that defines to build with MKL.

```<code><Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <UsingTask TaskName="ICMessage" AssemblyFile="$(VCTargetsPath)Intel.Build.ICLTasks.v160.dll" Condition="'$(PlatformToolset)' == 'v142'"/>

<!--"Could not expand {0} variable. Corresponsing version of Intel(R) MKL is not installed or the registry information may be incorrect."-->
  <Target Name="CheckIntelEnvironmentForVCLibsMKL" BeforeTargets="ClCompile" Condition="'$(UseIntelMKL)' != '' AND '$(UseIntelMKL)' != 'No' AND '$(UseEnv)' != 'true' AND '$(PlatformToolset)' == 'v142'">
    <ICMessage Code="WRN001" Type="Warning" Arguments="MKLProductDir;MKL"  Condition="'$(MKLProductDir)'==''" />
    <ICMessage Code="WRN001" Type="Warning" Arguments="MKLMajorVersion;MKL" Condition="'$(MKLMajorVersion)'==''" />
    <ICMessage Code="WRN001" Type="Warning" Arguments="MKLMinorVersion;MKL" Condition="'$(MKLMinorVersion)'==''" />
    <ICMessage Code="WRN001" Type="Warning" Arguments="MKLIncludeDir;MKL"  Condition="'$(MKLIncludeDir)'==''" />
    <ICMessage Code="WRN001" Type="Warning" Arguments="MKLLibDir;MKL" Condition="'$(MKLLibDir)'==''" />
    <ICMessage Code="WRN001" Type="Warning" Arguments="OmpLibDir;MKL" Condition="'$(OmpLibDir)'==''" />
  </Target>
</code>```

I checked the file is there Intel.Build.ICLTasks.v160.dll and seems like both versions search it on the same place but for some reason VS 2022 fails to find it.
Can you hint how to resolve this ?

答:
To fix this error I installed Intel C/C++ compilers
https://marketplace.visualstudio.com/items?itemName=intel-corporation.dpcpponline</p>

Body:
My C# project works with Intel Math Kernal Library when using Visual studio 2019.
I just installed VS 2022 and tried to build the project using old toolset (v142).

It fails to build with this error:

Severity    Code    Description Project File    Line    Suppression State
Error   MSB4062 The "ICMessage" task could not be loaded from the assembly C:\Program Files %28x86%29\Microsoft Visual Studio\2019\Professional\Msbuild\Microsoft\VC\v160\Intel.Build.ICLTasks.v160.dll. Could not load file or assembly 'file:///C:\Program Files %28x86%29\Microsoft Visual Studio\2019\Professional\Msbuild\Microsoft\VC\v160\Intel.Build.ICLTasks.v160.dll' or one of its dependencies. The system cannot find the file specified. Confirm that the <UsingTask> declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask.    StreamsProcessor    C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Msbuild\Microsoft\VC\v160\Platforms\x64\PlatformToolsets\v142\ImportAfter\Intel.Libs.MKL.v142.targets  37

This is the file that defines to build with MKL.

<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <UsingTask TaskName="ICMessage" AssemblyFile="$(VCTargetsPath)Intel.Build.ICLTasks.v160.dll" Condition="'$(PlatformToolset)' == 'v142'"/>

  <Target Name="CheckIntelEnvironmentForVCLibsMKL" BeforeTargets="ClCompile" Condition="'$(UseIntelMKL)' != '' AND '$(UseIntelMKL)' != 'No' AND '$(UseEnv)' != 'true' AND '$(PlatformToolset)' == 'v142'">
    <ICMessage Code="WRN001" Type="Warning" Arguments="MKLProductDir;MKL"  Condition="'$(MKLProductDir)'==''" />
    <ICMessage Code="WRN001" Type="Warning" Arguments="MKLMajorVersion;MKL" Condition="'$(MKLMajorVersion)'==''" />
    <ICMessage Code="WRN001" Type="Warning" Arguments="MKLMinorVersion;MKL" Condition="'$(MKLMinorVersion)'==''" />
    <ICMessage Code="WRN001" Type="Warning" Arguments="MKLIncludeDir;MKL"  Condition="'$(MKLIncludeDir)'==''" />
    <ICMessage Code="WRN001" Type="Warning" Arguments="MKLLibDir;MKL" Condition="'$(MKLLibDir)'==''" />
    <ICMessage Code="WRN001" Type="Warning" Arguments="OmpLibDir;MKL" Condition="'$(OmpLibDir)'==''" />
  </Target>

I checked the file is there Intel.Build.ICLTasks.v160.dll and seems like both versions search it on the same place but for some reason VS 2022 fails to find it.
Can you hint how to resolve this ?


来源: stackexchange

问:
How to remove empty partial view on submit ASP.NET
In my web application, I have more than 5 partial views in the main view.

So the partial views are controlled from the Drop down menu. With the value of the drop-down menu, I hide and show the related partial view on the main view.

The process is when I click the button it loads the partial view. If I want to add another record I can add it by clicking the Add New Record button. If I want to remove it I can delete the partial view.

The issue is If I add a new record and load the partial view and If I don't want it I removed the record, But when It submits the main form I return an error and that deleted partial view shows again.

Can I know how to delete it completely?

This is How I load the partial view in the Main view.

```<code><fieldset id="pnlGeneralItms" style="display:@(Model.GeneralItmsList == null || Model.GeneralItmsList.Count == 0? " none":"")">
  <legend>
    <h5>General Request Attachments / Bills</h5>
  </legend>
  <ul id="RequItms" style="list-style-type: none"> @if (Model != null && Model.GeneralItmsList != null) { foreach (Asp_PASMVC.Models.GeneralItms Itms in Model.GeneralItmsList) { Html.RenderPartial("_GeneralItms", Itms); } } </ul>
  <button type="button" id="addAnotherItm" class="btn btn-info" href="#">Add New Record</button>
  <script type="text/javascript">
    $(function() {
      $("#addAnotherItm").click(function() {
        $.get('/AppRequests/GeneralItmsPartialView', function(template) {
          $("#RequItms").append(template);
        });
      });
    });
  </script>
  <hr />
  <br />
</fieldset>
</code>```

This is the Partial View

```<code><li style="padding-bottom:15px"> @using (Html.BeginCollectionItem("GeneralItmsList")) { @Html.HiddenFor(model => model.TempID) @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="row">
    <div class="col-md-5 col-sm-6">
      <div class="form-group"> Type Line Description <div class="col-md-10"> @Html.EditorFor(model => model.Attachment_Description, new { htmlAttributes = new { @class = "form-control", placeholder = "Make it short" } }) @Html.ValidationMessageFor(model => model.Attachment_Description, "", new { @class = "text-danger" }) </div>
      </div>
    </div>
    <div class="col-md-3 col-sm-6">
      <div class="form-group"> Attachment Amount <div class="col-md-10">
          <div class="input-group-prepend">
            <span class="input-group-text">Rs.</span> @Html.EditorFor(model => model.Attachment_Amount, new { htmlAttributes = new { @class = "form-control" } })
          </div> @Html.ValidationMessageFor(model => model.Attachment_Amount, "", new { @class = "text-danger" })
        </div>
      </div>
    </div>
    <button type="button" class="btn btn-danger" onclick="$(this).parent().remove();">Remove</button>
  </div> } </li>

</code>```

This is how it shows. Even if I delete the highlighted record in submitting it returns the view with the deleted record.

Edited____

This is my controller

```<code>public ActionResult Create(AppRequest appRequest) {
    if (ModelState.IsValid) {
      if (appRequest.ApprovalPartyList?.ToString() != null) {

        if (appRequest.GeneralItmsList != null) {
          foreach(GeneralItms item in appRequest.GeneralItmsList) {
            HttpPostedFileBase file = Request.Files["ImageData" + item.TempID];
            item.Attachment = ConvertToBytes(file);
            item.FileType = Path.GetFileName(file.ContentType);
          }

          appRequest.General = new List < General > () {
            new General {

              GeneralItms = appRequest.GeneralItmsList,

            }
          };

        }

      }

      appRequest.Req_By = int.Parse(((System.Security.Claims.ClaimsIdentity) User.Identity).FindFirst("UserId").Value);
      appRequest.Company_Id = int.Parse((User.Identity as ClaimsIdentity).Claims.Where(c => c.Type == "CompanyID").FirstOrDefault().Value);
      appRequest.Create_By = int.Parse(((System.Security.Claims.ClaimsIdentity) User.Identity).FindFirst("UserId").Value);
      appRequest.Created_Date = DateTime.Now;
      appRequest.Modified_By = int.Parse(((System.Security.Claims.ClaimsIdentity) User.Identity).FindFirst("UserId").Value);
      appRequest.Modified_Date = DateTime.Now;
      appRequest.Status = true;
      try {
        db.AppRequest.Add(appRequest);
        db.SaveChanges();
      } catch (Exception ex) {

        TempData["msg"] = "error";
        return View(appRequest);
      }
</code>```

This is the Model

```<code>public class AppRequest {
  private zSqlDb db = new zSqlDb();

  [Key]
  public int Id {
    get;
    set;
  }

  [Required]
  [Display(Name = "Request Type")]
  public int ReqType {
    get;
    set;
  }

  [Required]
  [Display(Name = "Requesting By")]
  public int Req_By {
    get;
    set;
  }

  [Required]
  [Display(Name = "Requesting Date")]
  public DateTime Req_Date {
    get;
    set;
  } = DateTime.Now;

  [Required]
  [Display(Name = "Request Location")]
  public int Req_Location {
    get;
    set;
  }

  [Required]
  [Display(Name = "Request Heading")]
  public string Req_Heading {
    get;
    set;
  }

  [Display(Name = "Cover Note")]
  public string Req_CoverNote {
    get;
    set;
  }

  [Required]
  [Display(Name = "Company Name")]
  public int Company_Id {
    get;
    set;
  }
  public bool Status {
    get;
    set;
  }
  public int Create_By {
    get;
    set;
  }
  public DateTime Created_Date {
    get;
    set;
  } = DateTime.Now;
  public int Modified_By {
    get;
    set;
  }
  public DateTime Modified_Date {
    get;
    set;
  } = DateTime.Now;
  public int Approval_Status {
    get;
    set;
  }

  public virtual IList < General > General {
    get;
    set;
  }

  #region ILists

    //General
    [NotMapped]
  public IList < GeneralItms > GeneralItmsList {
    get;
    set;
  }

  #endregion

    [NotMapped]
  public int xSupp_Id {
    get;
    set;
  }

}

#region General
public class General {
  [Key]
  public int Id {
    get;
    set;
  }

  [Required]
  [ForeignKey("AppRequest")]
  public int Req_Id {
    get;
    set;
  }
  public virtual AppRequest AppRequest {
    get;
    set;
  }

  public string ApprovedNumber {
    get;
    set;
  }

  public bool IsSettled {
    get;
    set;
  }

  public virtual IList < GeneralItms > GeneralItms {
    get;
    set;
  }
}
public class GeneralItms {
  [Key]
  public int Id {
    get;
    set;
  }

  [Required]
  [ForeignKey("General")]

  public int General_Id {
    get;
    set;
  }

  public virtual General General {
    get;
    set;
  }
  public byte[] Attachment {
    get;
    set;
  }

  public string FileType {
    get;
    set;
  }

  [Required]
  public string Attachment_Description {
    get;
    set;
  }
  public decimal Attachment_Amount {
    get;
    set;
  }
  public bool Status {
    get;
    set;
  } = true;
  public bool IsApproved {
    get;
    set;
  } = false;

  [NotMapped]
  public int TempID {
    get;
    set;
  }

}
#endregion

</code>```

答:
How do you save and delete the information stored?

Edit i think that you just remove from the ui only and not the record you saved.

Edit 2 so as i told you before. you are saving the information in a Database. For you to actually remove that view you need to remove that row from the database as you did with save here.

ContentLicense: CC BY-SA 4.0

Body:
In my web application, I have more than 5 partial views in the main view.

So the partial views are controlled from the Drop down menu. With the value of the drop-down menu, I hide and show the related partial view on the main view.

The process is when I click the button it loads the partial view. If I want to add another record I can add it by clicking the Add New Record button. If I want to remove it I can delete the partial view.

The issue is If I add a new record and load the partial view and If I don't want it I removed the record, But when It submits the main form I return an error and that deleted partial view shows again.

Can I know how to delete it completely?

This is How I load the partial view in the Main view.

<fieldset id="pnlGeneralItms" style="display:@(Model.GeneralItmsList == null || Model.GeneralItmsList.Count == 0? " none":"")">
  <legend>

General Request Attachments / Bills

  </legend>

 @if (Model != null && Model.GeneralItmsList != null) { foreach (Asp_PASMVC.Models.GeneralItms Itms in Model.GeneralItmsList) { Html.RenderPartial("_GeneralItms", Itms); } }

  <button type="button" id="addAnotherItm" class="btn btn-info" href="#">Add New Record</button>

</fieldset>

This is the Partial View

 @using (Html.BeginCollectionItem("GeneralItmsList")) { @Html.HiddenFor(model => model.TempID) @Html.ValidationSummary(true, "", new { @class = "text-danger" })

 Type Line Description
 @Html.EditorFor(model => model.Attachment_Description, new { htmlAttributes = new { @class = "form-control", placeholder = "Make it short" } }) @Html.ValidationMessageFor(model => model.Attachment_Description, "", new { @class = "text-danger" })

 Attachment Amount

            Rs. @Html.EditorFor(model => model.Attachment_Amount, new { htmlAttributes = new { @class = "form-control" } })

 @Html.ValidationMessageFor(model => model.Attachment_Amount, "", new { @class = "text-danger" })

    <button type="button" class="btn btn-danger" onclick="$(this).parent().remove();">Remove</button>

 }

This is how it shows. Even if I delete the highlighted record in submitting it returns the view with the deleted record.

Edited____

This is my controller

public ActionResult Create(AppRequest appRequest) {
    if (ModelState.IsValid) {
      if (appRequest.ApprovalPartyList?.ToString() != null) {

        if (appRequest.GeneralItmsList != null) {
          foreach(GeneralItms item in appRequest.GeneralItmsList) {
            HttpPostedFileBase file = Request.Files["ImageData" + item.TempID];
            item.Attachment = ConvertToBytes(file);
            item.FileType = Path.GetFileName(file.ContentType);
          }

          appRequest.General = new List < General > () {
            new General {

              GeneralItms = appRequest.GeneralItmsList,

            }
          };

        }

      }

      appRequest.Req_By = int.Parse(((System.Security.Claims.ClaimsIdentity) User.Identity).FindFirst("UserId").Value);
      appRequest.Company_Id = int.Parse((User.Identity as ClaimsIdentity).Claims.Where(c => c.Type == "CompanyID").FirstOrDefault().Value);
      appRequest.Create_By = int.Parse(((System.Security.Claims.ClaimsIdentity) User.Identity).FindFirst("UserId").Value);
      appRequest.Created_Date = DateTime.Now;
      appRequest.Modified_By = int.Parse(((System.Security.Claims.ClaimsIdentity) User.Identity).FindFirst("UserId").Value);
      appRequest.Modified_Date = DateTime.Now;
      appRequest.Status = true;
      try {
        db.AppRequest.Add(appRequest);
        db.SaveChanges();
      } catch (Exception ex) {

        TempData["msg"] = "error";
        return View(appRequest);
      }

This is the Model

public class AppRequest {
  private zSqlDb db = new zSqlDb();

  [Key]
  public int Id {
    get;
    set;
  }

  [Required]
  [Display(Name = "Request Type")]
  public int ReqType {
    get;
    set;
  }

  [Required]
  [Display(Name = "Requesting By")]
  public int Req_By {
    get;
    set;
  }

  [Required]
  [Display(Name = "Requesting Date")]
  public DateTime Req_Date {
    get;
    set;
  } = DateTime.Now;

  [Required]
  [Display(Name = "Request Location")]
  public int Req_Location {
    get;
    set;
  }

  [Required]
  [Display(Name = "Request Heading")]
  public string Req_Heading {
    get;
    set;
  }

  [Display(Name = "Cover Note")]
  public string Req_CoverNote {
    get;
    set;
  }

  [Required]
  [Display(Name = "Company Name")]
  public int Company_Id {
    get;
    set;
  }
  public bool Status {
    get;
    set;
  }
  public int Create_By {
    get;
    set;
  }
  public DateTime Created_Date {
    get;
    set;
  } = DateTime.Now;
  public int Modified_By {
    get;
    set;
  }
  public DateTime Modified_Date {
    get;
    set;
  } = DateTime.Now;
  public int Approval_Status {
    get;
    set;
  }

  public virtual IList < General > General {
    get;
    set;
  }

  #region ILists

    //General
    [NotMapped]
  public IList < GeneralItms > GeneralItmsList {
    get;
    set;
  }

  #endregion

    [NotMapped]
  public int xSupp_Id {
    get;
    set;
  }

}

#region General
public class General {
  [Key]
  public int Id {
    get;
    set;
  }

  [Required]
  [ForeignKey("AppRequest")]
  public int Req_Id {
    get;
    set;
  }
  public virtual AppRequest AppRequest {
    get;
    set;
  }

  public string ApprovedNumber {
    get;
    set;
  }

  public bool IsSettled {
    get;
    set;
  }

  public virtual IList < GeneralItms > GeneralItms {
    get;
    set;
  }
}
public class GeneralItms {
  [Key]
  public int Id {
    get;
    set;
  }

  [Required]
  [ForeignKey("General")]

  public int General_Id {
    get;
    set;
  }

  public virtual General General {
    get;
    set;
  }
  public byte[] Attachment {
    get;
    set;
  }

  public string FileType {
    get;
    set;
  }

  [Required]
  public string Attachment_Description {
    get;
    set;
  }
  public decimal Attachment_Amount {
    get;
    set;
  }
  public bool Status {
    get;
    set;
  } = true;
  public bool IsApproved {
    get;
    set;
  } = false;

  [NotMapped]
  public int TempID {
    get;
    set;
  }

}
#endregion


问:
I'm facing a problem, where it is taking so much time to display a list thad is added to a database
Iam currently working on a book management project and I'm using SQL Server from Visual Studio. I have a Book Category table in the database and I'm trying to place it in a combobox.

This the code - I don't see anything wrong with it but the categories are taking so long to be visible in the combobox.

Also the list is repetitive, is it maybe because of the while Loop? If so is there any way to fix it?

```<code>private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                con.ConnectionString = (@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\malek\source\repos\BookStore\BookStore\BOOKDB.mdf;Integrated Security=True");
                scmd.Connection = con;
                con.Open();
                scmd.CommandText = "SELECT CATEGORY FROM BOOKCAT";
                var rd = scmd.ExecuteReader();
                while (rd.Read())
                {
                    List.Add(Convert.ToString(rd[0]));
                }
                int i = 0;
                while (i < List.LongCount())
                {
                    comboBox1.Items.Add(List[i]);
                    i = i + 1;
                }

            }
            catch (Exception EX)
            {

                MessageBox.Show(EX.Message);
            }
            finally
            {
                con.Close();
            }
        }
</code>```

What did I miss?

NOTE: I am not getting any errors!!

答:
How do you mean with data binding?

Like this

```<code>var da = new SqlDataAdapter(
  "SELECT DISTINCT CATEGORY FROM BOOKCAT ORDER BY CATEGORY"
  @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\malek\source\repos\BookStore\BookStore\BOOKDB.mdf;Integrated Security=True"
);
var dt = new DataTable();
da.Fill(dt);
categoryComboBox.DisplayMember = "CATEGORY";
categoryComboBox.ValueMember = "CATEGORY";
categoryComboBox.DataSource = dt;
</code>```

And when you want the thing the user selected:

```<code> var cat = categoryComboBox.SelectedValue as string;
</code>```

Simple eh?

It gets even easier if you use a strongly typed dataset; for that you just add a new DataSet type file to your project (must use net framework not net core/5+), drag your db into your dataset, add a query to the category TableAdapter that gets the distinct categories (like above) then open the data sources window, change Category to a combo and tag it onto the form. No code to write; vs will write it all

Body:
Iam currently working on a book management project and I'm using SQL Server from Visual Studio. I have a Book Category table in the database and I'm trying to place it in a combobox.

This the code - I don't see anything wrong with it but the categories are taking so long to be visible in the combobox.

Also the list is repetitive, is it maybe because of the while Loop? If so is there any way to fix it?

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                con.ConnectionString = (@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\malek\source\repos\BookStore\BookStore\BOOKDB.mdf;Integrated Security=True");
                scmd.Connection = con;
                con.Open();
                scmd.CommandText = "SELECT CATEGORY FROM BOOKCAT";
                var rd = scmd.ExecuteReader();
                while (rd.Read())
                {
                    List.Add(Convert.ToString(rd[0]));
                }
                int i = 0;
                while (i < List.LongCount())
                {
                    comboBox1.Items.Add(List[i]);
                    i = i + 1;
                }

            }
            catch (Exception EX)
            {

                MessageBox.Show(EX.Message);
            }
            finally
            {
                con.Close();
            }
        }

What did I miss?

NOTE: I am not getting any errors!!

Body:
How do you mean with data binding?

Like this

var da = new SqlDataAdapter(
  "SELECT DISTINCT CATEGORY FROM BOOKCAT ORDER BY CATEGORY"
  @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\malek\source\repos\BookStore\BookStore\BOOKDB.mdf;Integrated Security=True"
);
var dt = new DataTable();
da.Fill(dt);
categoryComboBox.DisplayMember = "CATEGORY";
categoryComboBox.ValueMember = "CATEGORY";
categoryComboBox.DataSource = dt;

And when you want the thing the user selected:

 var cat = categoryComboBox.SelectedValue as string;

Simple eh?

It gets even easier if you use a strongly typed dataset; for that you just add a new DataSet type file to your project (must use net framework not net core/5+), drag your db into your dataset, add a query to the category TableAdapter that gets the distinct categories (like above) then open the data sources window, change Category to a combo and tag it onto the form. No code to write; vs will write it all


问:
Difference in ptr,&ptr,&ptr[0]
Below is the test code:

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

int funtion(int *ptr)
{
    int temp;
    temp = *ptr;
    printf("ptr = %p %p %p %d\n", ptr, &ptr, &ptr[0], *ptr);
    printf("*ptr = %d\n", *ptr);
    return temp;
}

int main()
{
    int i = 10;
    int *tp = &i;
    printf("tp = %p %p %p %d\n", tp, &tp, &tp[0], *tp);
    (void)funtion(tp);
    return 0;
}
answer:
tp = 0x7ffc1117392c 0x7ffc11173930 0x7ffc1117392c 10
ptr= 0x7ffc1117392c 0x7ffc111738f8 0x7ffc1117392c 10
*ptr =10
</code>```

**question:

what are the difference between tp &tp &tp[0]

Which passing parameter we should use.

is this difference only for passing parameter?**

答:
You are passing an int pointer to function. This is passed by value. Of course, the value they point to is the same.

```<code>int funtion(int *ptr)
{
    int temp  = *ptr;
    printf("ptr = %p %p %p %d\n", ptr, &ptr, &ptr[0], *ptr);
    printf("*ptr = %d\n", *ptr);
    return temp;
}
</code>```

temp is initialized with the value pointed to by ptr.

The first thing you print is ptr: the memory address you passed to function by value.

The second thing you print is &ptr. This is the address of that function argument. While this may be the same between function calls due to implementation-specific handling of the stack, it may also be different.

The third thing you print is &ptr[0]. This is the address is ptr[0], which is equivalent to writing *(ptr + 0) or just *ptr. Getting the address of this in turn is equivalent to just writing ptr.

The fourth thing you print is *ptr. Again, as with initializing temp this is just the int value that ptr points to.

Title: Difference in ptr,&ptr,&ptr[0]

Body:
Below is the test code:

#include <stdio.h>

int funtion(int *ptr)
{
    int temp;
    temp = *ptr;
    printf("ptr = %p %p %p %d\n", ptr, &ptr, &ptr[0], *ptr);
    printf("*ptr = %d\n", *ptr);
    return temp;
}

int main()
{
    int i = 10;
    int *tp = &i;
    printf("tp = %p %p %p %d\n", tp, &tp, &tp[0], *tp);
    (void)funtion(tp);
    return 0;
}
answer:
tp = 0x7ffc1117392c 0x7ffc11173930 0x7ffc1117392c 10
ptr= 0x7ffc1117392c 0x7ffc111738f8 0x7ffc1117392c 10
*ptr =10

**question:

what are the difference between tp &tp &tp[0]

Which passing parameter we should use.

is this difference only for passing parameter?**

Body:
You are passing an int pointer to function. This is passed by value. Of course, the value they point to is the same.

int funtion(int *ptr)
{
    int temp  = *ptr;
    printf("ptr = %p %p %p %d\n", ptr, &ptr, &ptr[0], *ptr);
    printf("*ptr = %d\n", *ptr);
    return temp;
}

temp is initialized with the value pointed to by ptr.

The first thing you print is ptr: the memory address you passed to function by value.

The second thing you print is &ptr. This is the address of that function argument. While this may be the same between function calls due to implementation-specific handling of the stack, it may also be different.

The third thing you print is &ptr[0]. This is the address is ptr[0], which is equivalent to writing *(ptr + 0) or just *ptr. Getting the address of this in turn is equivalent to just writing ptr.

The fourth thing you print is *ptr. Again, as with initializing temp this is just the int value that ptr points to.


问:
Gmail like file upload with jQuery
I would like to upload files just like google mail does. I would want to use jQuery and PHP to do it is there anyway of getting the progressbar etc.?

Here I added a video of how google does it. http://dl.getdropbox.com/u/5910/Jing/2009-04-02_1948.swf

No flash, no perl or cgi please..

I guess I can live without the progressbar now I am actually searching for information about jquery plugins or just what things I would need to look at

答: PHP doesn't support reporting of upload progress directly. So there is no way of reading the upload status back. However, there is a patch that might work. I haven't tried though.</p>

OwnerDisplayName: Thomaschaaf

ContentLicense: CC BY-SA 2.5

Title: Gmail like file upload with jQuery

LastEditorDisplayName: Thomaschaaf

OwnerDisplayName: Aaron Qian


问:
android garbage collector, freeing objects inside objects
I'm very curious about how this thing works inside Android. I have a class with two List<> inside, instantiated at runtime and loaded with objects created while reading some data, I want to know what happens with those Lists in this situation:

Class A has List B and List C with many other initialized objects
inside.

Another different class get a reference of List C from a
method of Class A, like  public List<myObject> GetList().

Somewhere in code, Class A is no longer used and application
signals that to garbage collector, setting object to null.

What happens with my List C that is referenced by other object?  What happens with Object class A?

I've tried to track garbage collector with Logcat running apk in debugger step-by-step but no luck at all. Sometimes it frees memory, sometimes not, I couldn't pinpoint any specific behaviour.

答: By default java creates an object by reference instead of by value. So, in this case if the garbage collector would pick up and empty all A B C and the then the other class that referenced C would be empty, since it didnt create a duplication of the class, it just referenced it.</p>

ContentLicense: CC BY-SA 3.0


问:
how to count the number of keys having duplicate values when the values are in a list
```<code>example_dict = {'v':['f','f','f','f','f','f','f','f'], 'c':['p','p','p','p','p','p','p','p','p'], 'a':['p','p','p','p','p','p','p','p'], 'w2' = ['f','f','f','f','f','f','f','f','f']}

#the code i have tried

flipping_example_dict = {}

for (key,value) in example_dict.items():
    if value not in flipped_example_dict:
        flipped_example_dict[value] = [key]
    else:
        flipped_example_dict[value].append[key]
</code>```
<p>#the error is ---> unhashable type: 'list'
#i need to find the number of keys having duplicate values. For example, the answer should be f = 2 and p = 2. This is just an example. My original dataset has appox. 1500 keys with similar problem.
#i had earlier tried to find the keys with an if statement having a condition as if value == 'p'. but it too didn't work as the values are in list and not in str.</p>

答:
Error Unhashable type: 'list' : This is because there is a list inside your dictionary and you are trying to compare a list with a dictionary in the if statement.

```<code>if value not in flipped_example_dict:
</code>```

According to the problme you have explained, this code works for me.

```<code>example_dict = {'First_list':['F','G','F'], 'Second_list':['P','H','P','P','P']}
result = {}
for key in example_dict.keys():
    for letter in list(set(example_dict[key])):
        if letter in result.keys():
            result[letter]+=1
        else:
            result[letter] = 1
print(result)
</code>```

Body:
example_dict = {'v':['f','f','f','f','f','f','f','f'], 'c':['p','p','p','p','p','p','p','p','p'], 'a':['p','p','p','p','p','p','p','p'], 'w2' = ['f','f','f','f','f','f','f','f','f']}

#the code i have tried

flipping_example_dict = {}

for (key,value) in example_dict.items():
    if value not in flipped_example_dict:
        flipped_example_dict[value] = [key]
    else:
        flipped_example_dict[value].append[key]

#the error is ---> unhashable type: 'list'
#i need to find the number of keys having duplicate values. For example, the answer should be f = 2 and p = 2. This is just an example. My original dataset has appox. 1500 keys with similar problem.
#i had earlier tried to find the keys with an if statement having a condition as if value == 'p'. but it too didn't work as the values are in list and not in str.

Body:
Error Unhashable type: 'list' : This is because there is a list inside your dictionary and you are trying to compare a list with a dictionary in the if statement.

if value not in flipped_example_dict:

According to the problme you have explained, this code works for me.

example_dict = {'First_list':['F','G','F'], 'Second_list':['P','H','P','P','P']}
result = {}
for key in example_dict.keys():
    for letter in list(set(example_dict[key])):
        if letter in result.keys():
            result[letter]+=1
        else:
            result[letter] = 1
print(result)


问:
How not to close browser after using selenium browser?
How not to close browser after using selenium browser?

I made autologin code but want not to close the browser.

答:
If your webdriver object is in a function, try making it global.

For Example:

def auto_login():
    global browser
    browser = webdriver.Safari()

    """
    rest of your code
    """
```


问:
How to get a custom collection based on a data that is most repeated (from top to bottom))
I have a table like this:

Basically this table is named favourite_products and contains product ids that are added as favourite for users.

Now I wanted to get a collection of most added product from this table.

So in this case, a product with an id of 10 would be on top of the collection.

But I don't know how to get this collection ordering by from most repeated product id (prd_id)...

Here is the Model:

```<code>class FavouriteProduct extends Model
{
    protected $table = 'favourite_products';
    protected $fillable = ['usr_id','prd_id'];

    public function user()
    {
        return $this->belongsTo(User::class, 'usr_id');
    }

    public function product()
    {
        return $this->belongsTo(Product::class, 'prd_id');
    }
}
</code>```

UPDATE #1:

Product.php Model:

```<code>public function favouritees()
    {
        return $this->belongsToMany(User::class, 'favourite_products', 'prd_id', 'usr_id');
    }
</code>```

答:
I think the following code solve your problem:

```<code>$most_liked_products = DB::table('favourite_products')
    ->select(DB::raw('count(prd_id) as total'), id)
    ->groupBy('total')
    ->orderByDesc('total')
    ->get();
</code>```

Please try it and give your feedback

Body:
I have a table like this:

Basically this table is named favourite_products and contains product ids that are added as favourite for users.

Now I wanted to get a collection of most added product from this table.

So in this case, a product with an id of 10 would be on top of the collection.

But I don't know how to get this collection ordering by from most repeated product id (prd_id)...

Here is the Model:

class FavouriteProduct extends Model
{
    protected $table = 'favourite_products';
    protected $fillable = ['usr_id','prd_id'];

    public function user()
    {
        return $this->belongsTo(User::class, 'usr_id');
    }

    public function product()
    {
        return $this->belongsTo(Product::class, 'prd_id');
    }
}

UPDATE #1:

Product.php Model:

public function favouritees()
    {
        return $this->belongsToMany(User::class, 'favourite_products', 'prd_id', 'usr_id');
    }

Body:
I think the following code solve your problem:

$most_liked_products = DB::table('favourite_products')
    ->select(DB::raw('count(prd_id) as total'), id)
    ->groupBy('total')
    ->orderByDesc('total')
    ->get();

Please try it and give your feedback


问:
Splitting an array into sequential groups
I have an array with elements [2, 3, 4, 5, 6, 7, 8, 9, 10, ...]. I wish to split this up as follows: [[2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], ...]. I am not sure how to do this because the elements in each split must be repeated, and I am unsure of how to create these repeated elements. Any help will be much appreciated.

答:
The zip idea generalised for varying chunk size:

```<code>lst = [2, 3, 4, 5, 6, 7, 8, 9, 10]
result = list(zip(*(lst[i:] for i in range(3))))
</code>```

Body:
The zip idea generalised for varying chunk size:

lst = [2, 3, 4, 5, 6, 7, 8, 9, 10]
result = list(zip(*(lst[i:] for i in range(3))))


问:
Extracting elements off an array of pointers
Suppose we have this main:

```<code>int main(int argc,char *argv[]){

}
</code>```

How could I manage to get the elements of *argv[],in order to extract some statistics off of each one(e.g letter count,numbers ,etc.)?

I have tried couple of things but didn't work(using pointers ).Eventually I tried a work-around,using strcpy() to copy each element of the array and that worked.
So my question is,are there other ways to achieve that?

Here's an example of my code that works:

```<code>int main(int argc,char *argv[]){
    char temp[50];
    strcpy(temp,argv[1]); //extracting the first element of the array.

</code>```

答:
Another way of doing so is as below:

```<code>int main(int argc,char argv[]){
char *temp = argv;
}
</code>```

This code will create a string named "temp" which is a copy of "argv[]". You can use to extract any stats you like without having to use the "strcopy" function.
Also, take note that I have changed the argument from
 int main(int argc, char *argv[])
to
int main(int argc, char argv[])

Body:
Suppose we have this main:

int main(int argc,char *argv[]){

}

How could I manage to get the elements of *argv[],in order to extract some statistics off of each one(e.g letter count,numbers ,etc.)?

I have tried couple of things but didn't work(using pointers ).Eventually I tried a work-around,using strcpy() to copy each element of the array and that worked.
So my question is,are there other ways to achieve that?

Here's an example of my code that works:

int main(int argc,char *argv[]){
    char temp[50];
    strcpy(temp,argv[1]); //extracting the first element of the array.

Body:
Another way of doing so is as below:

int main(int argc,char argv[]){
char *temp = argv;
}

This code will create a string named "temp" which is a copy of "argv[]". You can use to extract any stats you like without having to use the "strcopy" function.
Also, take note that I have changed the argument from
 int main(int argc, char *argv[])
to
int main(int argc, char argv[])


答:
zip() and comprehension, suggested above, are probably the ways to go in "real life", but in order to better understand the problem, consider this very simple approach:

```<code>data = [2, 3, 4, 5, 6, 7, 8, 9, 10]

result = []

for i in range(0,len(data)-2):
    result.append([data[i],data[i+1],data[i+2]])

print(result)
</code>```

Title: Splitting an array into sequential groups

Body: I have an array with elements [2, 3, 4, 5, 6, 7, 8, 9, 10, ...]. I wish to split this up as follows: [[2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], ...]. I am not sure how to do this because the elements in each split must be repeated, and I am unsure of how to create these repeated elements. Any help will be much appreciated.

Body:
zip() and comprehension, suggested above, are probably the ways to go in "real life", but in order to better understand the problem, consider this very simple approach:

data = [2, 3, 4, 5, 6, 7, 8, 9, 10]

result = []

for i in range(0,len(data)-2):
    result.append([data[i],data[i+1],data[i+2]])

print(result)


问:
How to check the specific element in string are equal in python?
There is a two input first input represent the index of the second input.I need to find the 'X' position of second input are same or not?

input:

```<code>123X56XX
Ahjutruu

Output:
  True
</code>```

Example:
X in input one at 4,7,8

position of 4,7,8 in second input is 'u' all are same so i need to print "true"

I tried using enumerate function but not came:

```<code>a="123X56XX"
b="Ahjutruu"
xi=[]

for i,val in enumerate(a):
  if val=='X':
    xi.append(i)
print(xi)
#next step only i dont know how to doo please help
</code>```

Next i dont know how to check

答:
Minor addition to your code.</p>
```<code>a="123X56XX"
b="Ahjutruu"
xi=[]
result = False
for i,val in enumerate(a):
  if val=='X':
    xi.append(i)
print(xi[0])

for index, value in enumerate(xi):
    if index < len(xi) - 1:
        if b[value] == b[xi[index+1]]:
            result = True
        else:
            result = False
print(result)
</code>```

Body:
There is a two input first input represent the index of the second input.I need to find the 'X' position of second input are same or not?

input:

123X56XX
Ahjutruu

Output:
  True

Example:
X in input one at 4,7,8

position of 4,7,8 in second input is 'u' all are same so i need to print "true"

I tried using enumerate function but not came:

a="123X56XX"
b="Ahjutruu"
xi=[]

for i,val in enumerate(a):
  if val=='X':
    xi.append(i)
print(xi)
#next step only i dont know how to doo please help

Next i dont know how to check

Body:
Minor addition to your code.

a="123X56XX"
b="Ahjutruu"
xi=[]
result = False
for i,val in enumerate(a):
  if val=='X':
    xi.append(i)
print(xi[0])

for index, value in enumerate(xi):
    if index < len(xi) - 1:
        if b[value] == b[xi[index+1]]:
            result = True
        else:
            result = False
print(result)


问:
How to change excel timestamp format ? Format change but date is not correct
```<code>$my = '13/02/2022 21:29:30';
$converted = date('d M Y h.i.s A', strtotime($my));
$reversed = date('d-m-Y H:i:s', strtotime($converted));
echo $reversed;
</code>```

// output
01-01-1970 00:00:00

but I want a correct date

答:
Create a DateTime Object from the string.

Then format the date!!

Happy Coding!

```<code>$my = '13/02/2022 21:29:30';
$date = DateTime::createFromFormat('d/m/Y H:i:s', $my);
echo $date->format('d-m-Y H:i:s');
</code>```

Body:
$my = '13/02/2022 21:29:30';
$converted = date('d M Y h.i.s A', strtotime($my));
$reversed = date('d-m-Y H:i:s', strtotime($converted));
echo $reversed;

// output
01-01-1970 00:00:00

but I want a correct date

Body:
Create a DateTime Object from the string.

Then format the date!!

Happy Coding!

$my = '13/02/2022 21:29:30';
$date = DateTime::createFromFormat('d/m/Y H:i:s', $my);
echo $date->format('d-m-Y H:i:s');


问:
android start activity with animation
Is it possible to ad an animation to an activity at runtime so when I start the activity, it starts with my animation? I want to specify some parameters to animation at runtime depending on some view's position. I've managed to ad an animation, but the animation was defined in a xml file so I was not able to edit the numbers from animation. Is it possible to do this?</p>

答:
Yes,

you can always use the android activity life cycle to do this, in this case you can perform your animation in the onCreate function.

Cheers.

Title: android start activity with animation


问:
Could not build the iOS app Flutter - 'Flutter/Flutter.h' file not found
I cannot run or build the iOS app. This always happens with the same error.

I have already repaired Flutter pub caches.

Deleted the pod files.

Removed the iOS folder and tried:

```<code>Launching lib/main.dart on iPhone 12 Pro Max in debug mode...
Running pod install...
Running Xcode build...
Xcode build done.                                           28.2s
Failed to build iOS app
Error output from Xcode build:
↳
    ** BUILD FAILED **

Xcode's output:
↳
    In file included from /Users/ravindu/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/webview_flutter_wkwebview-2.7.1/ios/Classes/JavaScriptChannelHandler.m:5:
    /Users/ravindu/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/webview_flutter_wkwebview-2.7.1/ios/Classes/JavaScriptChannelHandler.h:5:9: fatal error: 'Flutter/Flutter.h' file not found
    #import <Flutter/Flutter.h>
            ^~~~~~~~~~~~~~~~~~~
    1 error generated.
    In file included from /Users/ravindu/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/webview_flutter_wkwebview-2.7.1/ios/Classes/FlutterWebView.m:5:
    /Users/ravindu/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/webview_flutter_wkwebview-2.7.1/ios/Classes/FlutterWebView.h:5:9: fatal error: 'Flutter/Flutter.h' file not found
    #import <Flutter/Flutter.h>
            ^~~~~~~~~~~~~~~~~~~
    1 error generated.
    In file included from /Users/ravindu/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/webview_flutter_wkwebview-2.7.1/ios/Classes/FLTWebViewFlutterPlugin.m:5:
    /Users/ravindu/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/webview_flutter_wkwebview-2.7.1/ios/Classes/FLTWebViewFlutterPlugin.h:5:9: fatal error: 'Flutter/Flutter.h' file not found
    #import <Flutter/Flutter.h>
            ^~~~~~~~~~~~~~~~~~~
    1 error generated.
    In file included from /Users/ravindu/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/webview_flutter_wkwebview-2.7.1/ios/Classes/FLTWKProgressionDelegate.m:5:
    /Users/ravindu/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/webview_flutter_wkwebview-2.7.1/ios/Classes/FLTWKProgressionDelegate.h:5:9: fatal error: 'Flutter/Flutter.h' file not found
    #import <Flutter/Flutter.h>
            ^~~~~~~~~~~~~~~~~~~
    1 error generated.
    In file included from /Users/ravindu/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/webview_flutter_wkwebview-2.7.1/ios/Classes/FLTWKNavigationDelegate.m:5:
    /Users/ravindu/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/webview_flutter_wkwebview-2.7.1/ios/Classes/FLTWKNavigationDelegate.h:5:9: fatal error: 'Flutter/Flutter.h' file not found
    #import <Flutter/Flutter.h>
            ^~~~~~~~~~~~~~~~~~~
    1 error generated.
    In file included from /Users/ravindu/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/webview_flutter_wkwebview-2.7.1/ios/Classes/FLTCookieManager.m:5:
    /Users/ravindu/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/webview_flutter_wkwebview-2.7.1/ios/Classes/FLTCookieManager.h:5:9: fatal error: 'Flutter/Flutter.h' file not found
    #import <Flutter/Flutter.h>
            ^~~~~~~~~~~~~~~~~~~
    1 error generated.
    note: Using new build system
    note: Building targets in parallel
    note: Planning build
    note: Analyzing workspace
    note: Constructing build description
    note: Build preparation complete

Could not build the application for the simulator.
Error launching application on iPhone 12 Pro Max.
</code>```

Here is the pod file:

```<code># Uncomment this line to define a global platform for your project
 platform :ios, '11.0'

# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
  'Debug' => :debug,
  'Profile' => :release,
  'Release' => :release,
}

def flutter_root
  generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
  unless File.exist?(generated_xcode_build_settings_path)
    raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
  end

  File.foreach(generated_xcode_build_settings_path) do |line|
    matches = line.match(/FLUTTER_ROOT\=(.*)/)
    return matches[1].strip if matches
  end
  raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end

require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)

flutter_ios_podfile_setup

target 'Runner' do
  use_frameworks!
  use_modular_headers!

  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    # flutter_additional_ios_build_settings(target)
      target.build_configurations.each do |config|
         if config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'].to_f < 11.0
           config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '11.0'
         end
      end
  end
end
</code>```

Here is the Pubspec.yaml file:

```<code>name: fstore
publish_to: "none"
description: Mobile commerce app by Flutter

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 2.8.0+1

environment:
  sdk: ">=2.15.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter

  inspireui: 1.0.10

  # Base
  intl: 0.17.0
  crypto: 3.0.1
  path_provider: 2.0.8
  url_launcher: 6.0.17
  localstorage: 4.0.0+1
  http: 0.13.4
  http_auth: 1.0.1
  share: 2.0.4
  wakelock: 0.5.6

  # FIREBASE PACKAGES
  firebase_core: 1.10.5
  firebase_analytics: 9.0.2
  firebase_auth: 3.3.3
  firebase_remote_config: 1.0.2
  firebase_dynamic_links: 4.0.2
  cloud_firestore: 3.1.4

  # STATE MANAGEMENT
  provider: 6.0.1
  get_it: 7.2.0

  # SPLASH SCREEN, ONBOARD
  flare_loading: 3.0.0
  rive: 0.7.33

  # ICON FONTS
  cupertino_icons: 1.0.4

  # WEB TOOLS
  html_unescape: 2.0.0
  webview_flutter: 3.0.0
  webview_flutter_web: 0.1.0
  responsive_builder: 0.4.1
  webview_windows: 0.1.0
  flutter_inappwebview: 5.3.2
  # webview_flutter_wkwebview: ^2.7.1

  # HTML render
  flutter_widget_from_html_core: 0.8.3
  fwfh_text_style: ^2.7.0+1
  fwfh_webview: 0.6.2+1
  fwfh_svg: 0.7.2
  fwfh_cached_network_image: 0.7.0+2
  fwfh_url_launcher: 0.6.1+3
  fwfh_chewie: 0.7.0+1

  # MAP
  google_maps_flutter: 2.1.1
  location: 4.3.0
  maps_launcher: 2.0.1
  geocode: 1.0.1

  # AUTHENTICATION
  the_apple_sign_in: 1.1.1
  flutter_facebook_auth: 3.5.7
  google_sign_in: 5.2.1
  sms_autofill: 2.2.0

  # PUSH NOTIFICATION
  firebase_messaging: 11.2.3
  notification_permissions: 0.6.1
  flutter_local_notifications: 9.1.5
  onesignal_flutter: 3.2.7

  # FILES, IMAGES
  file_picker: 4.2.7
  cached_network_image: 3.2.0
  image: 3.1.0
  transparent_image: 2.0.0
  image_picker: 0.8.4+4
  flutter_native_image: 0.0.6+1
  multi_image_picker2: 5.0.2
  flutter_cache_manager: 3.3.0

  # ADS
  google_mobile_ads: 1.0.1

  # TOOLS
  google_fonts: 2.1.0
  random_string: 2.3.1
  json_annotation: 4.4.0
  timeago: 3.1.0
  universal_platform: 1.0.0+1
  uuid: 3.0.5
  easy_debounce: 2.0.1
  devicelocale: 0.5.0
  collection: 1.15.0
  visibility_detector: 0.2.2
  rate_my_app: 1.1.1+1
  enum_to_string: ^2.0.1
  flutter_linkify: ^5.0.2
  gms_check: ^1.0.0

  # UI
  flutter_spinkit: 5.1.0
  smooth_page_indicator: 1.0.0+2
  animated_text_kit: 4.2.1
  animations: 2.0.2
  flash: 2.0.3
  flutter_staggered_grid_view: 0.4.1
  flutter_swiper_null_safety: 1.0.2
  pull_to_refresh: 2.0.0
  implicitly_animated_reorderable_list: 0.4.2
  rubber: ^1.0.1
  pin_code_fields: 7.3.0
  country_code_picker: 2.0.2
  country_pickers: 2.0.0
  intro_slider: ^3.0.2
  dropdown_search: 2.0.1
  flutter_calendar_carousel: 2.1.0
  currency_text_input_formatter: 2.1.5
  flutter_zoom_drawer: ^2.1.1
  qr_code_scanner: 0.6.1
  paytm_allinonesdk: 1.1.4
  charts_flutter: ^0.12.0

  extended_image:
    git: https://github.com/inspireui/extended_image.git
  razorpay_flutter:
    git: https://github.com/inspireui/razorpay-flutter.git

  ###---- Some extra feature is disable by default -----###
  ### ▶ Audio Feature
  ### Search "Enable Audio feature" & uncomment to use - https://tppr.me/Z1TX5
  #  audio_manager: ^0.8.1

  ###  Webview Plugin
  ### Search "Enable webview payment plugin" & uncomment to use - https://tppr.me/wlgV1
  # flutter_webview_plugin: 0.4.0

  ###  Facebook Ads
  ### Search "Enable Facebook Ads" & uncomment to use  - https://tppr.me/9Pkf9
  # facebook_audience_network: 1.0.0-nullsafety.0

dev_dependencies:
  flutter_lints: 1.0.4
  flutter_native_splash: 1.3.2
#  convert_data:
#    path: _dev/convert_data

## Enable to use Flutter Test Driver
#  flutter_driver:
#    sdk: flutter
#  test: 1.16.5
#  dependency_validator: 3.1.0  # pub run dependency_validator

## Enable To run json serializer, run:
## flutter pub run build_runner build --build-filter="lib/models/serializers/*.dart" --delete-conflicting-outputs
## flutter pub run build_runner serve --build-filter="lib/models/serializers/*.dart"
#  build_runner: 2.0.3
#  json_serializable: 4.1.2

#  Run this script to generate the app icon: flutter pub run flutter_launcher_icons:main
flutter_icons:
  android: "launcher_icon"
  ios: true
  image_path: "assets/images/app_icon.png"

# For information on the generic Dart part of this file, see the
# following page: https://www.dartlang.org/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
  uses-material-design: true
  assets:
    - lib/config/
    - lib/config/mocks/
    - lib/config/states/
    - lib/config/stories/
    - assets/icons/credit_cards/
    - assets/icons/tabs/
    - assets/icons/payment/
    - assets/icons/logins/
    - assets/images/
    - assets/images/country/
    - assets/images/favicon/
    - assets/html/
    - google_fonts/

flutter_intl:
  enabled: true
  use_deferred_loading: true
</code>```

I have tried different methods and still same issue.

答:
i have the same issue before a thou days and in mycase the solution was to countinue this steps:

Backup Runner folder

Delete the ios folder

Go to a terminal and execute flutter create . in the flutter project folder

Paste your Runner folder back into the ios folder

pod deintegrate in the ios folder

pod install also in the ios folder

flutter clean in the flutter project folder

flutter pub get

flutter run

Please note that if you use firebase you need to re-insert the GoogleService-Info.plist file

Hope it helps!

Body:
I cannot run or build the iOS app. This always happens with the same error.

I have already repaired Flutter pub caches.

Deleted the pod files.

Removed the iOS folder and tried:

Launching lib/main.dart on iPhone 12 Pro Max in debug mode...
Running pod install...
Running Xcode build...
Xcode build done.                                           28.2s
Failed to build iOS app
Error output from Xcode build:
↳
    ** BUILD FAILED **

Xcode's output:
↳
    In file included from /Users/ravindu/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/webview_flutter_wkwebview-2.7.1/ios/Classes/JavaScriptChannelHandler.m:5:
    /Users/ravindu/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/webview_flutter_wkwebview-2.7.1/ios/Classes/JavaScriptChannelHandler.h:5:9: fatal error: 'Flutter/Flutter.h' file not found
    #import <Flutter/Flutter.h>
            ^~~~~~~~~~~~~~~~~~~
    1 error generated.
    In file included from /Users/ravindu/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/webview_flutter_wkwebview-2.7.1/ios/Classes/FlutterWebView.m:5:
    /Users/ravindu/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/webview_flutter_wkwebview-2.7.1/ios/Classes/FlutterWebView.h:5:9: fatal error: 'Flutter/Flutter.h' file not found
    #import <Flutter/Flutter.h>
            ^~~~~~~~~~~~~~~~~~~
    1 error generated.
    In file included from /Users/ravindu/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/webview_flutter_wkwebview-2.7.1/ios/Classes/FLTWebViewFlutterPlugin.m:5:
    /Users/ravindu/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/webview_flutter_wkwebview-2.7.1/ios/Classes/FLTWebViewFlutterPlugin.h:5:9: fatal error: 'Flutter/Flutter.h' file not found
    #import <Flutter/Flutter.h>
            ^~~~~~~~~~~~~~~~~~~
    1 error generated.
    In file included from /Users/ravindu/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/webview_flutter_wkwebview-2.7.1/ios/Classes/FLTWKProgressionDelegate.m:5:
    /Users/ravindu/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/webview_flutter_wkwebview-2.7.1/ios/Classes/FLTWKProgressionDelegate.h:5:9: fatal error: 'Flutter/Flutter.h' file not found
    #import <Flutter/Flutter.h>
            ^~~~~~~~~~~~~~~~~~~
    1 error generated.
    In file included from /Users/ravindu/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/webview_flutter_wkwebview-2.7.1/ios/Classes/FLTWKNavigationDelegate.m:5:
    /Users/ravindu/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/webview_flutter_wkwebview-2.7.1/ios/Classes/FLTWKNavigationDelegate.h:5:9: fatal error: 'Flutter/Flutter.h' file not found
    #import <Flutter/Flutter.h>
            ^~~~~~~~~~~~~~~~~~~
    1 error generated.
    In file included from /Users/ravindu/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/webview_flutter_wkwebview-2.7.1/ios/Classes/FLTCookieManager.m:5:
    /Users/ravindu/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/webview_flutter_wkwebview-2.7.1/ios/Classes/FLTCookieManager.h:5:9: fatal error: 'Flutter/Flutter.h' file not found
    #import <Flutter/Flutter.h>
            ^~~~~~~~~~~~~~~~~~~
    1 error generated.
    note: Using new build system
    note: Building targets in parallel
    note: Planning build
    note: Analyzing workspace
    note: Constructing build description
    note: Build preparation complete

Could not build the application for the simulator.
Error launching application on iPhone 12 Pro Max.

Here is the pod file:

# Uncomment this line to define a global platform for your project
 platform :ios, '11.0'

# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
  'Debug' => :debug,
  'Profile' => :release,
  'Release' => :release,
}

def flutter_root
  generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
  unless File.exist?(generated_xcode_build_settings_path)
    raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
  end

  File.foreach(generated_xcode_build_settings_path) do |line|
    matches = line.match(/FLUTTER_ROOT\=(.*)/)
    return matches[1].strip if matches
  end
  raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end

require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)

flutter_ios_podfile_setup

target 'Runner' do
  use_frameworks!
  use_modular_headers!

  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    # flutter_additional_ios_build_settings(target)
      target.build_configurations.each do |config|
         if config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'].to_f < 11.0
           config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '11.0'
         end
      end
  end
end

Here is the Pubspec.yaml file:

name: fstore
publish_to: "none"
description: Mobile commerce app by Flutter

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 2.8.0+1

environment:
  sdk: ">=2.15.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter

  inspireui: 1.0.10

  # Base
  intl: 0.17.0
  crypto: 3.0.1
  path_provider: 2.0.8
  url_launcher: 6.0.17
  localstorage: 4.0.0+1
  http: 0.13.4
  http_auth: 1.0.1
  share: 2.0.4
  wakelock: 0.5.6

  # FIREBASE PACKAGES
  firebase_core: 1.10.5
  firebase_analytics: 9.0.2
  firebase_auth: 3.3.3
  firebase_remote_config: 1.0.2
  firebase_dynamic_links: 4.0.2
  cloud_firestore: 3.1.4

  # STATE MANAGEMENT
  provider: 6.0.1
  get_it: 7.2.0

  # SPLASH SCREEN, ONBOARD
  flare_loading: 3.0.0
  rive: 0.7.33

  # ICON FONTS
  cupertino_icons: 1.0.4

  # WEB TOOLS
  html_unescape: 2.0.0
  webview_flutter: 3.0.0
  webview_flutter_web: 0.1.0
  responsive_builder: 0.4.1
  webview_windows: 0.1.0
  flutter_inappwebview: 5.3.2
  # webview_flutter_wkwebview: ^2.7.1

  # HTML render
  flutter_widget_from_html_core: 0.8.3
  fwfh_text_style: ^2.7.0+1
  fwfh_webview: 0.6.2+1
  fwfh_svg: 0.7.2
  fwfh_cached_network_image: 0.7.0+2
  fwfh_url_launcher: 0.6.1+3
  fwfh_chewie: 0.7.0+1

  # MAP
  google_maps_flutter: 2.1.1
  location: 4.3.0
  maps_launcher: 2.0.1
  geocode: 1.0.1

  # AUTHENTICATION
  the_apple_sign_in: 1.1.1
  flutter_facebook_auth: 3.5.7
  google_sign_in: 5.2.1
  sms_autofill: 2.2.0

  # PUSH NOTIFICATION
  firebase_messaging: 11.2.3
  notification_permissions: 0.6.1
  flutter_local_notifications: 9.1.5
  onesignal_flutter: 3.2.7

  # FILES, IMAGES
  file_picker: 4.2.7
  cached_network_image: 3.2.0
  image: 3.1.0
  transparent_image: 2.0.0
  image_picker: 0.8.4+4
  flutter_native_image: 0.0.6+1
  multi_image_picker2: 5.0.2
  flutter_cache_manager: 3.3.0

  # ADS
  google_mobile_ads: 1.0.1

  # TOOLS
  google_fonts: 2.1.0
  random_string: 2.3.1
  json_annotation: 4.4.0
  timeago: 3.1.0
  universal_platform: 1.0.0+1
  uuid: 3.0.5
  easy_debounce: 2.0.1
  devicelocale: 0.5.0
  collection: 1.15.0
  visibility_detector: 0.2.2
  rate_my_app: 1.1.1+1
  enum_to_string: ^2.0.1
  flutter_linkify: ^5.0.2
  gms_check: ^1.0.0

  # UI
  flutter_spinkit: 5.1.0
  smooth_page_indicator: 1.0.0+2
  animated_text_kit: 4.2.1
  animations: 2.0.2
  flash: 2.0.3
  flutter_staggered_grid_view: 0.4.1
  flutter_swiper_null_safety: 1.0.2
  pull_to_refresh: 2.0.0
  implicitly_animated_reorderable_list: 0.4.2
  rubber: ^1.0.1
  pin_code_fields: 7.3.0
  country_code_picker: 2.0.2
  country_pickers: 2.0.0
  intro_slider: ^3.0.2
  dropdown_search: 2.0.1
  flutter_calendar_carousel: 2.1.0
  currency_text_input_formatter: 2.1.5
  flutter_zoom_drawer: ^2.1.1
  qr_code_scanner: 0.6.1
  paytm_allinonesdk: 1.1.4
  charts_flutter: ^0.12.0

  extended_image:
    git: https://github.com/inspireui/extended_image.git
  razorpay_flutter:
    git: https://github.com/inspireui/razorpay-flutter.git

  ###---- Some extra feature is disable by default -----###
  ### ▶ Audio Feature
  ### Search "Enable Audio feature" & uncomment to use - https://tppr.me/Z1TX5
  #  audio_manager: ^0.8.1

  ###  Webview Plugin
  ### Search "Enable webview payment plugin" & uncomment to use - https://tppr.me/wlgV1
  # flutter_webview_plugin: 0.4.0

  ###  Facebook Ads
  ### Search "Enable Facebook Ads" & uncomment to use  - https://tppr.me/9Pkf9
  # facebook_audience_network: 1.0.0-nullsafety.0

dev_dependencies:
  flutter_lints: 1.0.4
  flutter_native_splash: 1.3.2
#  convert_data:
#    path: _dev/convert_data

## Enable to use Flutter Test Driver
#  flutter_driver:
#    sdk: flutter
#  test: 1.16.5
#  dependency_validator: 3.1.0  # pub run dependency_validator

## Enable To run json serializer, run:
## flutter pub run build_runner build --build-filter="lib/models/serializers/*.dart" --delete-conflicting-outputs
## flutter pub run build_runner serve --build-filter="lib/models/serializers/*.dart"
#  build_runner: 2.0.3
#  json_serializable: 4.1.2

#  Run this script to generate the app icon: flutter pub run flutter_launcher_icons:main
flutter_icons:
  android: "launcher_icon"
  ios: true
  image_path: "assets/images/app_icon.png"

# For information on the generic Dart part of this file, see the
# following page: https://www.dartlang.org/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
  uses-material-design: true
  assets:
    - lib/config/
    - lib/config/mocks/
    - lib/config/states/
    - lib/config/stories/
    - assets/icons/credit_cards/
    - assets/icons/tabs/
    - assets/icons/payment/
    - assets/icons/logins/
    - assets/images/
    - assets/images/country/
    - assets/images/favicon/
    - assets/html/
    - google_fonts/

flutter_intl:
  enabled: true
  use_deferred_loading: true

I have tried different methods and still same issue.


问:
Display Firestore Data with a datatype of map: Error: Objects are not valid as a React child
Retrieving from firestore:

```<code>const [product, setProduct] = useState([]);

  const getProducts = async () => {
    const querySnapshot = await getDocs(collection(db, "products"));
    const arr = [];
    querySnapshot.forEach((doc) => {
      arr.push({
        ...doc.data(),
        id: doc.id,
      });
    });
    setProduct(arr);
  };

  useEffect(() => {
    getProducts();
  }, []);
</code>```

I have this colorMap retrieved from Firestore:

```<code>export const data = [
  {
    colorMap: { red: 6, blue: 7, green: 8 },
    id: "a4TK38mByQbim4TwOHMY"
  },

  {
    colorMap: { Black: 20, Gold: 10 },
    id: "m08YmrlFxhxLxyc3hVjT"
  },
  {
    colorMap: { green: 9, red: 19 },
    id: "nN2w57SiDovbtQ6EBzGb"
  }
];
</code>```

How can I display it in the screen?

```<code> {product &&
        product.map((index) => (
          <>
            <b>{index.prodName + "-" + index.size + index.cat}</b>
            <li>{index.id}</li>
          </>
        ))}
</code>```

If I'll add this:

```<code><li>{index.colorMap}</li>
</code>```

It will cause an error:

Uncaught (in promise) Error: Objects are not valid as a React child
(found: object with keys {green, red, blue})

How do I resolve this? Any help would be appreciated. Thank you

答:
You can use Object.entries() and then map those items as shown below:

```<code>{product &&
  product.map((index) => (
  <div>
    <b>{index.prodName + "-" + index.size + index.cat}</b>
    <p>{index.id}</p>
    <ul>
      {
        Object.entries(index.colorMap).map((color) => (
          <li>{color[0]} - {color[1]}</li>
        ))
      }
    </ul>
  </div>
))}
</code>```

Body:
Retrieving from firestore:

const [product, setProduct] = useState([]);

  const getProducts = async () => {
    const querySnapshot = await getDocs(collection(db, "products"));
    const arr = [];
    querySnapshot.forEach((doc) => {
      arr.push({
        ...doc.data(),
        id: doc.id,
      });
    });
    setProduct(arr);
  };

  useEffect(() => {
    getProducts();
  }, []);

I have this colorMap retrieved from Firestore:

export const data = [
  {
    colorMap: { red: 6, blue: 7, green: 8 },
    id: "a4TK38mByQbim4TwOHMY"
  },

  {
    colorMap: { Black: 20, Gold: 10 },
    id: "m08YmrlFxhxLxyc3hVjT"
  },
  {
    colorMap: { green: 9, red: 19 },
    id: "nN2w57SiDovbtQ6EBzGb"
  }
];

How can I display it in the screen?

 {product &&
        product.map((index) => (
          <>
            {index.prodName + "-" + index.size + index.cat}

{index.id}

          </>
        ))}

If I'll add this:

{index.colorMap}

It will cause an error:

Uncaught (in promise) Error: Objects are not valid as a React child
(found: object with keys {green, red, blue})

How do I resolve this? Any help would be appreciated. Thank you

Body:
You can use Object.entries() and then map those items as shown below:

{product &&
  product.map((index) => (
  <div>
    <b>{index.prodName + "-" + index.size + index.cat}</b>
    <p>{index.id}</p>
    <ul>
      {
        Object.entries(index.colorMap).map((color) => (
          <li>{color[0]} - {color[1]}</li>
        ))
      }
    </ul>
  </div>
))}


问:
Fails to Generate Message
My message does not display after I run the code. Need some direction, I double checked my code. Might be a syntactical error somewhere

HTML-
<!doctype html>

```<code><html>
    <head>
        <title>Message Generator</title>
        <link rel="stylesheet" href="index.css">
        <center><div class="wordart blues"><span class="text">Message Generator</span></div></center>
    </head>
    <body>
        <div class="quoteDisplay"><center>Your random message will be displayed here</center></div>
        <div id="quote">
            <!--Quote will display here-->
        </div>
        <center><button onclick="messageGenerator()">Click Here</button></center>
        <script src="index.js"></script>
    </body>
</html>
</code>```

Javascript-

```<code>const first = ["Mom", "Dad", "Uncle", "Dog", "Cat", "Brother", "Sister", "Aunt", "Random Stranger", "Respect", "Honor", "Dignity", "Brain", "Life"]
const second = ["Ocean", "Sea", "Volcano", "Tornado", "Ditch", "Cave", "Typhoon", "Asia", "India"]
const third=["Unknown","To explore","To prove a point","To live life with no constraints","Just cause"]

function randomGenerate(value) {
    var item = value[Math.floor(Math.random() * value.length)];
    return item;
}

const messageGenerator = () => {
    let person = randomGenerate(first);
    let place = randomGenerate(second);
    let reason = randomGenerate(third);
    let finalSentence = `Your ${person} jumped in the ${place}\nReason: ${reason}`;
</code>```

document.getElementById("quoteDisplay").innerHTML=finalSentence;
}

答:
Looking at your HTML

```<code>    <div class="quoteDisplay"><center>Your random message will be displayed here</center></div>
    <div id="quote">
</code>```

Looking at your javascript
document.getElementById("quoteDisplay").innerHTML=finalSentence;

It should be document.getElementById("quote").innerText = finalSentence;

Title: Fails to Generate Message

Body:
My message does not display after I run the code. Need some direction, I double checked my code. Might be a syntactical error somewhere

HTML-
<!doctype html>

        <title>Message Generator</title>
        <link rel="stylesheet" href="index.css">

Message Generator

Your random message will be displayed here

        <button onclick="messageGenerator()">Click Here</button>

Javascript-

const first = ["Mom", "Dad", "Uncle", "Dog", "Cat", "Brother", "Sister", "Aunt", "Random Stranger", "Respect", "Honor", "Dignity", "Brain", "Life"]
const second = ["Ocean", "Sea", "Volcano", "Tornado", "Ditch", "Cave", "Typhoon", "Asia", "India"]
const third=["Unknown","To explore","To prove a point","To live life with no constraints","Just cause"]

function randomGenerate(value) {
    var item = value[Math.floor(Math.random() * value.length)];
    return item;
}

const messageGenerator = () => {
    let person = randomGenerate(first);
    let place = randomGenerate(second);
    let reason = randomGenerate(third);
    let finalSentence = `Your ${person} jumped in the ${place}\nReason: ${reason}`;

document.getElementById("quoteDisplay").innerHTML=finalSentence;
}

Body:
Looking at your HTML

    <div class="quoteDisplay"><center>Your random message will be displayed here</center></div>
    <div id="quote">

Looking at your javascript
document.getElementById("quoteDisplay").innerHTML=finalSentence;

It should be document.getElementById("quote").innerText = finalSentence;


问:
Similar libraries to react-query for angular
I have been working with both react and angular for quite some time and I encountered react-query, which is a very handy library.

So, for people who are wondering about the use case, react-query offers caching, infinite-query(Greatly helps with infinite scrolling or pagination), and retries on queries after intervals. I wish to achieve all this efficiently the same way react-query does.

Are there any similar well-maintained libraries for angular as well?
Suggestions are appreciated!

答:
Couple of recommendations

A good Graphql and over all rest consuming client Apollo
Angular

Caching with Apollo - Ex:

Infinite scrolling in Apollo - Ex:

Beside you can code using rxjs + Angular HttpModule as well, Ex: Infinite Scrolling, Caching


问:
Why a PHP warning appearing in Chrome but not in any other browser?
I'm writing a web application in PHP, and I'm getting the following warning in Google Chrome only:

Warning: Cannot use a scalar value as an array in
  M:\xampp\htdocs\MyProjectTitle\php\classes.php on line 18

Background: Please note that the web app works just fine in all browsers I tested (Firefox, Chrome, IE), but the warning appearing in Chrome is bugging the hell outta me.

Notes: I have tried restarting Chrome and clearing the Chrome cache. I have tried restarting the computer. I have tried searching the source code in FF and IE to see if the warning was just hidden, but to no avail. The warning is only popping up in Google Chrome, and I have no idea why.

UPDATE: Even though Safari also uses WebKit, it does not show the PHP warning. For some reason, Chrome is the only one that has the PHP warning. Weird stuff!

UPDATE: Here's the first 21 lines of code:

```<code>class Presenter {
    public function includeFile($filePath) {
        if (is_readable($filePath)) {
            include $filePath;
        } else {
            echo '<p><strong>ERROR 404</strong></p>';
            echo '<p>The resource you requested could not be located.</p>';
        }
    }

    public function sanitize($string) {
        return preg_replace("/\s/","_",$string);
    }

    public function set($varname,$value) {
        $this->$varname = $value;
        $_SESSION[$this->name][$varname] = $value;

        return $this;   // enables chaining!
    }

    // And there's more code after this, but I have cut it out here.
}
</code>```

Note: The above code is inside a PHP class.

UPDATE: I know exactly what lines of code are causing the warning in Chrome (although I still have no clue why Chrome is the only browser that shows the warning). Since my webapp works perfectly despite the warning in Chrome, I have used @ to suppress the warnings in Chrome (I'll fix the warning later).

答: I have the feeling that Chrome sends different data to the server, therefore you are having this error. If there's any $_POST data, or $_GET data please verify that with what other browsers send. You can easily display the contents using print_r() or var_dump() whichever you choose.

Body:
I'm writing a web application in PHP, and I'm getting the following warning in Google Chrome only:

Warning: Cannot use a scalar value as an array in
  M:\xampp\htdocs\MyProjectTitle\php\classes.php on line 18

Background: Please note that the web app works just fine in all browsers I tested (Firefox, Chrome, IE), but the warning appearing in Chrome is bugging the hell outta me.

Notes: I have tried restarting Chrome and clearing the Chrome cache. I have tried restarting the computer. I have tried searching the source code in FF and IE to see if the warning was just hidden, but to no avail. The warning is only popping up in Google Chrome, and I have no idea why.

UPDATE: Even though Safari also uses WebKit, it does not show the PHP warning. For some reason, Chrome is the only one that has the PHP warning. Weird stuff!

UPDATE: Here's the first 21 lines of code:

class Presenter {
    public function includeFile($filePath) {
        if (is_readable($filePath)) {
            include $filePath;
        } else {
            echo '
ERROR 404
';
            echo '
The resource you requested could not be located.
';
        }
    }

    public function sanitize($string) {
        return preg_replace("/\s/","_",$string);
    }

    public function set($varname,$value) {
        $this->$varname = $value;
        $_SESSION[$this->name][$varname] = $value;

        return $this;   // enables chaining!
    }

    // And there's more code after this, but I have cut it out here.
}

Note: The above code is inside a PHP class.

UPDATE: I know exactly what lines of code are causing the warning in Chrome (although I still have no clue why Chrome is the only browser that shows the warning). Since my webapp works perfectly despite the warning in Chrome, I have used @ to suppress the warnings in Chrome (I'll fix the warning later).


问:
How to change bottom line color and hint color of TextInputEditText?
I am using TextInputLayout and TetInputEditText to get floating hint. Now I want to change the color of hint and bottom line of an edit text. I want it to get changed when user clicks on edit text.

So I tried to change its color onClickListener of an edit text. But I did not found any change in color.

xml layout :

```<code><LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    android:orientation="vertical">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.TextInputLayout
            android:id="@+id/input_layout_item_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:layout_marginTop="20dp"
            android:paddingTop="05dp">
        <android.support.design.widget.TextInputEditText
            android:layout_width="240dp"
            android:layout_height="45dp"
            android:id="@+id/editTextItemName"
            android:layout_gravity="center_horizontal"
            android:hint="@string/item_name"
            android:textSize="12sp" />
        </android.support.design.widget.TextInputLayout>
    </LinearLayout>
</code>```

java code :

```<code>      public void setUpUI(){

        edt_Item_Name = (TextInputEditText) findViewById(R.id.editTextItemName);
        edt_Item_quantity = (TextInputEditText)findViewById(R.id.editTextItemQuantity);
        edt_Item_Unit = (TextInputEditText)findViewById(R.id.editTextItemUnit);

        textInput_Item_name = (TextInputLayout)findViewById(R.id.input_layout_item_name);
        textInput_Item_quantity = (TextInputLayout)findViewById(R.id.input_layout_item_quantity);
        textInput_Item_Unit = (TextInputLayout)findViewById(R.id.input_layout_item_unit);

        edt_Item_Name.getBackground().mutate().setColorFilter(ContextCompat.getColor(this, R.color.edtColor), PorterDuff.Mode.SRC_ATOP);

        edt_Item_Name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                edt_Item_Name.setHintTextColor(ContextCompat.getColor(SearchActivity.this, R.color.edtColor));
                edt_Item_Name.getBackground().mutate().setColorFilter(ContextCompat.getColor(SearchActivity.this, R.color.edtColor), PorterDuff.Mode.SRC_ATOP);
            }
        });
    }

}
</code>```

Output :

How can I achieve this?

答:
To change hint color, use:

android:textColorHint="@color/blue"```
</div>
</div>
</p>
<p>in your TextInputLayout, for example:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColorHint="@color/blue"
        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Text"/>
    </com.google.android.material.textfield.TextInputLayout>
      </code>```

Body:
I am using TextInputLayout and TetInputEditText to get floating hint. Now I want to change the color of hint and bottom line of an edit text. I want it to get changed when user clicks on edit text.

So I tried to change its color onClickListener of an edit text. But I did not found any change in color.

xml layout :

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    android:orientation="vertical">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.TextInputLayout
            android:id="@+id/input_layout_item_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:layout_marginTop="20dp"
            android:paddingTop="05dp">
        <android.support.design.widget.TextInputEditText
            android:layout_width="240dp"
            android:layout_height="45dp"
            android:id="@+id/editTextItemName"
            android:layout_gravity="center_horizontal"
            android:hint="@string/item_name"
            android:textSize="12sp" />
        </android.support.design.widget.TextInputLayout>
    </LinearLayout>

java code :

      public void setUpUI(){

        edt_Item_Name = (TextInputEditText) findViewById(R.id.editTextItemName);
        edt_Item_quantity = (TextInputEditText)findViewById(R.id.editTextItemQuantity);
        edt_Item_Unit = (TextInputEditText)findViewById(R.id.editTextItemUnit);

        textInput_Item_name = (TextInputLayout)findViewById(R.id.input_layout_item_name);
        textInput_Item_quantity = (TextInputLayout)findViewById(R.id.input_layout_item_quantity);
        textInput_Item_Unit = (TextInputLayout)findViewById(R.id.input_layout_item_unit);

        edt_Item_Name.getBackground().mutate().setColorFilter(ContextCompat.getColor(this, R.color.edtColor), PorterDuff.Mode.SRC_ATOP);

        edt_Item_Name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                edt_Item_Name.setHintTextColor(ContextCompat.getColor(SearchActivity.this, R.color.edtColor));
                edt_Item_Name.getBackground().mutate().setColorFilter(ContextCompat.getColor(SearchActivity.this, R.color.edtColor), PorterDuff.Mode.SRC_ATOP);
            }
        });
    }

}

Output :

How can I achieve this?

Body:
To change hint color, use:

android:textColorHint="@color/blue"

in your TextInputLayout, for example:

    <com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColorHint="@color/blue"
        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Text"/>
    </com.google.android.material.textfield.TextInputLayout>


问:
multiple emulators with ADB
I'm testing a multi-user Android APK that I'm developing. For my test requirements I have to run 4 different emulators with 2 physical devices, total of 6 devices running my APK at the same time. I'm using android X86 emulator running in Virtualbox machines, working good with no issues at all compared with my tablet devices.

My problem is when I try to connect with ADB to more than 2 emulators, Eclipse just can't handle it, all of a sudden my ADB server quits and restart again, sometimes just can't recover . If I connect and disconnect from all emulators and physical devices, mananing always 2 at the same time, everything runs ok, but when I try to connect third, adb crash.

Any pointers on this odd behaviour of ADB?

My development environment its Eclipse Galileo V 3.5.2 R35 with Java SE 1.6.0_26 and Android SDK with platform 2.2

答:
I've found that what really stabilize things is to ALWAYS have an Android virtual devicer connected to ADB. No matter what you do with other ABD devices connected, ADB hardly crash in this way.

I've tested with 2 physycal devices and 5 Android x86 emulators running in VirtualBox, connected in ADB server together with a virtual device. I could only put 4 devices connected at the same time, more than that crashed server and needs an Eclipse restart to put all things back to work.

In short, keep always an Android virtual device connected to ADB server.

Title: multiple emulators with ADB


问:
One member of a list higher than the other
I am trying to create a navbar in my site, but every time I try to align the logo to the left the page selection is put higher, anyone have a solution?

Screenshot:

This is the html code:

```<code>  <div class="NavBar">
    <ul class="Items">
      <li class="Logo">
        <img src="images/logo1.png" alt="IM2B - Play your brand">
      </li>
      <li class="Links">
        <a class="active" href="#home">Home</a>
        <a href="#news">News</a>
        <a href="#contact">Contact</a>
        <a href="#about">About</a>
      </li>
    </ul>
  </div>
</code>```

This is the css code:

```<code>.NavBar {
  list-style-type: none;
  overflow: hidden;
  background-color: #333;
  padding: 20px;
}

.NavBar .Items {
  margin: auto;
  width: 60%;
  text-align: center;
  list-style: none;
}

.NavBar .Logo {
  float: left;
}

.NavBar .Links {
  display: inline-block;
  padding: 0px 16px;
}

.NavBar .Links a {
  color: #f2f2f2;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

.NavBar .Links a:hover {
  background-color: #ddd;
  color: black;
}

.NavBar .Links a.active {
  background-color: #04AA6D;
  color: white;
}
</code>```

答:
Add flex property to your outside navitems' containers:</p>
```<code> .NavBar .Items {
     margin: auto;
     display: flex;
     justify-content: space-around;
     align-items: center;
     /* width: 60%; */
     text-align: center;
     list-style: none;
 }

.NavBar .Links {
     border: 2px solid white;
     display: flex;
     justify-content: space-around;
     align-items: center;
}
</code>```

Body:
I am trying to create a navbar in my site, but every time I try to align the logo to the left the page selection is put higher, anyone have a solution?

Screenshot:

This is the html code:

        Home
        News
        Contact
        About

This is the css code:

.NavBar {
  list-style-type: none;
  overflow: hidden;
  background-color: #333;
  padding: 20px;
}

.NavBar .Items {
  margin: auto;
  width: 60%;
  text-align: center;
  list-style: none;
}

.NavBar .Logo {
  float: left;
}

.NavBar .Links {
  display: inline-block;
  padding: 0px 16px;
}

.NavBar .Links a {
  color: #f2f2f2;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

.NavBar .Links a:hover {
  background-color: #ddd;
  color: black;
}

.NavBar .Links a.active {
  background-color: #04AA6D;
  color: white;
}

Body:
Add flex property to your outside navitems' containers:

 .NavBar .Items {
     margin: auto;
     display: flex;
     justify-content: space-around;
     align-items: center;
     /* width: 60%; */
     text-align: center;
     list-style: none;
 }

.NavBar .Links {
     border: 2px solid white;
     display: flex;
     justify-content: space-around;
     align-items: center;
}


问:
pinject basic use case fails
Tried to use pinject (https://github.com/google/pinject) today for the first time, but for some reason this basic test fails on assert:

```<code>def test_container():
    from pinject import new_object_graph
    graph = new_object_graph(modules=None, classes=[Repository])
    repo1 = graph.provide(Repository)
    repo2 = graph.provide(Repository)
    assert repo1 is repo2
</code>```

Documentation states that:

Singleton scope (SINGLETON) is the default and always caches

答:
I don't know this library, but I notice in the documentation an example that is similar looking to yours and yet is completely different in terms of what it is expecting the pinspect library to do:

```<code>import pinject

class SomeClass(object):
    def __init__(self, foo):
        self.foo = foo

class SomeBindingSpec(pinject.BindingSpec):
        def provide_foo(self):
            return object()

obj_graph = pinject.new_object_graph(binding_specs=[SomeBindingSpec()])
some_class_1 = obj_graph.provide(SomeClass)
some_class_2 = obj_graph.provide(SomeClass)
print(some_class_1.foo is some_class_2.foo)
</code>```

This code is not testing if the two objects returned by obj_graph.provide are the same object.  Rather, those objects have had an object injected into them as attribute foo.  The code is checking to see if the same object has been injected into the two SomeClass objects.

The line that checks for equal objects is telling:

```<code>some_class_1.foo is some_class_2.foo
</code>```

Not only is this checking that the foo attribute of each some_class is the same object, it's pretty much telling you that you shouldn't expect some_class_1 and some_class_2 to be the same object, or why bother to check to see if their foo attributes are the same. If the two outer objects are the same object, then of course any attribute gotten by either reference to that one object would be the same.

So it seems to me that you are misunderstanding how the library works and at what point the notion of a SINGLETON is introduced.

Title: pinject basic use case fails

Body:
Tried to use pinject (https://github.com/google/pinject) today for the first time, but for some reason this basic test fails on assert:

def test_container():
    from pinject import new_object_graph
    graph = new_object_graph(modules=None, classes=[Repository])
    repo1 = graph.provide(Repository)
    repo2 = graph.provide(Repository)
    assert repo1 is repo2

Documentation states that:

Singleton scope (SINGLETON) is the default and always caches

Body:
I don't know this library, but I notice in the documentation an example that is similar looking to yours and yet is completely different in terms of what it is expecting the pinspect library to do:

import pinject

class SomeClass(object):
    def __init__(self, foo):
        self.foo = foo

class SomeBindingSpec(pinject.BindingSpec):
        def provide_foo(self):
            return object()

obj_graph = pinject.new_object_graph(binding_specs=[SomeBindingSpec()])
some_class_1 = obj_graph.provide(SomeClass)
some_class_2 = obj_graph.provide(SomeClass)
print(some_class_1.foo is some_class_2.foo)

This code is not testing if the two objects returned by obj_graph.provide are the same object.  Rather, those objects have had an object injected into them as attribute foo.  The code is checking to see if the same object has been injected into the two SomeClass objects.

The line that checks for equal objects is telling:

some_class_1.foo is some_class_2.foo

Not only is this checking that the foo attribute of each some_class is the same object, it's pretty much telling you that you shouldn't expect some_class_1 and some_class_2 to be the same object, or why bother to check to see if their foo attributes are the same. If the two outer objects are the same object, then of course any attribute gotten by either reference to that one object would be the same.

So it seems to me that you are misunderstanding how the library works and at what point the notion of a SINGLETON is introduced.


问:
EF Core Connection to Azure SQL with Managed Identity
I am using EF Core to connect to a Azure SQL Database deployed to Azure App Services. I am using an access token (obtained via the Managed Identities) to connect to Azure SQL database.

Here is how I am doing that:

Startup.cs:

```<code>public void ConfigureServices(IServiceCollection services)
{
    //code ignored for simplicity
    services.AddDbContext<MyCustomDBContext>();

    services.AddTransient<IDBAuthTokenService, AzureSqlAuthTokenService>();
}
</code>```

MyCustomDBContext.cs

```<code>public partial class MyCustomDBContext : DbContext
{
    public IConfiguration Configuration { get; }
    public IDBAuthTokenService authTokenService { get; set; }

    public CortexContext(IConfiguration configuration, IDBAuthTokenService tokenService, DbContextOptions<MyCustomDBContext> options)
        : base(options)
    {
        Configuration = configuration;
        authTokenService = tokenService;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        SqlConnection connection = new SqlConnection();
        connection.ConnectionString = Configuration.GetConnectionString("defaultConnection");
        connection.AccessToken = authTokenService.GetToken().Result;

        optionsBuilder.UseSqlServer(connection);
    }
}
</code>```

AzureSqlAuthTokenService.cs

```<code>public class AzureSqlAuthTokenService : IDBAuthTokenService
{
    public async Task<string> GetToken()
    {
        AzureServiceTokenProvider provider = new AzureServiceTokenProvider();
        var token = await provider.GetAccessTokenAsync("https://database.windows.net/");

        return token;
    }
}
</code>```

This works fine and I can get data from the database. But I am not sure if this is the right way to do it.

My questions:

Is this a right way to do it or will it have issues with performance?

Do I need to worry about token expiration? I am not caching the token as of now.

Does EF Core has any better way to handle this?

答:
After the arrival of Microsoft.Data.SqlClient - new version of Entity framework core connector to sql - its very simple now:

```<code>Install-Package Microsoft.Data.SqlClient -Version 4.0.1
</code>```

Add connection string to Dotnet core application like below:

```<code>"Server=tcp:<server-name>.database.windows.net;Authentication=Active Directory Default; Database=<database-name>;"
</code>```

Then use it for conencting to Azure SQL using managed identity via Azure SQL connection like below:

```<code>            using (SqlConnection _connection = new SqlConnection(sqlConnectionString))
            {
                _connection.Open();

                // do some stuff with the sqlconnection to read or write record in SQL.

                _connection.Close();

                return true;
            }
</code>```

Refer here for detailed article

Body:
I am using EF Core to connect to a Azure SQL Database deployed to Azure App Services. I am using an access token (obtained via the Managed Identities) to connect to Azure SQL database.

Here is how I am doing that:

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    //code ignored for simplicity
    services.AddDbContext<MyCustomDBContext>();

    services.AddTransient<IDBAuthTokenService, AzureSqlAuthTokenService>();
}

MyCustomDBContext.cs

public partial class MyCustomDBContext : DbContext
{
    public IConfiguration Configuration { get; }
    public IDBAuthTokenService authTokenService { get; set; }

    public CortexContext(IConfiguration configuration, IDBAuthTokenService tokenService, DbContextOptions<MyCustomDBContext> options)
        : base(options)
    {
        Configuration = configuration;
        authTokenService = tokenService;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        SqlConnection connection = new SqlConnection();
        connection.ConnectionString = Configuration.GetConnectionString("defaultConnection");
        connection.AccessToken = authTokenService.GetToken().Result;

        optionsBuilder.UseSqlServer(connection);
    }
}

AzureSqlAuthTokenService.cs

public class AzureSqlAuthTokenService : IDBAuthTokenService
{
    public async Task<string> GetToken()
    {
        AzureServiceTokenProvider provider = new AzureServiceTokenProvider();
        var token = await provider.GetAccessTokenAsync("https://database.windows.net/");

        return token;
    }
}

This works fine and I can get data from the database. But I am not sure if this is the right way to do it.

My questions:

Is this a right way to do it or will it have issues with performance?

Do I need to worry about token expiration? I am not caching the token as of now.

Does EF Core has any better way to handle this?

Body:
After the arrival of Microsoft.Data.SqlClient - new version of Entity framework core connector to sql - its very simple now:

Install-Package Microsoft.Data.SqlClient -Version 4.0.1

Add connection string to Dotnet core application like below:

"Server=tcp:<server-name>.database.windows.net;Authentication=Active Directory Default; Database=<database-name>;"

Then use it for conencting to Azure SQL using managed identity via Azure SQL connection like below:

            using (SqlConnection _connection = new SqlConnection(sqlConnectionString))
            {
                _connection.Open();

                // do some stuff with the sqlconnection to read or write record in SQL.

                _connection.Close();

                return true;
            }

Refer here for detailed article


问:
message.channel.awaitmessages() filter not working with constant id
I have this command that is supposed to only accept user inputs from me.
I am trying to use this code but there is nothing in the console.

me = await client.users.fetch("< my id >")
mee = msg
mee.author = me
let filter = m => m.author.id === mee.author.id
msg.channel.awaitMessages(filter, { max: 1, time: 50000, errors:
   ['time'], })
      .then(async (collected) => {
      mesg = collected.first
      console.log(mesg.content)
   })
```

答:
There's really no reason to be fetching a user if the only thing you need is their ID - which you're already using for the fetch itself.

What you're currently trying to do - overriding the author of an existing message - doesn't really make much sense.

Your filter can (likely) be simplified down to the following.

let filter = m => m.author.id === "<your id>"
```