问:
How to parse string value from xlworksheet to time(hh:mm) value into the newsheet?
I can't convert my object "Time" which has properties in0 and out0 from string to DateTime.

```<code>for (int row = 2; row <= rw; row++)
                    {
                        for (cCnt = 6; cCnt <= 6; cCnt++)
                        {
                            var in0 = (String)(xlworkSheet.Cells[row, 7]
                             as Excel.Range).Value;
                            Time.In0 = in0;
                            Console.WriteLine(Time.In0.ToString());
                            DateTime dtnew = DateTime.Parse(in0);

                            Excel.Range formatRange;
                            formatRange = xlNewSheet.Cells[row, 7];
                            formatRange.NumberFormat = "hh:mm";
                            xlNewSheet.Cells[row, 7].Value = Time.In0;

                        }
                    }
 //this is my class
  public class DateandTime
      {
       public string In0 { get; set; }
       public string Out0 { get; set; }
       public string In1 { get; set; }
       public string Out1 { get; set; }
       public string In2 { get; set; }
       public string Out2 { get; set; }
       public string In3 { get; set; }
       public string Out3 { get; set; }
       public string In4 { get; set; }
       public string Out4 { get; set; }
       public string break_time { get; set; }

         }
</code>```

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: String was not recognized as a valid DateTime.

答:
The reason you're getting this error is that when you use DateTime.Parse(string), the current culture of the thread is used to interpret that date/time. While .NET will assume it is for today if you don't provide a date, the time format is unknown to it: it doesn't know how to interpret a 4 digit number. We have to provide information as to how to interpret this string.

One way you could approach this is to use DateTime's TryParseExact method, and then format the result:

```<code>private static bool TryFormatTime(string time, out string formattedTime)
{
    formattedTime = null;
    DateTime parsedDate;
    if (!DateTime.TryParseExact(time, "HHmm", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out parsedDate))
    {
        return false;
    }

    formattedTime = parsedDate.ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture);
    return true;
}
</code>```

Or you can just handle it as a string manipulation. The following code verifies the length, that all of the characters are digits, and then adds a ::

```<code>private static bool TryFormatTime(string time, out string formattedTime)
{
    formattedTime = null;
    if (time.Length != 4 || !time.All(c => char.IsDigit(c)))
    {
        return false;
    }

    formattedTime = string.Format("{0}:{1}", time.Substring(0, 2), time.Substring(2, 2));
    return true;
}
</code>```

Both of these can be used as follows:

```<code>if (TryFormatTime("0655", out time))
{
    Console.WriteLine(time);
}
else
{
    Console.WriteLine("bad time");
}
</code>```

Try them online

Body:
I can't convert my object "Time" which has properties in0 and out0 from string to DateTime.

for (int row = 2; row <= rw; row++)
                    {
                        for (cCnt = 6; cCnt <= 6; cCnt++)
                        {
                            var in0 = (String)(xlworkSheet.Cells[row, 7]
                             as Excel.Range).Value;
                            Time.In0 = in0;
                            Console.WriteLine(Time.In0.ToString());
                            DateTime dtnew = DateTime.Parse(in0);

                            Excel.Range formatRange;
                            formatRange = xlNewSheet.Cells[row, 7];
                            formatRange.NumberFormat = "hh:mm";
                            xlNewSheet.Cells[row, 7].Value = Time.In0;

                        }
                    }
 //this is my class
  public class DateandTime
      {
       public string In0 { get; set; }
       public string Out0 { get; set; }
       public string In1 { get; set; }
       public string Out1 { get; set; }
       public string In2 { get; set; }
       public string Out2 { get; set; }
       public string In3 { get; set; }
       public string Out3 { get; set; }
       public string In4 { get; set; }
       public string Out4 { get; set; }
       public string break_time { get; set; }

         }

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: String was not recognized as a valid DateTime.

Body:
The reason you're getting this error is that when you use DateTime.Parse(string), the current culture of the thread is used to interpret that date/time. While .NET will assume it is for today if you don't provide a date, the time format is unknown to it: it doesn't know how to interpret a 4 digit number. We have to provide information as to how to interpret this string.

One way you could approach this is to use DateTime's TryParseExact method, and then format the result:

private static bool TryFormatTime(string time, out string formattedTime)
{
    formattedTime = null;
    DateTime parsedDate;
    if (!DateTime.TryParseExact(time, "HHmm", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out parsedDate))
    {
        return false;
    }

    formattedTime = parsedDate.ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture);
    return true;
}

Or you can just handle it as a string manipulation. The following code verifies the length, that all of the characters are digits, and then adds a ::

private static bool TryFormatTime(string time, out string formattedTime)
{
    formattedTime = null;
    if (time.Length != 4 || !time.All(c => char.IsDigit(c)))
    {
        return false;
    }

    formattedTime = string.Format("{0}:{1}", time.Substring(0, 2), time.Substring(2, 2));
    return true;
}

Both of these can be used as follows:

if (TryFormatTime("0655", out time))
{
    Console.WriteLine(time);
}
else
{
    Console.WriteLine("bad time");
}

Try them online


来源: stackexchange

问:
Registry.LocalMachine.OpenSubKey() returns a result different from Registry Editor
I'm trying to Create an installer for my CAD plugin, and need to get the AutoCAD install location. but the return values of RegistryKey.GetSubKeyNames() is different from what I see in Registry Editor.

```<code>string registry_key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using (Microsoft.Win32.RegistryKey key = Registry.LocalMachine.OpenSubKey(registry_key))
{
    foreach (string subkey_name in key.GetSubKeyNames())
    {
        Console.WriteLine(subkey_name);
    }
}
</code>```

output:

AddressBook

  Autodesk Application Manager

  Autodesk Content Service

  Autodesk Material Library 2015

  Autodesk Material Library Base Resolution Image Library 2015

  Connection Manager

  DirectDrawEx

  DXM_Runtime

  f528b707

  Fontcore

  ...

In Registry Editor:

animizvideocn_is1

  AutoCAD 2015

  Autodesk 360

  Connection Manager

  ...

AutoCAD 2015 is what i need

答:
Your installer seems to be a 32 bit application, or at least runs as a 32 bit process.

Therefore, Windows redirects

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

to

HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall

To access the non redirected node, follow the instructions here.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to Create an installer for my CAD plugin, and need to get the AutoCAD install location. but the return values of RegistryKey.GetSubKeyNames() is different from what I see in Registry Editor.

string registry_key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using (Microsoft.Win32.RegistryKey key = Registry.LocalMachine.OpenSubKey(registry_key))
{
    foreach (string subkey_name in key.GetSubKeyNames())
    {
        Console.WriteLine(subkey_name);
    }
}

output:

AddressBook

  Autodesk Application Manager

  Autodesk Content Service

  Autodesk Material Library 2015

  Autodesk Material Library Base Resolution Image Library 2015

  Connection Manager

  DirectDrawEx

  DXM_Runtime

  f528b707

  Fontcore

  ...

In Registry Editor:

animizvideocn_is1

  AutoCAD 2015

  Autodesk 360

  Connection Manager

  ...

AutoCAD 2015 is what i need


问:
Return different datatypes in a method in java
I have a very silly question in java. I have a main method which in turns calls a method passing one string value. But in return I need to get 3 string values. Can someone please assist?

In main method, I pass only one string value and it has to return 3 string or may be at times 2 string and one int.

```<code>public static void main(String[] args) {
        List <String> ls= cusmethod("string1");
        ls.get(0); //get string A
}

Private static string cusmethod(String test)
{
    String A = "A"+test;
    String B = "B"+test;
    String C = "C"+test;

    // Need to return all these 3 string to main method.
    return A , B, C;
}
</code>```

The method should return the 3 string values to the main method. Please advise how to achieve this. I am not sure how to return these strings to main method and how to retrieve these string in main

答:
Try returning a list in your helper method:</p>

```<code>private static List<String> cusmethod(String test) {
    List<String> list = new ArrayList<>();
    list.add("A" + test);
    list.add("B" + test);
    list.add("C" + test);

    return list;
}
</code>```

Body:
I have a very silly question in java. I have a main method which in turns calls a method passing one string value. But in return I need to get 3 string values. Can someone please assist?

In main method, I pass only one string value and it has to return 3 string or may be at times 2 string and one int.

public static void main(String[] args) {
        List <String> ls= cusmethod("string1");
        ls.get(0); //get string A
}

Private static string cusmethod(String test)
{
    String A = "A"+test;
    String B = "B"+test;
    String C = "C"+test;

    // Need to return all these 3 string to main method.
    return A , B, C;
}

The method should return the 3 string values to the main method. Please advise how to achieve this. I am not sure how to return these strings to main method and how to retrieve these string in main

Body:
Try returning a list in your helper method:

private static List<String> cusmethod(String test) {
    List<String> list = new ArrayList<>();
    list.add("A" + test);
    list.add("B" + test);
    list.add("C" + test);

    return list;
}


问:
Not properly set Data in GridView
i'm trying retrieve data from database and dispay in gridview. for create Header i'm using HeaderTemplet Tag. but in gridview always first column of employee id is blank.

my code is as under of aspx page:

```<code><head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView1" runat="server" Width="99%" GridLines="Both" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="false">
                <Columns>
                    <asp:TemplateField>
                        <HeaderTemplate>

                            <tr>

                                <th style="padding: 2.5px; width: 10%;" >eid</th>

                                <th style="padding: 2.5px; width: 55%;" >First Name</th>
                                <th style="padding: 2.5px;" >Last Name</th>

                        </HeaderTemplate>

                    </asp:TemplateField>

                    <asp:BoundField DataField="idemp" />
                    <asp:BoundField DataField="fname" />
                    <asp:BoundField DataField="lname" />

<asp:TemplateField>

                    <ItemTemplate>

                        <asp:GridView ID="GridView2" runat="server" Width="99%" GridLines="Both" AutoGenerateColumns="false" CssClass="ChildGrid">

                        </asp:GridView>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

    </div>
</form>
</code>```

code behind:

```<code>namespace WebApplication2
{
    public partial class WebForm1 : System.Web.UI.Page

    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Populate the GridView.
                bindGridview();
            }

        }

        public void bindGridview()
        {
            DataTable dt = new DataTable();
            string constr = @"server=127.0.0.1;user id=root;pwd=n0711p2010p;database=emp";
            using (MySqlConnection con = new MySqlConnection(constr))
            {
                MySqlCommand cmd = new MySqlCommand("select idemp,fname,lname from emp", con);
                con.Open();
                MySqlDataReader dtreader = cmd.ExecuteReader();
                dt.Load(dtreader);
                if (dt.Rows.Count >0)
                {
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                    con.Close();

                }
            }

        }

        //RowDataBound Event
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //Checking the RowType of the Row
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataTable dt = new DataTable();

                string constr = @"server=127.0.0.1;user id=root;pwd=n0711p2010p;database=emp";
                using (MySqlConnection con = new MySqlConnection(constr))
                {
                    con.Open();
                    GridView child_gridview = (GridView)e.Row.FindControl("GridView2");
                    String CountryId = (e.Row.RowIndex+1).ToString();
                    MySqlCommand cmd = new MySqlCommand("select salary,post from emp where idemp="+CountryId, con);

                    MySqlDataReader dtreader = cmd.ExecuteReader();
                    dt.Load(dtreader);
                    if (dt.Rows.Count > 0)
                    {
                        child_gridview.DataSource = dt;
                        child_gridview.DataBind();

                    }
                }
            }
        }

    }
}
</code>```

and output is as under:

first column of gridview is always empty.when using HeaderTemplet tag.
and  i want to achieve like this.

答:
Seems like you are retrieving the data just fine but not displaying it properly.

You are mistakenly using  TemplateField to define headers.

You can simply do the following:

```<code><asp:GridView ID="GridView1" runat="server" Width="99%" GridLines="Both" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="false">
                <Columns>

                <asp:BoundField DataField="idemp" headertext="Employee ID" />
                <asp:BoundField DataField="fname" headertext="First Name" />
                <asp:BoundField DataField="lname" headertext="Last Name" />

        </Columns>
    </asp:GridView>
</code>```

As you can see the Header names are defined right in bound column.

Enjoy, and let me know if still having issue

Title: Not properly set Data in GridView

Body:
i'm trying retrieve data from database and dispay in gridview. for create Header i'm using HeaderTemplet Tag. but in gridview always first column of employee id is blank.

my code is as under of aspx page:

    <title></title>

    <form id="form1" runat="server">

            <asp:GridView ID="GridView1" runat="server" Width="99%" GridLines="Both" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="false">
                <Columns>
                    <asp:TemplateField>
                        <HeaderTemplate>

                                eid

                                First Name
                                Last Name

                        </HeaderTemplate>

                    </asp:TemplateField>

                    <asp:BoundField DataField="idemp" />
                    <asp:BoundField DataField="fname" />
                    <asp:BoundField DataField="lname" />

<asp:TemplateField>

                    <ItemTemplate>

                        <asp:GridView ID="GridView2" runat="server" Width="99%" GridLines="Both" AutoGenerateColumns="false" CssClass="ChildGrid">

                        </asp:GridView>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

</form>

code behind:

namespace WebApplication2
{
    public partial class WebForm1 : System.Web.UI.Page

    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Populate the GridView.
                bindGridview();
            }

        }

        public void bindGridview()
        {
            DataTable dt = new DataTable();
            string constr = @"server=127.0.0.1;user id=root;pwd=n0711p2010p;database=emp";
            using (MySqlConnection con = new MySqlConnection(constr))
            {
                MySqlCommand cmd = new MySqlCommand("select idemp,fname,lname from emp", con);
                con.Open();
                MySqlDataReader dtreader = cmd.ExecuteReader();
                dt.Load(dtreader);
                if (dt.Rows.Count >0)
                {
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                    con.Close();

                }
            }

        }

        //RowDataBound Event
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //Checking the RowType of the Row
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataTable dt = new DataTable();

                string constr = @"server=127.0.0.1;user id=root;pwd=n0711p2010p;database=emp";
                using (MySqlConnection con = new MySqlConnection(constr))
                {
                    con.Open();
                    GridView child_gridview = (GridView)e.Row.FindControl("GridView2");
                    String CountryId = (e.Row.RowIndex+1).ToString();
                    MySqlCommand cmd = new MySqlCommand("select salary,post from emp where idemp="+CountryId, con);

                    MySqlDataReader dtreader = cmd.ExecuteReader();
                    dt.Load(dtreader);
                    if (dt.Rows.Count > 0)
                    {
                        child_gridview.DataSource = dt;
                        child_gridview.DataBind();

                    }
                }
            }
        }

    }
}

and output is as under:

first column of gridview is always empty.when using HeaderTemplet tag.
and  i want to achieve like this.

Body:
Seems like you are retrieving the data just fine but not displaying it properly.

You are mistakenly using  TemplateField to define headers.

You can simply do the following:

<asp:GridView ID="GridView1" runat="server" Width="99%" GridLines="Both" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="false">
                <Columns>

                <asp:BoundField DataField="idemp" headertext="Employee ID" />
                <asp:BoundField DataField="fname" headertext="First Name" />
                <asp:BoundField DataField="lname" headertext="Last Name" />

        </Columns>
    </asp:GridView>

As you can see the Header names are defined right in bound column.

Enjoy, and let me know if still having issue


问:
Connect to CRM and get data
I'm writing an ASP.NET app that should connect to dynamics CRM and fetch the contacts info. In the view it should return a list of the contacts with their info. There is some data in the testing CRM I'm provided with but I can't get the entities (e.g. table name and its columns), so I can't create my models in VS, since I don't know what props to put there.

Is there a way to get the entites with the code, or how can this problem be solved?

I've tried early-bound generator, and it won't work. I tried with ADO.NET entity data model but doesn't work either.

答:
This article will give you step by step way to connect to CRM.

Once you get sucessfully connected to CRM, try below code which will give you complete information about all the contact Records.

```<code>try
 {
 ClientCredentials clientCredentials = new ClientCredentials();
 clientCredentials.UserName.UserName = "<ProvideUserName>@<ProvideYourOrgName>.onmicrosoft.com";
 clientCredentials.UserName.Password = "<ProvideYourPassword>";

// For Dynamics 365 Customer Engagement V9.X, set Security Protocol as TLS12
 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// Get the URL from CRM, Navigate to Settings -> Customizations -> Developer Resources
// Copy and Paste Organization Service Endpoint Address URL
organizationService = (IOrganizationService)new OrganizationServiceProxy(new Uri("https://<ProvideYourOrgName>.api.<CRMRegion>.dynamics.com/XRMServices/2011/Organization.svc"),
 null, clientCredentials, null);

if (organizationService != null)
 {
 Guid userid = ((WhoAmIResponse)organizationService.Execute(new WhoAmIRequest())).UserId;

if (userid != Guid.Empty)
 {
 Console.WriteLine("Connection Established Successfully...");
 // your logic here.
                    queryExpressionTest(organizationService);

 }
 }
 else
 {
 Console.WriteLine("Failed to Established Connection!!!");
 }
 }
 catch (Exception ex)
 {
 Console.WriteLine("Exception caught - " + ex.Message);
 }
 Console.ReadKey();
 }
        private static void queryExpressionTest(IOrganizationService organizationService)
        {
            QueryExpression qe = new QueryExpression();
            qe.EntityName = "contact";
            qe.ColumnSet= new ColumnSet(true); // this will give you all the columns of contact record
            //qe.ColumnSet= new ColumnSet("name", "accountnumber"); you could also restrict which particualr attributes you wish to retrieve from contact record.

            EntityCollection coll = organizationService.RetrieveMultiple(qe);
            foreach (Entity cont in coll.Entities)
            {
                Console.WriteLine("Name of contact: " + cont.GetAttributeValue<string>("fullname"));
                Console.WriteLine("Email of contact " + cont.GetAttributeValue<string>("email"));
                /**
                Now you can add all the attributes you wish to show
                */
            }

        }
</code>```

Title: Connect to CRM and get data

Body:
This article will give you step by step way to connect to CRM.

Once you get sucessfully connected to CRM, try below code which will give you complete information about all the contact Records.

try
 {
 ClientCredentials clientCredentials = new ClientCredentials();
 clientCredentials.UserName.UserName = "<ProvideUserName>@<ProvideYourOrgName>.onmicrosoft.com";
 clientCredentials.UserName.Password = "<ProvideYourPassword>";

// For Dynamics 365 Customer Engagement V9.X, set Security Protocol as TLS12
 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// Get the URL from CRM, Navigate to Settings -> Customizations -> Developer Resources
// Copy and Paste Organization Service Endpoint Address URL
organizationService = (IOrganizationService)new OrganizationServiceProxy(new Uri("https://<ProvideYourOrgName>.api.<CRMRegion>.dynamics.com/XRMServices/2011/Organization.svc"),
 null, clientCredentials, null);

if (organizationService != null)
 {
 Guid userid = ((WhoAmIResponse)organizationService.Execute(new WhoAmIRequest())).UserId;

if (userid != Guid.Empty)
 {
 Console.WriteLine("Connection Established Successfully...");
 // your logic here.
                    queryExpressionTest(organizationService);

 }
 }
 else
 {
 Console.WriteLine("Failed to Established Connection!!!");
 }
 }
 catch (Exception ex)
 {
 Console.WriteLine("Exception caught - " + ex.Message);
 }
 Console.ReadKey();
 }
        private static void queryExpressionTest(IOrganizationService organizationService)
        {
            QueryExpression qe = new QueryExpression();
            qe.EntityName = "contact";
            qe.ColumnSet= new ColumnSet(true); // this will give you all the columns of contact record
            //qe.ColumnSet= new ColumnSet("name", "accountnumber"); you could also restrict which particualr attributes you wish to retrieve from contact record.

            EntityCollection coll = organizationService.RetrieveMultiple(qe);
            foreach (Entity cont in coll.Entities)
            {
                Console.WriteLine("Name of contact: " + cont.GetAttributeValue<string>("fullname"));
                Console.WriteLine("Email of contact " + cont.GetAttributeValue<string>("email"));
                /**
                Now you can add all the attributes you wish to show
                */
            }

        }


问:
Homestead: downgrade to MySQL 5.6 by reinstalling the box
I've just set up my local environment based on the latest Homestead box. The box comes with MySQL 5.7, which causes various problems with my migrations. The migrations were working fine on MySQL 5.6.

Now, the production server uses 5.6, so (instead of adjusting all the failing migration queries) I would like to downgrade my local MySQL to version 5.6, to get the localhost working.

Obviously, this can be done via vagrant ssh (manual downgrade). However, I was thinking, is there a way to reinstall the Homestead box using an older version that uses MySQL 5.6?

Note:

Surely, some of you will suggest getting the queries right for version 5.7 in case of possible upgrade on production server. I also consider that. But currently I just want to know how do I get my hands the on older Homestead versions.

答:
Just execute this command inside vagrant:

```<code>apt-get install -y mysql-server-5.6
</code>```

After this, mysql version will be 5.6

ContentLicense: CC BY-SA 3.0

Body:
Just execute this command inside vagrant:

apt-get install -y mysql-server-5.6

After this, mysql version will be 5.6


问:
calling multiple action from an effect
please watch the edit

I have an effect that will retrieve from http a list of object.

When retrieved, I want that same effect to dispatch for each object an action that will open a channel in order to get live update of those object

```<code>  @Effect()
  getUsedDrones$ = this.actions$.pipe(
    ofType<featureActions.GetUsedDronesRequest>(featureActions.ActionTypes.GetUsedDronesRequest),
    switchMap((action) =>
      this.droneDataService.getUsedDrones(action.payload).pipe(
        map(drones => {
          drones.forEach((drone) => new featureActions.OpenUsedDroneUpdateChannelRequest({ droneId: drone.id, projectId : environment.projectId }));
          new featureActions.GetUsedDronesSuccess({drones});
        }),
        catchError((error: HttpErrorResponse) => {
          this.snackBar.open(this.translate.instant('ERRORS.HTTP.GENERIC'), this.translate.instant('BUTTONS.OK'), {duration: 2500});
          return of(new featureActions.GetUsedDronesFailed({error}));
        }),
      ),
    ),
  );
</code>```

basically, after calling my api and retrieving the drones, I need to call this for each drone

```<code>    map(drones => {
      drones.forEach((drone) => new featureActions.OpenUsedDroneUpdateChannelRequest({ droneId: drone.id, projectId : environment.projectId }));
      new featureActions.GetUsedDronesSuccess({drones});
    }),
</code>```

and then trigger the success of the retrieval.

the other action will basically call this

```<code>  startUpdate$ = this.actions$.pipe(
    ofType<featureActions.OpenUsedDroneUpdateChannelRequest>(featureActions.ActionTypes.OpenUsedDroneUpdateChannelRequest),
    switchMap((action) =>
      this.droneDataService.openUsedDroneUpdateChannel(action.payload).pipe(
        map(result => {
          if (this.currentUpdateEventList.has(action.payload.droneId)) { return; }
          new featureActions.OpenUsedDroneUpdateChannelSuccess(result);
          this.currentUpdateEventList.set(action.payload.droneId, [
            `get_position_drone${action.payload.droneId}`,
            `get_status_drone${action.payload.droneId}`
          ])
          this.sseService.subscribe(`get_position_drone${action.payload.droneId}`, (position: Cartesian3) => {
            new featureActions.SetUsedDronePosition({droneId : action.payload.droneId, position});
          });
          this.sseService.subscribe(`get_status_drone${action.payload.droneId}`, (status: IDroneStatus) => {
            new featureActions.SetUsedDroneStatus({droneId : action.payload.droneId, status});
          });
        }),
        catchError((error: HttpErrorResponse) => {
          this.snackBar.open(this.translate.instant('ERRORS.HTTP.DRONE.NOT_UPDATABLE', {droneId: action.payload.droneId}), this.translate.instant('BUTTONS.OK'), {duration: 2500});
          return of(new featureActions.OpenUsedDroneUpdateChannelFailed({error}));
        }),
      )
    )
  );
</code>```

Now, the problem I have is the following, My first foreach return this error

core.js:15724 ERROR Error: Effect "UsedDronesEffect.getUsedDrones$"
  dispatched an invalid action: undefined

core.js:15724 ERROR TypeError: Actions must be objects
      at ActionsSubject.push../node_modules/@ngrx/store/fesm5/store.js.ActionsSubject.next

EDIT : I Fixed the error but, now my forEach action are not dispatched

```<code>    map(drones => {

      drones.forEach((drone) => new featureActions.OpenUsedDroneUpdateChannelRequest({ droneId: drone.id, projectId : environment.projectId }));
      return new featureActions.GetUsedDronesSuccess({drones});
    }),
</code>```

How can I return a list of action based on the amount of drone I have, and end up with success ?

EDIT 2 :

shouldn't this work ?

```<code>map(drones => {
  const actions = [];
  drones.forEach((drone) => actions.push(new featureActions.OpenUsedDroneUpdateChannelRequest({ droneId: drone.id, projectId : environment.projectId })));
  actions.push(new featureActions.GetUsedDronesSuccess({drones}));
  return merge(actions);
}),
</code>```

答:
Check this out. I hope this will resolve your issue.

dispatching multiple actions from single Effect @ngrx

Title: calling multiple action from an effect

Body:
please watch the edit

I have an effect that will retrieve from http a list of object.

When retrieved, I want that same effect to dispatch for each object an action that will open a channel in order to get live update of those object

  @Effect()
  getUsedDrones$ = this.actions$.pipe(
    ofType<featureActions.GetUsedDronesRequest>(featureActions.ActionTypes.GetUsedDronesRequest),
    switchMap((action) =>
      this.droneDataService.getUsedDrones(action.payload).pipe(
        map(drones => {
          drones.forEach((drone) => new featureActions.OpenUsedDroneUpdateChannelRequest({ droneId: drone.id, projectId : environment.projectId }));
          new featureActions.GetUsedDronesSuccess({drones});
        }),
        catchError((error: HttpErrorResponse) => {
          this.snackBar.open(this.translate.instant('ERRORS.HTTP.GENERIC'), this.translate.instant('BUTTONS.OK'), {duration: 2500});
          return of(new featureActions.GetUsedDronesFailed({error}));
        }),
      ),
    ),
  );

basically, after calling my api and retrieving the drones, I need to call this for each drone

    map(drones => {
      drones.forEach((drone) => new featureActions.OpenUsedDroneUpdateChannelRequest({ droneId: drone.id, projectId : environment.projectId }));
      new featureActions.GetUsedDronesSuccess({drones});
    }),

and then trigger the success of the retrieval.

the other action will basically call this

  startUpdate$ = this.actions$.pipe(
    ofType<featureActions.OpenUsedDroneUpdateChannelRequest>(featureActions.ActionTypes.OpenUsedDroneUpdateChannelRequest),
    switchMap((action) =>
      this.droneDataService.openUsedDroneUpdateChannel(action.payload).pipe(
        map(result => {
          if (this.currentUpdateEventList.has(action.payload.droneId)) { return; }
          new featureActions.OpenUsedDroneUpdateChannelSuccess(result);
          this.currentUpdateEventList.set(action.payload.droneId, [
            `get_position_drone${action.payload.droneId}`,
            `get_status_drone${action.payload.droneId}`
          ])
          this.sseService.subscribe(`get_position_drone${action.payload.droneId}`, (position: Cartesian3) => {
            new featureActions.SetUsedDronePosition({droneId : action.payload.droneId, position});
          });
          this.sseService.subscribe(`get_status_drone${action.payload.droneId}`, (status: IDroneStatus) => {
            new featureActions.SetUsedDroneStatus({droneId : action.payload.droneId, status});
          });
        }),
        catchError((error: HttpErrorResponse) => {
          this.snackBar.open(this.translate.instant('ERRORS.HTTP.DRONE.NOT_UPDATABLE', {droneId: action.payload.droneId}), this.translate.instant('BUTTONS.OK'), {duration: 2500});
          return of(new featureActions.OpenUsedDroneUpdateChannelFailed({error}));
        }),
      )
    )
  );

Now, the problem I have is the following, My first foreach return this error

core.js:15724 ERROR Error: Effect "UsedDronesEffect.getUsedDrones$"
  dispatched an invalid action: undefined

core.js:15724 ERROR TypeError: Actions must be objects
      at ActionsSubject.push../node_modules/@ngrx/store/fesm5/store.js.ActionsSubject.next

EDIT : I Fixed the error but, now my forEach action are not dispatched

    map(drones => {

      drones.forEach((drone) => new featureActions.OpenUsedDroneUpdateChannelRequest({ droneId: drone.id, projectId : environment.projectId }));
      return new featureActions.GetUsedDronesSuccess({drones});
    }),

How can I return a list of action based on the amount of drone I have, and end up with success ?

EDIT 2 :

shouldn't this work ?

map(drones => {
  const actions = [];
  drones.forEach((drone) => actions.push(new featureActions.OpenUsedDroneUpdateChannelRequest({ droneId: drone.id, projectId : environment.projectId })));
  actions.push(new featureActions.GetUsedDronesSuccess({drones}));
  return merge(actions);
}),


问:
Devise issues with soft-deleted Records. Any idea, how to fix it?
I'm using discard gem for Soft deletion. Once user gets Soft-Deleted, user can still receive forget password emails. Because Devise password controller does not care either its soft-deleted or not ?

I'm using following Devise modules, it seems, i may need to fix for all modules:-

:confirmable,

:recoverable,

:timeoutable,

:trackable

:lockable

:authenticatable

Though I'm able to fix login issue with authenticatable by overriding find_for_authentication method in user model, but it doesn't seem to be working with other Devise modules.

Any Idea, how i can fix soft-deletion issues with Devise ?

I'm using devise(4.6.2), discard (1.0.0), Rails 5.1.6.2

答:
Finally I'm able to fix it by overriding following method in user.rb. any one else, if facing the same issue, can fix it in following way:</p>

```<code># Override to add condition to ignore soft deleted users
def self.find_first_by_auth_conditions(conditions, opts = {})
  opts.reverse_merge!(discarded_at: nil)

  super
 end
</code>```

Body:
Finally I'm able to fix it by overriding following method in user.rb. any one else, if facing the same issue, can fix it in following way:

# Override to add condition to ignore soft deleted users
def self.find_first_by_auth_conditions(conditions, opts = {})
  opts.reverse_merge!(discarded_at: nil)

  super
 end


问:
Error with setRequestHeader in GET request
The following JS function should be sending out a GET request to

http://127.0.0.1:5000/api.xml

with

?query=toast

```<code>function sendRequest(str){
    var request = new XMLHttpRequest();
    console.log('sending request');
    request.onreadystatechange = function() {
        if (request.readyState == XMLHttpRequest.DONE) {
            json=request.responseText;
            //json.forEach(function(obj) {
            //});
            for (word in json){
                var row=table.insertRow();
                var scoreC=row.insertCell();
                var wordC=row.insertCell();
                scoreC.innerHTML=json[word];
                wordC.innerHTML=word;
            }
        } else {
            concole.log("Silence on the line");
        }
    }
    request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    request.open('GET', 'http://127.0.0.1:5000/api.xml?query='+str, true);
    request.send();
  // and give it some content
    //var newContent = document.createTextNode(resp);
    //console.log(resp.responseType);
}
</code>```

Instead, it always queries

http://127.0.0.1:5000/?word=toast

ignoring the fact that I required a GET on

http://127.0.0.1:5000/api.xml

答:
1)As Stephan Schrijver lined out

```<code>request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
</code>```

is only valid when it follows

```<code>request.open('POST', 'http://127.0.0.1:5000/api.xml?query='+str, true);
</code>```

as part of a POST request

It is no longer required for GET requests

2) Also,

```<code>request.open('GET', 'http://127.0.0.1:5000/api.html?query='+str, true);
</code>```

must be defined before the readyStateChange function

Body:
The following JS function should be sending out a GET request to

http://127.0.0.1:5000/api.xml

with

?query=toast

function sendRequest(str){
    var request = new XMLHttpRequest();
    console.log('sending request');
    request.onreadystatechange = function() {
        if (request.readyState == XMLHttpRequest.DONE) {
            json=request.responseText;
            //json.forEach(function(obj) {
            //});
            for (word in json){
                var row=table.insertRow();
                var scoreC=row.insertCell();
                var wordC=row.insertCell();
                scoreC.innerHTML=json[word];
                wordC.innerHTML=word;
            }
        } else {
            concole.log("Silence on the line");
        }
    }
    request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    request.open('GET', 'http://127.0.0.1:5000/api.xml?query='+str, true);
    request.send();
  // and give it some content
    //var newContent = document.createTextNode(resp);
    //console.log(resp.responseType);
}

Instead, it always queries

http://127.0.0.1:5000/?word=toast

ignoring the fact that I required a GET on

http://127.0.0.1:5000/api.xml

Body:
1)As Stephan Schrijver lined out

request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

is only valid when it follows

request.open('POST', 'http://127.0.0.1:5000/api.xml?query='+str, true);

as part of a POST request

It is no longer required for GET requests

2) Also,

request.open('GET', 'http://127.0.0.1:5000/api.html?query='+str, true);

must be defined before the readyStateChange function


问:
How to refer to unnamed object in R
I want to perform a simple task in R. I want to call a method on an object which has not been assigned to any variable yet.
Like this:

```<code>a <- c(5, 2, 11, 3)
b <- order(a, decreasing = TRUE)[1:floor(0.1 * length(.))]
</code>```

So I guess, I would like to to find, what to pass to length function here. I know that I can perform it like this:

```<code>a <- c(5, 2, 11, 3)
b <- order(a, decreasing = TRUE)
b <- b[1:floor(0.1 * length(b))]
</code>```

But I wanted to make it like I wrote above.

答:
There is as far as i know, no implemented way that will achieve higher efficiency than the base code

```<code>a <- c(5, 2, 11, 3)
b <- order(a, decreasing = TRUE)
b[1:floor(0.1 * length(b))]
</code>```

However one can achieve something similar to what you are asking, using either the magrittr, the dplyr or similar packages, which allow for piping calls. This would look similar to

```<code>a <- c(5, 2, 11, 3)
c <- a %>% order(., decreasing = TRUE) %>% .[1:floor(0.1 * length(.))]
identical(b[1:floor(0.1 * length(b))],c)
[1] TRUE
</code>```

Title: How to refer to unnamed object in R

Body:
I want to perform a simple task in R. I want to call a method on an object which has not been assigned to any variable yet.
Like this:

a <- c(5, 2, 11, 3)
b <- order(a, decreasing = TRUE)[1:floor(0.1 * length(.))]

So I guess, I would like to to find, what to pass to length function here. I know that I can perform it like this:

a <- c(5, 2, 11, 3)
b <- order(a, decreasing = TRUE)
b <- b[1:floor(0.1 * length(b))]

But I wanted to make it like I wrote above.

Body:
There is as far as i know, no implemented way that will achieve higher efficiency than the base code

a <- c(5, 2, 11, 3)
b <- order(a, decreasing = TRUE)
b[1:floor(0.1 * length(b))]

However one can achieve something similar to what you are asking, using either the magrittr, the dplyr or similar packages, which allow for piping calls. This would look similar to

a <- c(5, 2, 11, 3)
c <- a %>% order(., decreasing = TRUE) %>% .[1:floor(0.1 * length(.))]
identical(b[1:floor(0.1 * length(b))],c)
[1] TRUE


问:
how to handle server connection error and internet connection error and show different messages for each one in volley android?
what I want is to show different messages for connection errors, what I mean when there is a server connection error show to user that there is a server issue and if no internet tell the user that no internet connection, how I can achieve that with volley?

I already try the following code :

```<code>public void onErrorResponse(VolleyError error) {
    if (error instanceof TimeoutError) {
        Snackbar.make(contextView,getString(R.string.no_internen_connection_msg),Snackbar.LENGTH_LONG).show();
    } else if (error instanceof NetworkError) {
        Snackbar.make(contextView,getString(R.string.no_internen_connection_msg),Snackbar.LENGTH_LONG).show();
    } else if (error instanceof NoConnectionError) {
        Snackbar.make(contextView,getString(R.string.server_con_err_msg),Snackbar.LENGTH_LONG).show();
    } else {
        if (parseNetworkError(error).getMessage() != null) {
            //do something
        }else {
            //do something
        }
    }
}
</code>```

But the condition of NoConnectionError show this warning "condition error instanceof NoConnectionError is always false"

and its always shows the internet connection error even if there is an internet connection but the problem is the server connection error.

答:
'Here is the solution'

```<code>            @Override
            public void onErrorResponse(VolleyError error) {
                String json = null;
                String json_js = null;

                NetworkResponse response = error.networkResponse;
                if(response != null && response.data != null){
                    int codee=response.statusCode;
                    switch(response.statusCode){
                        case 400:
                            json = new String(response.data);
                            json = trimMessage(json, "message");
                            if(json != null) displayMessage(json);
//                            json_js=json;
//                            JSONObject jj=json;
                            callback.onSuccess(json_js,json);
                            break;
                        case 401:
                            callback.onSuccess(json_js,"401");
                            break;
                        case 405:

                            callback.onSuccess(json_js,"Sending Wrong Request");
                            break;
                        default:
                            callback.onSuccess(json_js,error.toString());

                    }
                    //Additional cases
                }
                else {
                    String message;
                    if (error instanceof NetworkError) {
                        message = "Cannot connect to Internet...Please check your
                        connection!";
                        callback.onSuccess(json_js, message);

                    } else if (error instanceof ServerError) {
                        message = "The server could not be found. Please try again
                             after some time!!";
                        callback.onSuccess(json_js, message);

                    } else if (error instanceof AuthFailureError) {
                        message = "Cannot connect to Internet...Please check your
                          connection!";
                        callback.onSuccess(json_js, message);

                    } else if (error instanceof ParseError) {
                        message = "Parsing error! Please try again after some
                         time!!";
                        callback.onSuccess(json_js, message);

                    } else if (error instanceof NoConnectionError) {
                        message = "Cannot connect to Internet...Please check your
                         connection!";
                        callback.onSuccess(json_js, message);

                    } else if (error instanceof TimeoutError) {
                        message = "Connection TimeOut! Please check your internet
                        connection.";
                        callback.onSuccess(json_js, message);

                    }
</code>```

'Hope you get the answer'

Body:
what I want is to show different messages for connection errors, what I mean when there is a server connection error show to user that there is a server issue and if no internet tell the user that no internet connection, how I can achieve that with volley?

I already try the following code :

public void onErrorResponse(VolleyError error) {
    if (error instanceof TimeoutError) {
        Snackbar.make(contextView,getString(R.string.no_internen_connection_msg),Snackbar.LENGTH_LONG).show();
    } else if (error instanceof NetworkError) {
        Snackbar.make(contextView,getString(R.string.no_internen_connection_msg),Snackbar.LENGTH_LONG).show();
    } else if (error instanceof NoConnectionError) {
        Snackbar.make(contextView,getString(R.string.server_con_err_msg),Snackbar.LENGTH_LONG).show();
    } else {
        if (parseNetworkError(error).getMessage() != null) {
            //do something
        }else {
            //do something
        }
    }
}

But the condition of NoConnectionError show this warning "condition error instanceof NoConnectionError is always false"

and its always shows the internet connection error even if there is an internet connection but the problem is the server connection error.

Body:
'Here is the solution'

            @Override
            public void onErrorResponse(VolleyError error) {
                String json = null;
                String json_js = null;

                NetworkResponse response = error.networkResponse;
                if(response != null && response.data != null){
                    int codee=response.statusCode;
                    switch(response.statusCode){
                        case 400:
                            json = new String(response.data);
                            json = trimMessage(json, "message");
                            if(json != null) displayMessage(json);
//                            json_js=json;
//                            JSONObject jj=json;
                            callback.onSuccess(json_js,json);
                            break;
                        case 401:
                            callback.onSuccess(json_js,"401");
                            break;
                        case 405:

                            callback.onSuccess(json_js,"Sending Wrong Request");
                            break;
                        default:
                            callback.onSuccess(json_js,error.toString());

                    }
                    //Additional cases
                }
                else {
                    String message;
                    if (error instanceof NetworkError) {
                        message = "Cannot connect to Internet...Please check your
                        connection!";
                        callback.onSuccess(json_js, message);

                    } else if (error instanceof ServerError) {
                        message = "The server could not be found. Please try again
                             after some time!!";
                        callback.onSuccess(json_js, message);

                    } else if (error instanceof AuthFailureError) {
                        message = "Cannot connect to Internet...Please check your
                          connection!";
                        callback.onSuccess(json_js, message);

                    } else if (error instanceof ParseError) {
                        message = "Parsing error! Please try again after some
                         time!!";
                        callback.onSuccess(json_js, message);

                    } else if (error instanceof NoConnectionError) {
                        message = "Cannot connect to Internet...Please check your
                         connection!";
                        callback.onSuccess(json_js, message);

                    } else if (error instanceof TimeoutError) {
                        message = "Connection TimeOut! Please check your internet
                        connection.";
                        callback.onSuccess(json_js, message);

                    }

'Hope you get the answer'


问:
hidden columns are still shown in my browser, what's the problem?
I have an excel worksheet with some hidden columns.

I want to export it as a webpage, so I save that with html format but when I open it in my browser(IE and chrome), the hidden columns are still displayed.

What can I do to solve this problem?

Thanks :)

Body:
Find the nth column you want to hide and apply CSS like below. Make sure your CSS is inside the <style> block;

In the below example, I am hiding the second column.

Read more about nt-child CSS pseudo-class

table tr td:nth-child(2) {
  display: none;
}

<table>
  <tbody>
    <tr>
      <td>Visible Header</td>
      <td>Hidden Header</td>
    </tr>
    <tr>
      <td>Visible Column</td>
      <td>Hidden Column</td>
    </tr>
  </tbody>
</table>


问:
Django context value for home page
I have a model that takes a Boolean update from the admin. If the admin clicks it, the end user can or cannot access the a view. The problem is that the view is accessible through the home page which has a base file and it requires the id of the user to check against.
I get this error NoReverseMatch at /home/
I am unable to understand how can I pass the context value to the base file. I don't want to create another view for as it's a base file.

I tried context_processors but it gives me this error at the home.view
int() argument must be a string or a number, not builtin_function_or_method

I have two functions in context_processors, each has it's own characteristics.

Here is the code

settings.py

TEMPLATES = [{
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'projectfiles.context_processors.emp_base_context',
                'projectfiles.context_processors.lev_base_context',
            ],},},]

```

<p><strong>models.py</strong></p>

<pre class="lang-py prettyprint-override"><code>class Employee(models.Model):

    allowed = models.BooleanField(default=True)
    employee_name = models.OneToOneField(User, on_delete = models.CASCADE)
    employee_designation = models.CharField(max_length = 5)
    employee_department = models.CharField(max_length = 5)

    Annual_leave = models.PositiveSmallIntegerField(default=5)
    Sick_leave = models.PositiveSmallIntegerField(default=5)
    Casual_leave = models.PositiveSmallIntegerField(default=5)
    Half_pay = models.PositiveSmallIntegerField(default=5)
    Emergency_leave = models.PositiveSmallIntegerField(default=5)

class Leave(models.Model):
    employee_leaves = models.ForeignKey(Employee, on_delete=models.CASCADE)
    leave_Type = models.CharField(max_length=25)
    leave_qty = models.PositiveSmallIntegerField(default=0)
    description = models.CharField(max_length=75, blank=True, null=True)
    submit_date = models.DateTimeField(auto_now_add=True)
    from_date = models.DateField(auto_now=False, auto_now_add=False)
    to_date = models.DateField(auto_now=False, auto_now_add=False)
    leave_status = models.CharField(max_length=10, default="Pending")

</code>```

context_processors.py

from .models import Employee, Leave

def emp_base_context(request):
    emp_data = Employee.objects.get(id=id)

    return {
        'emp_base_context': emp_base_context}

```

<p><strong>urls.py</strong></p>

<pre class="lang-py prettyprint-override"><code>urlpatterns = [
    url(r'^(?i)Home/$', views.home, name='Home-Page'),
    url(r'^(?i)request/(?P<emp_id>\d+)$', views.request_leave,
        name='Leave-Page'),  # leave request
</code>```

views.py

def request_leave(request, emp_id):  # Requesting leave
    employee = Employee.objects.get(id=emp_id)
    if employee.allowed == True:
        form = Leave_Form(request.POST)
        if form.is_valid():
            abc = form.save(commit=False)
            abc.employee_leaves = request.user.employee
            abc.save()
        form = Leave_Form
        context = {'employee': employee, 'form': form}
        return render(request, 'projectfiles/reqleave.html', context)
    else:
        return render(request, "projectfiles/banned.html")
```

<p><strong>base.html</strong></p>

<pre class="lang-html prettyprint-override"><code><nav id="mynav" class="navbar navbar-expand-sm bg-dark">
                  class="glyphicon glyphicon-folder-close"></span> Leave Management System</a>
            </h4>
          </div>
          <div class="panel-collapse collapse panel-scroll" id="accordion">
            <div class="panel panel-default">
              <div class="panel-heading">
                <h4 class="panel-title">
                  <span
                      class="glyphicon glyphicon-folder-close"></span> Home
                </h4>
              </div>
              <div id="collapseOne" class="panel-collapse collapse">
                <div class="panel-body">
                  <table class="table">
                    <tbody>
                      <tr>
                        <td>

                       The request page   **<span class="glyphicon glyphicon-pencil text-primary"></span> Request Leave**
                        </td>
                      </tr>
                      <tr>
                        <td>
                        <span class="glyphicon glyphicon-pencil text-primary"></span> Notifications
                        </td>
                      </tr>
                      <td>
                        <span class="glyphicon glyphicon-file text-info"></span> About
                      </td>
                      </tr>

                    </tbody>
                  </table>
                </div>
              </div>
            </div>
            <div class="panel panel-default">
              <div class="panel-heading">
                <h4 class="panel-title">
                  <span
                      class="glyphicon glyphicon-user"></span> {{user.username}}
                </h4>
              </div>
              <div id="collapseThree" class="panel-collapse collapse ">
                <div class="panel-body">

                </div>
              </div>
            </div>
            <div class="panel panel-default">
              <div class="panel-heading">
                <h4 class="panel-title">
                  <span
                      class="glyphicon glyphicon-th"></span>Remaining Leaves
                </h4>
              </div>
              <div id="collapseTwo" class="panel-collapse collapse ">
                <div class="panel-body">
                  <table class="table">
                    <tbody>
                      <tr>
                        <td>
                          Annual<span class="label label-success"><font color='red'><br><small>Remaining leaves</small></font></span>
                        </td>
                      </tr>
                      <tr>
                        <td>
                          Emergency<span class="label label-success"><font color='red'><br><small>Remaining leaves</small></font></span>
                        </td>
                      </tr>
                      <tr>
                        <td>
                          Sick<span class="label label-success"><font color='red'><br><small>Remaining leaves</small></font></span>
                        </td>
                      </tr>
                      <tr>
                        <td>
                          Casual<span class="label label-success"><font color='red'><br><small>Remaining leaves</small></font></span>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
              </div>
            </div>
          </div>
        </div>

      </div>

    </div>
  </div>
</div>
<div id="push"></div>
</code>```

errors

```<code>Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/home/

Django Version: 1.11.20
Python Version: 2.7.16
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'projectfiles',
 'crispy_forms']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\Bitswits 3\Desktop\Intern Work\LMS\LMS\projectfiles\views.py" in home
  25.     return render(request, "projectfiles/HomePage.html")

File "C:\Python27\lib\site-packages\django\shortcuts.py" in render
  30.     content = loader.render_to_string(template_name, context, request, using=using)

File "C:\Python27\lib\site-packages\django\template\loader.py" in render_to_string
  68.     return template.render(context, request)

File "C:\Python27\lib\site-packages\django\template\backends\django.py" in render
  66.             return self.template.render(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in render
  205.                 with context.bind_template(self):

File "C:\Python27\lib\contextlib.py" in __enter__
  17.             return self.gen.next()

File "C:\Python27\lib\site-packages\django\template\context.py" in bind_template
  263.             updates.update(processor(self.request))

File "C:\Users\Bitswits 3\Desktop\Intern Work\LMS\LMS\projectfiles\context_processors.py" in emp_base_context
  7.     emp_data = Employee.objects.get(id=id)

File "C:\Python27\lib\site-packages\django\db\models\manager.py" in manager_method
  85.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "C:\Python27\lib\site-packages\django\db\models\query.py" in get
  371.         clone = self.filter(*args, **kwargs)

File "C:\Python27\lib\site-packages\django\db\models\query.py" in filter
  787.         return self._filter_or_exclude(False, *args, **kwargs)

File "C:\Python27\lib\site-packages\django\db\models\query.py" in _filter_or_exclude
  805.             clone.query.add_q(Q(*args, **kwargs))

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in add_q
  1250.         clause, _ = self._add_q(q_object, self.used_aliases)

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in _add_q
  1276.                     allow_joins=allow_joins, split_subq=split_subq,

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in build_filter
  1210.             condition = self.build_lookup(lookups, col, value)

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in build_lookup
  1104.                 return final_lookup(lhs, rhs)

File "C:\Python27\lib\site-packages\django\db\models\lookups.py" in __init__
  24.         self.rhs = self.get_prep_lookup()

File "C:\Python27\lib\site-packages\django\db\models\lookups.py" in get_prep_lookup
  74.             return self.lhs.output_field.get_prep_value(self.rhs)

File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py" in get_prep_value
  966.         return int(value)

Exception Type: TypeError at /home/
Exception Value: int() argument must be a string or a number, not 'builtin_function_or_method'

</code>```

error 2.0

```<code>Request Method: GET
Request URL: http://127.0.0.1:8000/home/

Traceback:

File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

Exception Type: TypeError at /home/
Exception Value: home() takes exactly 2 arguments (1 given)

</code>```

UPDATED

```<code>url(r'^(?i)request/(?P<emp_id>\d+)$', views.request_leave,
        name='Leave-Page'),

<a href="{% url "Leave-Page" request.user.id %}"><span class="glyphicon glyphicon-pencil text-primary"></span> Request Leave</>

def request_leave(request, emp_id):  # Requesting leave
    employee = Employee.objects.get(employee_name=emp_id)
    if employee.allowed == True:
        form = Leave_Form(request.POST)
        if form.is_valid():
            abc = form.save(commit=False)
            abc.employee_leaves = request.user.employee
            abc.save()
        form = Leave_Form
        context = {'employee': employee, 'form': form}
        # context = {'form': form}
        return render(request, 'projectfiles/reqleave.html', context)
    else:
        return render(request, "projectfiles/banned.html")

using context_processor was passing the id to the entire view, I just needed to use it for request and by comparing the user id with the employee name worked for me.

</code>```

I expect, when the user is allowed by the admin from the back end then the user is able to access the request page and apply, otherwise the view redirects the user to a different page.

答:
From the docs:

A context processor has a very simple interface: It’s a Python
  function that takes one argument, an HttpRequest object, and returns a
  dictionary that gets added to the template context. Each context
  processor must return a dictionary.

So when you do: emp_data = Employee.objects.get(id=id) Django is raising the exception.

```<code>>>> Test.objects.get(id=id)
Traceback (most recent call last):
TypeError: int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method'
>>> id
<built-in function id>
</code>```

If you're trying to retrieve the user logged in:

```<code>def emp_base_context(request):
    emp_data = Employee.objects.get(id=request.user.id)

    return {
        'emp_base_context': emp_base_context}
</code>```

Title: Django context value for home page

Body:
I have a model that takes a Boolean update from the admin. If the admin clicks it, the end user can or cannot access the a view. The problem is that the view is accessible through the home page which has a base file and it requires the id of the user to check against.
I get this error NoReverseMatch at /home/
I am unable to understand how can I pass the context value to the base file. I don't want to create another view for as it's a base file.

I tried context_processors but it gives me this error at the home.view
int() argument must be a string or a number, not builtin_function_or_method

I have two functions in context_processors, each has it's own characteristics.

Here is the code

settings.py

TEMPLATES = [{
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'projectfiles.context_processors.emp_base_context',
                'projectfiles.context_processors.lev_base_context',
            ],},},]

models.py

class Employee(models.Model):

    allowed = models.BooleanField(default=True)
    employee_name = models.OneToOneField(User, on_delete = models.CASCADE)
    employee_designation = models.CharField(max_length = 5)
    employee_department = models.CharField(max_length = 5)

    Annual_leave = models.PositiveSmallIntegerField(default=5)
    Sick_leave = models.PositiveSmallIntegerField(default=5)
    Casual_leave = models.PositiveSmallIntegerField(default=5)
    Half_pay = models.PositiveSmallIntegerField(default=5)
    Emergency_leave = models.PositiveSmallIntegerField(default=5)

class Leave(models.Model):
    employee_leaves = models.ForeignKey(Employee, on_delete=models.CASCADE)
    leave_Type = models.CharField(max_length=25)
    leave_qty = models.PositiveSmallIntegerField(default=0)
    description = models.CharField(max_length=75, blank=True, null=True)
    submit_date = models.DateTimeField(auto_now_add=True)
    from_date = models.DateField(auto_now=False, auto_now_add=False)
    to_date = models.DateField(auto_now=False, auto_now_add=False)
    leave_status = models.CharField(max_length=10, default="Pending")

context_processors.py

from .models import Employee, Leave

def emp_base_context(request):
    emp_data = Employee.objects.get(id=id)

    return {
        'emp_base_context': emp_base_context}

urls.py

urlpatterns = [
    url(r'^(?i)Home/$', views.home, name='Home-Page'),
    url(r'^(?i)request/(?P<emp_id>\d+)$', views.request_leave,
        name='Leave-Page'),  # leave request

views.py

def request_leave(request, emp_id):  # Requesting leave
    employee = Employee.objects.get(id=emp_id)
    if employee.allowed == True:
        form = Leave_Form(request.POST)
        if form.is_valid():
            abc = form.save(commit=False)
            abc.employee_leaves = request.user.employee
            abc.save()
        form = Leave_Form
        context = {'employee': employee, 'form': form}
        return render(request, 'projectfiles/reqleave.html', context)
    else:
        return render(request, "projectfiles/banned.html")

base.html

                  class="glyphicon glyphicon-folder-close"> Leave Management System

                   Home

                       The request page   ** Request Leave**

                         Notifications

                         About

                   {{user.username}}

                  Remaining Leaves

                          Annual
Remaining leaves

                          Emergency
Remaining leaves

                          Sick
Remaining leaves

                          Casual
Remaining leaves

errors

Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/home/

Django Version: 1.11.20
Python Version: 2.7.16
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'projectfiles',
 'crispy_forms']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\Bitswits 3\Desktop\Intern Work\LMS\LMS\projectfiles\views.py" in home
  25.     return render(request, "projectfiles/HomePage.html")

File "C:\Python27\lib\site-packages\django\shortcuts.py" in render
  30.     content = loader.render_to_string(template_name, context, request, using=using)

File "C:\Python27\lib\site-packages\django\template\loader.py" in render_to_string
  68.     return template.render(context, request)

File "C:\Python27\lib\site-packages\django\template\backends\django.py" in render
  66.             return self.template.render(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in render
  205.                 with context.bind_template(self):

File "C:\Python27\lib\contextlib.py" in __enter__
  17.             return self.gen.next()

File "C:\Python27\lib\site-packages\django\template\context.py" in bind_template
  263.             updates.update(processor(self.request))

File "C:\Users\Bitswits 3\Desktop\Intern Work\LMS\LMS\projectfiles\context_processors.py" in emp_base_context
  7.     emp_data = Employee.objects.get(id=id)

File "C:\Python27\lib\site-packages\django\db\models\manager.py" in manager_method
  85.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "C:\Python27\lib\site-packages\django\db\models\query.py" in get
  371.         clone = self.filter(*args, **kwargs)

File "C:\Python27\lib\site-packages\django\db\models\query.py" in filter
  787.         return self._filter_or_exclude(False, *args, **kwargs)

File "C:\Python27\lib\site-packages\django\db\models\query.py" in _filter_or_exclude
  805.             clone.query.add_q(Q(*args, **kwargs))

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in add_q
  1250.         clause, _ = self._add_q(q_object, self.used_aliases)

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in _add_q
  1276.                     allow_joins=allow_joins, split_subq=split_subq,

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in build_filter
  1210.             condition = self.build_lookup(lookups, col, value)

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in build_lookup
  1104.                 return final_lookup(lhs, rhs)

File "C:\Python27\lib\site-packages\django\db\models\lookups.py" in __init__
  24.         self.rhs = self.get_prep_lookup()

File "C:\Python27\lib\site-packages\django\db\models\lookups.py" in get_prep_lookup
  74.             return self.lhs.output_field.get_prep_value(self.rhs)

File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py" in get_prep_value
  966.         return int(value)

Exception Type: TypeError at /home/
Exception Value: int() argument must be a string or a number, not 'builtin_function_or_method'

error 2.0

Request Method: GET
Request URL: http://127.0.0.1:8000/home/

Traceback:

File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

Exception Type: TypeError at /home/
Exception Value: home() takes exactly 2 arguments (1 given)

UPDATED

url(r'^(?i)request/(?P<emp_id>\d+)$', views.request_leave,
        name='Leave-Page'),

 Request Leave</>

def request_leave(request, emp_id):  # Requesting leave
    employee = Employee.objects.get(employee_name=emp_id)
    if employee.allowed == True:
        form = Leave_Form(request.POST)
        if form.is_valid():
            abc = form.save(commit=False)
            abc.employee_leaves = request.user.employee
            abc.save()
        form = Leave_Form
        context = {'employee': employee, 'form': form}
        # context = {'form': form}
        return render(request, 'projectfiles/reqleave.html', context)
    else:
        return render(request, "projectfiles/banned.html")

using context_processor was passing the id to the entire view, I just needed to use it for request and by comparing the user id with the employee name worked for me.

I expect, when the user is allowed by the admin from the back end then the user is able to access the request page and apply, otherwise the view redirects the user to a different page.

Body:
From the docs:

A context processor has a very simple interface: It’s a Python
  function that takes one argument, an HttpRequest object, and returns a
  dictionary that gets added to the template context. Each context
  processor must return a dictionary.

So when you do: emp_data = Employee.objects.get(id=id) Django is raising the exception.

>>> Test.objects.get(id=id)
Traceback (most recent call last):
TypeError: int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method'
>>> id
<built-in function id>

If you're trying to retrieve the user logged in:

def emp_base_context(request):
    emp_data = Employee.objects.get(id=request.user.id)

    return {
        'emp_base_context': emp_base_context}


问:
Unsupported Media Type returned when using Paging on APIController marked Controller
After adding paging to an API Controller, I now receive a json error with Unsupported Media Type.

I am using ASP.NET Core 2.2.  I can work around the problem by commenting out the [ApiController] attribute on the Controller, but this is obviously not preferred and I would like to understand what the underlying issue is.

public async Task<ActionResult<BlogPost>> Get(ResourceParameters resourceParameters)
{
    return Ok(await _repository.GetBlogPostsAsync(resourceParameters));
}
```

<pre class="lang-cs prettyprint-override"><code>// The problem is suppressed by commenting out the ApiController attribute
[Route("api/[controller]")]
//[ApiController]
public class BlogController : ControllerBase
..
</code>```

The response

```<code>// 20190530081824
// https://localhost:5001/api/blog
{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.13",
    "title": "Unsupported Media Type",
    "status": 415,
    "traceId": "0HLN4PRV4JD94:00000001"
}
</code>```

答:
Try to change your code to this

```<code>[Route("api/[controller]/")]
[ApiController]
public class BlogController : Controller
</code>```

and

```<code>public async Task<ActionResult<BlogPost>> Get([FromQuery] ResourceParameters resourceParameters)
{
    return Ok(await _repository.GetBlogPostsAsync(resourceParameters));
}
</code>```

Make sure to have FromQuery or FromBody depend on your object you submit

Body:
After adding paging to an API Controller, I now receive a json error with Unsupported Media Type.

I am using ASP.NET Core 2.2.  I can work around the problem by commenting out the [ApiController] attribute on the Controller, but this is obviously not preferred and I would like to understand what the underlying issue is.

public async Task<ActionResult<BlogPost>> Get(ResourceParameters resourceParameters)
{
    return Ok(await _repository.GetBlogPostsAsync(resourceParameters));
}

// The problem is suppressed by commenting out the ApiController attribute
[Route("api/[controller]")]
//[ApiController]
public class BlogController : ControllerBase
..

The response

// 20190530081824
// https://localhost:5001/api/blog
{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.13",
    "title": "Unsupported Media Type",
    "status": 415,
    "traceId": "0HLN4PRV4JD94:00000001"
}

Body:
Try to change your code to this

[Route("api/[controller]/")]
[ApiController]
public class BlogController : Controller

and

public async Task<ActionResult<BlogPost>> Get([FromQuery] ResourceParameters resourceParameters)
{
    return Ok(await _repository.GetBlogPostsAsync(resourceParameters));
}

Make sure to have FromQuery or FromBody depend on your object you submit


问:
Android:java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM
I want to show the Bitmap image in ImageView from sd card which is stored already. After run my application is crash and getting OutOfMemoryError error of:

(java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM)

I have no idea or why its out of memory. I think my image size is very large so I tried to change it.

```<code>Iterator<String> it = imageArray.iterator();
while (it.hasNext()) {
  Object element = it.next();
  String objElement = element.toString();
  Log.e("objElement ", " = " + objElement);
  final ImageView imageView = new ImageView (getContext());
  final ProgressBar pBar = new ProgressBar(getContext(), null,
                                           android.R.attr.progressBarStyleSmall);
  imageView.setTag(it);
  pBar.setTag(it);

  imageView.setImageResource(R.drawable.img_placeholder);
  pBar.setVisibility(View.VISIBLE);

  if (objElement.endsWith(mp3_Pattern)) {
     Log.e("Mp3 ", " ends with ");
     pBar.setVisibility(View.GONE);
     imageView.setImageResource(R.drawable.audio_control);
  }
  if (objElement.endsWith(png_Pattern)) {
     Bitmap bitmap = BitmapFactory.decodeFile(objElement);
     int size = Math.min(bitmap.getWidth(), bitmap.getHeight());
     int x = (bitmap.getWidth() - size) / 2;
     int y = (bitmap.getHeight() - size) / 2;
     Bitmap bitmap_Resul = Bitmap.createBitmap(bitmap, x, y, size, size);
     Log.e("bitmap_Resul "," = "+ bitmap_Resul);

     if (bitmap_Resul != bitmap) {
        bitmap.recycle();
     }
     imageView.setImageBitmap(bitmap_Resul);
     Log.e("png_Pattern ", " ends with ");
     Log.e(" bitmap "," = " + bitmap);
  }

  holder.linearLayout.addView(imageView);
  holder.linearLayout.addView(pBar);
</code>```

The log cat information:

```<code>08-27 14:11:15.307    1857-1857/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.tazeen.classnkk, PID: 1857
    java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM
            at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
            at android.graphics.Bitmap.nativeCreate(Native Method)
            at android.graphics.Bitmap.createBitmap(Bitmap.java:812)
            at android.graphics.Bitmap.createBitmap(Bitmap.java:789)
            at android.graphics.Bitmap.createBitmap(Bitmap.java:709)
            at android.graphics.Bitmap.createBitmap(Bitmap.java:634)
            at com.example.tazeen.classnkk.AllPosts_Page$MyListAdapter.getView(AllPosts_Page.java:357)
            at android.widget.AbsListView.obtainView(AbsListView.java:2347)
            at android.widget.ListView.makeAndAddView(ListView.java:1864)
            at android.widget.ListView.fillDown(ListView.java:698)
            at android.widget.ListView.fillFromTop(ListView.java:759)
            at android.widget.ListView.layoutChildren(ListView.java:1659)
            at android.widget.AbsListView.onLayout(AbsListView.java:2151)
            at android.view.View.layout(View.java:15671)
            at android.view.ViewGroup.layout(ViewGroup.java:5038)
            at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
            at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
            at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
            at android.view.View.layout(View.java:15671)
            at android.view.ViewGroup.layout(ViewGroup.java:5038)
            at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
            at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
            at android.view.View.layout(View.java:15671)
            at android.view.ViewGroup.layout(ViewGroup.java:5038)
            at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
            at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
            at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
            at android.view.View.layout(View.java:15671)
            at android.view.ViewGroup.layout(ViewGroup.java:5038)
            at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
            at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
            at android.view.View.layout(View.java:15671)
            at android.view.ViewGroup.layout(ViewGroup.java:5038)
            at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2086)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1843)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1061)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5885)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
            at android.view.Choreographer.doCallbacks(Choreographer.java:580)
            at android.view.Choreographer.doFrame(Choreographer.java:550)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
</code>```

答: add this to your manifest under applications?  android:largeHeap="true"</p>

Body:
I want to show the Bitmap image in ImageView from sd card which is stored already. After run my application is crash and getting OutOfMemoryError error of:

(java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM)

I have no idea or why its out of memory. I think my image size is very large so I tried to change it.

Iterator<String> it = imageArray.iterator();
while (it.hasNext()) {
  Object element = it.next();
  String objElement = element.toString();
  Log.e("objElement ", " = " + objElement);
  final ImageView imageView = new ImageView (getContext());
  final ProgressBar pBar = new ProgressBar(getContext(), null,
                                           android.R.attr.progressBarStyleSmall);
  imageView.setTag(it);
  pBar.setTag(it);

  imageView.setImageResource(R.drawable.img_placeholder);
  pBar.setVisibility(View.VISIBLE);

  if (objElement.endsWith(mp3_Pattern)) {
     Log.e("Mp3 ", " ends with ");
     pBar.setVisibility(View.GONE);
     imageView.setImageResource(R.drawable.audio_control);
  }
  if (objElement.endsWith(png_Pattern)) {
     Bitmap bitmap = BitmapFactory.decodeFile(objElement);
     int size = Math.min(bitmap.getWidth(), bitmap.getHeight());
     int x = (bitmap.getWidth() - size) / 2;
     int y = (bitmap.getHeight() - size) / 2;
     Bitmap bitmap_Resul = Bitmap.createBitmap(bitmap, x, y, size, size);
     Log.e("bitmap_Resul "," = "+ bitmap_Resul);

     if (bitmap_Resul != bitmap) {
        bitmap.recycle();
     }
     imageView.setImageBitmap(bitmap_Resul);
     Log.e("png_Pattern ", " ends with ");
     Log.e(" bitmap "," = " + bitmap);
  }

  holder.linearLayout.addView(imageView);
  holder.linearLayout.addView(pBar);

The log cat information:

08-27 14:11:15.307    1857-1857/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.tazeen.classnkk, PID: 1857
    java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM
            at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
            at android.graphics.Bitmap.nativeCreate(Native Method)
            at android.graphics.Bitmap.createBitmap(Bitmap.java:812)
            at android.graphics.Bitmap.createBitmap(Bitmap.java:789)
            at android.graphics.Bitmap.createBitmap(Bitmap.java:709)
            at android.graphics.Bitmap.createBitmap(Bitmap.java:634)
            at com.example.tazeen.classnkk.AllPosts_Page$MyListAdapter.getView(AllPosts_Page.java:357)
            at android.widget.AbsListView.obtainView(AbsListView.java:2347)
            at android.widget.ListView.makeAndAddView(ListView.java:1864)
            at android.widget.ListView.fillDown(ListView.java:698)
            at android.widget.ListView.fillFromTop(ListView.java:759)
            at android.widget.ListView.layoutChildren(ListView.java:1659)
            at android.widget.AbsListView.onLayout(AbsListView.java:2151)
            at android.view.View.layout(View.java:15671)
            at android.view.ViewGroup.layout(ViewGroup.java:5038)
            at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
            at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
            at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
            at android.view.View.layout(View.java:15671)
            at android.view.ViewGroup.layout(ViewGroup.java:5038)
            at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
            at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
            at android.view.View.layout(View.java:15671)
            at android.view.ViewGroup.layout(ViewGroup.java:5038)
            at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
            at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
            at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
            at android.view.View.layout(View.java:15671)
            at android.view.ViewGroup.layout(ViewGroup.java:5038)
            at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
            at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
            at android.view.View.layout(View.java:15671)
            at android.view.ViewGroup.layout(ViewGroup.java:5038)
            at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2086)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1843)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1061)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5885)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
            at android.view.Choreographer.doCallbacks(Choreographer.java:580)
            at android.view.Choreographer.doFrame(Choreographer.java:550)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)


问:
INNER JOIN two table get error SQL Statment not ended properly
I have two table which I want to select Name from t2.
The situation is following.
I have t1 Policy which containt EmployeeID
And table t2 which containt Name
Now I want to select which Employee release policy.
So in t1(Policy- AUTO.POL) I have column: SIFRA_RAD
and t2(Employee-AUTO.SIFRAD) I have colum: SIFRA_R, Ime

I try something like this:

```<code>select auto.pol.sifra_rad, auto.sifrad.ime
from auto.sifrad
inner join auto.pol on  auto.sifrad.ime = auto.pol.sifra_rad;
</code>```

After that I get error

```<code>ORA-00933: SQL command not properly ended
</code>```

I have no idea what is wrong here. Any suggestion?

答:
The problem comes from query, and we fix it </p>

```<code>select p.sifra_rad, s.ime from auto.sifrad s, auto.pol p where s.ime = p.sifra_rad
</code>```

Body:
I have two table which I want to select Name from t2.
The situation is following.
I have t1 Policy which containt EmployeeID
And table t2 which containt Name
Now I want to select which Employee release policy.
So in t1(Policy- AUTO.POL) I have column: SIFRA_RAD
and t2(Employee-AUTO.SIFRAD) I have colum: SIFRA_R, Ime

I try something like this:

select auto.pol.sifra_rad, auto.sifrad.ime
from auto.sifrad
inner join auto.pol on  auto.sifrad.ime = auto.pol.sifra_rad;

After that I get error

ORA-00933: SQL command not properly ended

I have no idea what is wrong here. Any suggestion?

Body:
The problem comes from query, and we fix it

select p.sifra_rad, s.ime from auto.sifrad s, auto.pol p where s.ime = p.sifra_rad


问:
Php MongoDB Write a CSV File
I have searched the internet, and could not get any specific details about it.

The environment is Windows 8, WAMP , MONGODB

I am trying to design a webpage, which have 4 fields: Name,Contact,Device,Email. After an user hits the submit button, the data inserts in the MongoDb. All this works fine.

The issue starts when I try to write the inserted data in the csv file, as this is the requirement. I have tried MongoDB Export command in the cmd, and it works fine, but trying to call the same using exec function in the php script is proving to be futile.

I have tried with this also, by storing the command in a .bat file, and then calling the .bat file using the php's exec function, still, no effect

```<code><?php
echo '```';

// Outputs all the result of shellcommand "ls", and returns
// the last output line into $last_line. Stores the return value
// of the shell command in $retval.
exec("c:\WINDOWS\system32\cmd.exe /c START C:\wamp\bin\mongodb\mongodb-win32-x86_64-2008plus-2.4.3\conf\export.bat");

?>
```

I have enabled the checbox interaction with desktop in my WAMP server.

I don't need any specific help related with the coding, all I need is some direction on how to proceed ahead, as I know that I am missing something. Also, I reiterate, did not get anything specific on the Internet, hence, posting the question.

Kindly let me know on how to achieve this.

Thanks to everyone

答:
```<code>set_time_limit(0);
ob_start();
error_reporting(E_ALL);
ini_set("display_errors",1);

$conn = new MongoClient("mongodb://Hostname:27017", array("replicaSet" => "rs0"));

if(!$conn){
    die("Unable to connect with mongodb");
}

$db = $conn-><DB NAME>; // DB name
$col1 = $db-><colname>;
$col2 = $db-><colname>; // collection name which u want .
$filterCountry = array("status"=>"1"); // where query
$records = $col1->find($filterCountry);

$fp= fopen('exampleTest11.csv', 'w'); // open csv file in which u want write data.

$headings[] = "Code";
$headings[] = "Status" ;
$headings[] = "EMP CODE";

fputcsv($fp, $headings);      // PUT Headings .
$cnt =0;
foreach($records as $val)   {

    $csvarr = array();
    $csvarr['code']= $val['code'];  // fetch data from database.
    $csvarr['Status']= $val['status'];
    $csvarr['emp_code']= $val['emp_code'];

    fputcsv($fp, $csvarr);
    $cnt++;
}

echo "Completed Successfully..".$cnt;
</code>```

Title: Php MongoDB Write a CSV File

Body:
I have searched the internet, and could not get any specific details about it.

The environment is Windows 8, WAMP , MONGODB

I am trying to design a webpage, which have 4 fields: Name,Contact,Device,Email. After an user hits the submit button, the data inserts in the MongoDb. All this works fine.

The issue starts when I try to write the inserted data in the csv file, as this is the requirement. I have tried MongoDB Export command in the cmd, and it works fine, but trying to call the same using exec function in the php script is proving to be futile.

I have tried with this also, by storing the command in a .bat file, and then calling the .bat file using the php's exec function, still, no effect

<?php
echo '
';

// Outputs all the result of shellcommand "ls", and returns
// the last output line into $last_line. Stores the return value
// of the shell command in $retval.
exec("c:\WINDOWS\system32\cmd.exe /c START C:\wamp\bin\mongodb\mongodb-win32-x86_64-2008plus-2.4.3\conf\export.bat");

?>

I have enabled the checbox interaction with desktop in my WAMP server.

I don't need any specific help related with the coding, all I need is some direction on how to proceed ahead, as I know that I am missing something. Also, I reiterate, did not get anything specific on the Internet, hence, posting the question.

Kindly let me know on how to achieve this.

Thanks to everyone


问:
UserDefaults not working on didload in my project
I have a login screen LoginViewController and homescreen HomeScreenController which is pushed when the user is successfully logged in).
I have declared a variable for UserDefaults as below in a seperate class:

```<code>class User {
    static var isLoggedIn = UserDefaults.standard.bool(forKey:"islogged")
}
</code>```

When the  user clicks login Button, the code is as below

```<code>ButtonAction:
{
    User.isLoggedin = true
    //Performsegue........to homescreen
}

ViewDidload {

    if user.isloggedin == true {
        //Performsegue......homescreen
    }
    else {
        Show some alerts
    }
}
</code>```

Here in my case...nothing happens...sorry for the rough code since I am using my smartphone to ask this question.

Am I missing something in appdelegate or somewhere else.
I just want to use the variables as it is because I don't want to change the entire code in my project.
The project is actually complicated and I just made an example to make you guys understand my situation.
This is not the exact code.

答:
I think this is happening coz you are calling the UserDefaults within the User class. This does not get executed until the class is initialized.

Try to do this directly in viewDidLoad(), it should work.

```<code>if UserDefaults.standard.bool(forKey:"islogged") {
    Performsegue......homescreen
}else{
    Show some alerts
}
</code>```

Body:
I have a login screen LoginViewController and homescreen HomeScreenController which is pushed when the user is successfully logged in).
I have declared a variable for UserDefaults as below in a seperate class:

class User {
    static var isLoggedIn = UserDefaults.standard.bool(forKey:"islogged")
}

When the  user clicks login Button, the code is as below

ButtonAction:
{
    User.isLoggedin = true
    //Performsegue........to homescreen
}

ViewDidload {

    if user.isloggedin == true {
        //Performsegue......homescreen
    }
    else {
        Show some alerts
    }
}

Here in my case...nothing happens...sorry for the rough code since I am using my smartphone to ask this question.

Am I missing something in appdelegate or somewhere else.
I just want to use the variables as it is because I don't want to change the entire code in my project.
The project is actually complicated and I just made an example to make you guys understand my situation.
This is not the exact code.

Body:
I think this is happening coz you are calling the UserDefaults within the User class. This does not get executed until the class is initialized.

Try to do this directly in viewDidLoad(), it should work.

if UserDefaults.standard.bool(forKey:"islogged") {
    Performsegue......homescreen
}else{
    Show some alerts
}


答:
Try this instead of  your isLoggedIn line of code</p>

```<code>static var isLoggedIn: Bool {
    get {
        return UserDefaults.standard.bool(forKey: "isLoggedIn")
    }
    set {
        UserDefaults.standard.setValue(newValue, forKey: "isLoggedIn")
        UserDefaults.standard.synchronize()
    }
}
</code>```

Title: UserDefaults not working on didload in my project

Body:
Try this instead of  your isLoggedIn line of code

static var isLoggedIn: Bool {
    get {
        return UserDefaults.standard.bool(forKey: "isLoggedIn")
    }
    set {
        UserDefaults.standard.setValue(newValue, forKey: "isLoggedIn")
        UserDefaults.standard.synchronize()
    }
}