问:
How to get the name of the item that is being checked by the user in next activity in android?
I'm working on an android app where user will select the food quantity and move to the checkout screen to purchase that similar to what foodpanda, swiggy does.

But I'm unable to fetch the content of the item being selected using the quantity. It is showing the package name instead of the item name.

Code -

```<code>public class Food implements Parcelable,Serializable {
    String Foodname;
    int CartQuantity = 0;
    double FoodPrice;

    public Food(String Foodname, int cartQuantity, double FoodPrice) {
        this.Foodname = Foodname;
        this.CartQuantity = cartQuantity;
        this.FoodPrice = FoodPrice;
    }

    protected Food(Parcel in) {
        Foodname = in.readString();
        CartQuantity = in.readInt();
        FoodPrice = in.readDouble();
    }

    public static final Creator<Food> CREATOR = new Creator<Food>() {
        @Override
        public Food createFromParcel(Parcel in) {
            return new Food(in);
        }

        @Override
        public Food[] newArray(int size) {
            return new Food[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
            dest.writeString(this.Foodname);
            dest.writeInt(this.CartQuantity);
            dest.writeDouble(this.FoodPrice);
    }
}
</code>```

ListAdapter.class -

```<code>public class ListAdapter extends BaseAdapter {
    public ArrayList<Food> listproducts;
    private Context context;

    public ListAdapter(Context context,ArrayList<Food> listproducts){
        this.context=context;
        this.listproducts=listproducts;
    }
    @Override
    public int getCount() {
        return listproducts.size();
    }

    @Override
    public Food getItem(int position) {
        return listproducts.get(position);
    }

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

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View row;
        final ListViewHolder listViewHolder;
        if(convertView == null)
        {
            LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = layoutInflater.inflate(R.layout.list_item,parent,false);
            listViewHolder = new ListViewHolder();
            listViewHolder.foodName = row.findViewById(R.id.lblListItem);
            listViewHolder.foodPrice = row.findViewById(R.id.lblListItem1);
            listViewHolder.cartQuantity = row.findViewById(R.id.integer_number);
            listViewHolder.increment = row.findViewById(R.id.increase);
            listViewHolder.decrement = row.findViewById(R.id.decrease);
            row.setTag(listViewHolder);
        }
        else
        {
            row=convertView;
            listViewHolder= (ListViewHolder) row.getTag();
        }
        final Food food=getItem(position);

        listViewHolder.foodName.setText(food.Foodname);
        listViewHolder.foodPrice.setText(food.FoodPrice+" $");
        listViewHolder.cartQuantity.setText(food.CartQuantity+"");
        listViewHolder.increment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                updateQuantity(position,listViewHolder.cartQuantity,1);
            }
        });
        //listViewHolder.edTextQuantity.setText("0");
        listViewHolder.decrement.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateQuantity(position,listViewHolder.cartQuantity,-1);

            }
        });

        return row;
    }

    private void updateQuantity(int position, TextView edTextQuantity, int value) {

        Food food = getItem(position);
        if(value > 0&&food.CartQuantity<10)
        {
            food.CartQuantity = food.CartQuantity + 1;
        }
        else
        {
            if(food.CartQuantity > 0)
            {
                food.CartQuantity = food.CartQuantity - 1;
            }

        }
        edTextQuantity.setText(food.CartQuantity+"");
    }
}
</code>```

This is what I've tried and this is what I'm getting from this code.

Activity where the user will select the items to order

Activity which displays the selected items by the user

Instead of showing the item name, price and quantity, it is displaying the package name.
How can I get the required values by changing the code?

答:
What i understand from your question is you want to get the products
selected in food adapter in your next activity.

Firstly create a method in your adapter:

```<code>public ArrayList<Food> getSelectedProducts(){
   ArrayList<Food> selected = new ArrayList<>();
   for(Food food:listProducts){
      if(food.getCartQuantity() > 0){
        selected.add(food);
       }
   }
     return selected;
 }
</code>```

now get the selected items in current activity:

```<code>ArrayList<Food> products = adapter.getSelectedProducts();
</code>```

then put the products in an intent your are using to navigate to the next activity as:

```<code>Intent intent = new Intent("your intent");
intent.putExtra("data", (Serializable)products);
startActivity(intent);
</code>```

In your next activity get selected items as:

```<code>ArrayList<Food> selectedProducts = getIntent().getSerializableExtra("data");
</code>```

that's it!

Body:
I'm working on an android app where user will select the food quantity and move to the checkout screen to purchase that similar to what foodpanda, swiggy does.

But I'm unable to fetch the content of the item being selected using the quantity. It is showing the package name instead of the item name.

Code -

public class Food implements Parcelable,Serializable {
    String Foodname;
    int CartQuantity = 0;
    double FoodPrice;

    public Food(String Foodname, int cartQuantity, double FoodPrice) {
        this.Foodname = Foodname;
        this.CartQuantity = cartQuantity;
        this.FoodPrice = FoodPrice;
    }

    protected Food(Parcel in) {
        Foodname = in.readString();
        CartQuantity = in.readInt();
        FoodPrice = in.readDouble();
    }

    public static final Creator<Food> CREATOR = new Creator<Food>() {
        @Override
        public Food createFromParcel(Parcel in) {
            return new Food(in);
        }

        @Override
        public Food[] newArray(int size) {
            return new Food[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
            dest.writeString(this.Foodname);
            dest.writeInt(this.CartQuantity);
            dest.writeDouble(this.FoodPrice);
    }
}

ListAdapter.class -

public class ListAdapter extends BaseAdapter {
    public ArrayList<Food> listproducts;
    private Context context;

    public ListAdapter(Context context,ArrayList<Food> listproducts){
        this.context=context;
        this.listproducts=listproducts;
    }
    @Override
    public int getCount() {
        return listproducts.size();
    }

    @Override
    public Food getItem(int position) {
        return listproducts.get(position);
    }

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

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View row;
        final ListViewHolder listViewHolder;
        if(convertView == null)
        {
            LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = layoutInflater.inflate(R.layout.list_item,parent,false);
            listViewHolder = new ListViewHolder();
            listViewHolder.foodName = row.findViewById(R.id.lblListItem);
            listViewHolder.foodPrice = row.findViewById(R.id.lblListItem1);
            listViewHolder.cartQuantity = row.findViewById(R.id.integer_number);
            listViewHolder.increment = row.findViewById(R.id.increase);
            listViewHolder.decrement = row.findViewById(R.id.decrease);
            row.setTag(listViewHolder);
        }
        else
        {
            row=convertView;
            listViewHolder= (ListViewHolder) row.getTag();
        }
        final Food food=getItem(position);

        listViewHolder.foodName.setText(food.Foodname);
        listViewHolder.foodPrice.setText(food.FoodPrice+" $");
        listViewHolder.cartQuantity.setText(food.CartQuantity+"");
        listViewHolder.increment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                updateQuantity(position,listViewHolder.cartQuantity,1);
            }
        });
        //listViewHolder.edTextQuantity.setText("0");
        listViewHolder.decrement.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateQuantity(position,listViewHolder.cartQuantity,-1);

            }
        });

        return row;
    }

    private void updateQuantity(int position, TextView edTextQuantity, int value) {

        Food food = getItem(position);
        if(value > 0&&food.CartQuantity<10)
        {
            food.CartQuantity = food.CartQuantity + 1;
        }
        else
        {
            if(food.CartQuantity > 0)
            {
                food.CartQuantity = food.CartQuantity - 1;
            }

        }
        edTextQuantity.setText(food.CartQuantity+"");
    }
}

This is what I've tried and this is what I'm getting from this code.

Activity where the user will select the items to order

Activity which displays the selected items by the user

Instead of showing the item name, price and quantity, it is displaying the package name.
How can I get the required values by changing the code?

Body:
What i understand from your question is you want to get the products
selected in food adapter in your next activity.

Firstly create a method in your adapter:

public ArrayList<Food> getSelectedProducts(){
   ArrayList<Food> selected = new ArrayList<>();
   for(Food food:listProducts){
      if(food.getCartQuantity() > 0){
        selected.add(food);
       }
   }
     return selected;
 }

now get the selected items in current activity:

ArrayList<Food> products = adapter.getSelectedProducts();

then put the products in an intent your are using to navigate to the next activity as:

Intent intent = new Intent("your intent");
intent.putExtra("data", (Serializable)products);
startActivity(intent);

In your next activity get selected items as:

ArrayList<Food> selectedProducts = getIntent().getSerializableExtra("data");

that's it!


来源: stackexchange

问:
Why is my array outputting one row
My $aExtensionObjects print_r fine shows all of the things in the array but $aExtensionName only seems to output one why?

```<code>$aExtensionObjects Array:

Array ( [0] => Extension Object ( [iID:private] => [sExtensionName:private] => 2147483647 [db:private] => MySQLiPluggin Object ( [sqliConnection:private] => mysqli Object ( ) [Query:private] => [getResult:private] => ) [bExisting] => 1 ) [1] => Extension Object ( [iID:private] => [sExtensionName:private] => 876378990 [db:private] => MySQLiPluggin Object ( [sqliConnection:private] => mysqli Object ( ) [Query:private] => [getResult:private] => ) [bExisting] => 1 )) ) Etc..

$aExtensionName Array:

Array ( [] => 989898 )
</code>```

The code [ed: maybe?]

```<code>    $manExtensionManager  = new extensionManager();

    $aExtensionObjects   = $manExtensionManager->getallExtensions();

    $aExtensionName      = array();

for($iCount=0; $iCount<count($aExtensionObjects);$iCount++){
    $Extension = $aExtensionObjects[$iCount];
    $aExtensionName[$Extension->getExtensionID()] = $Extension->getExtensionName();
}
</code>```

答:
I think  your $Extension->getExtensionID() always returns one id that's why array is just getting one item.

check out you function getExtensionID()

And also can you confirm you are missing $ and - to just typo mistake or you really forgot in your program.

You can confirm if you function getExtensionID() is not working properly by doing

```<code>$aExtensionName[]=$Extension->getExtensionName();
</code>```

and print_r($aExtensionName) and see what is in it

ContentLicense: CC BY-SA 2.5

Title: Why is my array outputting one row

Body:
My $aExtensionObjects print_r fine shows all of the things in the array but $aExtensionName only seems to output one why?

$aExtensionObjects Array:

Array ( [0] => Extension Object ( [iID:private] => [sExtensionName:private] => 2147483647 [db:private] => MySQLiPluggin Object ( [sqliConnection:private] => mysqli Object ( ) [Query:private] => [getResult:private] => ) [bExisting] => 1 ) [1] => Extension Object ( [iID:private] => [sExtensionName:private] => 876378990 [db:private] => MySQLiPluggin Object ( [sqliConnection:private] => mysqli Object ( ) [Query:private] => [getResult:private] => ) [bExisting] => 1 )) ) Etc..

$aExtensionName Array:

Array ( [] => 989898 )

The code [ed: maybe?]

    $manExtensionManager  = new extensionManager();

    $aExtensionObjects   = $manExtensionManager->getallExtensions();

    $aExtensionName      = array();

for($iCount=0; $iCount<count($aExtensionObjects);$iCount++){
    $Extension = $aExtensionObjects[$iCount];
    $aExtensionName[$Extension->getExtensionID()] = $Extension->getExtensionName();
}

Body:
I think  your $Extension->getExtensionID() always returns one id that's why array is just getting one item.

check out you function getExtensionID()

And also can you confirm you are missing $ and - to just typo mistake or you really forgot in your program.

You can confirm if you function getExtensionID() is not working properly by doing

$aExtensionName[]=$Extension->getExtensionName();

and print_r($aExtensionName) and see what is in it


问:
javascript - pass a parameter through a submit form function
On clicking the retire user checkbox I am triggering the form submit for ("RetireUser", "Users")
My script is navigating to /Users/RetireUser but I need to pass the Id parameter.
Didn't have much luck with ajax
Thanks in advance for the help

```<code>@foreach (var item in UsersModel)
        {
            <tr>
                <td>@Html.DisplayFor(modelItem => item.Username)</td>
                <td>@Html.DisplayFor(modelItem => item.FirstName)</td>
                <td>@Html.DisplayFor(modelItem => item.LastName)</td>
                <td>@Html.DisplayFor(modelItem => item.Email)</td>
                <td>@Html.DisplayFor(modelItem => item.Phone)</td>
                <td>@Html.DisplayFor(modelItem => item.Status)</td>
                <td>@Html.DisplayFor(modelItem => item.DateRetired)</td>
                <td>@Html.DisplayFor(modelItem => item.DateAdded)</td>

                @using (Html.BeginForm("RetireUser", "Users", FormMethod.Post, new { role = "form", id="retire_user" }))
                {
                    <td>@Html.CheckBoxFor(modelItem => item.RetireUser)</td>
                }
                <td><a href="@Url.Action("GetUserById", "Users", new { id = item.Id })">Edit</a></td>
            </tr>
        }

<script>
$('#item_RetireUser').click(function () {
    $('#retire_user').submit();
});
</code>```

the html
the script

答: if it's a html why not give each  a id i.e  here 12 is user_id and with the help of jquery you can retrieve and send that id via ajax or normal url call.</p>

ContentLicense: CC BY-SA 3.0

Body:
On clicking the retire user checkbox I am triggering the form submit for ("RetireUser", "Users")
My script is navigating to /Users/RetireUser but I need to pass the Id parameter.
Didn't have much luck with ajax
Thanks in advance for the help

@foreach (var item in UsersModel)
        {

                @Html.DisplayFor(modelItem => item.Username)
                @Html.DisplayFor(modelItem => item.FirstName)
                @Html.DisplayFor(modelItem => item.LastName)
                @Html.DisplayFor(modelItem => item.Email)
                @Html.DisplayFor(modelItem => item.Phone)
                @Html.DisplayFor(modelItem => item.Status)
                @Html.DisplayFor(modelItem => item.DateRetired)
                @Html.DisplayFor(modelItem => item.DateAdded)

                @using (Html.BeginForm("RetireUser", "Users", FormMethod.Post, new { role = "form", id="retire_user" }))
                {
                    @Html.CheckBoxFor(modelItem => item.RetireUser)
                }
                Edit

        }


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

Error:

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

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

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

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

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

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

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

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

MainActivity.java:

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

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

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

import java.io.InputStreamReader;

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

import java.util.ArrayList;

public class MainActivity extends Activity {

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

        sendGetRequest();

     }

public String sendGetRequest() {

         String NEW_ICON = "icon";

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

        try {

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

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

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

            OutputStream os = myURLConnection.getOutputStream();

            os.close();

            myURLConnection.connect();

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

            StringBuffer sb = new StringBuffer();

            String line;

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

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

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

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

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

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

                   String s =dataArray[0];

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

                    IconArrayList.add(s);

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

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

                }

            }// end of for loop

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

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

        } catch (Exception e) {

        }
        return null;

    }
</code>```

BaseAdapter:

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

    String flags[];

    LayoutInflater inflter;

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

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

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

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

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

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

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

答:
1. You used String array on CustomAdapter 's constructor. But you passed ArrayList<String> from Activity class. So make these ArrayList on CustomAdapter-

```<code>    private ArrayList<String> NameArrayList;
    private ArrayList<String> IconArrayList;

    public CustomAdapter(getApplicationContext(), ArrayList<String> NameArrayList, ArrayList<String> IconArrayList) {
        this.NameArrayList= NameArrayList;
        this.IconArrayList= IconArrayList;
        inflter = (LayoutInflater.from(applicationContext));
    }
</code>```

2. You are fetching data from server by API call on MainThread. Try to keep this part on separate Thread for better performance (Some times you would not get any data from server for slow connection or large processing time). And Use Handler for communication  between these Threads Because you need to detect when finish api call and get data successfully. OR You can use any third party AndroidNetworking library for Thread safe network call.

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

Error:

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

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

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

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

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

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

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

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

MainActivity.java:

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

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

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

import java.io.InputStreamReader;

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

import java.util.ArrayList;

public class MainActivity extends Activity {

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

        sendGetRequest();

     }

public String sendGetRequest() {

         String NEW_ICON = "icon";

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

        try {

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

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

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

            OutputStream os = myURLConnection.getOutputStream();

            os.close();

            myURLConnection.connect();

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

            StringBuffer sb = new StringBuffer();

            String line;

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

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

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

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

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

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

                   String s =dataArray[0];

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

                    IconArrayList.add(s);

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

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

                }

            }// end of for loop

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

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

        } catch (Exception e) {

        }
        return null;

    }

BaseAdapter:

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

    String flags[];

    LayoutInflater inflter;

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

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

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

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

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

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

        return view;
    }
}

Body:
1. You used String array on CustomAdapter 's constructor. But you passed ArrayList<String> from Activity class. So make these ArrayList on CustomAdapter-

    private ArrayList<String> NameArrayList;
    private ArrayList<String> IconArrayList;

    public CustomAdapter(getApplicationContext(), ArrayList<String> NameArrayList, ArrayList<String> IconArrayList) {
        this.NameArrayList= NameArrayList;
        this.IconArrayList= IconArrayList;
        inflter = (LayoutInflater.from(applicationContext));
    }

2. You are fetching data from server by API call on MainThread. Try to keep this part on separate Thread for better performance (Some times you would not get any data from server for slow connection or large processing time). And Use Handler for communication  between these Threads Because you need to detect when finish api call and get data successfully. OR You can use any third party AndroidNetworking library for Thread safe network call.


问:
What is the best way of storing string data
I am keep hearing that many string containers so i am confused. What are those and which is the best one

string builder

arraylist

list<>

I know it may depend how big your string is and how much modification exists but generally which one of them a programmer prefer?

答:
The best way to store string data is in a string.

That's why it's there for.

If you want to manipulate a string that's a different story - since strings are immutable, any change you need to make will create a new string, meaning new memory allocation and sometimes extra time.

When concatenating strings, I think I remember the magic number is about 5 or 6 - so anything less than 6 parts is better to concatenate using the string concatenation operator (+), and anything more it's better to use a StringBuilder. Do not use string.Format to concatenate strings, it has a massive overhead and very poor performance compared to the other two options I've mentioned.


问:
How do I protect JavaScript files?
I know it's impossible to hide source code but, for example, if I have to link a JavaScript file from my CDN to a web page and I don't want the people to know the location and/or content of this script, is this possible?

For example, to link a script from a website, we use:

```<code><script type="text/javascript" src="http://somedomain.example/scriptxyz.js">
</script>
</code>```

Now, is possible to hide from the user where the script comes from, or hide the script content and still use it on a web page?

For example, by saving it in my private CDN that needs password to access files, would that work? If not, what would work to get what I want?

答:
Just off the top of my head, you could do something like this (if you can create server-side scripts, which it sounds like you can):

Instead of loading the script like normal, send an AJAX request to a PHP page (it could be anything; I just use it myself). Have the PHP locate the file (maybe on a non-public part of the server), open it with file_get_contents, and return (read: echo) the contents as a string.

When this string returns to the JavaScript, have it create a new script tag, populate its innerHTML with the code you just received, and attach the tag to the page. (You might have trouble with this; innerHTML may not be what you need, but you can experiment.)

If you do this a lot, you might even want to set up a PHP page that accepts a GET variable with the script's name, so that you can dynamically grab different scripts using the same PHP. (Maybe you could use POST instead, to make it just a little harder for other people to see what you're doing. I don't know.)

EDIT: I thought you were only trying to hide the location of the script. This obviously wouldn't help much if you're trying to hide the script itself.

ContentLicense: CC BY-SA 4.0

Title: How do I protect JavaScript files?

Body:
I know it's impossible to hide source code but, for example, if I have to link a JavaScript file from my CDN to a web page and I don't want the people to know the location and/or content of this script, is this possible?

For example, to link a script from a website, we use:

Now, is possible to hide from the user where the script comes from, or hide the script content and still use it on a web page?

For example, by saving it in my private CDN that needs password to access files, would that work? If not, what would work to get what I want?


问:
jQuery focus() not working
When the user clicks the search (magnifying glass) icon on the website, the search bar slides down into view. After the search bar slides down, I want the cursor to start blinking inside the search bar, so the user can start typing right away. But I can't get that cursor to move into the search bar. I've tried everything I can think of to get it to work!

The website (search icon is in the header)

The jQuery code:

```<code>jQuery(document).ready(function() {
    //show/hide search bar on icon click
    jQuery('#search-icon').click(function(e) {
        e.preventDefault();
        jQuery('#mobile-nav').css('display','none');
        jQuery('#search-box').slideToggle('fast',function() {
            if (jQuery('#search-box').css('display') == 'block') {
                window.setTimeout(function() {
                    jQuery('#search-box').focus().val(jQuery('#search-box').val());
                }, 0);
            }
        });
    });
});
</code>```

答:
$('#search-box').on('focus', function(event){
  var searchQuery = $('#search-box').val();
  console.log(searchQuery);
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='search-box' type='text'/></code>```

Title: jQuery focus() not working

Body:
When the user clicks the search (magnifying glass) icon on the website, the search bar slides down into view. After the search bar slides down, I want the cursor to start blinking inside the search bar, so the user can start typing right away. But I can't get that cursor to move into the search bar. I've tried everything I can think of to get it to work!

The website (search icon is in the header)

The jQuery code:

jQuery(document).ready(function() {
    //show/hide search bar on icon click
    jQuery('#search-icon').click(function(e) {
        e.preventDefault();
        jQuery('#mobile-nav').css('display','none');
        jQuery('#search-box').slideToggle('fast',function() {
            if (jQuery('#search-box').css('display') == 'block') {
                window.setTimeout(function() {
                    jQuery('#search-box').focus().val(jQuery('#search-box').val());
                }, 0);
            }
        });
    });
});

Body:
$('#search-box').on('focus', function(event){
  var searchQuery = $('#search-box').val();
  console.log(searchQuery);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='search-box' type='text'/>


问:
Publishing AWS Lambda .Net Core
I want to use AWS Lambda function. I created a sample AWS Lambda project (.net core 1) in Visual Studio 2017. I created a simple function and published it to AWS Lambda. It seems to be working when I press "Invoke" button. However, this function doesn't appear in AWS console. I wanted to set a timer (cron) when this function will be executed but I am not able to access it through AWS console.

```<code>public class Function
{
    public async Task<string> FunctionHandler()
    {
        HttpClient client = new HttpClient();

        var response = await client.PostAsync("http://cb910302.ngrok.io/dashboard/test", null);
        var responseString = await response.Content.ReadAsStringAsync();

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

I followed some tutorials (e.g. http://www.dotnetforall.com/publishing-running-net-core-aws-lambda/) but the lambda function just doesn't appear in my console after I publish it (even though the invoke button works and successfully executes the function). I googled that problem but it looks like no one had such problem which makes me feel that I am just missing a simple thing.

答: As I thought the problem was in a region. I was just looking for a lambda function in a wrong region. Therefore, I couldn't find it.</p>

Title: Publishing AWS Lambda .Net Core

Body:
I want to use AWS Lambda function. I created a sample AWS Lambda project (.net core 1) in Visual Studio 2017. I created a simple function and published it to AWS Lambda. It seems to be working when I press "Invoke" button. However, this function doesn't appear in AWS console. I wanted to set a timer (cron) when this function will be executed but I am not able to access it through AWS console.

public class Function
{
    public async Task<string> FunctionHandler()
    {
        HttpClient client = new HttpClient();

        var response = await client.PostAsync("http://cb910302.ngrok.io/dashboard/test", null);
        var responseString = await response.Content.ReadAsStringAsync();

        return responseString;
    }
}

I followed some tutorials (e.g. http://www.dotnetforall.com/publishing-running-net-core-aws-lambda/) but the lambda function just doesn't appear in my console after I publish it (even though the invoke button works and successfully executes the function). I googled that problem but it looks like no one had such problem which makes me feel that I am just missing a simple thing.


问:
Adding values in a for loop
I cant figure out how to add the values after it spits out the numbers.
it says:

Number: 5 // I typed 5

  1 2 3 4 5

  The sum is.

So i need to add those number 1 2 3 4 5 but cant figure out how.

```<code> import java.util.Scanner
 public class AddingValuesWithAForLoop
 {
      public static void main( String[] args )
      {
          Scanner keyboard = new Scanner(System.in);
          System.out.println( " \n" );

          System.out.println( "Number: " );
          int number = keyboard.nextInt();
          int sum = 0;

          for (int run=1; run<=number; run=run+1)
          {
              System.out.print( run + " " );
              sum = sum + 1 ;
          }

          System.out.println( "The sum is . " );
     }
 }
</code>```

答:
Hope this answer help you.

Assume that input value is 6, So internally add all the consecutive numbers until 6.  I.e Since the input value is 6, output should be like this
0+1+2+3+4+5=15

Refer to the below snippet

```<code>public void testAdding() {
    int inputVal = 6;
    String input = "";
    int adder = 0;
    for(int i=0; i < inputVal; i++) {
        input = String.valueOf(i);
        if(inputVal == (i+1)) {
            System.out.print(input);
        } else {
            System.out.print(input+"+");
        }
        adder =+ i + adder;
    }
    System.out.print("="+adder);
}
</code>```

Title: Adding values in a for loop

Body:
I cant figure out how to add the values after it spits out the numbers.
it says:

Number: 5 // I typed 5

  1 2 3 4 5

  The sum is.

So i need to add those number 1 2 3 4 5 but cant figure out how.

 import java.util.Scanner
 public class AddingValuesWithAForLoop
 {
      public static void main( String[] args )
      {
          Scanner keyboard = new Scanner(System.in);
          System.out.println( " \n" );

          System.out.println( "Number: " );
          int number = keyboard.nextInt();
          int sum = 0;

          for (int run=1; run<=number; run=run+1)
          {
              System.out.print( run + " " );
              sum = sum + 1 ;
          }

          System.out.println( "The sum is . " );
     }
 }

Body:
Hope this answer help you.

Assume that input value is 6, So internally add all the consecutive numbers until 6.  I.e Since the input value is 6, output should be like this
0+1+2+3+4+5=15

Refer to the below snippet

public void testAdding() {
    int inputVal = 6;
    String input = "";
    int adder = 0;
    for(int i=0; i < inputVal; i++) {
        input = String.valueOf(i);
        if(inputVal == (i+1)) {
            System.out.print(input);
        } else {
            System.out.print(input+"+");
        }
        adder =+ i + adder;
    }
    System.out.print("="+adder);
}


问:
Get names data in alphabetical order with section headings in php mysql
I have a table like below, was trying to get the data in JSON format 2D array but no success. I've tried different methods, but unable to achieve it. Please guide me to get the result.

***Forgot to upload the code, here is the updated question with my trial code.

```<code>id   company_name
-----------------
1    Alexa
2    Cisco
3    Blackberry
4    Amazon
5    Deka
6    Colgate
7    Dell
8    BBC
</code>```

I want to get that data like below in 2D JSON format array.

```<code>[
    {
      id: 1,
      heading: 'A',
      data: [
        {id: 4, text: 'Amazon'},
        {id: 1, text: 'Alexa'},
      ]
    },
    {
      id: 2,
      heading: 'B',
      data: [
        {id: 8, text: 'BBC'},
        {id: 3, text: 'Blackberry'},
      ]
    },
    {
        id: 3,
        heading: 'C',
        data: [
          {id: 2, text: 'Cisco'},
          {id: 6, text: 'Colgate'},
        ]
    },
    {
        id: 4,
        heading: 'D',
        data: [
          {id: 5, text: 'Deka'},
          {id: 7, text: 'Dell'},
        ]
    }
]
</code>```

I am trying with the below code, but not yet succeed. I am still trying, if anyone come up with a help, would be very much appreciated.

```<code>$query = mysqli_query($dblink,"SELECT id,company_name FROM company_names ORDER BY company_name");

$data = array();
while($row = mysqli_fetch_assoc($query)) {
  $id = $row["id"];
  $letter = strtolower(substr($row["company_name"],0,1));
  if(is_numeric($letter)) $letter = "0-9";
  if(!isset($data[$letter])){
  $data[$letter] = array();}
  $data[$letter][] = $row["company_name"];
}

echo json_encode($data);
</code>```

答:
Really, I added to your code only setting additional columns to the result array.

```<code>$data = array();
$id = 1;
while($row = mysqli_fetch_assoc($query)) {
  $letter = strtoupper($row["company_name"]{0});
  if(is_numeric($letter)) $letter = "0-9";
  if(!isset($data[$letter])) {
     $data[$letter]['heading'] = $letter;
     $data[$letter]['id'] = $id++;
  }
  $data[$letter]['data'][] = $row;
}

echo json_encode($data);
</code>```

demo

Body:
I have a table like below, was trying to get the data in JSON format 2D array but no success. I've tried different methods, but unable to achieve it. Please guide me to get the result.

***Forgot to upload the code, here is the updated question with my trial code.

id   company_name
-----------------
1    Alexa
2    Cisco
3    Blackberry
4    Amazon
5    Deka
6    Colgate
7    Dell
8    BBC

I want to get that data like below in 2D JSON format array.

[
    {
      id: 1,
      heading: 'A',
      data: [
        {id: 4, text: 'Amazon'},
        {id: 1, text: 'Alexa'},
      ]
    },
    {
      id: 2,
      heading: 'B',
      data: [
        {id: 8, text: 'BBC'},
        {id: 3, text: 'Blackberry'},
      ]
    },
    {
        id: 3,
        heading: 'C',
        data: [
          {id: 2, text: 'Cisco'},
          {id: 6, text: 'Colgate'},
        ]
    },
    {
        id: 4,
        heading: 'D',
        data: [
          {id: 5, text: 'Deka'},
          {id: 7, text: 'Dell'},
        ]
    }
]

I am trying with the below code, but not yet succeed. I am still trying, if anyone come up with a help, would be very much appreciated.

$query = mysqli_query($dblink,"SELECT id,company_name FROM company_names ORDER BY company_name");

$data = array();
while($row = mysqli_fetch_assoc($query)) {
  $id = $row["id"];
  $letter = strtolower(substr($row["company_name"],0,1));
  if(is_numeric($letter)) $letter = "0-9";
  if(!isset($data[$letter])){
  $data[$letter] = array();}
  $data[$letter][] = $row["company_name"];
}

echo json_encode($data);

Body:
Really, I added to your code only setting additional columns to the result array.

$data = array();
$id = 1;
while($row = mysqli_fetch_assoc($query)) {
  $letter = strtoupper($row["company_name"]{0});
  if(is_numeric($letter)) $letter = "0-9";
  if(!isset($data[$letter])) {
     $data[$letter]['heading'] = $letter;
     $data[$letter]['id'] = $id++;
  }
  $data[$letter]['data'][] = $row;
}

echo json_encode($data);

demo


问:
Android Studio says "cannot resolve method" but method exists and compiles
I am trying to debug the behaviour of Android Studio regarding syntax highlighting and definition following for files in the java SDK folder. The project builds fine, but Android Studio itself will not behave consistent with this in the editor.

I have read the responses in the following link in detail and it does not fix the problem:
Android Studio says "cannot resolve symbol" but project compiles

I have tried all those solutions, including "Invalidate and Restart", Clean, Rebuild, checking the sdk directory is correct, checking the all the dependencies are present, resyncing the gradle, changing the compileSdkVersion to the minSdkVersion and it still refuses to follow expected behaviour.

Android studio is highlighting some methods and symbols in red, and will not follow them when I hit CTRL+B on them (go to definition). However when I simply open the file, the methods and symbols are in there fine.

For example, for sdk\sources\android-14\..., in a RingtonePreference class, in ...android\preference\RingtonePreference.java, there is a line:

```<code>PreferenceFragment owningFragment = getPreferenceManager().getFragment();
</code>```

The method getFragment() is highlighted red for "cannot resolve method".

I then hit CTRL+B on getPreferenceManager(), which jumps to:

```<code>public PreferenceManager getPreferenceManager() {
    return mPreferenceManager;
}
</code>```

I then hit CTRL+B on PreferenceManager, which jumps to the file ...android\preference\PreferenceManager.java. In that file there is the following:

```<code>PreferenceFragment getFragment() {
    return mFragment;
}
</code>```

It is beyond me what on earth else Android Studio needs to function as would be expected. What am I doing wrong here?

For reference, this is how my project is using the RingtoneManager, but there is no "cannot resolve" Android Studio red highlighting in this:

```<code>import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.preference.RingtonePreference;
import android.util.AttributeSet;

public class ExtRingtonePreference extends RingtonePreference {
private String mInitialRingtone;

public ExtRingtonePreference(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

public ExtRingtonePreference(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public ExtRingtonePreference(Context context) {
    super(context);
}

@Override
protected Uri onRestoreRingtone() {
    if(mInitialRingtone == null) {
        return null;
    } else {
        return Uri.parse(mInitialRingtone);
    }
}

public void setInitialRingtone(String initialRingtone) {
    this.mInitialRingtone = initialRingtone;
}

}
</code>```

答: Even i had the same problem after changing the git branch, the way i fixed it is by changing in app/build.gradle (e.g. add blank line) and IDE ask to Sync** the project and after syncing it got fixed.

Body:
I am trying to debug the behaviour of Android Studio regarding syntax highlighting and definition following for files in the java SDK folder. The project builds fine, but Android Studio itself will not behave consistent with this in the editor.

I have read the responses in the following link in detail and it does not fix the problem:
Android Studio says "cannot resolve symbol" but project compiles

I have tried all those solutions, including "Invalidate and Restart", Clean, Rebuild, checking the sdk directory is correct, checking the all the dependencies are present, resyncing the gradle, changing the compileSdkVersion to the minSdkVersion and it still refuses to follow expected behaviour.

Android studio is highlighting some methods and symbols in red, and will not follow them when I hit CTRL+B on them (go to definition). However when I simply open the file, the methods and symbols are in there fine.

For example, for sdk\sources\android-14\..., in a RingtonePreference class, in ...android\preference\RingtonePreference.java, there is a line:

PreferenceFragment owningFragment = getPreferenceManager().getFragment();

The method getFragment() is highlighted red for "cannot resolve method".

I then hit CTRL+B on getPreferenceManager(), which jumps to:

public PreferenceManager getPreferenceManager() {
    return mPreferenceManager;
}

I then hit CTRL+B on PreferenceManager, which jumps to the file ...android\preference\PreferenceManager.java. In that file there is the following:

PreferenceFragment getFragment() {
    return mFragment;
}

It is beyond me what on earth else Android Studio needs to function as would be expected. What am I doing wrong here?

For reference, this is how my project is using the RingtoneManager, but there is no "cannot resolve" Android Studio red highlighting in this:

import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.preference.RingtonePreference;
import android.util.AttributeSet;

public class ExtRingtonePreference extends RingtonePreference {
private String mInitialRingtone;

public ExtRingtonePreference(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

public ExtRingtonePreference(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public ExtRingtonePreference(Context context) {
    super(context);
}

@Override
protected Uri onRestoreRingtone() {
    if(mInitialRingtone == null) {
        return null;
    } else {
        return Uri.parse(mInitialRingtone);
    }
}

public void setInitialRingtone(String initialRingtone) {
    this.mInitialRingtone = initialRingtone;
}

}


问:
Return value from overloaded operator Segmentation Fail
Got in header

```<code>DuzaLiczba operator>(const DuzaLiczba& right) const;
string& getData();
virtual ~DuzaLiczba();
private:
string& data;
</code>```

In my class overloaded operators return string in "\002\994\23923\"

```<code>return DuzaLiczba(wynik);
</code>```

In main

```<code>        cout << dl3.getData();
        cout.flush();
</code>```

cout.flush throws Segmentation fail.

Return in class is in ascii?
And heres problem. Got any advice?

答:
```<code>class DuzaLiczba {
public:
    DuzaLiczba(string& input);
    DuzaLiczba(const DuzaLiczba& orig);
    bool operator==(const DuzaLiczba &other) const;
    bool operator!=(const DuzaLiczba &other) const;
    DuzaLiczba operator+(const DuzaLiczba& right) const;
    DuzaLiczba operator-(const DuzaLiczba& right) const;
     DuzaLiczba operator<(const DuzaLiczba& right) const;
    DuzaLiczba operator>(const DuzaLiczba& right) const;
    string& getData();
    virtual ~DuzaLiczba();
private:
    string& data;

};
</code>```

And == operator

```<code>bool DuzaLiczba::operator==(const DuzaLiczba &other) const {
string liczba1 = this->data;
string liczba2 = right.data;
char index1 = liczba1.length();
char index2 = liczba2.length();
short k;
short o;
short f = 0; //przeniesienie
string wynik;
int sizefi = 0;
char temp;
int i = 0;
//"gupie" to C# RUUUULEEEZ
// http://www.youtube.com/watch?v=bXoc9hOIj3M hahahaa "D

if (liczba1.length() == liczba2.length()) { //najpierw dlugosc szybciej niz pokolei
    for (i = 0; i < index1; i++) {
        if (liczba1[i] == liczba2[i]) {   //sprawdza kazdy element jesli sie rozni to false
            wynik =
                    "TRUE";

        } else {
            wynik = "FALSE";
        }

    }

} else {
    wynik = "FALSE";
}

return DuzaLiczba(wynik);

 }
</code>```

And retturn data

```<code>string& DuzaLiczba::getData() {
 return data; //zwoloniony string
     }
</code>```

All i want to return a string.
dl1 = "123089127312890372109371203971293012903"
dl2 = "12837129037812903812903"
eg. DuzaLiczba dl3(dl1+dl2)
and cout it.

Code inside class do math great.

Or create overloader operator "<<".

Body:
Got in header

DuzaLiczba operator>(const DuzaLiczba& right) const;
string& getData();
virtual ~DuzaLiczba();
private:
string& data;

In my class overloaded operators return string in "\002\994\23923\"

return DuzaLiczba(wynik);

In main

        cout << dl3.getData();
        cout.flush();

cout.flush throws Segmentation fail.

Return in class is in ascii?
And heres problem. Got any advice?

Body:
class DuzaLiczba {
public:
    DuzaLiczba(string& input);
    DuzaLiczba(const DuzaLiczba& orig);
    bool operator==(const DuzaLiczba &other) const;
    bool operator!=(const DuzaLiczba &other) const;
    DuzaLiczba operator+(const DuzaLiczba& right) const;
    DuzaLiczba operator-(const DuzaLiczba& right) const;
     DuzaLiczba operator<(const DuzaLiczba& right) const;
    DuzaLiczba operator>(const DuzaLiczba& right) const;
    string& getData();
    virtual ~DuzaLiczba();
private:
    string& data;

};

And == operator

bool DuzaLiczba::operator==(const DuzaLiczba &other) const {
string liczba1 = this->data;
string liczba2 = right.data;
char index1 = liczba1.length();
char index2 = liczba2.length();
short k;
short o;
short f = 0; //przeniesienie
string wynik;
int sizefi = 0;
char temp;
int i = 0;
//"gupie" to C# RUUUULEEEZ
// http://www.youtube.com/watch?v=bXoc9hOIj3M hahahaa "D

if (liczba1.length() == liczba2.length()) { //najpierw dlugosc szybciej niz pokolei
    for (i = 0; i < index1; i++) {
        if (liczba1[i] == liczba2[i]) {   //sprawdza kazdy element jesli sie rozni to false
            wynik =
                    "TRUE";

        } else {
            wynik = "FALSE";
        }

    }

} else {
    wynik = "FALSE";
}

return DuzaLiczba(wynik);

 }

And retturn data

string& DuzaLiczba::getData() {
 return data; //zwoloniony string
     }

All i want to return a string.
dl1 = "123089127312890372109371203971293012903"
dl2 = "12837129037812903812903"
eg. DuzaLiczba dl3(dl1+dl2)
and cout it.

Code inside class do math great.

Or create overloader operator "<<".


问:
TinyMCE - Chrome browser - Can't paste images in Chrome as in FF
I'm using the TinyMCE WYSIWYG editor control and while it is possible to copy and paste image fractions in FireFox, it is impossible in Chrome.

I've tried upgrading to TinyMCE ver. 4.0.16 (previously had ver. 3.5.8) with still no possible way to make it work.

Has anyone been able to do this?

Example to how this looks in FireFox:

Thanks in advance!

答:
I've just got this working.

Remove "Paste" from the plugins list and set "paste_data_images: true"

Works a treat!


问:
How to write a custom Leanbacks VerticalGridView in Android TV?
I want to implement a Row from the Details screen of the Leanback library into a customized screen. The row will be the one below. I have already implemented the HorizontalGridView and have managed to get the items to be shown.

My layout:

```<code><android.support.v17.leanback.widget.HorizontalGridView
android:id="@+id/detail_related"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</code>```

My Java:

```<code>RecyclerView.Adapter mAdapter = new SimilarAssetsAdapter();
mBinding.detailRelated.setAdapter(mAdapter);
</code>```

The problem I am encountering is that I cannot focus on any of the items but the focus is on the whole HorizontalGridView. How do I solve this?

答:
If your view is a custom one, make sure you add the following to your customized view to get focus:</p>

```<code>setFocusable(true);
setFocusableInTouchMode(true);
</code>```

Body:
I want to implement a Row from the Details screen of the Leanback library into a customized screen. The row will be the one below. I have already implemented the HorizontalGridView and have managed to get the items to be shown.

My layout:

<android.support.v17.leanback.widget.HorizontalGridView
android:id="@+id/detail_related"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

My Java:

RecyclerView.Adapter mAdapter = new SimilarAssetsAdapter();
mBinding.detailRelated.setAdapter(mAdapter);

The problem I am encountering is that I cannot focus on any of the items but the focus is on the whole HorizontalGridView. How do I solve this?

Body:
If your view is a custom one, make sure you add the following to your customized view to get focus:

setFocusable(true);
setFocusableInTouchMode(true);


问:
How can I animate the road in iPhone Xcode?
I am going to animate the road, simply calling 1 image again and again from top to bottom.  Can anyone suggest how this is possible?</p>

答:
You'll want to look at a UIScrollView. Put a UIImageView in it, then use the following code:

```<code>
-(void)scroll{
    CGPoint currentPoint = scrollView.contentOffset;
    CGPoint scrollPoint = CGPointMake(currentPoint.x, currentPoint.y + 1);
    [scrollView setContentOffset:scrollPoint animated:NO];

    if(scrollPoint.y == scrollView.contentSize.height+5)//If we've reached the bottom, reset slightly past top, to give ticker look
    {
        [scrollView setContentOffset:CGPointMake (0,-125)];
    }
}
</code>```

Run that code with a looping NSTimer and you'll be set :)

Body:
You'll want to look at a UIScrollView. Put a UIImageView in it, then use the following code:

-(void)scroll{
    CGPoint currentPoint = scrollView.contentOffset;
    CGPoint scrollPoint = CGPointMake(currentPoint.x, currentPoint.y + 1);
    [scrollView setContentOffset:scrollPoint animated:NO];

    if(scrollPoint.y == scrollView.contentSize.height+5)//If we've reached the bottom, reset slightly past top, to give ticker look
    {
        [scrollView setContentOffset:CGPointMake (0,-125)];
    }
}

Run that code with a looping NSTimer and you'll be set :)


问:
Fix “compile error: next without for” error in VBA?
I cant seem to figure out this. I would like to search my worksheets to see if there is a "=REF!" and if there is a error to not run my code. The problem with it is that when I run it the error in the code is revolved around the next part </p>

```<code>Sub logs()

Dim numberofsheets As Integer

For numberofsheets = 1 To 5

Set checkRange = Sheets("Final Four").Range("A1:Z100")
 If IsError(CheckCell) And _
       CVErr(CheckCell) = CVErr(2023) Then
Exit Sub
End If

Next

Set checkRange = Sheets("Top Left").Range("A1:Z100")
 If IsError(CheckCell) And _
       CVErr(CheckCell) = CVErr(2023) Then
Exit Sub
End If

Next

Set checkRange = Sheets("Bottom Left").Range("A1:Z100")
 If IsError(CheckCell) And _
        CVErr(CheckCell) = CVErr(2023) Then
Exit Sub
End If

Next

Set checkRange = Sheets("Top Right").Range("A1:Z100")
 If IsError(CheckCell) And _
       CVErr(CheckCell) = CVErr(2023) Then
Exit Sub
End If

Next

Set checkRange = Sheets("Bottom Right").Range("A1:Z100")
 If IsError(CheckCell) And _
       CVErr(CheckCell) = CVErr(2023) Then
Exit Sub
End If

ActiveSheet.EnableCalculation = True

lst = Sheets("data").UsedRange.Rows.Count
x = lst + 1

        ' Display a message when one of the designated cells has been
        ' changed.
        ' Place your code here.
        Sheets("data").Range("A" & x) = ActiveSheet.Range("I3")
        Sheets("data").Range("B" & x) = ActiveSheet.Range("I4")

End Sub
</code>```

<p>Not sure how to do this. I'm very new at it. </p>

答:
I think you are looking for something like the For loop below to implement in your code:

```<code>Sub logs()

Dim Sht As Worksheet
Dim checkRange As Range, CheckCell As Range

For Each Sht In ThisWorkbook.Sheets ' loop through your worksheets
    With Sht
        Select Case .Name  ' check for the sheet.Name
            Case "Final Four", "Top Left", "Bottom Left", "Top Right", "Bottom Right"
                Set checkRange = .Range("A1:Z100") ' set the range for the current sheet

                For Each CheckCell In checkRange
                    If IsError(CheckCell) Then
                        If CheckCell.Value = CVErr(2023) Then Exit Sub

                        ' you can use the following syntax as well
                        If CheckCell.Value = CVErr(xlErrRef) Then Exit Sub
                    End If
                Next CheckCell
                Set checkRange = Nothing
            Case Else
                ' do nothing

        End Select
    End With
Next Sht

' rest of your code

End Sub
</code>```

Body:
I cant seem to figure out this. I would like to search my worksheets to see if there is a "=REF!" and if there is a error to not run my code. The problem with it is that when I run it the error in the code is revolved around the next part

Sub logs()

Dim numberofsheets As Integer

For numberofsheets = 1 To 5

Set checkRange = Sheets("Final Four").Range("A1:Z100")
 If IsError(CheckCell) And _
       CVErr(CheckCell) = CVErr(2023) Then
Exit Sub
End If

Next

Set checkRange = Sheets("Top Left").Range("A1:Z100")
 If IsError(CheckCell) And _
       CVErr(CheckCell) = CVErr(2023) Then
Exit Sub
End If

Next

Set checkRange = Sheets("Bottom Left").Range("A1:Z100")
 If IsError(CheckCell) And _
        CVErr(CheckCell) = CVErr(2023) Then
Exit Sub
End If

Next

Set checkRange = Sheets("Top Right").Range("A1:Z100")
 If IsError(CheckCell) And _
       CVErr(CheckCell) = CVErr(2023) Then
Exit Sub
End If

Next

Set checkRange = Sheets("Bottom Right").Range("A1:Z100")
 If IsError(CheckCell) And _
       CVErr(CheckCell) = CVErr(2023) Then
Exit Sub
End If

ActiveSheet.EnableCalculation = True

lst = Sheets("data").UsedRange.Rows.Count
x = lst + 1

        ' Display a message when one of the designated cells has been
        ' changed.
        ' Place your code here.
        Sheets("data").Range("A" & x) = ActiveSheet.Range("I3")
        Sheets("data").Range("B" & x) = ActiveSheet.Range("I4")

End Sub

Not sure how to do this. I'm very new at it.

Body:
I think you are looking for something like the For loop below to implement in your code:

Sub logs()

Dim Sht As Worksheet
Dim checkRange As Range, CheckCell As Range

For Each Sht In ThisWorkbook.Sheets ' loop through your worksheets
    With Sht
        Select Case .Name  ' check for the sheet.Name
            Case "Final Four", "Top Left", "Bottom Left", "Top Right", "Bottom Right"
                Set checkRange = .Range("A1:Z100") ' set the range for the current sheet

                For Each CheckCell In checkRange
                    If IsError(CheckCell) Then
                        If CheckCell.Value = CVErr(2023) Then Exit Sub

                        ' you can use the following syntax as well
                        If CheckCell.Value = CVErr(xlErrRef) Then Exit Sub
                    End If
                Next CheckCell
                Set checkRange = Nothing
            Case Else
                ' do nothing

        End Select
    End With
Next Sht

' rest of your code

End Sub


问:
@expo/vector-icons not loaded when running from subfolder
I'm trying to use create-react-native-app with expo in a monorepo setup. When I start the app from a subfolder app/ and import @expo/vector-icons I get an error that the font family is missing.

```<code>"fontFamily" 'material' is not a system font and has not been loaded
through Expo.Font.loadAsync.
</code>```

If I start the app in the main src/ folder the icons load fine.

I've configured my rn-cli.config.js so that the app compiles and runs fine for other dependencies. My project is setup like a monorepo so that I can have multiple native apps in the repo.

```<code>src/
  MainApp.js
  package.json
  app/App.js
  app/app.json
  app/package.json
  app/rn-cli.config.js
  ...
</code>```

I've tried a couple things to no avail:

Install @expo/vector-icons in the subfolder package.json

Setting "assetExts": ["ttf"] in the app.json file.

My code (mostly from a fresh creat-react-native-app):

app/App.js

```<code>export { default } from "../MainApp";
</code>```

app/app.json

```<code>{
  "expo": {
    "sdkVersion": "22.0.0",
    "react": "16.0.0-beta.5"
  }
}
</code>```

app/package.json

```<code>{
  "private": true,
  "main": "./node_modules/react-native-scripts/build/bin/crna-entry.js",
  "scripts": {
    "native": "react-native-scripts start"
  },
  "dependencies": {
    "@expo/vector-icons": "^6.2.1",
    "expo": "^22.0.0",
    "react-native": "^0.49.0",
    "react-native-scripts": "1.7.0"
  }
}
</code>```

app/rn-cli.config.js

```<code>const blacklist = require("metro-bundler/src/blacklist");
const path = require("path");

const roots = [process.cwd(), path.resolve(__dirname, "..")];

const config = {
  getProjectRoots: () => roots,

  /**
   * Specify where to look for assets that are referenced using
   * `image!<image_name>`. Asset directories for images referenced using
   * `./<image.extension>` don't require any entry in here.
   */
  getAssetRoots: () => roots,

  /**
   * Returns a regular expression for modules that should be ignored by the
   * packager on a given platform.
   */
  getBlacklistRE: () =>
    blacklist([
      // Ignore the local react-native so that we avoid duplicate modules
      /\/app\/node_modules\/react-native\/.*/
    ])
};

module.exports = config;
</code>```

package.json

```<code>{
  "name": "react-native-app",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "react-native-scripts": "1.7.0"
  },
  "scripts": {
    "native": "cd app && yarn native"
  },
  "dependencies": {
    "@expo/vector-icons": "^6.2.1",
    "expo": "^22.0.0",
    "react": "16.0.0-beta.5",
    "react-native": "^0.49.0"
  }
}
</code>```

MainApp.js

```<code>import React from "react";
import { StyleSheet, Text, View } from "react-native";
import MaterialIcons from "react-native-vector-icons/MaterialIcons";

export default class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text>Open up App.js to start working on your app!</Text>
        <Text>Changes you make will automatically reload.</Text>
        <Text>Shake your phone to open the developer menu.</Text>
        <MaterialIcons name="search" color="black" size={32} />
        <MaterialIcons name="location-searching" color="black" size={32} />
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center"
  }
});
</code>```

答: Seems like the problem was that I had two different expo modules. Getting rid of the one in the subfolder made it work.</p>

Body:
I'm trying to use create-react-native-app with expo in a monorepo setup. When I start the app from a subfolder app/ and import @expo/vector-icons I get an error that the font family is missing.

"fontFamily" 'material' is not a system font and has not been loaded
through Expo.Font.loadAsync.

If I start the app in the main src/ folder the icons load fine.

I've configured my rn-cli.config.js so that the app compiles and runs fine for other dependencies. My project is setup like a monorepo so that I can have multiple native apps in the repo.

src/
  MainApp.js
  package.json
  app/App.js
  app/app.json
  app/package.json
  app/rn-cli.config.js
  ...

I've tried a couple things to no avail:

Install @expo/vector-icons in the subfolder package.json

Setting "assetExts": ["ttf"] in the app.json file.

My code (mostly from a fresh creat-react-native-app):

app/App.js

export { default } from "../MainApp";

app/app.json

{
  "expo": {
    "sdkVersion": "22.0.0",
    "react": "16.0.0-beta.5"
  }
}

app/package.json

{
  "private": true,
  "main": "./node_modules/react-native-scripts/build/bin/crna-entry.js",
  "scripts": {
    "native": "react-native-scripts start"
  },
  "dependencies": {
    "@expo/vector-icons": "^6.2.1",
    "expo": "^22.0.0",
    "react-native": "^0.49.0",
    "react-native-scripts": "1.7.0"
  }
}

app/rn-cli.config.js

const blacklist = require("metro-bundler/src/blacklist");
const path = require("path");

const roots = [process.cwd(), path.resolve(__dirname, "..")];

const config = {
  getProjectRoots: () => roots,

  /**
   * Specify where to look for assets that are referenced using
   * `image!<image_name>`. Asset directories for images referenced using
   * `./<image.extension>` don't require any entry in here.
   */
  getAssetRoots: () => roots,

  /**
   * Returns a regular expression for modules that should be ignored by the
   * packager on a given platform.
   */
  getBlacklistRE: () =>
    blacklist([
      // Ignore the local react-native so that we avoid duplicate modules
      /\/app\/node_modules\/react-native\/.*/
    ])
};

module.exports = config;

package.json

{
  "name": "react-native-app",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "react-native-scripts": "1.7.0"
  },
  "scripts": {
    "native": "cd app && yarn native"
  },
  "dependencies": {
    "@expo/vector-icons": "^6.2.1",
    "expo": "^22.0.0",
    "react": "16.0.0-beta.5",
    "react-native": "^0.49.0"
  }
}

MainApp.js

import React from "react";
import { StyleSheet, Text, View } from "react-native";
import MaterialIcons from "react-native-vector-icons/MaterialIcons";

export default class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text>Open up App.js to start working on your app!</Text>
        <Text>Changes you make will automatically reload.</Text>
        <Text>Shake your phone to open the developer menu.</Text>
        <MaterialIcons name="search" color="black" size={32} />
        <MaterialIcons name="location-searching" color="black" size={32} />
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center"
  }
});


问:
Finding name of executable sending packet in a netfilter hook
I'm writing a kernel module that uses a netfilter hook to filter TCP packets and need to find out the path to the executable that is sending the packets. So far I have used the following approach but it prints names that are seemingly unrelated to the executables used (/usr/lib/firefox/firefox, usr/bin/telnet.netkit and /usr/bin/wget).

```<code>pid_t pid = current->pid;
struct path path;
char buff[BUFF_LEN];
snprintf (buff, BUFF_LEN, "/proc/%d/exe", pid);
if(!kern_path(buff, LOOKUP_FOLLOW, &path)) {
    struct dentry* procEntry = path.dentry;
    printk("Process: %s\n", procEntry->d_name.name);
    printk("Parent: %s\n", procEntry->d_parent->d_name.name);
}
</code>```

Kernel log output:

答:
This reads like a poor quality college assignment and I have a distinct impression something of the sort already appeared here.

Your code most likely executes from an interrupt context, i.e. a random thread got interrupted to do packet processing and 'current' is a pointer to said random thread. This should be easy to verify e.g. by obtaining a backtrace -- doable with WARN_ONCE and the like.

Looking for executable name of current by going through procfs is weirdly bad. procfs has to do more work and ends up accessing what's effectively current anyway. To make matters worse, you fail to put the found path thus you leak resources. If this code indeed executes from an interrupt handler, the result is not only nonsensical but can't be safely obtained with this method due to sleep potential.

Even if you were to obtain the "right" executable name, the entire assignment is crap. There are many ways in which one process can alter execution of another. thus effectively bypassing whatever filter you have in place. Interestingly there is a way to just change your process name to something else without execing anything, once more invalidating the concept.

The best you can do is filter by credentials, but they are not process-specific. In principle you can add selinux labels to files and filter by that, but once more that's weak.

In short, the assignment is bullshit.

Body:
I'm writing a kernel module that uses a netfilter hook to filter TCP packets and need to find out the path to the executable that is sending the packets. So far I have used the following approach but it prints names that are seemingly unrelated to the executables used (/usr/lib/firefox/firefox, usr/bin/telnet.netkit and /usr/bin/wget).

pid_t pid = current->pid;
struct path path;
char buff[BUFF_LEN];
snprintf (buff, BUFF_LEN, "/proc/%d/exe", pid);
if(!kern_path(buff, LOOKUP_FOLLOW, &path)) {
    struct dentry* procEntry = path.dentry;
    printk("Process: %s\n", procEntry->d_name.name);
    printk("Parent: %s\n", procEntry->d_parent->d_name.name);
}

Kernel log output:


问:
Direct Arithmetic Operations on Small-sized Numbers in RISC Architectures
Are there any RISC architectures which allow arithmetic operations to be applied individually to bytes, half-words and other data cells, whose size is less than the size of the CPU general purpose registers?

In Intel x86 (IA-32) and x86-64 (known as EM64T or AMD64) processors not only the whole register is available, but its smaller parts are operable as well. Intel ISA allows to perform all the arithmetic operations on the whole register, it's half, quarter and a byte (to be more precise, two bytes in the register are available, for example AL and AH in RAX). After the operation is performed, we can make an overflow check, and if an overflow has occurred during the previous operation, it can be easily handled. No matter whether we've operated on the whole word (32-bit wide for IA-32 and 64-bit wide for EM64T) or the arithmetic instruction was executed over the data of smaller size (half-word, quarter-word or a byte), if the result exceeds the size of the chosen data cell, the corresponding flag (OF or CF) will be set to 1. So in Intel architecture there is no need to emulate processing such errors, which occur in operations with small-sized data, with a chain of instructions analyzing higher bits of the result.

The question is are there any RISC architectures in which direct arithmetic operations on small data are possible, these operations are implemented by means of the processor hardware (no software emulation is required to perform them), and overflows, carries and borrows occurring in such operations with bytes, half-words etc. are traced by the processor equipment, they should not be checked in a software manner. Or perhaps this approach contradicts the whole RISC philosophy and no RISC processor neither in the present nor in the past has ever implemented it?

答:
Are there any ...

Do you only speak about commercial CPUs on the market or also about student projects on university etc.?

I myself designed a RISC CPU for education purposes which can do 8-, 16- and 32-bit operations. So this shows that it is at least possible to do this.

64-bit embedded PowerPC architectures also have something similar: They can do 32-bit operations in the low 32 bits of the 64-bit registers.

This architecture does not have 8- and 16-bit operations. However CISC CPUs also do not support all widths supported by other computers with smaller widths:

x86 neither supports 4-bit operations nor 12-bit operations although there are CPUs (Intel 4004 and DEC PDP-8) using these widths.

After the operation is performed, we can make an overflow check, and if an overflow has occurred during the previous operation, it can be easily handled.

The 64-bit SPARC architecture is interesting here:

To enable 32-bit software to be executed on 64-bit CPUs there are some special features.

One of them is that all flags (carry, zero, ...) are duplicate: Once for the low 32 bits and once for the whole 64 bits.

So after doing an "ADD" operation (which can only be done 64-bit) you can either check for the 64-bit flags or the 32-bit flags.


问:
UISlider with ProgressView combined
Is there an apple-house-made way to get a UISlider with a ProgressView. This is used by many streaming applications e.g. native quicktimeplayer or youtube.
(Just to be sure: i'm only in the visualization interested)

cheers Simon

答:
Here is a solution in Objective C. https://github.com/abhimuralidharan/BufferSlider

The idea is to create a UIProgressview as a property in the UISlider subclass and add the required constraints programatically.

```<code>#import <UIKit/UIKit.h> //.h file

@interface BufferSlider : UISlider
@property(strong,nonatomic) UIProgressView *bufferProgress;
@end

#import "BufferSlider.h" //.m file

@implementation BufferSlider

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}
-(void)setup {
    self.bufferProgress = [[UIProgressView alloc] initWithFrame:self.bounds];
    self.minimumTrackTintColor = [UIColor redColor];
    self.maximumTrackTintColor = [UIColor clearColor];
    self.value = 0.2;
    self.bufferProgress.backgroundColor = [UIColor clearColor];
    self.bufferProgress.userInteractionEnabled = NO;
    self.bufferProgress.progress = 0.7;
    self.bufferProgress.progressTintColor = [[UIColor blueColor] colorWithAlphaComponent:0.5];
    self.bufferProgress.trackTintColor = [[UIColor lightGrayColor] colorWithAlphaComponent:2];
    [self addSubview:self.bufferProgress];
    [self setThumbImage:[UIImage imageNamed:@"redThumb"] forState:UIControlStateNormal];
    self.bufferProgress.translatesAutoresizingMaskIntoConstraints = NO;

    NSLayoutConstraint *left = [NSLayoutConstraint constraintWithItem:self.bufferProgress attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeft multiplier:1 constant:0];
    NSLayoutConstraint *centerY = [NSLayoutConstraint constraintWithItem:self.bufferProgress attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1 constant:0.75];  // edit the constant value based on the thumb image
    NSLayoutConstraint *right = [NSLayoutConstraint constraintWithItem:self.bufferProgress attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTrailing multiplier:1 constant:0];

    [self addConstraints:@[left,right,centerY]];
    [self sendSubviewToBack:self.bufferProgress];
}
- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        [self setup];
    }
    return self;
}
@end
</code>```

Title: UISlider with ProgressView combined

Body:
Here is a solution in Objective C. https://github.com/abhimuralidharan/BufferSlider

The idea is to create a UIProgressview as a property in the UISlider subclass and add the required constraints programatically.

#import <UIKit/UIKit.h> //.h file

@interface BufferSlider : UISlider
@property(strong,nonatomic) UIProgressView *bufferProgress;
@end

#import "BufferSlider.h" //.m file

@implementation BufferSlider

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}
-(void)setup {
    self.bufferProgress = [[UIProgressView alloc] initWithFrame:self.bounds];
    self.minimumTrackTintColor = [UIColor redColor];
    self.maximumTrackTintColor = [UIColor clearColor];
    self.value = 0.2;
    self.bufferProgress.backgroundColor = [UIColor clearColor];
    self.bufferProgress.userInteractionEnabled = NO;
    self.bufferProgress.progress = 0.7;
    self.bufferProgress.progressTintColor = [[UIColor blueColor] colorWithAlphaComponent:0.5];
    self.bufferProgress.trackTintColor = [[UIColor lightGrayColor] colorWithAlphaComponent:2];
    [self addSubview:self.bufferProgress];
    [self setThumbImage:[UIImage imageNamed:@"redThumb"] forState:UIControlStateNormal];
    self.bufferProgress.translatesAutoresizingMaskIntoConstraints = NO;

    NSLayoutConstraint *left = [NSLayoutConstraint constraintWithItem:self.bufferProgress attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeft multiplier:1 constant:0];
    NSLayoutConstraint *centerY = [NSLayoutConstraint constraintWithItem:self.bufferProgress attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1 constant:0.75];  // edit the constant value based on the thumb image
    NSLayoutConstraint *right = [NSLayoutConstraint constraintWithItem:self.bufferProgress attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTrailing multiplier:1 constant:0];

    [self addConstraints:@[left,right,centerY]];
    [self sendSubviewToBack:self.bufferProgress];
}
- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        [self setup];
    }
    return self;
}
@end


问:
Break lines in g.drawString in Java SE
This is exactly what I'm trying to do:

```<code>Graphics2D g2 = (Graphics2D) g;
g2.setFont(new Font("Serif", Font.PLAIN, 5));
g2.setPaint(Color.black);
g2.drawString("Line 1\nLine 2", x, y);
</code>```

That line prints like this:

```<code>Line1Line2
</code>```

I want it like this:

```<code>Line1
Line2
</code>```

How can I do this in drawString ?

As well as how can I do a tab space for a line??

答:
Here's a snippet I used to draw text in a JPanel with tab expansion and multiple lines:

```<code>import javax.swing.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;

public class Scratch {
    public static void main(String argv[]) {
        JFrame frame = new JFrame("FrameDemo");

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel() {
            @Override
            public void paint(Graphics graphics) {
                graphics.drawRect(100, 100, 1, 1);
                String message =
                        "abc\tdef\n" +
                        "abcx\tdef\tghi\n" +
                        "xxxxxxxxdef\n" +
                        "xxxxxxxxxxxxxxxxghi\n";
                int x = 100;
                int y = 100;
                FontMetrics fontMetrics = graphics.getFontMetrics();
                Rectangle2D tabBounds = fontMetrics.getStringBounds(
                        "xxxxxxxx",
                        graphics);
                int tabWidth = (int)tabBounds.getWidth();
                String[] lines = message.split("\n");
                for (String line : lines) {
                    int xColumn = x;
                    String[] columns = line.split("\t");
                    for (String column : columns) {
                        if (xColumn != x) {
                            // Align to tab stop.
                            xColumn += tabWidth - (xColumn-x) % tabWidth;
                        }
                        Rectangle2D columnBounds = fontMetrics.getStringBounds(
                                column,
                                graphics);
                        graphics.drawString(
                                column,
                                xColumn,
                                y + fontMetrics.getAscent());
                        xColumn += columnBounds.getWidth();
                    }
                    y += fontMetrics.getHeight();
                }
            }

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(400, 200);
            }
        };
        frame.getContentPane().add(panel, BorderLayout.CENTER);

        frame.pack();

        frame.setVisible(true);    }
}
</code>```

It really seemed like Utilities.drawTabbedText() was promising, but I couldn't figure out what it needed as input.

Title: Break lines in g.drawString in Java SE

Body:
This is exactly what I'm trying to do:

Graphics2D g2 = (Graphics2D) g;
g2.setFont(new Font("Serif", Font.PLAIN, 5));
g2.setPaint(Color.black);
g2.drawString("Line 1\nLine 2", x, y);

That line prints like this:

Line1Line2

I want it like this:

Line1
Line2

How can I do this in drawString ?

As well as how can I do a tab space for a line??

Body:
Here's a snippet I used to draw text in a JPanel with tab expansion and multiple lines:

import javax.swing.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;

public class Scratch {
    public static void main(String argv[]) {
        JFrame frame = new JFrame("FrameDemo");

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel() {
            @Override
            public void paint(Graphics graphics) {
                graphics.drawRect(100, 100, 1, 1);
                String message =
                        "abc\tdef\n" +
                        "abcx\tdef\tghi\n" +
                        "xxxxxxxxdef\n" +
                        "xxxxxxxxxxxxxxxxghi\n";
                int x = 100;
                int y = 100;
                FontMetrics fontMetrics = graphics.getFontMetrics();
                Rectangle2D tabBounds = fontMetrics.getStringBounds(
                        "xxxxxxxx",
                        graphics);
                int tabWidth = (int)tabBounds.getWidth();
                String[] lines = message.split("\n");
                for (String line : lines) {
                    int xColumn = x;
                    String[] columns = line.split("\t");
                    for (String column : columns) {
                        if (xColumn != x) {
                            // Align to tab stop.
                            xColumn += tabWidth - (xColumn-x) % tabWidth;
                        }
                        Rectangle2D columnBounds = fontMetrics.getStringBounds(
                                column,
                                graphics);
                        graphics.drawString(
                                column,
                                xColumn,
                                y + fontMetrics.getAscent());
                        xColumn += columnBounds.getWidth();
                    }
                    y += fontMetrics.getHeight();
                }
            }

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(400, 200);
            }
        };
        frame.getContentPane().add(panel, BorderLayout.CENTER);

        frame.pack();

        frame.setVisible(true);    }
}

It really seemed like Utilities.drawTabbedText() was promising, but I couldn't figure out what it needed as input.


问:
Console calculator program in C++ not working correctly
I'm kind of new to programming in C++, and after a bit of learning how it works, I tried making this console calculator application, which takes in two numbers from the user x and y, and then adds, subtracts, multiplies or divides the two numbers depending on the third z input. I'm using code blocks as the IDE, and the code is as follows:

```<code>#include <iostream>

//First input value
int x;
//Second input value;
int y;
//Operator value;
int z;
int main()
{
    //Asks user for first number
    std::cout << "Input first number" << std::endl;
    std::cin >> x;
    std::cout << "" << std::endl;

    //Asks user for second number
    std::cout << "Input second number" << std::endl;
    std::cin >> y;
    std::cout << "" << std::endl;

    //Asks user for operation
    std::cout << "Input operation: 1 for add, 2 for sub, 3 for multiply, 4 for divide" << std::endl;
    std::cin >> z;

    //Displaying the desired output
    if (z = 1)
    {
        std::cout << x + y << std::endl;
    }
    else if (z = 2)
    {
        std::cout << x - y << std::endl;
    }
    else if (z = 3)
    {
        std::cout << x * y << std::endl;
    }
    else (z = 4);
    {
        std::cout << x / y << std::endl;
    }

    //Just a stupid comment
    std::cout << "Thank you for using this piece of shit xD. Press any key to end" << std::endl;
    return 0;
}
</code>```

Even though it compiles without any errors, every operation input seems to add the numbers together rather than the desired operation. Could anyone tell me what I'm doing wrong here?

答:
Here you are just assigning the value in 'Z' variable (Z=1, Z=2..) in "if and else if" condition, That is wrong for checking the values. However, in this case you can use switch case. Like as below.</p>

```<code>switch(z){
    case 1:
    std::cout << x + y << std::endl;
    break;
    case 2:
    std::cout << x - y << std::endl;
    break;
    case 3:
    std::cout << x * y << std::endl;
    break;
    case 4:
    std::cout << x / y << std::endl;
    break;
    default:
    std::cout << "select proper option" << std::endl;

}
</code>```

Body:
I'm kind of new to programming in C++, and after a bit of learning how it works, I tried making this console calculator application, which takes in two numbers from the user x and y, and then adds, subtracts, multiplies or divides the two numbers depending on the third z input. I'm using code blocks as the IDE, and the code is as follows:

#include <iostream>

//First input value
int x;
//Second input value;
int y;
//Operator value;
int z;
int main()
{
    //Asks user for first number
    std::cout << "Input first number" << std::endl;
    std::cin >> x;
    std::cout << "" << std::endl;

    //Asks user for second number
    std::cout << "Input second number" << std::endl;
    std::cin >> y;
    std::cout << "" << std::endl;

    //Asks user for operation
    std::cout << "Input operation: 1 for add, 2 for sub, 3 for multiply, 4 for divide" << std::endl;
    std::cin >> z;

    //Displaying the desired output
    if (z = 1)
    {
        std::cout << x + y << std::endl;
    }
    else if (z = 2)
    {
        std::cout << x - y << std::endl;
    }
    else if (z = 3)
    {
        std::cout << x * y << std::endl;
    }
    else (z = 4);
    {
        std::cout << x / y << std::endl;
    }

    //Just a stupid comment
    std::cout << "Thank you for using this piece of shit xD. Press any key to end" << std::endl;
    return 0;
}

Even though it compiles without any errors, every operation input seems to add the numbers together rather than the desired operation. Could anyone tell me what I'm doing wrong here?

Body:
Here you are just assigning the value in 'Z' variable (Z=1, Z=2..) in "if and else if" condition, That is wrong for checking the values. However, in this case you can use switch case. Like as below.

switch(z){
    case 1:
    std::cout << x + y << std::endl;
    break;
    case 2:
    std::cout << x - y << std::endl;
    break;
    case 3:
    std::cout << x * y << std::endl;
    break;
    case 4:
    std::cout << x / y << std::endl;
    break;
    default:
    std::cout << "select proper option" << std::endl;

}


问:
MS SQL value change
I have a SQL query that looks like this.

```<code>Select Timestamp, Value From [dbo].[nro_ReadRawDataByTimeFunction](
  'SV/SVTP01.BONF0335-D1-W1-BL1',
  '2017-11-01 00:00',
  '2017-12-01 00:00')
GO
</code>```

This will return

```<code>    Timestamp        | Value
1   2017-11-01 10:00 | 0
2   2017-11-01 11:00 | 0
3   2017-11-01 12:00 | 0
4   2017-11-01 13:00 | 1
5   2017-11-01 14:00 | 1
6   2017-11-01 15:00 | 0
7   2017-11-01 16:00 | 0
8   2017-11-01 17:00 | 0
9   2017-11-01 18:00 | 1
10  2017-11-01 19:00 | 0
</code>```

The full list is alot larger, and I'm only interested in in results where value change from last result, so in this case row 1,4,6,9,10

I know how to do it if it's directly from a table but not when it's from a function

答:
What i ended with is as following

```<code>@DECLARE @startDate DATE,
@tagName nVarChar(200);

WITH CTE AS(
        SELECT Timestamp As StopTime, Value As [OFF], LAG(Value,1) OVER (order by Timestamp) As [ON], Quality
        FROM [dbo].[nrp_ReadRawDataByTimeFunction] (@TagName,@startDate, DATEADD(MONTH,2,@startDate))
        Where Quality & 127 = 100
),
CalenderCTE AS(
        SELECT [DATE] = DATEADD(Day,Number,@startDate)
        FROM master..spt_values
        WHERE Type='P'
        AND DATEADD(day,Number,@startDate) < DATEADD(MONTH,1,@startDate)
)

SELECT * FROM CTE
FULL OUTER JOIN
CalenderCTE on CalenderCTE.Date = CAST(CTE.StopTime as [Date])
Where CTE.[OFF] != CTE.[ON}
</code>```

This is just a tiny part of the query since it doing alot more which ain't included in the original post.

Thanks all for your input's, it help me on the way to the final result.

Title: MS SQL value change

Body:
I have a SQL query that looks like this.

Select Timestamp, Value From [dbo].[nro_ReadRawDataByTimeFunction](
  'SV/SVTP01.BONF0335-D1-W1-BL1',
  '2017-11-01 00:00',
  '2017-12-01 00:00')
GO

This will return

    Timestamp        | Value
1   2017-11-01 10:00 | 0
2   2017-11-01 11:00 | 0
3   2017-11-01 12:00 | 0
4   2017-11-01 13:00 | 1
5   2017-11-01 14:00 | 1
6   2017-11-01 15:00 | 0
7   2017-11-01 16:00 | 0
8   2017-11-01 17:00 | 0
9   2017-11-01 18:00 | 1
10  2017-11-01 19:00 | 0

The full list is alot larger, and I'm only interested in in results where value change from last result, so in this case row 1,4,6,9,10

I know how to do it if it's directly from a table but not when it's from a function

Body:
What i ended with is as following

@DECLARE @startDate DATE,
@tagName nVarChar(200);

WITH CTE AS(
        SELECT Timestamp As StopTime, Value As [OFF], LAG(Value,1) OVER (order by Timestamp) As [ON], Quality
        FROM [dbo].[nrp_ReadRawDataByTimeFunction] (@TagName,@startDate, DATEADD(MONTH,2,@startDate))
        Where Quality & 127 = 100
),
CalenderCTE AS(
        SELECT [DATE] = DATEADD(Day,Number,@startDate)
        FROM master..spt_values
        WHERE Type='P'
        AND DATEADD(day,Number,@startDate) < DATEADD(MONTH,1,@startDate)
)

SELECT * FROM CTE
FULL OUTER JOIN
CalenderCTE on CalenderCTE.Date = CAST(CTE.StopTime as [Date])
Where CTE.[OFF] != CTE.[ON}

This is just a tiny part of the query since it doing alot more which ain't included in the original post.

Thanks all for your input's, it help me on the way to the final result.


问:
How do I protect JavaScript files?
I know it's impossible to hide source code but, for example, if I have to link a JavaScript file from my CDN to a web page and I don't want the people to know the location and/or content of this script, is this possible?

For example, to link a script from a website, we use:

```<code><script type="text/javascript" src="http://somedomain.example/scriptxyz.js">
</script>
</code>```

Now, is possible to hide from the user where the script comes from, or hide the script content and still use it on a web page?

For example, by saving it in my private CDN that needs password to access files, would that work? If not, what would work to get what I want?

答:
Forget it, this is not doable.

No matter what you try it will not work. All a user needs to do to discover your code and it's location is to look in the net tab in firebug or use fiddler to see what requests are being made.

Title: How do I protect JavaScript files?

Body:
I know it's impossible to hide source code but, for example, if I have to link a JavaScript file from my CDN to a web page and I don't want the people to know the location and/or content of this script, is this possible?

For example, to link a script from a website, we use:

Now, is possible to hide from the user where the script comes from, or hide the script content and still use it on a web page?

For example, by saving it in my private CDN that needs password to access files, would that work? If not, what would work to get what I want?


问:
How to comment multiple lines in Visual Studio Code?
I cannot find a way to comment and uncomment multiple lines of code in Visual Studio Code.

Is it possible to comment and uncomment multiple lines in Visual Studio Code using some shortcut? If yes, how to do it?

答:
In MacOS comment out multi-lines in Visual Studio Code by keyboard shortcut:

Option + Shift + A

```<code>/*
...
...
*/
</code>```

Or,

Select all lines and then press CTRL + /

Body:
In MacOS comment out multi-lines in Visual Studio Code by keyboard shortcut:

Option + Shift + A

/*
...
...
*/

Or,

Select all lines and then press CTRL + /