问:
Issue with expandablelistview indicator
I am creating multilevel expandable list view with list view. So I want indicator of the list view changed when clicking it.I have two png images in drawable folder.The click event not working properly.When clicking the minus sign is not coming.I am referring this.
my main activity

```<code>public class MainActivity extends Activity {

    List<NLevelItem> lists;
    ListView listView;
    RequestQueue requestQueue1, requestQueue2;
    int[] firstcatid = null,secondcatid = null;
    String firsttitle[] = null,secondtitle[] = null;
    int j = 0;
    //ArrayList<Group> list,list2,list3;
    NLevelItem parent;
    Boolean b=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.listView1);
        lists = new ArrayList<NLevelItem>();
       // Random rng = new Random();
        final LayoutInflater inflater = LayoutInflater.from(this);
        requestQueue1= Volley.newRequestQueue(this);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://www.fasr.com/cntrldata/ezproductfristcategory.php",
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        try {
                            //list = new ArrayList<Group>();
                            JSONArray ja = response.getJSONArray("hi");
                            JSONArray ja2 = response.getJSONArray("hi2");
                            JSONArray ja3 = response.getJSONArray("hi3");
                            firsttitle = new String[ja.length()];
                            firstcatid = new int[ja.length()];
                            JSONObject jsonObject2 = null, jsonObject3 = null, jsonObject;
                            for (int i = 0; i < ja.length(); i++) {

                                jsonObject = ja.getJSONObject(i);

                                // Log.e("hie",jsonObject2.getInt("second_category_id")+"");
                                //jsonObject3 = ja3.getJSONObject(i);
                                firstcatid[i] = jsonObject.getInt("first_category_id");
                                firsttitle[i] = jsonObject.getString("first_category_name");
                            }
                            secondcatid = new int[ja2.length()];
                            for (int i = 0; i < ja2.length(); i++) {
                                jsonObject2 = ja2.getJSONObject(i);
                                secondcatid[i] = jsonObject2.getInt("second_category_id");
                            }
                            for (int i = 0; i < ja.length(); i++) {

                                final NLevelItem grandParent = new NLevelItem(new SomeObject(firsttitle[i]), null, new NLevelView() {

                                    @Override
                                    public View getView(NLevelItem item) {
                                        final View view = inflater.inflate(R.layout.list_item, null);
                                        TextView tv = (TextView) view.findViewById(R.id.textView);
                                        final ImageView iv=(ImageView)view.findViewById(R.id.imageView);
                                        //tv.setBackgroundColor(Color.GREEN);

                                        iv.setVisibility(View.VISIBLE);
/*
                                        view.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                Toast.makeText(getApplicationContext(),"hello",Toast.LENGTH_SHORT).show();
                                                if(!b){
                                                    iv.setBackgroundResource(R.drawable.ic_action_minus);
                                                    b=true;
                                                }else {
                                                    b=false;
                                                    iv.setBackgroundResource(R.drawable.ic_action_add);
                                                }
                                            }
                                        });*/

                                        String name = (String) ((SomeObject) item.getWrappedObject()).getName();
                                        tv.setText(name);
                                        return view;
                                    }
                                });
                                lists.add(grandParent);
                                //int numChildren = rng.nextInt(4) + 1;
                                for (int j = 0; j < ja2.length(); j++) {
                                    jsonObject2 = ja2.getJSONObject(j);

                                    if (firstcatid[i] == jsonObject2.getInt("first_category_id")) {

                                        parent = new NLevelItem(new SomeObject(jsonObject2.getString("second_category_name")), grandParent, new NLevelView() {

                                            @Override
                                            public View getView(NLevelItem item) {
                                                View view = inflater.inflate(R.layout.list_item, null);
                                                TextView tv = (TextView) view.findViewById(R.id.textView);
                                                //tv.setBackgroundColor(Color.YELLOW);
                                                tv.setPadding(20,0,0,0);
                                                String name = (String) ((SomeObject) item.getWrappedObject()).getName();
                                                tv.setText(name);
                                                return view;
                                            }
                                        });

                                        lists.add(parent);     }                              // int grandChildren = rng.nextInt(5) + 1;
                                    for (int k = 0; k < ja3.length(); k++) {
                                        jsonObject3 = ja3.getJSONObject(k);
                                        if (secondcatid[j] == jsonObject3.getInt("second_category_id")) {
                                        NLevelItem child = new NLevelItem(new SomeObject(jsonObject3.getString("third_category_name")), parent, new NLevelView() {

                                            @Override
                                            public View getView(NLevelItem item) {
                                                View view = inflater.inflate(R.layout.list_item, null);
                                                TextView tv = (TextView) view.findViewById(R.id.textView);
                                                //tv.setBackgroundColor(Color.GRAY);
                                                tv.setPadding(40,0,0,0);
                                                String name = (String) ((SomeObject) item.getWrappedObject()).getName();
                                                tv.setText(name);
                                                return view;
                                            }
                                        });

                                        lists.add(child);}
                                    }
                                }
                            }

                            NLevelAdapter adapter = new NLevelAdapter(lists);
                            listView.setAdapter(adapter);
                            listView.setOnItemClickListener(new OnItemClickListener() {

                                @Override
                                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                                        long arg3) {
                                    ((NLevelAdapter) listView.getAdapter()).toggle(arg2);
                                    ((NLevelAdapter) listView.getAdapter()).getFilter().filter();

                                }
                            });
                            // Toast.makeText(getApplicationContext(),url[2],Toast.LENGTH_SHORT).show();
                            //output.setText(data);
                            //ExpListItems =  list;
                            // ExpAdapter = new ExpandListAdapter(getApplicationContext(), ExpListItems);
                            // ExpandList.setAdapter(ExpAdapter);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Volley", error.toString());

                    }
                }
        );
        requestQueue1.add(jsonObjectRequest);

    }

    class SomeObject {
        public String name;

        public SomeObject(String name) {
            this.name = name;
        }
        public String getName() {
            return name;
        }
    }
</code>```

my listitem xml is

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"

    android:id="@+id/listItemContainer">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textSize="15sp"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        android:textColor="#020202" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView"
        android:visibility="invisible"
        android:layout_gravity="right"
        android:layout_marginLeft="5dp"
        android:src="@drawable/ic_action_add"
        android:layout_alignParentEnd="false"
        android:layout_alignParentRight="true" />

</RelativeLayout>
</code>```

my pic is

答:
```<code>            @Override
            public View getView(NLevelItem item)
            {
                View convertView = inflater.inflate(R.layout.seperated_cows_first_row, null);

                TextView tv = (TextView) convertView.findViewById(R.id.tct_name);
                ImageView icon = (ImageView) convertView.findViewById(R.id.select_icon);

                String name = ((ListObject) item.getWrappedObject()).getName();
                tv.setText(name);

                if (item.isExpanded())
                    icon.setBackgroundResource(R.drawable.list_item_selector_icon_down);
                else
                    icon.setBackgroundResource(R.drawable.list_item_selector_icon_up);

                return convertView;
            }
</code>```

this solved my issue

Title: Issue with expandablelistview indicator

Body:
I am creating multilevel expandable list view with list view. So I want indicator of the list view changed when clicking it.I have two png images in drawable folder.The click event not working properly.When clicking the minus sign is not coming.I am referring this.
my main activity

public class MainActivity extends Activity {

    List<NLevelItem> lists;
    ListView listView;
    RequestQueue requestQueue1, requestQueue2;
    int[] firstcatid = null,secondcatid = null;
    String firsttitle[] = null,secondtitle[] = null;
    int j = 0;
    //ArrayList<Group> list,list2,list3;
    NLevelItem parent;
    Boolean b=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.listView1);
        lists = new ArrayList<NLevelItem>();
       // Random rng = new Random();
        final LayoutInflater inflater = LayoutInflater.from(this);
        requestQueue1= Volley.newRequestQueue(this);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://www.fasr.com/cntrldata/ezproductfristcategory.php",
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        try {
                            //list = new ArrayList<Group>();
                            JSONArray ja = response.getJSONArray("hi");
                            JSONArray ja2 = response.getJSONArray("hi2");
                            JSONArray ja3 = response.getJSONArray("hi3");
                            firsttitle = new String[ja.length()];
                            firstcatid = new int[ja.length()];
                            JSONObject jsonObject2 = null, jsonObject3 = null, jsonObject;
                            for (int i = 0; i < ja.length(); i++) {

                                jsonObject = ja.getJSONObject(i);

                                // Log.e("hie",jsonObject2.getInt("second_category_id")+"");
                                //jsonObject3 = ja3.getJSONObject(i);
                                firstcatid[i] = jsonObject.getInt("first_category_id");
                                firsttitle[i] = jsonObject.getString("first_category_name");
                            }
                            secondcatid = new int[ja2.length()];
                            for (int i = 0; i < ja2.length(); i++) {
                                jsonObject2 = ja2.getJSONObject(i);
                                secondcatid[i] = jsonObject2.getInt("second_category_id");
                            }
                            for (int i = 0; i < ja.length(); i++) {

                                final NLevelItem grandParent = new NLevelItem(new SomeObject(firsttitle[i]), null, new NLevelView() {

                                    @Override
                                    public View getView(NLevelItem item) {
                                        final View view = inflater.inflate(R.layout.list_item, null);
                                        TextView tv = (TextView) view.findViewById(R.id.textView);
                                        final ImageView iv=(ImageView)view.findViewById(R.id.imageView);
                                        //tv.setBackgroundColor(Color.GREEN);

                                        iv.setVisibility(View.VISIBLE);
/*
                                        view.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                Toast.makeText(getApplicationContext(),"hello",Toast.LENGTH_SHORT).show();
                                                if(!b){
                                                    iv.setBackgroundResource(R.drawable.ic_action_minus);
                                                    b=true;
                                                }else {
                                                    b=false;
                                                    iv.setBackgroundResource(R.drawable.ic_action_add);
                                                }
                                            }
                                        });*/

                                        String name = (String) ((SomeObject) item.getWrappedObject()).getName();
                                        tv.setText(name);
                                        return view;
                                    }
                                });
                                lists.add(grandParent);
                                //int numChildren = rng.nextInt(4) + 1;
                                for (int j = 0; j < ja2.length(); j++) {
                                    jsonObject2 = ja2.getJSONObject(j);

                                    if (firstcatid[i] == jsonObject2.getInt("first_category_id")) {

                                        parent = new NLevelItem(new SomeObject(jsonObject2.getString("second_category_name")), grandParent, new NLevelView() {

                                            @Override
                                            public View getView(NLevelItem item) {
                                                View view = inflater.inflate(R.layout.list_item, null);
                                                TextView tv = (TextView) view.findViewById(R.id.textView);
                                                //tv.setBackgroundColor(Color.YELLOW);
                                                tv.setPadding(20,0,0,0);
                                                String name = (String) ((SomeObject) item.getWrappedObject()).getName();
                                                tv.setText(name);
                                                return view;
                                            }
                                        });

                                        lists.add(parent);     }                              // int grandChildren = rng.nextInt(5) + 1;
                                    for (int k = 0; k < ja3.length(); k++) {
                                        jsonObject3 = ja3.getJSONObject(k);
                                        if (secondcatid[j] == jsonObject3.getInt("second_category_id")) {
                                        NLevelItem child = new NLevelItem(new SomeObject(jsonObject3.getString("third_category_name")), parent, new NLevelView() {

                                            @Override
                                            public View getView(NLevelItem item) {
                                                View view = inflater.inflate(R.layout.list_item, null);
                                                TextView tv = (TextView) view.findViewById(R.id.textView);
                                                //tv.setBackgroundColor(Color.GRAY);
                                                tv.setPadding(40,0,0,0);
                                                String name = (String) ((SomeObject) item.getWrappedObject()).getName();
                                                tv.setText(name);
                                                return view;
                                            }
                                        });

                                        lists.add(child);}
                                    }
                                }
                            }

                            NLevelAdapter adapter = new NLevelAdapter(lists);
                            listView.setAdapter(adapter);
                            listView.setOnItemClickListener(new OnItemClickListener() {

                                @Override
                                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                                        long arg3) {
                                    ((NLevelAdapter) listView.getAdapter()).toggle(arg2);
                                    ((NLevelAdapter) listView.getAdapter()).getFilter().filter();

                                }
                            });
                            // Toast.makeText(getApplicationContext(),url[2],Toast.LENGTH_SHORT).show();
                            //output.setText(data);
                            //ExpListItems =  list;
                            // ExpAdapter = new ExpandListAdapter(getApplicationContext(), ExpListItems);
                            // ExpandList.setAdapter(ExpAdapter);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Volley", error.toString());

                    }
                }
        );
        requestQueue1.add(jsonObjectRequest);

    }

    class SomeObject {
        public String name;

        public SomeObject(String name) {
            this.name = name;
        }
        public String getName() {
            return name;
        }
    }

my listitem xml is

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"

    android:id="@+id/listItemContainer">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textSize="15sp"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        android:textColor="#020202" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView"
        android:visibility="invisible"
        android:layout_gravity="right"
        android:layout_marginLeft="5dp"
        android:src="@drawable/ic_action_add"
        android:layout_alignParentEnd="false"
        android:layout_alignParentRight="true" />

</RelativeLayout>

my pic is

Body:
            @Override
            public View getView(NLevelItem item)
            {
                View convertView = inflater.inflate(R.layout.seperated_cows_first_row, null);

                TextView tv = (TextView) convertView.findViewById(R.id.tct_name);
                ImageView icon = (ImageView) convertView.findViewById(R.id.select_icon);

                String name = ((ListObject) item.getWrappedObject()).getName();
                tv.setText(name);

                if (item.isExpanded())
                    icon.setBackgroundResource(R.drawable.list_item_selector_icon_down);
                else
                    icon.setBackgroundResource(R.drawable.list_item_selector_icon_up);

                return convertView;
            }

this solved my issue


来源: stackexchange

问:
Dealing with Dependencies when instantiating MVC objects in Java
I know that's not the most amazing title in the world, but bear with me.
I'm developing an application in Java, for part of which I'm using the MVC design pattern.

Above is my understanding of the MVC structure, or at least how I'm choosing to implement it. However I've run into a problem instantiating the objects. Since any given controller requires a reference to it's view pair, and any given view requires a reference to it's controller pair, I'm not sure how to actually create the objects.

I could pass the view into the controller as null and then immediately set it, but not only does this feel like bad coding practice it raised questions about where I actually should be creating the view. Is it something normally delegated to the controller? Any guidance would be greatly appreciated.

答:
You can pass one as a constructor parameter to the other like this:</p>

```<code>public class Controller {
    private View view;

    public Controller() {
        this.view = new View(this);
    }
}

public class View {
    private Controller controller;

    public View(Controller controller) {
        this.controller = controller;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can pass one as a constructor parameter to the other like this:

public class Controller {
    private View view;

    public Controller() {
        this.view = new View(this);
    }
}

public class View {
    private Controller controller;

    public View(Controller controller) {
        this.controller = controller;
    }
}


问:
How do I blur a widget in Flutter
I need to blur a widget, for example, a simple Container.
How do I blur it?

```<code>new Container(
  child: new Text('hello I am here'),
  height: 100.0,
  width: 100.0,
  color: Colors.red,
)
</code>```

Consider the above Container.

答:
You can create a Stack like:

First child: What you want to blur (in your case: Container)

Second child: BackdropFilter

And within the second child (BackdropFilter), there is the parameter child, which is used to insert a widget into the tree, that will not be affected by the BackdropFilter.

In your BackdropFilter, set filter: ImageFilter.blur(5.0, 5.0)

5.0 is amount of blur you wish.

ContentLicense: CC BY-SA 4.0

Title: How do I blur a widget in Flutter

Body:
I need to blur a widget, for example, a simple Container.
How do I blur it?

new Container(
  child: new Text('hello I am here'),
  height: 100.0,
  width: 100.0,
  color: Colors.red,
)

Consider the above Container.


问:
re.finditer (R or K but not RP or KP) in one line
I want to have index of P or K but not PR or PK in substring. Now I can do two-line code but it is slower than using for loop with if. I want very fast one with re.finditer, is it possible ?

```<code>proseq = "NSDSECPLSHDGYCLHDGVCMYIEALDKYACNCVVGYIGERCQYRDLKWWELRP"
xxx = [m.start() for m in re.finditer('(R|K)', proseq)]
yyy = [m.start() for m in re.finditer('(RP|KP)', proseq)]
print list(set(xxx)^set(yyy))
OUT> [40, 27, 44, 47]
</code>```

The for loop that is faster than mine (and it is sorted),

```<code>proseq = "NSDSECPLSHDGYCLHDGVCMYIEALDKYACNCVVGYIGERCQYRDLKWWELPR"
cut_sites=[]
for i in range(0,len(proseq)):
    if proseq[i]=='K' and proseq[i+1]!='P':
        cut_sites.append(i)
    elif proseq[i]=='R' and proseq[i+1]!='P':
        cut_sites.append(i)
OUT> [27, 40, 44, 47]
</code>```

Other fast ways are very welcomed.

答:
Use the regex (R|K)([^P]|$). This reads freely as "R or K, followed by a character which isn't P ([^P]), or the end of the string ($)".

Thid regex would practically give you the results without the need for another check.

Body:
I want to have index of P or K but not PR or PK in substring. Now I can do two-line code but it is slower than using for loop with if. I want very fast one with re.finditer, is it possible ?

proseq = "NSDSECPLSHDGYCLHDGVCMYIEALDKYACNCVVGYIGERCQYRDLKWWELRP"
xxx = [m.start() for m in re.finditer('(R|K)', proseq)]
yyy = [m.start() for m in re.finditer('(RP|KP)', proseq)]
print list(set(xxx)^set(yyy))
OUT> [40, 27, 44, 47]

The for loop that is faster than mine (and it is sorted),

proseq = "NSDSECPLSHDGYCLHDGVCMYIEALDKYACNCVVGYIGERCQYRDLKWWELPR"
cut_sites=[]
for i in range(0,len(proseq)):
    if proseq[i]=='K' and proseq[i+1]!='P':
        cut_sites.append(i)
    elif proseq[i]=='R' and proseq[i+1]!='P':
        cut_sites.append(i)
OUT> [27, 40, 44, 47]

Other fast ways are very welcomed.


问:
fixing the container width and height and making image responsive to the container using Query
Width and height of the div should be fixed

image inside the fixed div should be responsive and should not exceed the container height.

答:
Just adding max-width: 100%; max-height: 100%; to the image should work. The image should fit into the fixed-size container div:

<!DOCTYPE html>

 <meta charset="utf-8" />
 <title>Testcase</title>

```

It is important, that in the image-tag, you do not specify width and height attributes.

Body:
Just adding max-width: 100%; max-height: 100%; to the image should work. The image should fit into the fixed-size container div:

<!DOCTYPE html>
<html lang="de" style="height: 100%">
<head>
 <meta charset="utf-8" />
 <title>Testcase</title>
</head>
<body style="height: 100%">

 <div style="border: 1px solid red; margin: auto auto; width: 90%; height: 90%; overflow: hidden;">
  <img style="display: block; max-width: 100%; max-height: 100%; " src="http://via.placeholder.com/500x500" alt="">
 </div>
</body>
</html>

It is important, that in the image-tag, you do not specify width and height attributes.


问:
How to remove a cookie in Apache
I need to remove a cookie from the HTTP request that gets to the server. Doing it on the client (that writes this cookie) or on the server (that reads it) is not an option. I have Apache 2.0 that proxies requests between client and the server, so I was hoping to remove the cookie right there in Apache using mod_rewrite.

My question is, is there a way to remove a certain cookie from the HTTP request using mod_rewrite?

If not possible to remove just one cookie then as a last resort to remove all cookies from the request?

I am open to other suggestions of how to accomplish this if mod_rewrite is not the right tool for this task.

答:
I use this to unset all cookies (good to serve static content)</p>

```<code>Header unset Cookie
Header unset Set-Cookie
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to remove a cookie in Apache

Body:
I use this to unset all cookies (good to serve static content)

Header unset Cookie
Header unset Set-Cookie


问:
SnackBar goes behind NavigationBar after using FLAG_NO_LIMIT
I am trying to focus designing like this:

for this, I have added inside onCreate

```<code>getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
                WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
</code>```

Now Layout got expanded but it somehow hides my snackbar behind the nav bar which is not the desired result as it should be above.Here's my screenshot:

I might have approached wrong way and it would be very helpful if you correct me.

答:
From here: add margins for your snackbar, 48dp should be enough.

```<code>public static void displaySnackBarWithBottomMargin(Snackbar snackbar, int sideMargin, int marginBottom) {
    final View snackBarView = snackbar.getView();
    final CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) snackBarView.getLayoutParams();

    params.setMargins(params.leftMargin + sideMargin,
                params.topMargin,
                params.rightMargin + sideMargin,
                params.bottomMargin + marginBottom);

    snackBarView.setLayoutParams(params);
    snackbar.show();
}
</code>```

Body:
I am trying to focus designing like this:

for this, I have added inside onCreate

getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
                WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);

Now Layout got expanded but it somehow hides my snackbar behind the nav bar which is not the desired result as it should be above.Here's my screenshot:

I might have approached wrong way and it would be very helpful if you correct me.

Body:
From here: add margins for your snackbar, 48dp should be enough.

public static void displaySnackBarWithBottomMargin(Snackbar snackbar, int sideMargin, int marginBottom) {
    final View snackBarView = snackbar.getView();
    final CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) snackBarView.getLayoutParams();

    params.setMargins(params.leftMargin + sideMargin,
                params.topMargin,
                params.rightMargin + sideMargin,
                params.bottomMargin + marginBottom);

    snackBarView.setLayoutParams(params);
    snackbar.show();
}


问:
error in getting the fetching path
I actually trying to check my connection in connection file tester to check if it is connected to the database but the problem is I got this error

```<code>Warning: include(obj\database_connection\SqlHandler.php): failed to open stream: No such file or directory in /home/devhostt/public_html/bcc/gradingsystemmodule/root/root.php on line 16

Warning: include(): Failed opening 'obj\database_connection\SqlHandler.php' for inclusion (include_path='/home/devhostt/public_html/bcc/gradingsystemmodule:.:/opt/alt/php55/usr/share/pear:/opt/alt/php55/usr/share/php') in /home/devhostt/public_html/bcc/gradingsystemmodule/root/root.php on line 16

Fatal error: Class 'obj\database_connection\SqlHandler' not found in /home/devhostt/public_html/bcc/gradingsystemmodule/function/checkconnection.php on line 8
</code>```

and here is my code to set & get the path (root.php)

```<code><?php
error_reporting( E_ALL );

define("setRealpath", realpath("../"));

const ERROR_EXCEPTION_MESSAGE = "SOMETHING WENT WRONG HERE: ";

try
{
$getPath = array(setRealpath, get_include_path());

if(!set_include_path(implode($getPath, PATH_SEPARATOR)))
{
define("setRealpath", realpath("./"));
$getPath = array(setRealpath, get_include_path());
set_include_path(implode($getPath, PATH_SEPARATOR));
}

function GetClassFile($class)
{
$file = str_replace('/', '\\', $class).".php";
include $file;
}

spl_autoload_register('GetClassFile');

}
catch(Exception $x)
{
die(ERROR_EXCEPTION_MESSAGE.$x->getMessage());
}

?>
</code>```

here is the file where my connection (SqlHandler.php).

```<code><?php
namespace obj\connection_database;
use \PDO;
class SqlHandler extends Connection
{
const ERROR_EXCEPTION_MESSAGE = "SOMETHING WENT WRONG HERE:";

protected $db = null;

public function __construct()
{
$this->db = $this->getConnection();
}

public function checkConnection()
{
if($this->db)
{
return "CONNECTED";
}
return "NO CONNECTION";
}
}
?>
</code>```

and lastly here in this file where i'm trying to check the connection(checkconnection.php)

```<code><?php
error_reporting(E_ALL);

include "./root/root.php";

use \obj\database_connection\SqlHandler;

$checkConnection = new SqlHandler;

echo $checkConnection->checkConnection();
?>
</code>```

答: now i found my mistake, the only mistake is that i'm using the old version of php, instead of using php 7.1 version , i'm using php 5. so i change it and it works.</p>

Title: error in getting the fetching path

Body:
I actually trying to check my connection in connection file tester to check if it is connected to the database but the problem is I got this error

Warning: include(obj\database_connection\SqlHandler.php): failed to open stream: No such file or directory in /home/devhostt/public_html/bcc/gradingsystemmodule/root/root.php on line 16

Warning: include(): Failed opening 'obj\database_connection\SqlHandler.php' for inclusion (include_path='/home/devhostt/public_html/bcc/gradingsystemmodule:.:/opt/alt/php55/usr/share/pear:/opt/alt/php55/usr/share/php') in /home/devhostt/public_html/bcc/gradingsystemmodule/root/root.php on line 16

Fatal error: Class 'obj\database_connection\SqlHandler' not found in /home/devhostt/public_html/bcc/gradingsystemmodule/function/checkconnection.php on line 8

and here is my code to set & get the path (root.php)

<?php
error_reporting( E_ALL );

define("setRealpath", realpath("../"));

const ERROR_EXCEPTION_MESSAGE = "SOMETHING WENT WRONG HERE: ";

try
{
$getPath = array(setRealpath, get_include_path());

if(!set_include_path(implode($getPath, PATH_SEPARATOR)))
{
define("setRealpath", realpath("./"));
$getPath = array(setRealpath, get_include_path());
set_include_path(implode($getPath, PATH_SEPARATOR));
}

function GetClassFile($class)
{
$file = str_replace('/', '\\', $class).".php";
include $file;
}

spl_autoload_register('GetClassFile');

}
catch(Exception $x)
{
die(ERROR_EXCEPTION_MESSAGE.$x->getMessage());
}

?>

here is the file where my connection (SqlHandler.php).

<?php
namespace obj\connection_database;
use \PDO;
class SqlHandler extends Connection
{
const ERROR_EXCEPTION_MESSAGE = "SOMETHING WENT WRONG HERE:";

protected $db = null;

public function __construct()
{
$this->db = $this->getConnection();
}

public function checkConnection()
{
if($this->db)
{
return "CONNECTED";
}
return "NO CONNECTION";
}
}
?>

and lastly here in this file where i'm trying to check the connection(checkconnection.php)

<?php
error_reporting(E_ALL);

include "./root/root.php";

use \obj\database_connection\SqlHandler;

$checkConnection = new SqlHandler;

echo $checkConnection->checkConnection();
?>


问:
Unable to determine application identity of the caller - works on other machines
When attempting to debug an application the code line

```<code>using (IsolatedStorageFile scope isolatedStorageFile.GetUserStoreForApplication())
</code>```

is returning the exception

```<code>System.IO.IsolatedStorage.IsolatedStorageException:
'Unable to determine application identity of the caller.'
</code>```

The issue is that all other developers in our team can debug the code successfully. This would mean that there is nothing wrong with the code, but that the issue is on my machine.

答:
I have it working (though I don't know what was happening).

The exception was occurring when trying to debug the application in VS2017. It runs successfully when debugging the application in VS2015.

Body:
When attempting to debug an application the code line

using (IsolatedStorageFile scope isolatedStorageFile.GetUserStoreForApplication())

is returning the exception

System.IO.IsolatedStorage.IsolatedStorageException:
'Unable to determine application identity of the caller.'

The issue is that all other developers in our team can debug the code successfully. This would mean that there is nothing wrong with the code, but that the issue is on my machine.


问:
C sharp to Java : MemoryStream and BinaryReader
I am working on a network device and catching packets from it over network as UDP. In some parts i need to parse a byte array (packetBuffer) to get session header but i couldn't. I found a part of code but unfortunatelly it is C sharp and i also couldn't convert it to java. It is like below;

```<code>MemoryStream memstream = new MemoryStream(packetbuffer);
BinaryReader binreader = new BinaryReader(memstream);

byte[] sessionheader = binreader.ReadBytes(4);
ushort ROapdu_type = correctendianshortus(binreader.ReadUInt16());
</code>```

I need to find what MemoryStream and BinaryReader in C# equivalent in Java is.

I appreciate for all your helps.

答: you can use getData to get byte[], then extract 4 bytes from the result array and use ByteBuffer.wrap(result4Byte).getInt() to convert it into int(you may need to use order to set byte ordering to little/big endian) </p>

Body:
I am working on a network device and catching packets from it over network as UDP. In some parts i need to parse a byte array (packetBuffer) to get session header but i couldn't. I found a part of code but unfortunatelly it is C sharp and i also couldn't convert it to java. It is like below;

MemoryStream memstream = new MemoryStream(packetbuffer);
BinaryReader binreader = new BinaryReader(memstream);

byte[] sessionheader = binreader.ReadBytes(4);
ushort ROapdu_type = correctendianshortus(binreader.ReadUInt16());

I need to find what MemoryStream and BinaryReader in C# equivalent in Java is.

I appreciate for all your helps.


问:
Java - Store the changing int variable
So I'm trying to write the most simple game , everytime "the monster" attacks "the player" I want the variable "int totalHealth" to be lowered .

```<code>public void attack(Player somePlayer) {

    int totalHealth = somePlayer.getHitPoints() + somePlayer.getStrength();

    int remainingHealth = totalHealth - damage;
    if (remainingHealth == 0 || remainingHealth < 0) {
        System.out.println("Your player died");
    } else {
        System.out.println("The monster attacked " + somePlayer.getName() + " and made " + this.damage + " damage");
        System.out.println("Your remaining health is - " + (remainingHealth - somePlayer.getStrength()));
    }

}
</code>```

But the problem is that variable "remainingHealth" stays same , only the first time when I run the code it lowers , every next time it stays same,  I guess the problem is in this line :

```<code>int totalHealth = somePlayer.getHitPoints() + somePlayer.getStrength();
</code>```

I guess everytime I run the code

```<code>somePlayer.getHitpoints()
</code>```

takes the inserted integer from constructor and that's the problem.

I need to figure out the way to store the remaining health in a variable somehow

Player class :

```<code>public class Player implements ISavable{

private String name;
private int hitPoints ;
private int strength ;
private String weapon;
private int damage;
private int totalHealth = hitPoints + strength;

public Player(String name, int damage , int hitPoints , int strength) {
    this.name = name;
    this.damage = damage;
    this.weapon = "Sword";
    this.hitPoints = hitPoints;
    this.strength = strength;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getHitPoints() {
    return hitPoints;
}

public void setHitPoints(int hitPoints) {
    this.hitPoints = hitPoints;
}

public int getStrength() {
    return strength;
}

public void setStrength(int strength) {
    this.strength = strength;
}

public String getWeapon() {
    return weapon;
}

public void setWeapon(String weapon) {
    this.weapon = weapon;
}

public int getTotalHealth() {
    return totalHealth;
}

public void setTotalHealth(int totalHealth) {
    this.totalHealth = totalHealth;
}

@Override
public String toString() {
    return "Player{" +
            "name='" + name + '\'' +
            ", hitPoints=" + hitPoints +
            ", strength=" + strength +
            ", weapon='" + weapon + '\'' +
            '}';
}

@Override
public List<String> write() {
    List<String> values = new ArrayList<String>();
    values.add(0, this.name);
    values.add(1, "" + this.hitPoints);
    values.add(2, "" + this.strength);
    values.add(3, "" + this.weapon);
    values.add(4,"" + this.damage);
    return values;
}

@Override
public void read(List<String> savedValues) {
    if (savedValues != null && savedValues.size()>0){
        this.name = savedValues.get(0);
        this.hitPoints = Integer.parseInt(savedValues.get(1));
        this.strength = Integer.parseInt(savedValues.get(2));
        this.weapon = savedValues.get(3);
    }
}

public void attack(Monster someMonster){
    int health = someMonster.getHitPoints();
    int remainingHealth = health - damage;
    if (remainingHealth == 0 || remainingHealth < 0) {
        System.out.println("You killed the monster !!!");
    } else {
        System.out.println("You attacked the monster " + " and made " + this.damage + " damage");
        System.out.println("Monsters remaining health is - " + remainingHealth);
    }

    if (someMonster.isDead()){
        this.hitPoints = 100;
        this.strength = 50;
    }
}

public void healPlayer(Player somePlayer){
    int hp = somePlayer.getHitPoints();
    hp += 10;
    System.out.println("You healed the player for 10hp , your current hp is " + hp);
}
</code>```

}

答:
You should have a representation of health, defining in Player totalHealth.

You may use a method which calculate the total health (cause your player could get an item that increases strenght or an item that allow heal you).

Then you should use another variable in Player, remainingHealth and initialize it as remainingHealth = totalHealth

```<code>    public class Player {

    float totalHealth;
    float remainingHealth;
    ...

    public Player(...) {
        this.remainingHealth = this.totalHealth;
        ...
    }
    ...

}
</code>```

When you want decrease the health of your player you should use remainingHealth.

```<code>    public void attack(Player somePlayer) {

    somePlayer.remainingHealth -= this.damage;
    if (somePlayer.remainingHealth <= 0) {
        System.out.println("Your player died");
    } else {
        System.out.println("The monster attacked ...");
        System.out.println("Your remaining health is - " + somePlayer.remainingHealth);
    }

}
</code>```

Title: Java - Store the changing int variable

Body:
So I'm trying to write the most simple game , everytime "the monster" attacks "the player" I want the variable "int totalHealth" to be lowered .

public void attack(Player somePlayer) {

    int totalHealth = somePlayer.getHitPoints() + somePlayer.getStrength();

    int remainingHealth = totalHealth - damage;
    if (remainingHealth == 0 || remainingHealth < 0) {
        System.out.println("Your player died");
    } else {
        System.out.println("The monster attacked " + somePlayer.getName() + " and made " + this.damage + " damage");
        System.out.println("Your remaining health is - " + (remainingHealth - somePlayer.getStrength()));
    }

}

But the problem is that variable "remainingHealth" stays same , only the first time when I run the code it lowers , every next time it stays same,  I guess the problem is in this line :

int totalHealth = somePlayer.getHitPoints() + somePlayer.getStrength();

I guess everytime I run the code

somePlayer.getHitpoints()

takes the inserted integer from constructor and that's the problem.

I need to figure out the way to store the remaining health in a variable somehow

Player class :

public class Player implements ISavable{

private String name;
private int hitPoints ;
private int strength ;
private String weapon;
private int damage;
private int totalHealth = hitPoints + strength;

public Player(String name, int damage , int hitPoints , int strength) {
    this.name = name;
    this.damage = damage;
    this.weapon = "Sword";
    this.hitPoints = hitPoints;
    this.strength = strength;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getHitPoints() {
    return hitPoints;
}

public void setHitPoints(int hitPoints) {
    this.hitPoints = hitPoints;
}

public int getStrength() {
    return strength;
}

public void setStrength(int strength) {
    this.strength = strength;
}

public String getWeapon() {
    return weapon;
}

public void setWeapon(String weapon) {
    this.weapon = weapon;
}

public int getTotalHealth() {
    return totalHealth;
}

public void setTotalHealth(int totalHealth) {
    this.totalHealth = totalHealth;
}

@Override
public String toString() {
    return "Player{" +
            "name='" + name + '\'' +
            ", hitPoints=" + hitPoints +
            ", strength=" + strength +
            ", weapon='" + weapon + '\'' +
            '}';
}

@Override
public List<String> write() {
    List<String> values = new ArrayList<String>();
    values.add(0, this.name);
    values.add(1, "" + this.hitPoints);
    values.add(2, "" + this.strength);
    values.add(3, "" + this.weapon);
    values.add(4,"" + this.damage);
    return values;
}

@Override
public void read(List<String> savedValues) {
    if (savedValues != null && savedValues.size()>0){
        this.name = savedValues.get(0);
        this.hitPoints = Integer.parseInt(savedValues.get(1));
        this.strength = Integer.parseInt(savedValues.get(2));
        this.weapon = savedValues.get(3);
    }
}

public void attack(Monster someMonster){
    int health = someMonster.getHitPoints();
    int remainingHealth = health - damage;
    if (remainingHealth == 0 || remainingHealth < 0) {
        System.out.println("You killed the monster !!!");
    } else {
        System.out.println("You attacked the monster " + " and made " + this.damage + " damage");
        System.out.println("Monsters remaining health is - " + remainingHealth);
    }

    if (someMonster.isDead()){
        this.hitPoints = 100;
        this.strength = 50;
    }
}

public void healPlayer(Player somePlayer){
    int hp = somePlayer.getHitPoints();
    hp += 10;
    System.out.println("You healed the player for 10hp , your current hp is " + hp);
}

}

Body:
You should have a representation of health, defining in Player totalHealth.

You may use a method which calculate the total health (cause your player could get an item that increases strenght or an item that allow heal you).

Then you should use another variable in Player, remainingHealth and initialize it as remainingHealth = totalHealth

    public class Player {

    float totalHealth;
    float remainingHealth;
    ...

    public Player(...) {
        this.remainingHealth = this.totalHealth;
        ...
    }
    ...

}

When you want decrease the health of your player you should use remainingHealth.

    public void attack(Player somePlayer) {

    somePlayer.remainingHealth -= this.damage;
    if (somePlayer.remainingHealth <= 0) {
        System.out.println("Your player died");
    } else {
        System.out.println("The monster attacked ...");
        System.out.println("Your remaining health is - " + somePlayer.remainingHealth);
    }

}


问:
How to automatically open show / hide javascript tab and re-hide on second click
I have some tabs which show hidden information when clicked. But as they are now, they will open but only close when a new tab is clicked. If possible could I get help with these two issues:

1- I want to make the tab close again when you click it a second time.

2- I have links set up to open the page where each section starts. Is there anyway I can make the tab open automatically when that link is clicked?

I appreciate the help.

Edited to show the full code I have now:

$('.drop a').click(function() {
  var $content = $(this).parent().next().toggle();

  //HIDE THIS LINE IF YOU DO NOT WANT TO HIDE OTHER TABS ON CLICK
 $('.droptab').not($content).hide();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.droptab {
  display: none
}</code>```

post_title; ?>">

<?php echo $child->post_title; ?>

<?php echo apply_filters('the_content', $child->post_content); ?>

                ID ); ?>" class="button left">Get More Info

```

答:
You can use toogle instead for the current link and hide the others:

```<code>$('.drop a').click(function() {
  var content = $(this).parent().next();
  $('.droptab').not(content).hide(200);
  $(content).toggle(200);
});
</code>```

Working snippet

$('.drop a').click(function() {
  var content = $(this).parent().next();
  $('.droptab').not(content).hide(200);
  $(content).toggle(200);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.droptab {
  display: none
}</code>```

    MAIN TITLE

MAIN TITLE CONTENT

    SECOND TITLE

SECOND TITLE CONTENT

```

Body:
I have some tabs which show hidden information when clicked. But as they are now, they will open but only close when a new tab is clicked. If possible could I get help with these two issues:

1- I want to make the tab close again when you click it a second time.

2- I have links set up to open the page where each section starts. Is there anyway I can make the tab open automatically when that link is clicked?

I appreciate the help.

Edited to show the full code I have now:

$('.drop a').click(function() {
  var $content = $(this).parent().next().toggle();

  //HIDE THIS LINE IF YOU DO NOT WANT TO HIDE OTHER TABS ON CLICK
 $('.droptab').not($content).hide();
});

.droptab {
  display: none
}

<a class="anchor" id="<?php echo $child->post_title; ?>">

<?php echo $child->post_title; ?>

<?php echo apply_filters('the_content', $child->post_content); ?>

                <a href="<?php the_field( 'get_more_url', $child->ID ); ?>" class="button left">Get More Info

Body:
You can use toogle instead for the current link and hide the others:

$('.drop a').click(function() {
  var content = $(this).parent().next();
  $('.droptab').not(content).hide(200);
  $(content).toggle(200);
});

Working snippet

$('.drop a').click(function() {
  var content = $(this).parent().next();
  $('.droptab').not(content).hide(200);
  $(content).toggle(200);
});

.droptab {
  display: none
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dropdowntabs">
  <a class="anchor" id="main-tab"></a>
  <h2 class="drop">
    <a>MAIN TITLE</a>
  </h2>
  <div class="droptab">
    <p>MAIN TITLE CONTENT</p>
  </div>
  <a class="anchor" id="second-tab"></a>
  <h2 class="drop">
    <a>SECOND TITLE</a>
  </h2>
  <div class="droptab">
    <p>SECOND TITLE CONTENT</p>
  </div>
</div>


问:
How to iterate object in JavaScript?
I have this object. I want to iterate this object in JavaScript. How is this possible?</p>

```<code>var dictionary = {
    "data": [
        {"id":"0","name":"ABC"},
        {"id":"1","name":"DEF"}
    ],
    "images": [
        {"id":"0","name":"PQR"},
        {"id":"1","name":"xyz"}
    ]
};
</code>```

答:
Using for and foreach loop  </p>

```<code>var dictionary = {
     data: [{ id: "0", name: "ABC" }, { id: "1", name: "DEF" }],
     images: [{ id: "0", name: "PQR" }, { id: "1", name: "xyz" }]
};
dictionary.data.forEach(item => {
     console.log(item.id + " " + item.name);
});

for (var i = 0; i < dictionary.data.length; i++) {
     console.log(dictionary.data[i].id + " " + dictionary.data[i].name);
}
</code>```

Title: How to iterate object in JavaScript?

Body:
I have this object. I want to iterate this object in JavaScript. How is this possible?

var dictionary = {
    "data": [
        {"id":"0","name":"ABC"},
        {"id":"1","name":"DEF"}
    ],
    "images": [
        {"id":"0","name":"PQR"},
        {"id":"1","name":"xyz"}
    ]
};

Body:
Using for and foreach loop

var dictionary = {
     data: [{ id: "0", name: "ABC" }, { id: "1", name: "DEF" }],
     images: [{ id: "0", name: "PQR" }, { id: "1", name: "xyz" }]
};
dictionary.data.forEach(item => {
     console.log(item.id + " " + item.name);
});

for (var i = 0; i < dictionary.data.length; i++) {
     console.log(dictionary.data[i].id + " " + dictionary.data[i].name);
}


问:
Sitecore Powershell search/filter by a droplink field
In a Sitecore content tree, I have a list of about 3000 articles.  Each article has an author field.  The author field is of type droplink.  I am trying to write a PowerShell script that gets me a count of articles that each author has written.

```<code>#This is where all the Authors lives
cd 'master:/sitecore/content/mysite/Global/Authors Folder'

#Get all the articles that each author has written
function ProcessItem($item)
{
$articles = Get-Item master: -Query "/sitecore/content/mySite/Home/Articles/2017//*[@@templatename='Article' and @Author='$item.Id']"
$articles.Count
}

#Get a list of authors
$itemsToProcess = Get-ChildItem -Recurse . | Where-Object { $_.TemplateName -match "Authors"  }
if($itemsToProcess -ne $null)
{
   $itemsToProcess | foreach {ProcessItem($_)}
}
</code>```

It appears that the call to get the articles by the author Id is not returning anything.  Therefore $articles.Count is always returning 0.  I tried to to @Author.Value='$item.Id' but still didn't get any results.  Can anyone see anything I could be doing wrong here?

答:
Unless you are testing against a single property you need to wrap the condition in brackets like this:</p>

```<code>$articles = Get-Item master: `
    -Query "/sitecore/content/mySite/Home/Articles/2017//*[@@templatename='Article' and @Author='$($item.Id)']"
</code>```

Body:
In a Sitecore content tree, I have a list of about 3000 articles.  Each article has an author field.  The author field is of type droplink.  I am trying to write a PowerShell script that gets me a count of articles that each author has written.

#This is where all the Authors lives
cd 'master:/sitecore/content/mysite/Global/Authors Folder'

#Get all the articles that each author has written
function ProcessItem($item)
{
$articles = Get-Item master: -Query "/sitecore/content/mySite/Home/Articles/2017//*[@@templatename='Article' and @Author='$item.Id']"
$articles.Count
}

#Get a list of authors
$itemsToProcess = Get-ChildItem -Recurse . | Where-Object { $_.TemplateName -match "Authors"  }
if($itemsToProcess -ne $null)
{
   $itemsToProcess | foreach {ProcessItem($_)}
}

It appears that the call to get the articles by the author Id is not returning anything.  Therefore $articles.Count is always returning 0.  I tried to to @Author.Value='$item.Id' but still didn't get any results.  Can anyone see anything I could be doing wrong here?

Body:
Unless you are testing against a single property you need to wrap the condition in brackets like this:

$articles = Get-Item master: `
    -Query "/sitecore/content/mySite/Home/Articles/2017//*[@@templatename='Article' and @Author='$($item.Id)']"


问:
Close all other sub-menus on click
Hello everyone,
Thank you for taking the time to view this post.

I have the following problem I am trying to create a menu with sub-menus.

Menu should:

Open sub-menus on click. (working)

Sub-menus stay open on selected menu. (working)

3. Once clicked in other menus the previous sub-menus should close. (not working)

HTML

```<code>      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <ul class="bottom-menu">
      <li class="drop"><a>Hyperlink 1</a></li>
      <li class="drop"><a>Hyperlink 2</a>
      <ul id="m1" class="bottom-menu-sub">
        <li><a href="#">Hyperlink Sub</a></li>
        <li><a href="#">Hyperlink Sub</a></li>
        <li><a href="#">Hyperlink Sub</a></li>
      </ul>
    </li>
    <li class="drop"><a>Hyperlink 3</a>
      <ul id="m2">
        <li><a href="#">Hyperlink Sub</a></li>
        <li><a href="#">Hyperlink Sub</a></li>
      </ul>
    </li>
    <li class="drop"><a>Hyperlink 4</a>
      <ul id="m3">
        <li><a href="#">Hyperlink Sub</a></li>
        <li><a href="#">Hyperlink Sub</a></li>
      </ul>
    </li>
</ul>
</code>```

CSS:

```<code>      .bottom-menu li ul {
      display:none;
      }
</code>```

JS:

```<code>jQuery(function ($) {
    // jQuery code in here can safely use $
    $('.bottom-menu li')
        .css({
        cursor: "pointer"
    });

    $(".drop>a").on('click', function (eventData) {
        var $listItem = $(this).closest('li');

        $listItem.find('ul').toggle();
        $listItem.toggleClass('open');

        $.cookie('open_items', 'the_value');
        openItems = new Array();
        $("li.drop").each(function (index, item) {
            if ($(item).hasClass('open')) {
                openItems.push(index);
            }
        });
        $.cookie('open_items', openItems.join(','));
    });

    if ($.cookie('open_items') && $.cookie('open_items').length > 0) {
        previouslyOpenItems = $.cookie('open_items');
        openItemIndexes = previouslyOpenItems.split(',');
        $(openItemIndexes).each(function (index, item) {
            $("li.drop").eq(item).addClass('open').find('ul').toggle();
        });
    }
});
</code>```

jsFiddle

答:
Hope this helps you.

jQuery(function ($) {
    // jQuery code in here can safely use $

    $(".drop>a").on('click', function (eventData) {
        var $listItem = $(this).closest('li');
    $('.drop ul').hide();
        $listItem.find('ul').toggle();
        $listItem.toggleClass('open');

        //$.cookie('open_items', 'the_value');
        openItems = new Array();
        $("li.drop").each(function (index, item) {
            if ($(item).hasClass('open')) {
                openItems.push(index);
            }
        });
        //$.cookie('open_items', openItems.join(','));
    });

    //if ($.cookie('open_items') && $.cookie('open_items').length > 0) {
    //    previouslyOpenItems = $.cookie('open_items');
    //    openItemIndexes = previouslyOpenItems.split(',');
    //    $(openItemIndexes).each(function (index, item) {
    //        $("li.drop").eq(item).addClass('open').find('ul').toggle();
    //   });
    //}
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.bottom-menu li ul {
    display:none;
}
.bottom-menu li{
  cursor: pointer;
}</code>```

Hyperlink 1

Hyperlink 2

Hyperlink Sub

Hyperlink Sub

Hyperlink Sub

Hyperlink 3

Hyperlink Sub

Hyperlink Sub

Hyperlink 4

Hyperlink Sub

Hyperlink Sub

If you open the "Hyperlink 2", the sub menu will show (that's as entended),
 Althought once you click "Hyperlink 3" the sub-menus of "Hyperlink 2" stay open.

```

Title: Close all other sub-menus on click

Body:
Hello everyone,
Thank you for taking the time to view this post.

I have the following problem I am trying to create a menu with sub-menus.

Menu should:

Open sub-menus on click. (working)

Sub-menus stay open on selected menu. (working)

3. Once clicked in other menus the previous sub-menus should close. (not working)

HTML

Hyperlink 1

Hyperlink 2

Hyperlink Sub

Hyperlink Sub

Hyperlink Sub

Hyperlink 3

Hyperlink Sub

Hyperlink Sub

Hyperlink 4

Hyperlink Sub

Hyperlink Sub

CSS:

      .bottom-menu li ul {
      display:none;
      }

JS:

jQuery(function ($) {
    // jQuery code in here can safely use $
    $('.bottom-menu li')
        .css({
        cursor: "pointer"
    });

    $(".drop>a").on('click', function (eventData) {
        var $listItem = $(this).closest('li');

        $listItem.find('ul').toggle();
        $listItem.toggleClass('open');

        $.cookie('open_items', 'the_value');
        openItems = new Array();
        $("li.drop").each(function (index, item) {
            if ($(item).hasClass('open')) {
                openItems.push(index);
            }
        });
        $.cookie('open_items', openItems.join(','));
    });

    if ($.cookie('open_items') && $.cookie('open_items').length > 0) {
        previouslyOpenItems = $.cookie('open_items');
        openItemIndexes = previouslyOpenItems.split(',');
        $(openItemIndexes).each(function (index, item) {
            $("li.drop").eq(item).addClass('open').find('ul').toggle();
        });
    }
});

jsFiddle

Body:
Hope this helps you.

jQuery(function ($) {
    // jQuery code in here can safely use $

    $(".drop>a").on('click', function (eventData) {
        var $listItem = $(this).closest('li');
    $('.drop ul').hide();
        $listItem.find('ul').toggle();
        $listItem.toggleClass('open');

        //$.cookie('open_items', 'the_value');
        openItems = new Array();
        $("li.drop").each(function (index, item) {
            if ($(item).hasClass('open')) {
                openItems.push(index);
            }
        });
        //$.cookie('open_items', openItems.join(','));
    });

    //if ($.cookie('open_items') && $.cookie('open_items').length > 0) {
    //    previouslyOpenItems = $.cookie('open_items');
    //    openItemIndexes = previouslyOpenItems.split(',');
    //    $(openItemIndexes).each(function (index, item) {
    //        $("li.drop").eq(item).addClass('open').find('ul').toggle();
    //   });
    //}
});

.bottom-menu li ul {
    display:none;
}
.bottom-menu li{
  cursor: pointer;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="bottom-menu">
    <li class="drop"><a>Hyperlink 1</a></li>
    <li class="drop"><a>Hyperlink 2</a>
      <ul id="m1" class="bottom-menu-sub">
        <li><a href="#">Hyperlink Sub</a></li>
        <li><a href="#">Hyperlink Sub</a></li>
        <li><a href="#">Hyperlink Sub</a></li>
      </ul>
    </li>
    <li class="drop"><a>Hyperlink 3</a>
      <ul id="m2">
        <li><a href="#">Hyperlink Sub</a></li>
        <li><a href="#">Hyperlink Sub</a></li>
      </ul>
    </li>
    <li class="drop"><a>Hyperlink 4</a>
      <ul id="m3">
        <li><a href="#">Hyperlink Sub</a></li>
        <li><a href="#">Hyperlink Sub</a></li>
      </ul>
    </li>
</ul>

<p>If you open the "Hyperlink 2", the sub menu will show (that's as entended),</br> Althought once you click "Hyperlink 3" the sub-menus of "Hyperlink 2" stay open.
</p>


问:
Selenium 3.7 webdriver Error: Timed out waiting for driver server to start
Upgraded to Selenium 3.7 recently and ran into error.

Error trace log:

Debug 1
  Debug 2
  Starting ChromeDriver 2.33.506106 (8a06c39c4582fbfbab6966dbb1c38a9173bfb1a2) on port 2198
  Only local connections are allowed.
  Exception in thread "main" org.openqa.selenium.WebDriverException: Timed out waiting for driver server to start.
  Build info: version: '3.7.1', revision: '8a0099a', time: '2017-11-06T21:07:36.161Z'
  System info: host: 'Maggies-MacBook-Pro-2.local', ip: '192.168.1.6', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.12.6', java.version: '1.8.0_121'
  Driver info: driver.version: ChromeDriver
      at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:192)
      at org.openqa.selenium.remote.service.DriverService.start(DriverService.java:178)
      at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:79)
      at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:600)
      at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:219)
      at org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:142)
      at org.openqa.selenium.chrome.ChromeDriver.(ChromeDriver.java:181)
      at org.openqa.selenium.chrome.ChromeDriver.(ChromeDriver.java:168)
      at org.openqa.selenium.chrome.ChromeDriver.(ChromeDriver.java:123)
      at AutomationFrameWork.FirstTestCase.main(FirstTestCase.java:13)
  Caused by: org.openqa.selenium.net.UrlChecker$TimeoutException: Timed out waiting for [http://localhost:2198/status] to be available after 20005 ms
      at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:100)
      at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:187)
      ... 9 more
  Caused by: java.util.concurrent.TimeoutException
      at java.util.concurrent.FutureTask.get(FutureTask.java:205)
      at com.google.common.util.concurrent.SimpleTimeLimiter.callWithTimeout(SimpleTimeLimiter.java:147)
      at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:75)
      ... 10 more

Code:

```<code>public static void main (String args[]){
    System.out.println("Debug 1");
    System.setProperty("webdriver.chrome.driver", "/Users/maggie/Documents/ToolsQA/Libs/chromedriver");
    System.out.println("Debug 2");
    WebDriver driver = new ChromeDriver();
    System.out.println("Debug 3");
    driver.get("http://www.google.com");
    driver.quit();
}
</code>```

Included Libraries:
selenium-server-standalone-3.7.1.jar

System Environment:

Mac OS: '10.12.6'

java.version: '1.8.0_121'

selenium-server-standalone-3.7.1.jar

geckodriver - v0.19.1

ChromeDriver 2.33

Chrome Version 62.0.3202.89 (64-bit)

Thank you for any thought.

答:
Change this

System.setProperty("webdriver.chrome.driver", "/Users/maggie/Documents/ToolsQA/Libs/chromedriver" to "/Users/maggie/Documents/ToolsQA/Libs/chromedriver.exe" and try this

Body:
Upgraded to Selenium 3.7 recently and ran into error.

Error trace log:

Debug 1
  Debug 2
  Starting ChromeDriver 2.33.506106 (8a06c39c4582fbfbab6966dbb1c38a9173bfb1a2) on port 2198
  Only local connections are allowed.
  Exception in thread "main" org.openqa.selenium.WebDriverException: Timed out waiting for driver server to start.
  Build info: version: '3.7.1', revision: '8a0099a', time: '2017-11-06T21:07:36.161Z'
  System info: host: 'Maggies-MacBook-Pro-2.local', ip: '192.168.1.6', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.12.6', java.version: '1.8.0_121'
  Driver info: driver.version: ChromeDriver
      at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:192)
      at org.openqa.selenium.remote.service.DriverService.start(DriverService.java:178)
      at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:79)
      at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:600)
      at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:219)
      at org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:142)
      at org.openqa.selenium.chrome.ChromeDriver.(ChromeDriver.java:181)
      at org.openqa.selenium.chrome.ChromeDriver.(ChromeDriver.java:168)
      at org.openqa.selenium.chrome.ChromeDriver.(ChromeDriver.java:123)
      at AutomationFrameWork.FirstTestCase.main(FirstTestCase.java:13)
  Caused by: org.openqa.selenium.net.UrlChecker$TimeoutException: Timed out waiting for [http://localhost:2198/status] to be available after 20005 ms
      at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:100)
      at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:187)
      ... 9 more
  Caused by: java.util.concurrent.TimeoutException
      at java.util.concurrent.FutureTask.get(FutureTask.java:205)
      at com.google.common.util.concurrent.SimpleTimeLimiter.callWithTimeout(SimpleTimeLimiter.java:147)
      at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:75)
      ... 10 more

Code:

public static void main (String args[]){
    System.out.println("Debug 1");
    System.setProperty("webdriver.chrome.driver", "/Users/maggie/Documents/ToolsQA/Libs/chromedriver");
    System.out.println("Debug 2");
    WebDriver driver = new ChromeDriver();
    System.out.println("Debug 3");
    driver.get("http://www.google.com");
    driver.quit();
}

Included Libraries:
selenium-server-standalone-3.7.1.jar

System Environment:

Mac OS: '10.12.6'

java.version: '1.8.0_121'

selenium-server-standalone-3.7.1.jar

geckodriver - v0.19.1

ChromeDriver 2.33

Chrome Version 62.0.3202.89 (64-bit)

Thank you for any thought.


问:
bash heredoc inside a vagrant vm provision heredoc
I like to use a bash heredoc inside the ruby heredoc from config.vm.provision, like so:

```<code>config.vm.provision "shell", inline: <<-SHELL
    cat >> foobar <<EOF
    bla bla
    foo foo
EOF
echo 'some other command'
SHELL
</code>```

But when the privision file is executed, everything to the end of the provision ends up in foobar.
I suspect that I need some escaping here.

答:
Why do you insist on the nested heredocs? What’s wrong with:</p>

```<code>config.vm.provision "shell", inline: %q|
    cat >> foobar <<EOF
    bla bla
    foo foo
EOF
echo 'some other command'
|
</code>```

Body:
I like to use a bash heredoc inside the ruby heredoc from config.vm.provision, like so:

config.vm.provision "shell", inline: <<-SHELL
    cat >> foobar <<EOF
    bla bla
    foo foo
EOF
echo 'some other command'
SHELL

But when the privision file is executed, everything to the end of the provision ends up in foobar.
I suspect that I need some escaping here.

Body:
Why do you insist on the nested heredocs? What’s wrong with:

config.vm.provision "shell", inline: %q|
    cat >> foobar <<EOF
    bla bla
    foo foo
EOF
echo 'some other command'
|


问:
after launch in landscape cannot force view to start in portrait
I know that this subject has been asked before, but I went over all solutions and none solved the case I'm having.

My app is all in portrait format, only one view controller in landscape format.

I added to all view controllers the following code to force Portrait Orientation regardless the device orientation:

```<code> - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
       return UIInterfaceOrientationMaskPortrait;
 }

 -(BOOL)shouldAutorotate{
      return NO;
 }
 - (UIInterfaceOrientationMask)supportedInterfaceOrientations
 {
      return UIInterfaceOrientationMaskPortrait;
 }

 -(void)ViewDidLoad()
 {
      [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait];
 }
</code>```

If the device is set in portrait mode the viewController opens correctly, but if the device is set landscape mode before opening the app, then the app launches the splash screen in landscape and opens the view controller in landscape with part of the view clipped, then it rotates it to portrait mode, and keeps part of the screen clipped, as shown in the picture.

in the app delegate:

```<code> - (UIInterfaceOrientationMask)supportedInterfaceOrientations
 {
      return UIInterfaceOrientationMaskPortrait;;
 }

 - (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
 {
      return UIInterfaceOrientationMaskAllButUpsideDown;
 }
</code>```

And in the appDelegate also, just before adding the view controller to the navigation controller I added the following:

```<code>[UIApplication sharedApplication].statusBarOrientation = UIInterfaceOrientationPortrait;
[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationPortrait] forKey:@"orientation"];
</code>```

答:
This seems to be a new thing since iOS 11. I fixed it by allowing autorotate but only supporting portrait.</p>

```<code>(BOOL)shouldAutorotate{
      return YES;
}
(UIInterfaceOrientationMask)supportedInterfaceOrientations
{
     return UIInterfaceOrientationMaskPortrait;
}
</code>```

Body:
I know that this subject has been asked before, but I went over all solutions and none solved the case I'm having.

My app is all in portrait format, only one view controller in landscape format.

I added to all view controllers the following code to force Portrait Orientation regardless the device orientation:

 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
       return UIInterfaceOrientationMaskPortrait;
 }

 -(BOOL)shouldAutorotate{
      return NO;
 }
 - (UIInterfaceOrientationMask)supportedInterfaceOrientations
 {
      return UIInterfaceOrientationMaskPortrait;
 }

 -(void)ViewDidLoad()
 {
      [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait];
 }

If the device is set in portrait mode the viewController opens correctly, but if the device is set landscape mode before opening the app, then the app launches the splash screen in landscape and opens the view controller in landscape with part of the view clipped, then it rotates it to portrait mode, and keeps part of the screen clipped, as shown in the picture.

in the app delegate:

 - (UIInterfaceOrientationMask)supportedInterfaceOrientations
 {
      return UIInterfaceOrientationMaskPortrait;;
 }

 - (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
 {
      return UIInterfaceOrientationMaskAllButUpsideDown;
 }

And in the appDelegate also, just before adding the view controller to the navigation controller I added the following:

[UIApplication sharedApplication].statusBarOrientation = UIInterfaceOrientationPortrait;
[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationPortrait] forKey:@"orientation"];

Body:
This seems to be a new thing since iOS 11. I fixed it by allowing autorotate but only supporting portrait.

(BOOL)shouldAutorotate{
      return YES;
}
(UIInterfaceOrientationMask)supportedInterfaceOrientations
{
     return UIInterfaceOrientationMaskPortrait;
}


问:
Any SQL Server multiple-recordset stored procedure gotchas?

Context

My current project is a large-ish public site (2 million pageviews per day) site running a mixture of asp classic and asp.net with a SQL Server 2005 back-end. We're heavy on reads, with occasional writes and virtually no updates/deletes. Our pages typically concern a single 'master' object with a stack of dependent (detail) objects.

I like the idea of returning all the data required for a page in a single proc (and absolutely no unnecesary data). True, this requires a dedicated proc for such pages, but some pages receive double-digit percentages of our overall site traffic so it's worth the time/maintenance hit. We typically only consume multiple-recordsets from our .net code, using System.Data.SqlClient.SqlDataReader and it's NextResult method. Oh, yeah, I'm not doing any updates/inserts in these procs either (except to table variables).

The question

SQL Server (2005) procs which return multiple recordsets are working well (in prod) for us so far but I am a little worried that multi-recordset procs are my new favourite hammer that i'm hitting every problem (nail) with. Are there any multi-recordset sql server proc gotchas I should know about? Anything that's going to make me wish I hadn't used them? Specifically anything about it affecting connection pooling, memory utilization etc.

答:
Here's a few gotchas for multiple-recordset stored procs:

They make it more difficult to reuse code.  If you're doing several queries, odds are you'd be able to reuse one of those queries on another page.

They make it more difficult to unit test.  Every time you make a change to one of the queries, you have to test all of the results.  If something changed, you have to dig through to see which query failed the unit test.

They make it more difficult to tune performance later.  If another DBA comes in behind you to help performance improve, they have to do more slicing and dicing to figure out where the problems are coming from.  Then, combine this with the code reuse problem - if they optimize one query, that query might be used in several different stored procs, and then they have to go fix all of them - which makes for more unit testing again.

They make error handling much more difficult.  Four of the queries in the stored proc might succeed, and the fifth fails.  You have to plan for that.

They can increase locking problems and incur load in TempDB.  If your stored procs are designed in a way that need repeatable reads, then the more queries you stuff into a stored proc, the longer it's going to take to run, and the longer it's going to take to return those results back to your app server.  That increased time means higher contention for locks, and the more SQL Server has to store in TempDB for row versioning.  You mentioned that you're heavy on reads, so this particular issue shouldn't be too bad for you, but you want to be aware of it before you reuse this hammer on a write-intensive app.

OwnerDisplayName: Jaysen Marais

LastEditorDisplayName: Jaysen Marais

OwnerDisplayName: Brent Ozar


问:
Difficult MySQL self-join please explain
This is supposed to be able to return a random post id. It is also said to be the fastest method using MySQL. </p>

```<code>SELECT t.id
FROM table t
JOIN (SELECT(FLOOR(max(id) * rand())) AS maxid FROM table)
AS tt
ON t.id >= tt.maxid
LIMIT 1
</code>```

<p>Can't seem to wrap my head around this, please help. </p>

答:
You pick a random ID number from your table with the "joined table"

```<code> SELECT(FLOOR(max(id) * rand())) AS maxid FROM table
</code>```

This will only return something you can use if the id's don't have holes in them (consequtive integers).
THat's why you're joining on this

```<code> ON t.id >= tt.maxid
</code>```

You'll get all the id's that are HIGHER then your random number. The limit then gets the first of those.

So an example: say you have these entries in table:
     1, 2, 5, 7, 8.

The floored random number will be smaller then 8, e.g. 3. You'll join will give you 5, 7 and 8 but returns only 5 because of the limit

Body:
This is supposed to be able to return a random post id. It is also said to be the fastest method using MySQL.

SELECT t.id
FROM table t
JOIN (SELECT(FLOOR(max(id) * rand())) AS maxid FROM table)
AS tt
ON t.id >= tt.maxid
LIMIT 1

Can't seem to wrap my head around this, please help.

Body:
You pick a random ID number from your table with the "joined table"

 SELECT(FLOOR(max(id) * rand())) AS maxid FROM table

This will only return something you can use if the id's don't have holes in them (consequtive integers).
THat's why you're joining on this

 ON t.id >= tt.maxid

You'll get all the id's that are HIGHER then your random number. The limit then gets the first of those.

So an example: say you have these entries in table:
     1, 2, 5, 7, 8.

The floored random number will be smaller then 8, e.g. 3. You'll join will give you 5, 7 and 8 but returns only 5 because of the limit


问:
How to click on a link based on another cell in same row C# asp.net
I have a landlord table, tenant table and a property table in my database.I have a html table that is dynamically created which shows the properties of the landlord that is signed in.When a tenant signs up it enters the propery ID which is the foreign key in the tenant table. When I click the view link on that html table, I would like it to be redirected to a new page showing the tenants that belong to that property.. I am unsure how to do this when the view link is clicked based on the property id in that row </p>

<p>This is my html table
and here is the code for the dynamically created table </p>

```<code>public partial class LandlordIndex : System.Web.UI.Page
{
    //creating an empty string
    string checkEmail = String.Empty;
    //constructing a string called table that will be used to create a dynamic table
    StringBuilder table = new StringBuilder();
    protected void Page_Load(object sender, EventArgs e)
    {
        checkEmail += Session["LandlordLogin"];
    //if session is not empty then show label with corresponding email used in log in
        if (Session["LandlordLogin"] != null)
        {
            lblWelcome.Text += Session["LandlordLogin"].ToString();
        }
        else
        {
            Response.Redirect("Login.aspx");
        }
        if (!Page.IsPostBack)
        {
        //Creating a connection to my database using the connection string
            SqlConnection con = new SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["rent-dbConnectionString1"].ToString();
            con.Open();
            SqlCommand comm = new SqlCommand();
            //preparing a query which will select all properties matching the landlord that is logged in at that moment
            comm.CommandText = "select p.Property_Id, p.Property_Address, p.Property_Num_Of_Tenants, p.Property_Vacant from Properties p inner join Landlords l On p.Landlord_Id = l.Landlord_Id where l.Landlord_Id = p.Landlord_Id and l.Landlord_Email = '" + checkEmail + "'";
            comm.Connection = con;
            SqlDataReader rd = comm.ExecuteReader();
            //creating a table depending on the data that is selected from the query
            table.Append("<table border='2' class='table table-striped table-bordered'>");
            table.Append("<tr><th>Property Number</th>");
            table.Append("<th>Address</th>");
            table.Append("<th>Number of Tenants</th>");
            table.Append("<th>Vacant?</th>");
            table.Append("<th>View</th>");
            table.Append("</tr>");
            if (rd.HasRows)
            {
                while(rd.Read())
                {
                    table.Append("<tr>");
                    table.Append("<td>" + rd[0] + "</td>");
                    table.Append("<td>" + rd[1] + "</td>");
                    table.Append("<td>" + rd[2] + "</td>");
                    table.Append("<td>" + rd[3] + "</td>");
                    table.Append("<td><a href=''>View</a></td>");
                    table.Append("</tr>");
                }
            }
            table.Append("</table>");
            PlaceHolder1.Controls.Add(new Literal { Text = table.ToString() });
            rd.Close();
        }
   }
}
</code>```

答:
1. Make another page for Displaying Tenants. i.e tenants.aspx

2. Send propertyId from current page while calling that page

```<code>Response.Redirect("tenants.aspx?Id="+propertyId );
</code>```

3. In Page_Load() function of tenants.aspx get propertyId

```<code>if (Request.QueryString["Id"]!= null)
string propertyId = Request.QueryString["Id"];
</code>```

4. Fetch tenants for that property by querying database.

5. Make dynamic table for tenants just as properties

Body:
I have a landlord table, tenant table and a property table in my database.I have a html table that is dynamically created which shows the properties of the landlord that is signed in.When a tenant signs up it enters the propery ID which is the foreign key in the tenant table. When I click the view link on that html table, I would like it to be redirected to a new page showing the tenants that belong to that property.. I am unsure how to do this when the view link is clicked based on the property id in that row

This is my html table
and here is the code for the dynamically created table

public partial class LandlordIndex : System.Web.UI.Page
{
    //creating an empty string
    string checkEmail = String.Empty;
    //constructing a string called table that will be used to create a dynamic table
    StringBuilder table = new StringBuilder();
    protected void Page_Load(object sender, EventArgs e)
    {
        checkEmail += Session["LandlordLogin"];
    //if session is not empty then show label with corresponding email used in log in
        if (Session["LandlordLogin"] != null)
        {
            lblWelcome.Text += Session["LandlordLogin"].ToString();
        }
        else
        {
            Response.Redirect("Login.aspx");
        }
        if (!Page.IsPostBack)
        {
        //Creating a connection to my database using the connection string
            SqlConnection con = new SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["rent-dbConnectionString1"].ToString();
            con.Open();
            SqlCommand comm = new SqlCommand();
            //preparing a query which will select all properties matching the landlord that is logged in at that moment
            comm.CommandText = "select p.Property_Id, p.Property_Address, p.Property_Num_Of_Tenants, p.Property_Vacant from Properties p inner join Landlords l On p.Landlord_Id = l.Landlord_Id where l.Landlord_Id = p.Landlord_Id and l.Landlord_Email = '" + checkEmail + "'";
            comm.Connection = con;
            SqlDataReader rd = comm.ExecuteReader();
            //creating a table depending on the data that is selected from the query
            table.Append("
");
            table.Append("
Property Number	");
            table.Append("Address	");
            table.Append("Number of Tenants	");
            table.Append("Vacant?	");
            table.Append("View	");
            table.Append("
");
            if (rd.HasRows)
            {
                while(rd.Read())
                {
                    table.Append("
");
                    table.Append("" + rd[0] + "	");
                    table.Append("" + rd[1] + "	");
                    table.Append("" + rd[2] + "	");
                    table.Append("" + rd[3] + "	");
                    table.Append("View	");
                    table.Append("
");
                }
            }
            table.Append("
");
            PlaceHolder1.Controls.Add(new Literal { Text = table.ToString() });
            rd.Close();
        }
   }
}

Body:
1. Make another page for Displaying Tenants. i.e tenants.aspx

2. Send propertyId from current page while calling that page

Response.Redirect("tenants.aspx?Id="+propertyId );

3. In Page_Load() function of tenants.aspx get propertyId

if (Request.QueryString["Id"]!= null)
string propertyId = Request.QueryString["Id"];

4. Fetch tenants for that property by querying database.

5. Make dynamic table for tenants just as properties


问:
React Native <ListItem onPress={...}> - why is this function executing?
I'm just starting to wrap my head around React Native and am using Redux for management of state, the NativeBase library for my UI components and react-native-router-flux is handling navigation between views.

Currently I'm building a basic list that is created from an array of guest objects. The list is stored in the Redux store and I'm able to access it and display accordingly. Each item in the list is associated with a guest within a guests array. I'd like to make each item in the list touchable, and then pass the relevant guest object as a property to the next view to display details.

To do so I'm using the onPress function which is a standard function associated with the ListItem component (see NativeBase docs here). I've also followed the documentation for react-native-router-flux and defined the navigation action outside of the component itself so that the ListItem calls it when pressed and not each time it renders.

My problem is that I am finding that the onPress={goToView2(guest)} function is being called each time the ListItem is rendered rather than specifically when the ListItem is pressed.

I am sure it must be something simple that I have omitted. Any suggestions?

View1.js - view that displays initial list of guests:

```<code>import React, { Component } from 'react';
import { Container, Header, Title, Content, Footer, FooterTab, Button, Icon,
  Text, List, ListItem } from 'native-base';
import { connect } from 'react-redux';
import { Actions as NavigationActions } from 'react-native-router-flux';

class View1 extends Component {
  render() {

    // This is the function that runs every time a ListItem component is rendered.
    // Why is this not only running on onPress?

    const goToView2 = (guest) => {
      NavigationActions.view2(guest);
      console.log('Navigation router run...');
    };

    return (
      <Container>
        <Header>
          <Title>Header</Title>
        </Header>

        <Content>
          <List
            dataArray={this.props.guests}
            renderRow={(guest) =>
              <ListItem button onPress={goToView2(guest)}>
                <Text>{guest.name}</Text>
                <Text note>{guest.email}</Text>
              </ListItem>
            }
          >
          </List>
        </Content>

        <Footer>
          <FooterTab>
            <Button transparent>
              <Icon name='ios-call' />
            </Button>
          </FooterTab>
        </Footer>
      </Container>
    );
  }
}

const mapStateToProps = state => {
  console.log('mapStateToProps state', state);
  return { guests: state.guests };
};

export default connect(mapStateToProps)(View1);
</code>```

View2.js - view that displays details of the selected guest from View1.js:

```<code>import React, { Component } from 'react';
import { Container, Header, Title, Content, Footer, FooterTab, Button, Icon,
  Text, List, ListItem } from 'native-base';

class View2 extends Component {
    render() {
        console.log('View2 props: ', this.props);

        return (
            <Container>
                <Header>
                    <Title>Header</Title>
                </Header>

                <Content>
                <Content>
                <List>
                    <ListItem>
                        <Text>{this.props.name}</Text>
                    </ListItem>
                </List>
            </Content>
                </Content>

                <Footer>
                    <FooterTab>
                        <Button transparent>
                            <Icon name='ios-call' />
                        </Button>
                    </FooterTab>
                </Footer>
            </Container>
        );
    }
}

export default View2;
</code>```

答:
```<code>const goToView2 = (guest) => {
      NavigationActions.view2(guest);
      console.log('Navigation router run...');
    };

<ListItem button onPress={this.goToView2(guest)}>
</code>```

if you're using arrow function in the function then its just this.goToView2(guest) ...writing arrow function inside a render method causes performance issues...even though its negligible, its better to avoid it

Body:
I'm just starting to wrap my head around React Native and am using Redux for management of state, the NativeBase library for my UI components and react-native-router-flux is handling navigation between views.

Currently I'm building a basic list that is created from an array of guest objects. The list is stored in the Redux store and I'm able to access it and display accordingly. Each item in the list is associated with a guest within a guests array. I'd like to make each item in the list touchable, and then pass the relevant guest object as a property to the next view to display details.

To do so I'm using the onPress function which is a standard function associated with the ListItem component (see NativeBase docs here). I've also followed the documentation for react-native-router-flux and defined the navigation action outside of the component itself so that the ListItem calls it when pressed and not each time it renders.

My problem is that I am finding that the onPress={goToView2(guest)} function is being called each time the ListItem is rendered rather than specifically when the ListItem is pressed.

I am sure it must be something simple that I have omitted. Any suggestions?

View1.js - view that displays initial list of guests:

import React, { Component } from 'react';
import { Container, Header, Title, Content, Footer, FooterTab, Button, Icon,
  Text, List, ListItem } from 'native-base';
import { connect } from 'react-redux';
import { Actions as NavigationActions } from 'react-native-router-flux';

class View1 extends Component {
  render() {

    // This is the function that runs every time a ListItem component is rendered.
    // Why is this not only running on onPress?

    const goToView2 = (guest) => {
      NavigationActions.view2(guest);
      console.log('Navigation router run...');
    };

    return (
      <Container>

          <Title>Header</Title>

        <Content>
          <List
            dataArray={this.props.guests}
            renderRow={(guest) =>
              <ListItem button onPress={goToView2(guest)}>
                <Text>{guest.name}</Text>
                <Text note>{guest.email}</Text>
              </ListItem>
            }
          >
          </List>
        </Content>

          <FooterTab>
            <Button transparent>
              <Icon name='ios-call' />
            </Button>
          </FooterTab>

      </Container>
    );
  }
}

const mapStateToProps = state => {
  console.log('mapStateToProps state', state);
  return { guests: state.guests };
};

export default connect(mapStateToProps)(View1);

View2.js - view that displays details of the selected guest from View1.js:

import React, { Component } from 'react';
import { Container, Header, Title, Content, Footer, FooterTab, Button, Icon,
  Text, List, ListItem } from 'native-base';

class View2 extends Component {
    render() {
        console.log('View2 props: ', this.props);

        return (
            <Container>

                    <Title>Header</Title>

                <Content>
                <Content>
                <List>
                    <ListItem>
                        <Text>{this.props.name}</Text>
                    </ListItem>
                </List>
            </Content>
                </Content>

                    <FooterTab>
                        <Button transparent>
                            <Icon name='ios-call' />
                        </Button>
                    </FooterTab>

            </Container>
        );
    }
}

export default View2;

Body:
const goToView2 = (guest) => {
      NavigationActions.view2(guest);
      console.log('Navigation router run...');
    };

<ListItem button onPress={this.goToView2(guest)}>

if you're using arrow function in the function then its just this.goToView2(guest) ...writing arrow function inside a render method causes performance issues...even though its negligible, its better to avoid it


问:
Pandas convert dataframe to Utf-8
I have a df that consist of 100 rows and 24 columns. The column type is string. It's throwing me the following error when I tried to append the data frame to KDB

```<code>UnicodeEncodeError: 'ascii' codec can't encode character '\xd3' in position 9: ordinal not in range(128)
</code>```

Here is an example of the first row in my df.

```<code>                        AnnouncementDate AuctionDate    BBT  \
_id
00000067   2012-12-11T00:00:00.000+00:00         NaN   FHLB

           CouponDividendRate DaysToSettle  \
_id
00000067                 0.61            1

                                        Description  \
_id
00000067                         FHLB 0.61 12/28/16

                     FirstSettlementDate           ISN IsAgency IsWhenIssued  \
_id
00000067   2012-12-28T00:00:00.000+00:00  US313381K796     True        False

           ...  OnTheRunTreasury OperationalIndicator  \
_id        ...
00000067   ...               NaN                False

          OriginalAmountOfPrincipal OriginalMaturityDate  \
_id
00000067                 13000000.0                  NaN

          PrincipalAmountOutstanding       SCSP       SMCP  \
_id
00000067                         0.0  313381K79   76000000

           SecurityTypeLevel1 SecurityTypeLevel2   TCK
_id
00000067          US-DOMESTIC                NaN   NaN
</code>```

My question is, is there an easy way to convert my df to utf-8 format?

Possibly something like df = df.encode('utf-8')

Thanks

答:
It depends on how you're outputting the data.  If you're simply using csv files, which you then import to KDB, then you can specify that easily:

```<code>df.to_csv('df_output.csv', encoding='utf-8')
</code>```

Or, you can set the encoding when you import the data to Pandas originally, using the same syntax.

If you're connecting directly to KDB using SQLAlchemy or something similar, you should try specifying this in the connection itself - see this question: Another UnicodeEncodeError when using pandas method to_sql with MySQL

Title: Pandas convert dataframe to Utf-8

Body:
I have a df that consist of 100 rows and 24 columns. The column type is string. It's throwing me the following error when I tried to append the data frame to KDB

UnicodeEncodeError: 'ascii' codec can't encode character '\xd3' in position 9: ordinal not in range(128)

Here is an example of the first row in my df.

                        AnnouncementDate AuctionDate    BBT  \
_id
00000067   2012-12-11T00:00:00.000+00:00         NaN   FHLB

           CouponDividendRate DaysToSettle  \
_id
00000067                 0.61            1

                                        Description  \
_id
00000067                         FHLB 0.61 12/28/16

                     FirstSettlementDate           ISN IsAgency IsWhenIssued  \
_id
00000067   2012-12-28T00:00:00.000+00:00  US313381K796     True        False

           ...  OnTheRunTreasury OperationalIndicator  \
_id        ...
00000067   ...               NaN                False

          OriginalAmountOfPrincipal OriginalMaturityDate  \
_id
00000067                 13000000.0                  NaN

          PrincipalAmountOutstanding       SCSP       SMCP  \
_id
00000067                         0.0  313381K79   76000000

           SecurityTypeLevel1 SecurityTypeLevel2   TCK
_id
00000067          US-DOMESTIC                NaN   NaN

My question is, is there an easy way to convert my df to utf-8 format?

Possibly something like df = df.encode('utf-8')

Thanks

Body:
It depends on how you're outputting the data.  If you're simply using csv files, which you then import to KDB, then you can specify that easily:

df.to_csv('df_output.csv', encoding='utf-8')

Or, you can set the encoding when you import the data to Pandas originally, using the same syntax.

If you're connecting directly to KDB using SQLAlchemy or something similar, you should try specifying this in the connection itself - see this question: Another UnicodeEncodeError when using pandas method to_sql with MySQL