问:
How to get the WordPress post thumbnail (featured image) URL?
I am using this function to get the featured images:

```<code><a href="#" rel="prettyPhoto">
    <?php the_post_thumbnail('thumbnail'); ?>
</a>
</code>```

Now I want to get the full featured image on click on the anchor tag for which I need a featured image URL in

```<code><a href="here" rel="prettyPhoto">
</code>```

How can I fix this?

答:
You will try this </p>

```<code><?php $url = wp_get_attachment_url(get_post_thumbnail_id($post->ID), 'full'); ?> // Here you can manage your image size like medium, thumbnail, or custom size
    <img src="<?php echo $url ?>"
/>
</code>```

Body:
I am using this function to get the featured images:

    <?php the_post_thumbnail('thumbnail'); ?>

Now I want to get the full featured image on click on the anchor tag for which I need a featured image URL in

How can I fix this?

Body:
You will try this

<?php $url = wp_get_attachment_url(get_post_thumbnail_id($post->ID), 'full'); ?> // Here you can manage your image size like medium, thumbnail, or custom size
    <img src="<?php echo $url ?>"
/>


来源: stackexchange

问:
How to pass multiple ArrayList to BaseAdapter in Android?
I am trying to pass some dynamic data to BaseAdapter to display it on listview .(using ArrayList),My current code gives me following error:

Error:

```<code>error: cannot find symbol variable ArrayList
error: cannot find symbol variable String
</code>```

Pointing to this part of code(ArrayList < String >):

```<code>CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), ArrayList<String> NameArrayList, ArrayList<String> IconArrayList);
</code>```

I check the Arraylist size and foundout that IconArrayList and NameArrayList are not empty using int itemCount = IconArrayList.size();

However If i pass following static string array to Baseadapter then it displays the data on listview!

```<code>String NameArrayList[] = {"USA", "China", "australia", "Portugle", "Norway", "NewZealand"};
String IconArrayList[] = {"http://awebsite.com/icons/usa.png", "http://awebsite.com/icons/china.png", "http://awebsite.com/icons/australia.png", "http://awebsite.com/icons/portugle.png", "http://awebsite.com/icons/norway.png", "http://awebsite.com/icons/new_zealand.png"};

CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), NameArrayList, IconArrayList);
</code>```

Could you guys help me fix above errors and pass arraylist successfully to baseAdapter so it displays it.Thanks in advance.

MainActivity.java:

```<code>import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy.Builder;

import java.io.InputStreamReader;

import java.net.URL;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.io.BufferedReader;

import java.util.ArrayList;

public class MainActivity extends Activity {

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

        sendGetRequest();

     }

public String sendGetRequest() {

         String NEW_ICON = "icon";

        ArrayList<String> IconArrayList =new ArrayList<String>();
        ArrayList<String> NameArrayList =new ArrayList<String>();
        ArrayList<String> UrlArrayList =new ArrayList<String>();

        try {

            StrictMode.setThreadPolicy(new Builder().permitAll().build());

            HttpURLConnection myURLConnection = (HttpURLConnection) new URL("http://awebsite.com/test/test.php").openConnection();

            myURLConnection.setReadTimeout(60000);
            myURLConnection.setConnectTimeout(60000);
            myURLConnection.setRequestMethod("GET");
            myURLConnection.setUseCaches(false);
            myURLConnection.setDoInput(true);
            myURLConnection.setDoOutput(true);
            myURLConnection.setRequestProperty("Content-Type", "html");
            myURLConnection.setRequestProperty("User-Agent", "Dalvik/2.1.0 (Linux; U; Android 6.0;)");

            OutputStream os = myURLConnection.getOutputStream();

            os.close();

            myURLConnection.connect();

            BufferedReader in = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream()));

            StringBuffer sb = new StringBuffer();

            String line;

            while ((line = in.readLine()) != null) {

                sb.append(line);
                sb.append("\\n");
            }
            in.close();

            String linesArray[] = sb.toString().split("#MYLIST:");

            for (int i = 0; i < linesArray.length; i++) {
                String currLine = linesArray[i];

                String[] dataArray = currLine.split(",");

                if (dataArray[0].contains(NEW_ICON)) {

                   String s =dataArray[0];

                    s = s.substring(s.indexOf("(") + 1);
                    s = s.substring(0, s.indexOf(")"));

                    IconArrayList.add(s);

                    if (dataArray[1].contains("http://")) {
                        String[] split = dataArray[1].split("http://");
                        String name = split[0];
                        String url = split[1];
                        url ="http://"+url;

                        //adding name and url to arraylist
                        NameArrayList.add(name);
                        UrlArrayList.add(url);
                      }

                }

            }// end of for loop

            //showing array list total
            int itemCount = IconArrayList.size();
            int itemCount2 = NameArrayList.size();
            int itemCount3 = UrlArrayList.size();

            ListView simpleList;
            simpleList = (ListView) findViewById(R.id.simpleListView);
            CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), ArrayList<String> NameArrayList, ArrayList<String> IconArrayList);
            simpleList.setAdapter(customAdapter);

        } catch (Exception e) {

        }
        return null;

    }
</code>```

BaseAdapter:

```<code>public class CustomAdapter extends BaseAdapter {
    Context context;
    String countryList[];

    String flags[];

    LayoutInflater inflter;

    public CustomAdapter(Context applicationContext, String[] countryList, String[] flags) {
        this.context = context;
        this.countryList = countryList;
        this.flags = flags;
        inflter = (LayoutInflater.from(applicationContext));
    }

    @Override
    public int getCount() {
        return countryList.length;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view = inflter.inflate(R.layout.activity_listview, null);
        TextView country = (TextView) view.findViewById(R.id.textView);
        ImageView icon = (ImageView) view.findViewById(R.id.icon);
        country.setText(countryList[i]);

        Picasso.with(view.getContext())
                .load(flags[i])
                //.resize(50,50)
                .into(icon);

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

答:
You are sending WRONG TYPE

```<code>CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), ArrayList<String> NameArrayList, ArrayList<String> IconArrayList);
</code>```

It will be

```<code> CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(),  NameArrayList,  IconArrayList);
</code>```

So, Your Constructor  will be

```<code>ArrayList<String> countryList;
ArrayList<String> flags;

public CustomAdapter(Context applicationContext,ArrayList<String> countryListOBJ, ArrayList<String> flagsOBJ) {
        this.context = context;
        this.countryList = countryListOBJ;
        this.flags = flagsOBJ;
        inflter = (LayoutInflater.from(applicationContext));
    }
</code>```

Then

```<code> @Override
    public int getCount() {
        return countryList.size();
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to pass some dynamic data to BaseAdapter to display it on listview .(using ArrayList),My current code gives me following error:

Error:

error: cannot find symbol variable ArrayList
error: cannot find symbol variable String

Pointing to this part of code(ArrayList < String >):

CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), ArrayList<String> NameArrayList, ArrayList<String> IconArrayList);

I check the Arraylist size and foundout that IconArrayList and NameArrayList are not empty using int itemCount = IconArrayList.size();

However If i pass following static string array to Baseadapter then it displays the data on listview!

String NameArrayList[] = {"USA", "China", "australia", "Portugle", "Norway", "NewZealand"};
String IconArrayList[] = {"http://awebsite.com/icons/usa.png", "http://awebsite.com/icons/china.png", "http://awebsite.com/icons/australia.png", "http://awebsite.com/icons/portugle.png", "http://awebsite.com/icons/norway.png", "http://awebsite.com/icons/new_zealand.png"};

CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), NameArrayList, IconArrayList);

Could you guys help me fix above errors and pass arraylist successfully to baseAdapter so it displays it.Thanks in advance.

MainActivity.java:

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy.Builder;

import java.io.InputStreamReader;

import java.net.URL;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.io.BufferedReader;

import java.util.ArrayList;

public class MainActivity extends Activity {

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

        sendGetRequest();

     }

public String sendGetRequest() {

         String NEW_ICON = "icon";

        ArrayList<String> IconArrayList =new ArrayList<String>();
        ArrayList<String> NameArrayList =new ArrayList<String>();
        ArrayList<String> UrlArrayList =new ArrayList<String>();

        try {

            StrictMode.setThreadPolicy(new Builder().permitAll().build());

            HttpURLConnection myURLConnection = (HttpURLConnection) new URL("http://awebsite.com/test/test.php").openConnection();

            myURLConnection.setReadTimeout(60000);
            myURLConnection.setConnectTimeout(60000);
            myURLConnection.setRequestMethod("GET");
            myURLConnection.setUseCaches(false);
            myURLConnection.setDoInput(true);
            myURLConnection.setDoOutput(true);
            myURLConnection.setRequestProperty("Content-Type", "html");
            myURLConnection.setRequestProperty("User-Agent", "Dalvik/2.1.0 (Linux; U; Android 6.0;)");

            OutputStream os = myURLConnection.getOutputStream();

            os.close();

            myURLConnection.connect();

            BufferedReader in = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream()));

            StringBuffer sb = new StringBuffer();

            String line;

            while ((line = in.readLine()) != null) {

                sb.append(line);
                sb.append("\\n");
            }
            in.close();

            String linesArray[] = sb.toString().split("#MYLIST:");

            for (int i = 0; i < linesArray.length; i++) {
                String currLine = linesArray[i];

                String[] dataArray = currLine.split(",");

                if (dataArray[0].contains(NEW_ICON)) {

                   String s =dataArray[0];

                    s = s.substring(s.indexOf("(") + 1);
                    s = s.substring(0, s.indexOf(")"));

                    IconArrayList.add(s);

                    if (dataArray[1].contains("http://")) {
                        String[] split = dataArray[1].split("http://");
                        String name = split[0];
                        String url = split[1];
                        url ="http://"+url;

                        //adding name and url to arraylist
                        NameArrayList.add(name);
                        UrlArrayList.add(url);
                      }

                }

            }// end of for loop

            //showing array list total
            int itemCount = IconArrayList.size();
            int itemCount2 = NameArrayList.size();
            int itemCount3 = UrlArrayList.size();

            ListView simpleList;
            simpleList = (ListView) findViewById(R.id.simpleListView);
            CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), ArrayList<String> NameArrayList, ArrayList<String> IconArrayList);
            simpleList.setAdapter(customAdapter);

        } catch (Exception e) {

        }
        return null;

    }

BaseAdapter:

public class CustomAdapter extends BaseAdapter {
    Context context;
    String countryList[];

    String flags[];

    LayoutInflater inflter;

    public CustomAdapter(Context applicationContext, String[] countryList, String[] flags) {
        this.context = context;
        this.countryList = countryList;
        this.flags = flags;
        inflter = (LayoutInflater.from(applicationContext));
    }

    @Override
    public int getCount() {
        return countryList.length;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view = inflter.inflate(R.layout.activity_listview, null);
        TextView country = (TextView) view.findViewById(R.id.textView);
        ImageView icon = (ImageView) view.findViewById(R.id.icon);
        country.setText(countryList[i]);

        Picasso.with(view.getContext())
                .load(flags[i])
                //.resize(50,50)
                .into(icon);

        return view;
    }
}

Body:
You are sending WRONG TYPE

CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), ArrayList<String> NameArrayList, ArrayList<String> IconArrayList);

It will be

 CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(),  NameArrayList,  IconArrayList);

So, Your Constructor  will be

ArrayList<String> countryList;
ArrayList<String> flags;

public CustomAdapter(Context applicationContext,ArrayList<String> countryListOBJ, ArrayList<String> flagsOBJ) {
        this.context = context;
        this.countryList = countryListOBJ;
        this.flags = flagsOBJ;
        inflter = (LayoutInflater.from(applicationContext));
    }

Then

 @Override
    public int getCount() {
        return countryList.size();
    }


问:
Updating Android SDK: "A folder failed to be moved."
While trying to update my Android SDK I am encountering this error when trying to install this particular package:

How do I fix this?

答: I just stopped the emulator, and problem was solved.</p>


问:
Remove sorting arrows in jQuery DataTables
I am using the jQuery DataTables plugin.

Is there a way I can get rid of the little arrows they display in the headers to indicate sorting options ?
I would like to keep the functionality that by click on a header it sorts by this column, I just dont want to display the arrow icons as they change the layout of my column headers.

Firebug shows my headers as follows:

```<code><th class="sorting" role="columnheader" tabindex="0" aria-controls="myTable" rowspan="1" colspan="1" style="width: 151px;" aria-label="Category: activate to sort column ascending">Category</th>
</code>```

答:
(Since DataTables 1.10) If you don't need it, disabling ordering is one way to prevent the arrow controls from appearing. Do this on table initialization by specifying the "ordering" option as false.

Example:

```<code>$("#example").DataTable({
   "ordering": false
});
</code>```

JSFiddle

Documentation:

Enable or disable ordering of columns - it is as simple as that!

Caveat: no sorting at all.

Another alternative is to disable ordering across all columns. Then you can set ordering programmatically with the control arrow(s) only displaying on sorted column(s):

```<code>var after = $('#after').DataTable({
  "order": [[1,"asc"]],                       // sorting 2nd column
  "columnDefs": [
    { "orderable": false, "targets": "_all" } // Applies the option to all columns
  ]
});
</code>```

JSFiddle

ContentLicense: CC BY-SA 4.0

Body:
I am using the jQuery DataTables plugin.

Is there a way I can get rid of the little arrows they display in the headers to indicate sorting options ?
I would like to keep the functionality that by click on a header it sorts by this column, I just dont want to display the arrow icons as they change the layout of my column headers.

Firebug shows my headers as follows:

Category

Body:
(Since DataTables 1.10) If you don't need it, disabling ordering is one way to prevent the arrow controls from appearing. Do this on table initialization by specifying the "ordering" option as false.

Example:

$("#example").DataTable({
   "ordering": false
});

JSFiddle

Documentation:

Enable or disable ordering of columns - it is as simple as that!

Caveat: no sorting at all.

Another alternative is to disable ordering across all columns. Then you can set ordering programmatically with the control arrow(s) only displaying on sorted column(s):

var after = $('#after').DataTable({
  "order": [[1,"asc"]],                       // sorting 2nd column
  "columnDefs": [
    { "orderable": false, "targets": "_all" } // Applies the option to all columns
  ]
});

JSFiddle


问:
How to handle empty URL parameter in react router dom (4.xx)
I have route defined as below :

```<code><Route path='/result/:searchTerm' component={Result}/>
</code>```

It works fine. For example localhost:3000/result/cat page works. But when the user decided to remove the :searchTerm from the URL and opens just localhost:3000/result/ it shows empty page. No errors or anything. Just empty page. It is not even hitting my component {Result} too.

So my doubt is how to handle this scenario.? Say I want to redirect the user who tries to open /result/ without :searchTerms to my index page.? How to do that.?

答:
If you want to redirect the user to another page if the param is not added, you would do the following

```<code><Switch>
   <Redirect from='/result/' to='/' exact />
   <Route path='/result/:searchTerm' component={Result}/>
</Switch>
</code>```

However if you wish to show the same page then without the params too, you could just use optional path params.
 Check this answer for more details: How to make path param to be optional in react router dom(v4)?

Body:
I have route defined as below :

<Route path='/result/:searchTerm' component={Result}/>

It works fine. For example localhost:3000/result/cat page works. But when the user decided to remove the :searchTerm from the URL and opens just localhost:3000/result/ it shows empty page. No errors or anything. Just empty page. It is not even hitting my component {Result} too.

So my doubt is how to handle this scenario.? Say I want to redirect the user who tries to open /result/ without :searchTerms to my index page.? How to do that.?

Body:
If you want to redirect the user to another page if the param is not added, you would do the following

<Switch>
   <Redirect from='/result/' to='/' exact />
   <Route path='/result/:searchTerm' component={Result}/>
</Switch>

However if you wish to show the same page then without the params too, you could just use optional path params.
 Check this answer for more details: How to make path param to be optional in react router dom(v4)?


问:
how to view in table from return JSON value using asp.net mvc
When dropdown onchange id is pass to the database and returning corresponding fields

```<code><div class="col-lg-4">
                        <fieldset class="form-group">
                            <label class="form-label" for="exampleInput">Domain Name</label>
                            @Html.DropDownList("DomainID", null, "--- Select Domain Name ---", new { @class = "select2-arrow" })
                        </fieldset>
                    </div>
</code>```

The returned JSON value we need to view corresponding fields in table.

```<code><script>
        $(document).ready(function () {

            $("#DomainID").change(function () {

                var id = $(this).val();
                $("#example tbody tr").remove();

                $.ajax({

                    type: 'POST',

                    url: '@Url.Action("ViewModules")',
                    dataType: 'json',
                    data: { id: id },
                    success: function (data) {
                        var items = '';
                        $.each(data, function (i, item) {

                            var rows = "<tr>"
                            + "<td>" + item.ModuleName + "</td>"
                            + "<td>" + item.Url + "</td>"
                            + "</tr>";
                            $('#example tbody').append(rows);
                        });

                    },
                    error: function (ex) {
                        var r = jQuery.parseJSON(response.responseText);
                        alert("Message: " + r.Message);
                        alert("StackTrace: " + r.StackTrace);
                        alert("ExceptionType: " + r.ExceptionType);
                    }
                });
                return false;
            })
        });
    </script>
</code>```

Table code

```<code><table id="example" class="display table table-bordered" cellspacing="0" width="100%;">
                        <thead>
                            <tr>
                                @*<th>S#</th>*@
                                <th>Module Name</th>
                                <th>Url</th>
                                @*<th>Roles</th>
                                <th>Action</th>*@
                            </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>
</code>```

controller code:

```<code>[HttpPost]
        [MyExceptionHandler]
        public ActionResult ViewModules(int id)
        {
            Domain_Bind();
            dynamic mymodel = new ExpandoObject();
            userType type = new userType();
            mymodel.viewRoleModules = type.GetRoleModulesViews(id);
            return Json(mymodel, JsonRequestBehavior.AllowGet);

        }
</code>```

In above code it returns 3 arrays value return Json(mymodel, JsonRequestBehavior.AllowGet);

we are pass to javascript but it shows undefined

In above image you can see there is 3 value but i cannot able to pass item.ModuleName  which is present inside the rows.

When the function success also the value shows undefined.

```<code>public List<ViewRoleModules> GetRoleModulesViews(int id)
            {
                using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Admin"].ConnectionString))
                {
                    List<ViewRoleModules> EmpList = new List<ViewRoleModules>();
                    SqlCommand com = new SqlCommand("MEDEIL_Modules_SelectDomainModules", conn);
                    com.CommandType = CommandType.StoredProcedure;
                    com.Parameters.AddWithValue("@DomainID", id);
                    SqlDataAdapter da = new SqlDataAdapter(com);
                    DataTable dt = new DataTable();

                    conn.Open();
                    da.Fill(dt);
                    conn.Close();
                    foreach (DataRow dr in dt.Rows)
                    {

                        EmpList.Add(

                            new ViewRoleModules
                            {
                                ModuleID = Convert.ToInt32(dr["ModuleID"]),
                                CompanyTypeID = Convert.ToInt32(dr["CompanyTypeID"]),
                                DomainID = Convert.ToInt32(dr["DomainID"]),
                                ParentModuleID = Convert.ToInt32(dr["ParentModuleID"]),
                                ModuleName = Convert.ToString(dr["ModuleName"]),
                                FolderName = Convert.ToString(dr["FolderName"] == DBNull.Value ? null : dr["FolderName"].ToString()),
                                Url = Convert.ToString(dr["Url"]),
                                TabOrder = Convert.ToInt32(dr["TabOrder"]),
                                Style = Convert.ToString(dr["Style"]),
                                Status = Convert.ToString(dr["Status"]),
                                IsTab = Convert.ToString(dr["IsTab"]),
                                ApprovalProcess = Convert.ToString(dr["ApprovalProcess"]),
                                CreatedBy = Convert.ToInt32(dr["CreatedBy"] == DBNull.Value ? null : dr["CreatedBy"].ToString()),
                                CreatedDate = Convert.ToDateTime(dr["CreatedDate"]),
                                ModifiedBy = Convert.ToInt32(dr["ModifiedBy"] == DBNull.Value ? null : dr["ModifiedBy"].ToString()),
                                ModifiedDate = Convert.ToDateTime(dr["ModifiedDate"] == DBNull.Value ? null : dr["ModifiedDate"].ToString())
                            }
                        );
                    }

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

答: should it be item.viewRoleModules[0].ModuleName etc ? </p>

Body:
When dropdown onchange id is pass to the database and returning corresponding fields

                        <fieldset class="form-group">
                            Domain Name
                            @Html.DropDownList("DomainID", null, "--- Select Domain Name ---", new { @class = "select2-arrow" })
                        </fieldset>

The returned JSON value we need to view corresponding fields in table.

Table code

                                @*S#	*@
                                Module Name
                                Url
                                @*Roles
                                Action	*@

controller code:

[HttpPost]
        [MyExceptionHandler]
        public ActionResult ViewModules(int id)
        {
            Domain_Bind();
            dynamic mymodel = new ExpandoObject();
            userType type = new userType();
            mymodel.viewRoleModules = type.GetRoleModulesViews(id);
            return Json(mymodel, JsonRequestBehavior.AllowGet);

        }

In above code it returns 3 arrays value return Json(mymodel, JsonRequestBehavior.AllowGet);

we are pass to javascript but it shows undefined

In above image you can see there is 3 value but i cannot able to pass item.ModuleName  which is present inside the rows.

When the function success also the value shows undefined.

public List<ViewRoleModules> GetRoleModulesViews(int id)
            {
                using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Admin"].ConnectionString))
                {
                    List<ViewRoleModules> EmpList = new List<ViewRoleModules>();
                    SqlCommand com = new SqlCommand("MEDEIL_Modules_SelectDomainModules", conn);
                    com.CommandType = CommandType.StoredProcedure;
                    com.Parameters.AddWithValue("@DomainID", id);
                    SqlDataAdapter da = new SqlDataAdapter(com);
                    DataTable dt = new DataTable();

                    conn.Open();
                    da.Fill(dt);
                    conn.Close();
                    foreach (DataRow dr in dt.Rows)
                    {

                        EmpList.Add(

                            new ViewRoleModules
                            {
                                ModuleID = Convert.ToInt32(dr["ModuleID"]),
                                CompanyTypeID = Convert.ToInt32(dr["CompanyTypeID"]),
                                DomainID = Convert.ToInt32(dr["DomainID"]),
                                ParentModuleID = Convert.ToInt32(dr["ParentModuleID"]),
                                ModuleName = Convert.ToString(dr["ModuleName"]),
                                FolderName = Convert.ToString(dr["FolderName"] == DBNull.Value ? null : dr["FolderName"].ToString()),
                                Url = Convert.ToString(dr["Url"]),
                                TabOrder = Convert.ToInt32(dr["TabOrder"]),
                                Style = Convert.ToString(dr["Style"]),
                                Status = Convert.ToString(dr["Status"]),
                                IsTab = Convert.ToString(dr["IsTab"]),
                                ApprovalProcess = Convert.ToString(dr["ApprovalProcess"]),
                                CreatedBy = Convert.ToInt32(dr["CreatedBy"] == DBNull.Value ? null : dr["CreatedBy"].ToString()),
                                CreatedDate = Convert.ToDateTime(dr["CreatedDate"]),
                                ModifiedBy = Convert.ToInt32(dr["ModifiedBy"] == DBNull.Value ? null : dr["ModifiedBy"].ToString()),
                                ModifiedDate = Convert.ToDateTime(dr["ModifiedDate"] == DBNull.Value ? null : dr["ModifiedDate"].ToString())
                            }
                        );
                    }

                    return EmpList;
                }
            }


问:
How to focus or select a cell in Excel
How to focus a cell in Excel VSTO using C# or to select first cell using C# in VSTO?</p>

答:
```<code> Excel.Application ExcelApp = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
            Excel.Workbook book = ExcelApp.ActiveWorkbook;
            Excel.Worksheet sheet = book.ActiveSheet;
            Excel.Range ExcelRange = sheet.get_Range("A1");
            ExcelRange.Select();
</code>```

Title: How to focus or select a cell in Excel


问:
Weblogic blocks Rest Post call by asking for authentication
I am trying to post a file to a URL programmatically. This URL is protected by its own username/password.
I have inherited this URL (or application) - so it is in my ownership. It is basically a web application used to host some files.

I have created an HttpClient which takes HttpPost consisting of the URL and file to be uploaded.

```<code>  this.httpClient = new DefaultHttpClient();
this.httpClient.getCredentialsProvider().setCredentials(new AuthScope(this.host, this.port), new UsernamePasswordCredentials(this.username, this.password));

  HttpResponse response = this.httpClient.execute(httpPost, this.context);
  HttpEntity resEntity = response.getEntity();

  log("Received HTTP response: " + response.getStatusLine().getReasonPhrase(), LogLevel.INFO.getLevel());
</code>```

But somehow weblogic authentication blocks it and I receive "Unauthorized" response. If I use the username/password of weblogic admin console, then authentication is fine but fails while uploading since the URL is protected by a different credential(Same as the one I am trying to upload with).

Any idea what am I doing worng? Why weblogic is asking for its own authentication?

答: I found the solution for this issue. I needed to set enforce-valid-basic-auth-credentials equal to false in domain config.xml . This bypasses weblogic authentication and the application authentication kicks in.</p>

Body:
I am trying to post a file to a URL programmatically. This URL is protected by its own username/password.
I have inherited this URL (or application) - so it is in my ownership. It is basically a web application used to host some files.

I have created an HttpClient which takes HttpPost consisting of the URL and file to be uploaded.

  this.httpClient = new DefaultHttpClient();
this.httpClient.getCredentialsProvider().setCredentials(new AuthScope(this.host, this.port), new UsernamePasswordCredentials(this.username, this.password));

  HttpResponse response = this.httpClient.execute(httpPost, this.context);
  HttpEntity resEntity = response.getEntity();

  log("Received HTTP response: " + response.getStatusLine().getReasonPhrase(), LogLevel.INFO.getLevel());

But somehow weblogic authentication blocks it and I receive "Unauthorized" response. If I use the username/password of weblogic admin console, then authentication is fine but fails while uploading since the URL is protected by a different credential(Same as the one I am trying to upload with).

Any idea what am I doing worng? Why weblogic is asking for its own authentication?


问:
PHP $_POST function with a table
I have a table, in a grid of 4x4. Assume they're all black boxes. I now have it so that when I hover, they turn grey.

However, how would I make it so that if you click on a table cell, it stays grey, and I can somehow pass that cell's coordinates to a $_POST function? I hope I am being descriptive enough.

答:
Library agnostic way of doing it: http://jsfiddle.net/sdleihssirhc/eBD9L/

It uses td:hover, so it won't work on IE6 and whatnot.

ContentLicense: CC BY-SA 2.5

Title: PHP $_POST function with a table


问:
How to check the cycles in Prolog?
I have the Prolog predicates:

```<code>gen(c1, c2).
gen(c2, c1).
gen(c2, c3).
gen(c3, c1).
</code>```

I want to write a rule to check that there are no cycles in the gen/2 predicates. How should I write this rule?

答:
At beginning we will try to consider it from top to bottom.

What mean that there is no cycle?

~False that it has any cycle.

What mean that it has any cycle ?

~I can go from one node to same node, through other nodes.

How can I check that I can go to the same node through other nodes?

~ Append to the empty list nodes, that I can go from start one, and than add other nodes that I can archive from these nodes (and don't add NODES THAT I ALREADY HAVE IN LIST!!!!!!!!!)

```<code>node(X) :-
        gen(X,_) ; gen(_,X).

canGoTo(X,N, Nodes) :-
        member(X2, [X|Nodes]), gen(X2, X1),
        \+ member(X1, Nodes),
        canGoTo(X, N, [X1|Nodes]).

canGoTo(_,N,N).

canGoTo(X,Nodes) :- canGoTo(X,Nodes,[]).

canGoToSelf(X) :- canGoTo(X,Nodes), member(X,Nodes),!.

isCycle() :- node(X) , canGoToSelf(X),!.

noCycles() :- \+ isCycle().
</code>```

Title: How to check the cycles in Prolog?

Body:
I have the Prolog predicates:

gen(c1, c2).
gen(c2, c1).
gen(c2, c3).
gen(c3, c1).

I want to write a rule to check that there are no cycles in the gen/2 predicates. How should I write this rule?

Body:
At beginning we will try to consider it from top to bottom.

What mean that there is no cycle?

~False that it has any cycle.

What mean that it has any cycle ?

~I can go from one node to same node, through other nodes.

How can I check that I can go to the same node through other nodes?

~ Append to the empty list nodes, that I can go from start one, and than add other nodes that I can archive from these nodes (and don't add NODES THAT I ALREADY HAVE IN LIST!!!!!!!!!)

node(X) :-
        gen(X,_) ; gen(_,X).

canGoTo(X,N, Nodes) :-
        member(X2, [X|Nodes]), gen(X2, X1),
        \+ member(X1, Nodes),
        canGoTo(X, N, [X1|Nodes]).

canGoTo(_,N,N).

canGoTo(X,Nodes) :- canGoTo(X,Nodes,[]).

canGoToSelf(X) :- canGoTo(X,Nodes), member(X,Nodes),!.

isCycle() :- node(X) , canGoToSelf(X),!.

noCycles() :- \+ isCycle().


问:
queryset.update is not working in for loop
I want to change the name for any database variable if its match abc.

```<code>def icall(modeladmin, request, queryset):
    for pri in queryset:
        print('from test:', pri.name, pri.title) # priting if working fine
        if pri.name == 'abc':        # loop is matching the condition
            pri.update(name='zzz')  ## the value is not getting update in DB
        else:
            print("gg not mached")
</code>```

the pri.update(name='zzz') os not working here.

can someone please help me to know the correct statement to update the database based on the if else condition.

答:
You cannot update a single object using the update query. Can update objects in a queryset as a whole using update. Please refer the document for clarification: Django Update query

In your case. You can do:

```<code>queryset.filter(name='abc').update(name='zzz')
</code>```

instead of the for-loop.

OR

```<code>for pri in queryset:
    if pri.name == 'abc':        # loop is matching the condition
        pri.name='zzz'
        pri.save() # save the updated value
</code>```

This is in case you have signals attached to your models. The Update query does not actually use django save and consequently does not emit pre_save,  post_save signals.

Body:
I want to change the name for any database variable if its match abc.

def icall(modeladmin, request, queryset):
    for pri in queryset:
        print('from test:', pri.name, pri.title) # priting if working fine
        if pri.name == 'abc':        # loop is matching the condition
            pri.update(name='zzz')  ## the value is not getting update in DB
        else:
            print("gg not mached")

the pri.update(name='zzz') os not working here.

can someone please help me to know the correct statement to update the database based on the if else condition.

Body:
You cannot update a single object using the update query. Can update objects in a queryset as a whole using update. Please refer the document for clarification: Django Update query

In your case. You can do:

queryset.filter(name='abc').update(name='zzz')

instead of the for-loop.

OR

for pri in queryset:
    if pri.name == 'abc':        # loop is matching the condition
        pri.name='zzz'
        pri.save() # save the updated value

This is in case you have signals attached to your models. The Update query does not actually use django save and consequently does not emit pre_save,  post_save signals.


问:
Generate a random geopoint from a fixed distance from a given latitude and longitude
I am writing a java program to generate a all the longitude and latitude with a fixed distance from my my given point. the distance must be exact 2000km, not withub 2000km.

this is my code

```<code>public static void getLocation(double x0, double y0, int meters) {
        Random random = new Random();

        // Convert radius from meters to degrees
        double radiusInDegrees = meters / 111000f;

        double u = random.nextDouble();
        double v = random.nextDouble();
        double w = radiusInDegrees * Math.sqrt(u);
        double t = 2 * Math.PI * v;
        double x = w * Math.cos(t);
        double y = w * Math.sin(t);

        // Adjust the x-coordinate for the shrinking of the east-west distances
       // double new_x = x / Math.cos(Math.toRadians(y0));

        double foundLongitude = x + x0;
        double foundLatitude = y + y0;
        System.out.println("Longitude: " + foundLongitude + "  Latitude: " + foundLatitude );
    }
</code>```

How do I make all the point generate equal distance from the geo point, like forming a circle?

答:
```<code>public static void generatePoint(double latitude, double longitude, double distanceInMetres, double bearing) {
        Random random = new Random();

        //int bear = random.nextInt(360);
        double brngRad = Math.toRadians(bearing);
        double latRad = Math.toRadians(latitude);
        double lonRad = Math.toRadians(longitude);
        int earthRadiusInMetres = 6371000;
        double distFrac = distanceInMetres / earthRadiusInMetres;

        double latitudeResult = Math.asin(Math.sin(latRad) * Math.cos(distFrac) + Math.cos(latRad) * Math.sin(distFrac) * Math.cos(brngRad));
        double a = Math.atan2(Math.sin(brngRad) * Math.sin(distFrac) * Math.cos(latRad), Math.cos(distFrac) - Math.sin(latRad) * Math.sin(latitudeResult));
        double longitudeResult = (lonRad + a + 3 * Math.PI) % (2 * Math.PI) - Math.PI;

        System.out.println("bearing: "+bearing+ ", latitude: " + Math.toDegrees(latitudeResult) + ", longitude: " + Math.toDegrees(longitudeResult));
    }
</code>```

need to add bearing

Body:
I am writing a java program to generate a all the longitude and latitude with a fixed distance from my my given point. the distance must be exact 2000km, not withub 2000km.

this is my code

public static void getLocation(double x0, double y0, int meters) {
        Random random = new Random();

        // Convert radius from meters to degrees
        double radiusInDegrees = meters / 111000f;

        double u = random.nextDouble();
        double v = random.nextDouble();
        double w = radiusInDegrees * Math.sqrt(u);
        double t = 2 * Math.PI * v;
        double x = w * Math.cos(t);
        double y = w * Math.sin(t);

        // Adjust the x-coordinate for the shrinking of the east-west distances
       // double new_x = x / Math.cos(Math.toRadians(y0));

        double foundLongitude = x + x0;
        double foundLatitude = y + y0;
        System.out.println("Longitude: " + foundLongitude + "  Latitude: " + foundLatitude );
    }

How do I make all the point generate equal distance from the geo point, like forming a circle?

Body:
public static void generatePoint(double latitude, double longitude, double distanceInMetres, double bearing) {
        Random random = new Random();

        //int bear = random.nextInt(360);
        double brngRad = Math.toRadians(bearing);
        double latRad = Math.toRadians(latitude);
        double lonRad = Math.toRadians(longitude);
        int earthRadiusInMetres = 6371000;
        double distFrac = distanceInMetres / earthRadiusInMetres;

        double latitudeResult = Math.asin(Math.sin(latRad) * Math.cos(distFrac) + Math.cos(latRad) * Math.sin(distFrac) * Math.cos(brngRad));
        double a = Math.atan2(Math.sin(brngRad) * Math.sin(distFrac) * Math.cos(latRad), Math.cos(distFrac) - Math.sin(latRad) * Math.sin(latitudeResult));
        double longitudeResult = (lonRad + a + 3 * Math.PI) % (2 * Math.PI) - Math.PI;

        System.out.println("bearing: "+bearing+ ", latitude: " + Math.toDegrees(latitudeResult) + ", longitude: " + Math.toDegrees(longitudeResult));
    }

need to add bearing


问:
No resource found that matches the given name: attr 'android:keyboardNavigationCluster'. when updating to Support Library 26.0.0
I've got this issue while updating to the latest Support Library version 26.0.0 (https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-0):

Error:(18, 21) No resource found that matches the given name: attr
  'android:keyboardNavigationCluster'.

```<code>/.../app/build/intermediates/res/merged/beta/debug/values-v26/values-v26.xml
Error:(15, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:(18, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:(15, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:(18, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:Execution failed for task ':app:processBetaDebugResources'.
</code>```

com.android.ide.common.process.ProcessException: Failed to execute aapt

The file is from the support library:

```<code><style name="Base.V26.Widget.AppCompat.Toolbar" parent="Base.V7.Widget.AppCompat.Toolbar">
    <item name="android:touchscreenBlocksFocus">true</item>
    <item name="android:keyboardNavigationCluster">true</item>
</style>
</code>```

We're using the following versions:

```<code>ext.COMPILE_SDK_VERSION = 26
ext.BUILD_TOOLS_VERSION = "26.0.1"

ext.MIN_SDK_VERSION = 17
ext.TARGET_SDK_VERSION = 26
ext.ANDROID_SUPPORT_LIBRARY_VERSION = "26.0.0"
ext.GOOGLE_PLAY_SERVICES_LIBRARY_VERSION = "11.0.2"
</code>```

```<code>compile 'com.android.support:appcompat-v7:' + ANDROID_SUPPORT_LIBRARY_VERSION
compile 'com.android.support:design:' + ANDROID_SUPPORT_LIBRARY_VERSION
compile 'com.android.support:recyclerview-v7:' + ANDROID_SUPPORT_LIBRARY_VERSION
</code>```

Any ideas?

答:
update these in gradle

compileSdkVersion 27
buildToolsVersion '27.0.1'

Body:
I've got this issue while updating to the latest Support Library version 26.0.0 (https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-0):

Error:(18, 21) No resource found that matches the given name: attr
  'android:keyboardNavigationCluster'.

/.../app/build/intermediates/res/merged/beta/debug/values-v26/values-v26.xml
Error:(15, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:(18, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:(15, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:(18, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:Execution failed for task ':app:processBetaDebugResources'.

com.android.ide.common.process.ProcessException: Failed to execute aapt

The file is from the support library:

We're using the following versions:

ext.COMPILE_SDK_VERSION = 26
ext.BUILD_TOOLS_VERSION = "26.0.1"

ext.MIN_SDK_VERSION = 17
ext.TARGET_SDK_VERSION = 26
ext.ANDROID_SUPPORT_LIBRARY_VERSION = "26.0.0"
ext.GOOGLE_PLAY_SERVICES_LIBRARY_VERSION = "11.0.2"

compile 'com.android.support:appcompat-v7:' + ANDROID_SUPPORT_LIBRARY_VERSION
compile 'com.android.support:design:' + ANDROID_SUPPORT_LIBRARY_VERSION
compile 'com.android.support:recyclerview-v7:' + ANDROID_SUPPORT_LIBRARY_VERSION

Any ideas?


问:
How to handle very large arrays in php?
I have this block of code.

```<code>$input = 4;
$list_N = array('0', '1');
for($n=1; $n<=$input; $n++) {

    if($n%2 == 0) {
        $c++;
    }

    $reverse_list_N = array_reverse($list_N);

    $A = array();
    $B = array();

    for($i=0; $i<count($list_N); $i++) {
        $A[] = '0' . $list_N[$i];
        $B[] = '1' . $reverse_list_N[$i];
    }

    $list_N = array_merge($A[], $B[]);

    if($n == 1) {
        $list_N = array('0', '1');
    }
}
$array_sliced = array_slice($list_N, -1*$input, $input);
for($i=0; $i<count($array_sliced); $i++) {
    $output = implode("\n", $array_sliced);
}
echo "```"; print_r($output); echo "```";
</code>```

What this code does is, it generates following data (starting from (0,1)):

```<code>0,1
00, 01, 11, 10
000, 001, 011, 010, 110, 111, 101, 100
....... and so on
</code>```

When $input = 4; the output is:

```<code>1010
1011
1001
1000
</code>```

And as you can see, after every loop the the elements in the $list_N array doubles than the previous one. And with this pace if $input = 25; then the array would have 33554432 elements which is very huge. And that is the problem I couldn't find a solution of. When $input = 60 I get this error

```<code>Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 36 bytes)
</code>```

on this line

```<code>$list_N = array_merge($A, $B);
</code>```

Even setting the memory limit to 2G did not solve it. So, how do I optimize my code in order to same the memory. Or, is there any other solution ?

Update: Following steps are used to generate the data.

```<code>$list_N is an array
$reverse_list is the reverse of $list_N
0 is appended in the beginning of every element in the $list_N array and stored in $A
1 is appended in the beginning of every element in the $reverse_list_N array and stored in $B
Array $A and array $B are merged and is stored in $list_N.
The main loop runs for $input number of times and the last $input number of elements are displayed from the final array.
</code>```

答:
@tadman was right. This requires a different approach. I ran the numbers, the array size at input 65 assuming just 1 byte per array element is 32 Exabytes (insane amount of memory required just to run this script).

Here is a working solution (make sure you enter the input to make the script run):

//we assume user will enter input as a valid positive integer > 1

```<code>fscanf(STDIN, "%d\n", $target);

$base=["0","1"];
$root=["0","1"];

$newArr=$base;
for($i=1;$i<7;$i++)//pre-initialize root array
  $newArr=genNextArray($newArr);

//echo "-----------\n";

//print_r($root);

//we're ready to display the output now based on the root array elements
displayNBits($target);

function displayNBits($target)
{
  global $root;
  $arr=array();

  for($i=0;$i<$target;$i++)
  {
    $elem=str_pad($root[$i],$target,"0",STR_PAD_LEFT);
    $elem[0]="1";
    $arr[]=$elem;

  }

  $arr=array_reverse($arr);

  for($i=0;$i<count($arr);$i++)
    echo $arr[$i]."\n";

  //print_r($arr);
}

function genNextArray($arr)
{
  global $root;

  $newArr= array(count($arr)*2);

  $ni=0;

  //0 prefix (left to right sweep)
  for($i=0;$i<count($arr);$i++)
  {
    $newArr[$ni]="0".$arr[$i];
    $ni++;
  }

  //1 prefix (right to left sweep)
  for($i=count($arr)-1;$i>=0;$i--)
  {
    $newArr[$ni]="1".$arr[$i];
    $root[]=$newArr[$ni];
    $ni++;
  }

  return $newArr;
}
</code>```

Title: How to handle very large arrays in php?

Body:
I have this block of code.

$input = 4;
$list_N = array('0', '1');
for($n=1; $n<=$input; $n++) {

    if($n%2 == 0) {
        $c++;
    }

    $reverse_list_N = array_reverse($list_N);

    $A = array();
    $B = array();

    for($i=0; $i<count($list_N); $i++) {
        $A[] = '0' . $list_N[$i];
        $B[] = '1' . $reverse_list_N[$i];
    }

    $list_N = array_merge($A[], $B[]);

    if($n == 1) {
        $list_N = array('0', '1');
    }
}
$array_sliced = array_slice($list_N, -1*$input, $input);
for($i=0; $i<count($array_sliced); $i++) {
    $output = implode("\n", $array_sliced);
}
echo "
"; print_r($output); echo "
";

What this code does is, it generates following data (starting from (0,1)):

0,1
00, 01, 11, 10
000, 001, 011, 010, 110, 111, 101, 100
....... and so on

When $input = 4; the output is:

1010
1011
1001
1000

And as you can see, after every loop the the elements in the $list_N array doubles than the previous one. And with this pace if $input = 25; then the array would have 33554432 elements which is very huge. And that is the problem I couldn't find a solution of. When $input = 60 I get this error

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 36 bytes)

on this line

$list_N = array_merge($A, $B);

Even setting the memory limit to 2G did not solve it. So, how do I optimize my code in order to same the memory. Or, is there any other solution ?

Update: Following steps are used to generate the data.

$list_N is an array
$reverse_list is the reverse of $list_N
0 is appended in the beginning of every element in the $list_N array and stored in $A
1 is appended in the beginning of every element in the $reverse_list_N array and stored in $B
Array $A and array $B are merged and is stored in $list_N.
The main loop runs for $input number of times and the last $input number of elements are displayed from the final array.

Body:
@tadman was right. This requires a different approach. I ran the numbers, the array size at input 65 assuming just 1 byte per array element is 32 Exabytes (insane amount of memory required just to run this script).

Here is a working solution (make sure you enter the input to make the script run):

//we assume user will enter input as a valid positive integer > 1

fscanf(STDIN, "%d\n", $target);

$base=["0","1"];
$root=["0","1"];

$newArr=$base;
for($i=1;$i<7;$i++)//pre-initialize root array
  $newArr=genNextArray($newArr);

//echo "-----------\n";

//print_r($root);

//we're ready to display the output now based on the root array elements
displayNBits($target);

function displayNBits($target)
{
  global $root;
  $arr=array();

  for($i=0;$i<$target;$i++)
  {
    $elem=str_pad($root[$i],$target,"0",STR_PAD_LEFT);
    $elem[0]="1";
    $arr[]=$elem;

  }

  $arr=array_reverse($arr);

  for($i=0;$i<count($arr);$i++)
    echo $arr[$i]."\n";

  //print_r($arr);
}

function genNextArray($arr)
{
  global $root;

  $newArr= array(count($arr)*2);

  $ni=0;

  //0 prefix (left to right sweep)
  for($i=0;$i<count($arr);$i++)
  {
    $newArr[$ni]="0".$arr[$i];
    $ni++;
  }

  //1 prefix (right to left sweep)
  for($i=count($arr)-1;$i>=0;$i--)
  {
    $newArr[$ni]="1".$arr[$i];
    $root[]=$newArr[$ni];
    $ni++;
  }

  return $newArr;
}


问:
Magento Product rating calculation performance
If my web pages show many products (include title and rating), then web page needs to calculate rating percentage by every products with following code.
I am sure this kinds of calculation will slow down my web page.
Is this the only choice that i can choose, or is there any better performance code that i can use?</p>

```<code>            if (count($reviews) > 0)
            {
                foreach ($reviews->getItems() as $review)
                {
                    foreach( $review->getRatingVotes() as $vote )
                    {
                        $ratings[] = $vote->getPercent();
                    }
                }
                $avg = array_sum($ratings)/count($ratings);
            }
</code>```

答:
You can use below code to get rating on any page:</p>

```<code><?php
    $storeId = Mage::app()->getStore()->getId();
    $summaryData = Mage::getModel('review/review_summary')->setStoreId($storeId)  ->load($_product->getId());
    ?>
<?php if($_product->getRatingSummary()): ?>
<?php if($summaryData['rating_summary']){ ?><div class="rating-box"><div class="rating" style="width:<?php echo $summaryData['rating_summary']; ?>%"></div></div>(<?php echo $_product->getRatingSummary()->getReviewsCount(); ?>)<?php } ?>
<?php endif; ?>
</code>```

Body:
If my web pages show many products (include title and rating), then web page needs to calculate rating percentage by every products with following code.
I am sure this kinds of calculation will slow down my web page.
Is this the only choice that i can choose, or is there any better performance code that i can use?

            if (count($reviews) > 0)
            {
                foreach ($reviews->getItems() as $review)
                {
                    foreach( $review->getRatingVotes() as $vote )
                    {
                        $ratings[] = $vote->getPercent();
                    }
                }
                $avg = array_sum($ratings)/count($ratings);
            }

Body:
You can use below code to get rating on any page:

<?php
    $storeId = Mage::app()->getStore()->getId();
    $summaryData = Mage::getModel('review/review_summary')->setStoreId($storeId)  ->load($_product->getId());
    ?>
<?php if($_product->getRatingSummary()): ?>
<?php if($summaryData['rating_summary']){ ?><div class="rating-box"><div class="rating" style="width:<?php echo $summaryData['rating_summary']; ?>%"></div></div>(<?php echo $_product->getRatingSummary()->getReviewsCount(); ?>)<?php } ?>
<?php endif; ?>


问:
Bluemix Git connect to Git Desktop
I have created a new project in Bluemix with a Text to Speech Service. I added a toolchain with a new Git Repo. I have created a key on the computer and copied that key into the Bluemix RepositoryDeploy Keys section.

When I go to the computer Git Desktop I get an authentication error. I have tried everything and can't get it to authenticate.

答:
Here are the steps I used to import a GitLab repository into GitHub Desktop:

Set up git authentication with SSH (I had trouble getting this to work with HTTPs -- kept getting Failed authentication errors). To generate a key, follow the instructions here.

Clone the repository using the git cli (git clone git@git.ng.bluemix.net:...)

Add to GitHub Desktop by going File > Add Local Repository

Finally, after making a change, I was able to sync the repository and push the changes up

I got a gpg error when I ran it for the first time and found this solution to solve that (you may / may not run into this):

```<code>git config --global gpg.program $(which gpg)
</code>```

https://github.com/isaacs/github/issues/675

Title: Bluemix Git connect to Git Desktop

Body:
Here are the steps I used to import a GitLab repository into GitHub Desktop:

Set up git authentication with SSH (I had trouble getting this to work with HTTPs -- kept getting Failed authentication errors). To generate a key, follow the instructions here.

Clone the repository using the git cli (git clone git@git.ng.bluemix.net:...)

Add to GitHub Desktop by going File > Add Local Repository

Finally, after making a change, I was able to sync the repository and push the changes up

I got a gpg error when I ran it for the first time and found this solution to solve that (you may / may not run into this):

git config --global gpg.program $(which gpg)

https://github.com/isaacs/github/issues/675


问:
No route to host error in socket programming
I am writing a simple client program which connects to a the ip address "172.31.1.34" and sends a message. Everything works fine but I am not able to recieve any message from the server. The error says "no route to host".
My code</p>

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main()
{
    struct sockaddr_in server,client;
    int s1,s2,len;
    int n;
    char buffer[500];

    strcpy(buffer,"GET http://172.31.1.34/ HTTP/1.0\n\n");
    bzero((char *)&client,sizeof(client));
    client.sin_port = htons(80);
    client.sin_addr.s_addr = inet_addr("172.31.1.34");
    client.sin_family = AF_INET;
    s2 = socket(AF_INET,SOCK_DGRAM,0);

    if(connect(s2,(struct sockaddr *)&client,sizeof(client)) == -1) {
        perror("can't connect\n");
        exit(1);
    }
    n = send(s2,buffer,strlen(buffer),0);
    if(n < 0) {
        perror("message not sent");
        exit(1);
    }
    while(1) {
        memset(buffer,0,sizeof(buffer));
        n = recv(s2,buffer,500,0);
        if(n < 0) {
            perror("coudnot read");
            exit(1);
        }
        buffer[n] = '\0';
        printf("%s",buffer);
    }

    close(s2);
    return 0;
}
</code>```

答:
Try the code below instead:</p>

```<code>client.sin_addr.s_addr = inet_addr("172.31.1.34");
inet_pton(AF_INET, "172.31.1.34", &client.sin_addr);
</code>```

Body:
I am writing a simple client program which connects to a the ip address "172.31.1.34" and sends a message. Everything works fine but I am not able to recieve any message from the server. The error says "no route to host".
My code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main()
{
    struct sockaddr_in server,client;
    int s1,s2,len;
    int n;
    char buffer[500];

    strcpy(buffer,"GET http://172.31.1.34/ HTTP/1.0\n\n");
    bzero((char *)&client,sizeof(client));
    client.sin_port = htons(80);
    client.sin_addr.s_addr = inet_addr("172.31.1.34");
    client.sin_family = AF_INET;
    s2 = socket(AF_INET,SOCK_DGRAM,0);

    if(connect(s2,(struct sockaddr *)&client,sizeof(client)) == -1) {
        perror("can't connect\n");
        exit(1);
    }
    n = send(s2,buffer,strlen(buffer),0);
    if(n < 0) {
        perror("message not sent");
        exit(1);
    }
    while(1) {
        memset(buffer,0,sizeof(buffer));
        n = recv(s2,buffer,500,0);
        if(n < 0) {
            perror("coudnot read");
            exit(1);
        }
        buffer[n] = '\0';
        printf("%s",buffer);
    }

    close(s2);
    return 0;
}

Body:
Try the code below instead:

client.sin_addr.s_addr = inet_addr("172.31.1.34");
inet_pton(AF_INET, "172.31.1.34", &client.sin_addr);


问:
Swift: can properties be required based on another property being set?
I want to re-use a single viewcontroller but re-purposed slightly and I'm wondering if there is a structured way to require some properties to be set based on another property.

For example assume that the viewcontroller has the following properties
- var displayMode: DisplayMode // see below
- var id: Int
- var description: String
- var name: String

If we are in quickView mode then I expect a ID and Description values to be set.
Else if we are in defaultView mode I expect the Name property to be set.

```<code>enum DisplayMode {
    case quickView
    case defaultView
}
</code>```

Obviously I could just set those and expect them to be set but I'm wondering if there is a structured Swift-like way of forcing this, like having the properties nested in the DisplayMode type?

答:
Consider using associated values for your enum cases, like so:

```<code>enum DisplayMode {
    case quickview(id: Int, description: String)
    case defaultview(name: String)
}
</code>```

This forces the user to provide valid associated values whenever a DisplayMode variable is declared:

```<code>var mode = DisplayMode.quickView(id: 11, description: "Prosecco")
</code>```

To get the associated values back out, you bind them to variables in your switch:

```<code>switch mode {
case let .quickView(id, description):
    // do something with id and description
case let .defaultview(name):
    // do something with name
}
</code>```

By using associated values, you wouldn't have to declare stand-alone properties (i.e. object variables) for id, description, or name.

Body:
I want to re-use a single viewcontroller but re-purposed slightly and I'm wondering if there is a structured way to require some properties to be set based on another property.

For example assume that the viewcontroller has the following properties
- var displayMode: DisplayMode // see below
- var id: Int
- var description: String
- var name: String

If we are in quickView mode then I expect a ID and Description values to be set.
Else if we are in defaultView mode I expect the Name property to be set.

enum DisplayMode {
    case quickView
    case defaultView
}

Obviously I could just set those and expect them to be set but I'm wondering if there is a structured Swift-like way of forcing this, like having the properties nested in the DisplayMode type?

Body:
Consider using associated values for your enum cases, like so:

enum DisplayMode {
    case quickview(id: Int, description: String)
    case defaultview(name: String)
}

This forces the user to provide valid associated values whenever a DisplayMode variable is declared:

var mode = DisplayMode.quickView(id: 11, description: "Prosecco")

To get the associated values back out, you bind them to variables in your switch:

switch mode {
case let .quickView(id, description):
    // do something with id and description
case let .defaultview(name):
    // do something with name
}

By using associated values, you wouldn't have to declare stand-alone properties (i.e. object variables) for id, description, or name.


问:
Wrapping Async/Main Thread blocks around code
I am writing some code to let the user tap a button to log in, and after the login is successful, immediately make another call to pull in data from the system if it's available. I'm a little confused about where I need/don't need to wrap my code in different thread blocks. Can I just put everything in DispatchQueue.main.async given that I'm doing UI work on the main thread? Here is my code flow - I was wondering if someone could review and let me know if I've got the right structure of wrapping code in async/main thread blocks.

```<code>let messageFrame = AlertCreator.progressBarDisplayer(view: self.view, message: "Loading", true)

DispatchQueue.main.async(execute: {

  //Present loading spinner while call is made
  self.view.addSubview(messageFrame)

  //Make an AUTH call using URLSession.shared.dataTask (with callback)
  UserSecurityService.AuthenticateUser(username: self.txtUsername.text!, password: self.txtPassword.text!)
     { (authenticationResponse) -> () in

        if (authenticationResponse.Status == ResponseCode.LOGIN_SUCCESS)
         {
              //If this user logged in successfully, and now need to import data, then do so, otherwise just proceed to the app.
              if (authenticationResponse.Value!.HasDataForImport) {

                         //Make ANOTHER async call using URLSession.shared.dataTask (with callback)
                          UserDataService.GetUserSettings()
                                { response in
                                     //Remove the spinner
                                     messageFrame.removeFromSuperview()

                                    if (response.Status == ResponseCode.OK)
                                    {
                                        //Success, go to dashboard
                                        self.presentHomeViewController()
                                    }
                                    else {
                                        //Show alert failure, with clicking 'ok' firing a callback to take the user to the dashboard
                                    }
                               }
                   }
                  else {
                      //Data does not exist, so just stop the spinner and take the user to the dashboard
                        self.presentHomeViewController()
                  }
          else if (authenticationResponse.Status == ResponseCode.INVALID_USERNAME_PASSWORD) {
                 //User entered the wrong username/password
                  messageFrame.removeFromSuperview()
                 <alert is created/presented here>
                 }
}) //main dispatch async execute
</code>```

If you noticed, I am making an async call to authenticate, that does something on the UI (shows a spinner to prevent any other activity, checks if the login was successful or not, and removes the spinner. It also potentially presents an alert, and then takes the user to a view controller.

My questions specifically are:

Should I not wrap this entire block in DispatchQueue.main.async, but
rather only the two web calls? I've done all kinds of combinations, most of which worked (and some that crashed), so I'm not entirely sure if I just need DispatchQueue.main.async, or need something nested inside of it such as a DispatchQueue.global(qos: DispatchQoS.QoSClass.userInteractive).async as well?

Should I wrap each web call, or only the outer one

Should I be wrapping the UI-related things in their own blocks, for example when I present alerts, view controllers, or even stop
the spinner? 3.

Thank you for any assistance / suggestions you could provide!

答:
I have tried adding DispatchQueue.main and DispatchQueue.global stub to your question just to show how to and when to switch between queue. This may not be a complete copy, paste solution as I dont have complete code of yours so I could not compile it. This is intended only to show how to use DispatchQueue

```<code>let messageFrame = AlertCreator.progressBarDisplayer(view: self.view, message: "Loading", true)
        //Present loading spinner while call is made
        self.view.addSubview(messageFrame)

        DispatchQueue.global(qos: .default).async {
            //Make an AUTH call using URLSession.shared.dataTask (with callback)
            UserSecurityService.AuthenticateUser(username: self.txtUsername.text!, password: self.txtPassword.text!)
            { (authenticationResponse) -> () in

                if (authenticationResponse.Status == ResponseCode.LOGIN_SUCCESS)
                {
                    //If this user logged in successfully, and now need to import data, then do so, otherwise just proceed to the app.
                    if (authenticationResponse.Value!.HasDataForImport) {

                        //Make ANOTHER async call using URLSession.shared.dataTask (with callback)
                        UserDataService.GetUserSettings()
                            { response in
                                //Remove the spinner
                                messageFrame.removeFromSuperview()

                                if (response.Status == ResponseCode.OK)
                                {
                                    DispatchQueue.main.async {
                                        //Success, go to dashboard
                                        self.presentHomeViewController()
                                    }
                                }
                                else {
                                    DispatchQueue.main.async {
                                        //Show alert failure, with clicking 'ok' firing a callback to take the user to the dashboard
                                    }
                                }
                        }
                    }
                    else {
                        DispatchQueue.main.async {
                            //Data does not exist, so just stop the spinner and take the user to the dashboard
                            self.presentHomeViewController()
                        }
                    }
                    else if (authenticationResponse.Status == ResponseCode.INVALID_USERNAME_PASSWORD) {
                        DispatchQueue.main.async {
                            //User entered the wrong username/password
                            messageFrame.removeFromSuperview()
                            <alert is created/presented here>
                        }
                    }
                }
                // final = final?.replacingOccurrences(of: "Rs.", with: "")
            }
        }
</code>```

Advice (Sort of)

Should I not wrap this entire block in DispatchQueue.main.async, but
  rather only the two web calls? I've done all kinds of combinations,
  most of which worked (and some that crashed), so I'm not entirely sure
  if I just need DispatchQueue.main.async, or need something nested
  inside of it such as a DispatchQueue.global(qos:
  DispatchQoS.QoSClass.userInteractive).async as well?

You should never wrap web service calls in DispatchQueue.main.async you should wrap it in DispatchQueue.global(qos: .default).async I am assuming Quality Of Service (QOS) to be default which is normally the case unless you have specific requirement for background,hight or low.
Thumb rule, update all your UI components on main thread. Because your main thread is associated with serialized MainQueue it is important to switch to mainQueue context.

DispatchQueue.main.async will only grab the main thread asynchronously where DispatchQueue.main.sync will try to grab main thread synchronously there by pausing the current execution of the main thread. But both will get you an access to main thread only So DispatchQueue.main.async is not a ideal way to make non UI related calls like web services.

Issue with making a long, non ui related task on main thread is that, there can only be one main thread in the entire life cycle of Application and because it gets busy with non UI related task and because Main Queue is Serialized all other ui tasks will starve in main queue waiting for main thread and hence will result in non responsive UI or at worst (best for user :P) results in iOS killing your app.

Should I wrap each web call, or only the outer one

That depends on how is your web call designed. If you use Alamofire/AFNewtorking kind of frameworks, they return the result on main thread even if you call the web service on non-ui thread. In such cases its necessary to switch to non-ui thread again. So in those scenarios you will have to wrap each web service calls in DispatchQueue.global.async else outer one should do just fine :)

In the answer I posted above assumes your web service call completion block returns the response using non-ui thread hence I have wrapped both web service calls in single DispatchQueue.global.async modify it if thats not the case.

Should I be wrapping the UI-related things in their own blocks, for
  example when I present alerts, view controllers, or even stop the
  spinner

Again depends. If the control reaches the UI component update statements on any thread other that main thread you should use DispatchQueue.main.async If you are sure your control reaches such statements always on main thread you dont need to wrap them. If you are unsure, then you can either blindly go and add a block around such statement or make it little more intelligent decision by adding a if condition to check if thread is main thread or not :)

One final advice : Context switching is not cheap so use it wisely.

Hope it helps

Body:
I am writing some code to let the user tap a button to log in, and after the login is successful, immediately make another call to pull in data from the system if it's available. I'm a little confused about where I need/don't need to wrap my code in different thread blocks. Can I just put everything in DispatchQueue.main.async given that I'm doing UI work on the main thread? Here is my code flow - I was wondering if someone could review and let me know if I've got the right structure of wrapping code in async/main thread blocks.

let messageFrame = AlertCreator.progressBarDisplayer(view: self.view, message: "Loading", true)

DispatchQueue.main.async(execute: {

  //Present loading spinner while call is made
  self.view.addSubview(messageFrame)

  //Make an AUTH call using URLSession.shared.dataTask (with callback)
  UserSecurityService.AuthenticateUser(username: self.txtUsername.text!, password: self.txtPassword.text!)
     { (authenticationResponse) -> () in

        if (authenticationResponse.Status == ResponseCode.LOGIN_SUCCESS)
         {
              //If this user logged in successfully, and now need to import data, then do so, otherwise just proceed to the app.
              if (authenticationResponse.Value!.HasDataForImport) {

                         //Make ANOTHER async call using URLSession.shared.dataTask (with callback)
                          UserDataService.GetUserSettings()
                                { response in
                                     //Remove the spinner
                                     messageFrame.removeFromSuperview()

                                    if (response.Status == ResponseCode.OK)
                                    {
                                        //Success, go to dashboard
                                        self.presentHomeViewController()
                                    }
                                    else {
                                        //Show alert failure, with clicking 'ok' firing a callback to take the user to the dashboard
                                    }
                               }
                   }
                  else {
                      //Data does not exist, so just stop the spinner and take the user to the dashboard
                        self.presentHomeViewController()
                  }
          else if (authenticationResponse.Status == ResponseCode.INVALID_USERNAME_PASSWORD) {
                 //User entered the wrong username/password
                  messageFrame.removeFromSuperview()
                 <alert is created/presented here>
                 }
}) //main dispatch async execute

If you noticed, I am making an async call to authenticate, that does something on the UI (shows a spinner to prevent any other activity, checks if the login was successful or not, and removes the spinner. It also potentially presents an alert, and then takes the user to a view controller.

My questions specifically are:

Should I not wrap this entire block in DispatchQueue.main.async, but
rather only the two web calls? I've done all kinds of combinations, most of which worked (and some that crashed), so I'm not entirely sure if I just need DispatchQueue.main.async, or need something nested inside of it such as a DispatchQueue.global(qos: DispatchQoS.QoSClass.userInteractive).async as well?

Should I wrap each web call, or only the outer one

Should I be wrapping the UI-related things in their own blocks, for example when I present alerts, view controllers, or even stop
the spinner? 3.

Thank you for any assistance / suggestions you could provide!

Body:
I have tried adding DispatchQueue.main and DispatchQueue.global stub to your question just to show how to and when to switch between queue. This may not be a complete copy, paste solution as I dont have complete code of yours so I could not compile it. This is intended only to show how to use DispatchQueue

let messageFrame = AlertCreator.progressBarDisplayer(view: self.view, message: "Loading", true)
        //Present loading spinner while call is made
        self.view.addSubview(messageFrame)

        DispatchQueue.global(qos: .default).async {
            //Make an AUTH call using URLSession.shared.dataTask (with callback)
            UserSecurityService.AuthenticateUser(username: self.txtUsername.text!, password: self.txtPassword.text!)
            { (authenticationResponse) -> () in

                if (authenticationResponse.Status == ResponseCode.LOGIN_SUCCESS)
                {
                    //If this user logged in successfully, and now need to import data, then do so, otherwise just proceed to the app.
                    if (authenticationResponse.Value!.HasDataForImport) {

                        //Make ANOTHER async call using URLSession.shared.dataTask (with callback)
                        UserDataService.GetUserSettings()
                            { response in
                                //Remove the spinner
                                messageFrame.removeFromSuperview()

                                if (response.Status == ResponseCode.OK)
                                {
                                    DispatchQueue.main.async {
                                        //Success, go to dashboard
                                        self.presentHomeViewController()
                                    }
                                }
                                else {
                                    DispatchQueue.main.async {
                                        //Show alert failure, with clicking 'ok' firing a callback to take the user to the dashboard
                                    }
                                }
                        }
                    }
                    else {
                        DispatchQueue.main.async {
                            //Data does not exist, so just stop the spinner and take the user to the dashboard
                            self.presentHomeViewController()
                        }
                    }
                    else if (authenticationResponse.Status == ResponseCode.INVALID_USERNAME_PASSWORD) {
                        DispatchQueue.main.async {
                            //User entered the wrong username/password
                            messageFrame.removeFromSuperview()
                            <alert is created/presented here>
                        }
                    }
                }
                // final = final?.replacingOccurrences(of: "Rs.", with: "")
            }
        }

Advice (Sort of)

Should I not wrap this entire block in DispatchQueue.main.async, but
  rather only the two web calls? I've done all kinds of combinations,
  most of which worked (and some that crashed), so I'm not entirely sure
  if I just need DispatchQueue.main.async, or need something nested
  inside of it such as a DispatchQueue.global(qos:
  DispatchQoS.QoSClass.userInteractive).async as well?

You should never wrap web service calls in DispatchQueue.main.async you should wrap it in DispatchQueue.global(qos: .default).async I am assuming Quality Of Service (QOS) to be default which is normally the case unless you have specific requirement for background,hight or low.
Thumb rule, update all your UI components on main thread. Because your main thread is associated with serialized MainQueue it is important to switch to mainQueue context.

DispatchQueue.main.async will only grab the main thread asynchronously where DispatchQueue.main.sync will try to grab main thread synchronously there by pausing the current execution of the main thread. But both will get you an access to main thread only So DispatchQueue.main.async is not a ideal way to make non UI related calls like web services.

Issue with making a long, non ui related task on main thread is that, there can only be one main thread in the entire life cycle of Application and because it gets busy with non UI related task and because Main Queue is Serialized all other ui tasks will starve in main queue waiting for main thread and hence will result in non responsive UI or at worst (best for user :P) results in iOS killing your app.

Should I wrap each web call, or only the outer one

That depends on how is your web call designed. If you use Alamofire/AFNewtorking kind of frameworks, they return the result on main thread even if you call the web service on non-ui thread. In such cases its necessary to switch to non-ui thread again. So in those scenarios you will have to wrap each web service calls in DispatchQueue.global.async else outer one should do just fine :)

In the answer I posted above assumes your web service call completion block returns the response using non-ui thread hence I have wrapped both web service calls in single DispatchQueue.global.async modify it if thats not the case.

Should I be wrapping the UI-related things in their own blocks, for
  example when I present alerts, view controllers, or even stop the
  spinner

Again depends. If the control reaches the UI component update statements on any thread other that main thread you should use DispatchQueue.main.async If you are sure your control reaches such statements always on main thread you dont need to wrap them. If you are unsure, then you can either blindly go and add a block around such statement or make it little more intelligent decision by adding a if condition to check if thread is main thread or not :)

One final advice : Context switching is not cheap so use it wisely.

Hope it helps


问:
wordpress archive list of post separated yearly
I have an time line post page.
I want to separate this by publish year.
For example:

```<code>2014
post 1
post 2
post 3

2013
post 1
post 2
post 3
</code>```

Now post loop is ok. But I want add year each first line of yearly post loop.
I'm using the code below. How can I add the year?

```<code><?php $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;?>
<?php $media = new WP_Query(array(
                        'post_type' => 'post',
                        'category_name' => 'media',
                        'posts_per_page' => 50,
                        'paged' => $paged
                ));
?>

<?php if( $media->have_posts()) : while($media->have_posts()) : $media->the_post(); ?>
<span class="app_tl_time">2014</span>
<article class="app_tl_article">
    <span class="app_tl_arrow"></span>
                <div class="app_tl_title">
            <a href="<?php echo get_permalink(); ?>">
                 <?php the_title(); ?>
            </a>
        </div>
</article>

<?php endwhile; ?>
<?php if ($media->max_num_pages > 1) { ?>
    <nav class="prev-next-posts">
        <div class="prev-posts-link">
            <?php // display older posts link
                  echo get_next_posts_link( 'Prev', $media->max_num_pages );
            ?>
        </div>
        <div class="next-posts-link">
           <?php echo get_previous_posts_link( 'Next' ); // display newer posts link ?>
        </div>
    </nav>
<?php } ?>
<?php else: ?>
<article>
    <p><?php _e('Nothing.'); ?></p>
</article>
<?php endif; ?>
</div><!--app_timeline_grid-->
</code>```

答:
Try this code, you can get the result

$years = $wpdb->get_results( "SELECT YEAR(post_date) AS year FROM wp_posts WHERE post_type = 'post' AND post_status = 'publish' GROUP BY year DESC" );

foreach ( $years as $year ) {
    // get posts for each year
    $posts_this_year = $wpdb->get_results( "SELECT * FROM wp_posts WHERE post_type = 'post' AND post_status = 'publish' AND YEAR(post_date) = '" . $year->year . "'" );

    echo '
' . $year->year . '

';

    foreach ( $posts_this_year as $post ) {

        echo '
' . $post->post_title . '
';
    }
    echo '
';
}```

Body:
I have an time line post page.
I want to separate this by publish year.
For example:

2014
post 1
post 2
post 3

2013
post 1
post 2
post 3

Now post loop is ok. But I want add year each first line of yearly post loop.
I'm using the code below. How can I add the year?

<?php $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;?>
<?php $media = new WP_Query(array(
                        'post_type' => 'post',
                        'category_name' => 'media',
                        'posts_per_page' => 50,
                        'paged' => $paged
                ));
?>

<?php if( $media->have_posts()) : while($media->have_posts()) : $media->the_post(); ?>
2014

            <a href="<?php echo get_permalink(); ?>">
                 <?php the_title(); ?>

<?php endwhile; ?>
<?php if ($media->max_num_pages > 1) { ?>

            <?php // display older posts link
                  echo get_next_posts_link( 'Prev', $media->max_num_pages );
            ?>

           <?php echo get_previous_posts_link( 'Next' ); // display newer posts link ?>

<?php } ?>
<?php else: ?>

<?php _e('Nothing.'); ?>

<?php endif; ?>

Body:
Try this code, you can get the result

$years = $wpdb->get_results( "SELECT YEAR(post_date) AS year FROM wp_posts WHERE post_type = 'post' AND post_status = 'publish' GROUP BY year DESC" );

foreach ( $years as $year ) {
    // get posts for each year
    $posts_this_year = $wpdb->get_results( "SELECT * FROM wp_posts WHERE post_type = 'post' AND post_status = 'publish' AND YEAR(post_date) = '" . $year->year . "'" );

    echo '<h2>' . $year->year . '</h2><ul>';

    foreach ( $posts_this_year as $post ) {

        echo '<li>' . $post->post_title . '</li>';
    }
    echo '</ul>';
}


问:
How to merge two sorted arrays into a sorted array?
This was asked of me in an interview and this is the solution I provided:

```<code>public static int[] merge(int[] a, int[] b) {

    int[] answer = new int[a.length + b.length];
    int i = 0, j = 0, k = 0;
    while (i < a.length && j < b.length)
    {
        if (a[i] < b[j])
        {
            answer[k] = a[i];
            i++;
        }
        else
        {
            answer[k] = b[j];
            j++;
        }
        k++;
    }

    while (i < a.length)
    {
        answer[k] = a[i];
        i++;
        k++;
    }

    while (j < b.length)
    {
        answer[k] = b[j];
        j++;
        k++;
    }

    return answer;
}
</code>```

Is there a more efficient way to do this?

Edit: Corrected length methods.

答:
You could use 2 threads to fill the resulting array, one from front, one from back.

This can work without any synchronization in the case of numbers, e.g. if each thread inserts half of the values.

Body:
This was asked of me in an interview and this is the solution I provided:

public static int[] merge(int[] a, int[] b) {

    int[] answer = new int[a.length + b.length];
    int i = 0, j = 0, k = 0;
    while (i < a.length && j < b.length)
    {
        if (a[i] < b[j])
        {
            answer[k] = a[i];
            i++;
        }
        else
        {
            answer[k] = b[j];
            j++;
        }
        k++;
    }

    while (i < a.length)
    {
        answer[k] = a[i];
        i++;
        k++;
    }

    while (j < b.length)
    {
        answer[k] = b[j];
        j++;
        k++;
    }

    return answer;
}

Is there a more efficient way to do this?

Edit: Corrected length methods.


问:
Complexity of recursive code
I came across this question in a review for my class and I am having a difficult time understanding the professors justification and explanation of the solution. The question:
The following code computes 2^n for given n. Determine total number of lines executed. Justify your answer.

```<code>    Power2(int n)
    1) if(n=0)
    2)     return 1
    3) else
    4)     k=Power2(n/2)
    5)     k=k*k;
    6)     if(k is even)
    7)       return k
    8)     else
    9)       return 2*k
</code>```

The justification

I don't understand from the "hence" part on. If someone could break these steps down for me a little more and describe how these steps are equivalent, it would be a great help.

答:
The line 7) is wrong it should read 7) if (n is even).

Regarding the Hence part, they take

n = 2k

and show there are k iterations. Yet, from above equation we get

k = log2(n)

thus having k iterations is having log2(n) iterations.

The algorithm is O(log(n))

Title: Complexity of recursive code

Body:
I came across this question in a review for my class and I am having a difficult time understanding the professors justification and explanation of the solution. The question:
The following code computes 2^n for given n. Determine total number of lines executed. Justify your answer.

    Power2(int n)
    1) if(n=0)
    2)     return 1
    3) else
    4)     k=Power2(n/2)
    5)     k=k*k;
    6)     if(k is even)
    7)       return k
    8)     else
    9)       return 2*k

The justification

I don't understand from the "hence" part on. If someone could break these steps down for me a little more and describe how these steps are equivalent, it would be a great help.


问:
Magento 1.9 coupon code showing it's applied, but it's not working
We are facing Magento coupon code issue, some time it's showing coupon code
applied but it does not impact on cart total price change and not show discount amount as well, but if we try on other system some time it's working fine as expected.

We have checked cookies, server time zone, Magento timezone etc., everything seems fine.

I did not get any log errors either.

Is there any how we can get error why this happening , as this happen only some time, not always?

Our Magento version is 1.9.3.6. We upgraded few month ago from Magento 1.7 to 1.9.3.

答: You need to check cache. Disable Magento cache and check on different systems. If problem resolved then you can refresh cache by cron in every 5 minutes.</p>


问:
iphone toRadians toDegrees compiler problem
I am trying to convert a double to radians using the Objective c function toRadians like this:

```<code>double oldLat = toRadians(oldLocation.coordinate.latitude);
</code>```

but I keep getting a compiler warning and error or implicit declaration of toRadians and toDegrees

I included #import <math.h> but that didn't solve the problem for some reason.

any help would be greatly appreciated.

答:
try this coding:- ( radian to degree)           </p>

```<code>location = [[CCDirector sharedDirector] convertToGL:location];

        // Determine offset of location to projectile
        int offX = location.x - PROJECTILE_POSITION_X;
        int offY = location.y - PROJECTILE_POSITION_Y;

                int realX = winSize.width + (PROJECTILE_WIDTH/2);
        float ratio = (float) offY / (float) offX;
        int realY = (realX * ratio) + PROJECTILE_POSITION_Y;

        int offRealX = realX - PROJECTILE_POSITION_X;
        int offRealY = realY - PROJECTILE_POSITION_Y;

        // Determine angle to face
        float angleRadians = atanf((float)offRealY / (float)offRealX);
        float angleDegrees =  (__angleRadians__)/((__angleRadians__) * 57.29577951f);
</code>```

Body:
I am trying to convert a double to radians using the Objective c function toRadians like this:

double oldLat = toRadians(oldLocation.coordinate.latitude);

but I keep getting a compiler warning and error or implicit declaration of toRadians and toDegrees

I included #import <math.h> but that didn't solve the problem for some reason.

any help would be greatly appreciated.

Body:
try this coding:- ( radian to degree)

location = [[CCDirector sharedDirector] convertToGL:location];

        // Determine offset of location to projectile
        int offX = location.x - PROJECTILE_POSITION_X;
        int offY = location.y - PROJECTILE_POSITION_Y;

                int realX = winSize.width + (PROJECTILE_WIDTH/2);
        float ratio = (float) offY / (float) offX;
        int realY = (realX * ratio) + PROJECTILE_POSITION_Y;

        int offRealX = realX - PROJECTILE_POSITION_X;
        int offRealY = realY - PROJECTILE_POSITION_Y;

        // Determine angle to face
        float angleRadians = atanf((float)offRealY / (float)offRealX);
        float angleDegrees =  (__angleRadians__)/((__angleRadians__) * 57.29577951f);


问:
Google analytics shows statics of different account
I have two website accounts in google analytics. In one I have my old site A and new site B in another. Both of them are similar wordpress sites with different set of articles.I have placed analytics script on header files of both sites

When I check on the real time report of my old site, it shows some url's of my new site articles? There is no link or any sort of connection between these two sites

答:
Did you use the same tag in Google Tag Manager? Meaning...Do you have the same code in both sites? You will need the unique GTM- identifier...

Also make sure you set up different properties in Google backend.

```<code><!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXX');</script>
<!-- End Google Tag Manager -->

<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
</code>```

Make sure GTM-XXXX is different on both.

Body:
Did you use the same tag in Google Tag Manager? Meaning...Do you have the same code in both sites? You will need the unique GTM- identifier...

Also make sure you set up different properties in Google backend.

<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXX');</script>
<!-- End Google Tag Manager -->

<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->

Make sure GTM-XXXX is different on both.