问:
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?

答:
Here are the changes on your code:

```<code>public class ExpandableListAdapter extends BaseExpandableListAdapter {

static int count=0;
private Context _context;

HashMap<String,Food> selectedItems;

public List<String> listDataHeader; // header titles

// child data in format of header title, child title
public HashMap<String, ArrayList<Food>> _listDataChild;

CheckOutItems checkOutItems;

public ExpandableListAdapter(Context context, List<String> listDataHeader,
                             HashMap<String, ArrayList<Food>> listChildData) {
    this._context = context;
    this.listDataHeader = listDataHeader;
    this._listDataChild = listChildData;

    selectedItems = new HashMap<>();

    checkOutItems = (CheckOutItems)context;

}

@Override
public Food getChild(int groupPosition, int childPosititon) {
    return this._listDataChild.get(this.listDataHeader.get(groupPosition)).get(childPosititon);
}

@Override
public long getChildId(int groupPosition, int childPosition) {
    return childPosition;
}

Button button;
@Override
public View getChildView(final int groupPosition, final int childPosition,
                         boolean isLastChild, View convertView, ViewGroup parent) {

    View row;
    final ListViewHolder listViewHolder;
    if(convertView == null)
    {
        LayoutInflater layoutInflater = (LayoutInflater) this._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);
        listViewHolder.addButton = row.findViewById(R.id.addbtn);
        row.setTag(listViewHolder);
    }
    else
    {
        row=convertView;
        listViewHolder= (ListViewHolder) row.getTag();
    }
    final Food food=getChild(groupPosition,childPosition);

    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(groupPosition,childPosition,listViewHolder.cartQuantity,1);
        }
    });
    //listViewHolder.edTextQuantity.setText("0");
    listViewHolder.decrement.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            updateQuantity(groupPosition,childPosition,listViewHolder.cartQuantity,-1);

        }
    });

    listViewHolder.addButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            selectedItems.put(food.Foodname,food);
            checkOutItems.sendItems(selectedItems);
        }
    });

    return row;
}

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

    Food food = getChild(group,position);
    if(value > 0&&food.CartQuantity<10)
    {
        food.CartQuantity = food.CartQuantity + 1;
        count++;

    }
    else
    {
        if(food.CartQuantity > 0)
        {
            food.CartQuantity = food.CartQuantity - 1;
            count--;

        }

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

@Override
public int getChildrenCount(int groupPosition) {
    return _listDataChild.get(listDataHeader.get(groupPosition))
            .size();
}

@Override
public Object getGroup(int groupPosition) {
    return this.listDataHeader.get(groupPosition);
}

@Override
public int getGroupCount() {
    return this.listDataHeader.size();
}

@Override
public long getGroupId(int groupPosition) {
    return groupPosition;
}

@Override
public View getGroupView(int groupPosition, boolean isExpanded,
                         View convertView, ViewGroup parent) {
    String headerTitle = (String) getGroup(groupPosition);
    if (convertView == null) {
        LayoutInflater infalInflater = (LayoutInflater) this._context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.list_group, null);
    }

    TextView lblListHeader = (TextView) convertView
            .findViewById(R.id.lblListHeader);
    lblListHeader.setTypeface(null, Typeface.BOLD);
    lblListHeader.setText(headerTitle);

    return convertView;
}

@Override
public boolean hasStableIds() {
    return false;
}

@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
    return true;
}

interface CheckOutItems
{
    public void sendItems(HashMap<String,Food> selectedItems);
}
 }
</code>```

And here is link of Google Drive for the whole project:

https://drive.google.com/open?id=15utf5kuJJHUXDR1bOLeb7DAIDJ54RwOW

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:
Here are the changes on your code:

public class ExpandableListAdapter extends BaseExpandableListAdapter {

static int count=0;
private Context _context;

HashMap<String,Food> selectedItems;

public List<String> listDataHeader; // header titles

// child data in format of header title, child title
public HashMap<String, ArrayList<Food>> _listDataChild;

CheckOutItems checkOutItems;

public ExpandableListAdapter(Context context, List<String> listDataHeader,
                             HashMap<String, ArrayList<Food>> listChildData) {
    this._context = context;
    this.listDataHeader = listDataHeader;
    this._listDataChild = listChildData;

    selectedItems = new HashMap<>();

    checkOutItems = (CheckOutItems)context;

}

@Override
public Food getChild(int groupPosition, int childPosititon) {
    return this._listDataChild.get(this.listDataHeader.get(groupPosition)).get(childPosititon);
}

@Override
public long getChildId(int groupPosition, int childPosition) {
    return childPosition;
}

Button button;
@Override
public View getChildView(final int groupPosition, final int childPosition,
                         boolean isLastChild, View convertView, ViewGroup parent) {

    View row;
    final ListViewHolder listViewHolder;
    if(convertView == null)
    {
        LayoutInflater layoutInflater = (LayoutInflater) this._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);
        listViewHolder.addButton = row.findViewById(R.id.addbtn);
        row.setTag(listViewHolder);
    }
    else
    {
        row=convertView;
        listViewHolder= (ListViewHolder) row.getTag();
    }
    final Food food=getChild(groupPosition,childPosition);

    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(groupPosition,childPosition,listViewHolder.cartQuantity,1);
        }
    });
    //listViewHolder.edTextQuantity.setText("0");
    listViewHolder.decrement.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            updateQuantity(groupPosition,childPosition,listViewHolder.cartQuantity,-1);

        }
    });

    listViewHolder.addButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            selectedItems.put(food.Foodname,food);
            checkOutItems.sendItems(selectedItems);
        }
    });

    return row;
}

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

    Food food = getChild(group,position);
    if(value > 0&&food.CartQuantity<10)
    {
        food.CartQuantity = food.CartQuantity + 1;
        count++;

    }
    else
    {
        if(food.CartQuantity > 0)
        {
            food.CartQuantity = food.CartQuantity - 1;
            count--;

        }

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

@Override
public int getChildrenCount(int groupPosition) {
    return _listDataChild.get(listDataHeader.get(groupPosition))
            .size();
}

@Override
public Object getGroup(int groupPosition) {
    return this.listDataHeader.get(groupPosition);
}

@Override
public int getGroupCount() {
    return this.listDataHeader.size();
}

@Override
public long getGroupId(int groupPosition) {
    return groupPosition;
}

@Override
public View getGroupView(int groupPosition, boolean isExpanded,
                         View convertView, ViewGroup parent) {
    String headerTitle = (String) getGroup(groupPosition);
    if (convertView == null) {
        LayoutInflater infalInflater = (LayoutInflater) this._context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.list_group, null);
    }

    TextView lblListHeader = (TextView) convertView
            .findViewById(R.id.lblListHeader);
    lblListHeader.setTypeface(null, Typeface.BOLD);
    lblListHeader.setText(headerTitle);

    return convertView;
}

@Override
public boolean hasStableIds() {
    return false;
}

@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
    return true;
}

interface CheckOutItems
{
    public void sendItems(HashMap<String,Food> selectedItems);
}
 }

And here is link of Google Drive for the whole project:

https://drive.google.com/open?id=15utf5kuJJHUXDR1bOLeb7DAIDJ54RwOW


来源: stackexchange

问:
Xcode 9.2 Asset Catalog editor pane empty
Whenever I try to add a new resource or edit an existing resource in my Asset Catalog in Xcode 9.2, the editor pane is just totally empty. I have tried App Icon Set, Color Set, Image Set, and I get the same result every time. I have tried quitting Xcode and deleting Derived Data. I have no warnings or errors in my issue navigator. My build succeeds.

答: Select Image Set and click on Show Overview like below image.

ContentLicense: CC BY-SA 3.0


问:
How to get max of subseries in Pine script
Lets suppose we have series of numbers. It contains some values [..., 3, 6, 4, 7]. I would like to get maximum of 100 last elements.

I tried max(series[100]), but it looks like series[100] operator returns sub-series discarding last 100 elements.

答:
That's correct. In Pine-script everything become a series, even a constant once you are using it, since all functions return a series. This means, that you can always put (non-series) constants in, but you can never get them out.

I think what you want is:

```<code>//@version=3
study("Max of N", shorttitle="max", overlay=false)
nmax = highest(n, 100) // n is the series of ALL bars
plot(nmax, style=line)
</code>```

Body:
That's correct. In Pine-script everything become a series, even a constant once you are using it, since all functions return a series. This means, that you can always put (non-series) constants in, but you can never get them out.

I think what you want is:

//@version=3
study("Max of N", shorttitle="max", overlay=false)
nmax = highest(n, 100) // n is the series of ALL bars
plot(nmax, style=line)


问:
Limit filter inside scope of include filter not working in loopback
I have two tables, 'categoryinfo' and 'accounttag'.

The two tales have the following relation:

categoryinfo hasMany accounttag

accounttag belongsTo categoryinfo

I want to apply limit on:

the number of categories (set to 5) and

number of accounttags fetched from the relation for each category (set to 10)

However, the limit filter inside the scope of the include filter is not working properly and is fetching less results than the set limit for each category but the database contains more valid entries than the limit value.

categoryinfo.find(
    {
        where: {
            valid: 1
        },
        include: [
            {
                relation: 'accounttag',
                scope: {
                    where: {
                        valid: 1
                    },
                    order: 'rank ASC',
                    limit: 10,
                }
            }
        ],
        order: 'modifiedon DESC',
        limit: 5
    }
)

Is there any way to achieve the required result using the same filters?

答:
With the current stable Version of Loopback you cannot filter on Level 2 properties for Relational Databases. These are some of the Issues raised on the same in Loopback

https://github.com/strongloop/loopback/issues/517
https://github.com/strongloop/loopback/issues/683

As a matter of fact you might want to look into native sql queries in loopback and
  do the filtering there, or might need to use native javascript array
  methods for filtering


问:
How to implement Signal R in .net MVC?? Please suggest me a basic idea or walkthrough
I have an Existing website that was built in .net, is it possible to integrate the signalr on it? if Yes please let me know how..

Thank you in advance.

答:
Yes you can integrate SignalR your existing Project.
you can get detailed steps from this link.
you can skip 1st two steps as you are integrating it in existing one. Start from step 3 in the Link.

tutorial-getting-started-with-signalr

In this there's a demo explaining you how SignalR works and further you can customize methods in the way you want.

Hope this helps.


问:
How to read xml file in c# with specific attribute
I have an xml file with attribute

```<code> xmlns="http://www.reservwire.com/namespace/WebServices/Xml">
</code>```

When I remove this attribute, then I can read each tag. If I don't remove attribute I receive error message "Object refrence not set to instance of object"

My C# code:

```<code>XmlDocument xml = new XmlDocument();
xml.Load(Server.MapPath("~/HotelSearchCriteria/PrepareBooking.xml"));
string CommmitLevel = xml.DocumentElement
                         .SelectSingleNode("/BookingCreate/CommitLevel")
                         .InnerText;
</code>```

My XML:

```<code><BookingCreate xmlns="http://www.reservwire.com/namespace/WebServices/Xml">
  <Authority>
    <Org>danco</Org>
    <User>xmltest</User>
    <Password>xmltest</Password>
    <Language>en</Language>
    <Currency>EUR</Currency>
    <TestDebug>false</TestDebug>
    <Version>1.26</Version>
  </Authority>
  <QuoteId>17081233-3</QuoteId>
  <HotelStayDetails>
    <Room>
      <Guests>
        <Adult title="Mr" first="djkvb" last="jkj" />
        <Adult title="Mr" first="jfs" last="kjdjs" />
      </Guests>
    </Room>
  </HotelStayDetails>
  <HotelSearchCriteria>
    <AvailabilityStatus>allocation</AvailabilityStatus>
    <DetailLevel>basic</DetailLevel>
  </HotelSearchCriteria>
  <CommitLevel>prepare</CommitLevel>
</BookingCreate>
</code>```

What to do to read xml with xmlns attribute? It is necessary for me to have xmlns attribute.

答:
You need to specify the namespace, by using a namespace manager. This should work </p>

```<code>    XmlDocument bookingXml = new XmlDocument();
    bookingXml.Load("PrepareBooking.xml");
    XmlNamespaceManager ns = new XmlNamespaceManager(bookingXml.NameTable);
    ns.AddNamespace("booking", "http://www.reservwire.com/namespace/WebServices/Xml");
    var commitLevel = bookingXml.SelectSingleNode("//booking:BookingCreate//booking:CommitLevel", ns).InnerText;
</code>```

Body:
I have an xml file with attribute

 xmlns="http://www.reservwire.com/namespace/WebServices/Xml">

When I remove this attribute, then I can read each tag. If I don't remove attribute I receive error message "Object refrence not set to instance of object"

My C# code:

XmlDocument xml = new XmlDocument();
xml.Load(Server.MapPath("~/HotelSearchCriteria/PrepareBooking.xml"));
string CommmitLevel = xml.DocumentElement
                         .SelectSingleNode("/BookingCreate/CommitLevel")
                         .InnerText;

My XML:

<BookingCreate xmlns="http://www.reservwire.com/namespace/WebServices/Xml">
  <Authority>
    <Org>danco</Org>
    <User>xmltest</User>
    <Password>xmltest</Password>
    <Language>en</Language>
    <Currency>EUR</Currency>
    <TestDebug>false</TestDebug>
    <Version>1.26</Version>
  </Authority>
  <QuoteId>17081233-3</QuoteId>
  <HotelStayDetails>
    <Room>
      <Guests>
        <Adult title="Mr" first="djkvb" last="jkj" />
        <Adult title="Mr" first="jfs" last="kjdjs" />
      </Guests>
    </Room>
  </HotelStayDetails>
  <HotelSearchCriteria>
    <AvailabilityStatus>allocation</AvailabilityStatus>
    <DetailLevel>basic</DetailLevel>
  </HotelSearchCriteria>
  <CommitLevel>prepare</CommitLevel>
</BookingCreate>

What to do to read xml with xmlns attribute? It is necessary for me to have xmlns attribute.

Body:
You need to specify the namespace, by using a namespace manager. This should work

    XmlDocument bookingXml = new XmlDocument();
    bookingXml.Load("PrepareBooking.xml");
    XmlNamespaceManager ns = new XmlNamespaceManager(bookingXml.NameTable);
    ns.AddNamespace("booking", "http://www.reservwire.com/namespace/WebServices/Xml");
    var commitLevel = bookingXml.SelectSingleNode("//booking:BookingCreate//booking:CommitLevel", ns).InnerText;


问:
Div on click expands but does not contract on clicking again
When I click on my div it expands, but when i click again it does not contact. Clicking on the Div again should close/contract it back.

Below is my HTML code:

```<code><div style="height:35px;" onclick="style='height:auto'">
  <p style="color: #9DA4AB;font-size: 15px;">{{list.TASKDESC}}</p>
</div>
</code>```

Please note i am using IONIC and i am looking at a simplest way to achieve this.

答:
you can try something like this,

in your html,

```<code><ion-card *ngFor="let qa of groups; let i=index" text-wrap (click)="toggleGroup(i)" [ngClass]="{active: isGroupShown(i)}">

        //header
        <ion-card-header style="white-space: normal;">
            {{qa.id}}. {{qa.question}}
            <ion-icon style="position:absolute !important;right: 20px;" color="success" item-right [name]="isGroupShown(i) ? 'arrow-dropdown' : 'arrow-dropright'"></ion-icon>
        </ion-card-header>

        //content
        <ion-card-content *ngIf="isGroupShown(i)">
            {{qa.answer|removehtmltag}}
        </ion-card-content>
    </ion-card>
</code>```

in your ts,

```<code>export class ClassName{

shownGroup = null;

 constructor(){}
 toggleGroup(group) {
       if (this.isGroupShown(group)) {
           this.shownGroup = null;
       } else {
           this.shownGroup = group;
       }
   };

   isGroupShown(group) {
       return this.shownGroup === group;
   };
 }
</code>```

Body:
When I click on my div it expands, but when i click again it does not contact. Clicking on the Div again should close/contract it back.

Below is my HTML code:

{{list.TASKDESC}}

Please note i am using IONIC and i am looking at a simplest way to achieve this.

Body:
you can try something like this,

in your html,

<ion-card *ngFor="let qa of groups; let i=index" text-wrap (click)="toggleGroup(i)" [ngClass]="{active: isGroupShown(i)}">

        //header
        <ion-card-header style="white-space: normal;">
            {{qa.id}}. {{qa.question}}
            <ion-icon style="position:absolute !important;right: 20px;" color="success" item-right [name]="isGroupShown(i) ? 'arrow-dropdown' : 'arrow-dropright'"></ion-icon>
        </ion-card-header>

        //content
        <ion-card-content *ngIf="isGroupShown(i)">
            {{qa.answer|removehtmltag}}
        </ion-card-content>
    </ion-card>

in your ts,

export class ClassName{

shownGroup = null;

 constructor(){}
 toggleGroup(group) {
       if (this.isGroupShown(group)) {
           this.shownGroup = null;
       } else {
           this.shownGroup = group;
       }
   };

   isGroupShown(group) {
       return this.shownGroup === group;
   };
 }


问:
iOS Development: All I need to do is post a tweet
I've been researching the latest ways to integrate Twitter into my app and it appears the best (most painless) approach is to use the MGTwitterEngine, and the best tutorial I could find to implement this is a 3-part series.  If all I need to do is allow the user to login to their twitter account and post a single tweet that's always the same, is there an easier way to do that than following the tutorial I linked to?

Thanks so much for your wisdom.  If the alternatives aren't much easier, no problem, I'm not so lazy that I can't follow a tutorial, I was just wondering if there's a quicker way that I didn't see.

答:
I'm a big fan of st3fan's (Stefan Arentz) https://github.com/st3fan/iphone-twitter project. It's very easy to integrate and includes whole views that you can just use, easily customizable too.

Plan your Twitter implementation ahead - with an iPhone project you will want to use xAuth authentication which does not require a round trip to the web browser.* You have to first register your app and then request permission for your application to use this method. Check the Twitter developer pages for more details.

*or not. But I hate leaving the app to post tweets.

ContentLicense: CC BY-SA 2.5


问:
Unable to add elements in NSmutableArray more than 260 elements from my for loop
Here is the code. We are unable to get complete array elements. It's restricting to 260 elements but there are 360 elements.</p>

```<code>-(void)scheduleCal{
    float monthlyPayment = 0.0; //monthly Payment
    float loanAmount = 100000; //Loan Amount
    int years = 30;
    float intRate = 6;
    float i = intRate / 1200;
    int n = years * 12;// 360
    float rPower = pow(1+i, n);

    float mPayment = loanAmount*((i*(pow((1+i), n)))/((pow(1+i, n))-1));

    monthlyPayment = loanAmount * i * rPower / (rPower -1);

    NSLog(@"Monthly Payment:%0.2f %f",mPayment,round(monthlyPayment));

    float tempLoanAmount = loanAmount;

    self.array = [[NSMutableArray alloc] init];

    for (int r = 1; r <= n; r++) {
        float interestPayment = tempLoanAmount *i;
        double principalPayment = mPayment - interestPayment;

        tempLoanAmount -= principalPayment;

        NSDictionary *dic = @{@"sno":[NSString stringWithFormat:@"%d",r],@"principal": [NSString stringWithFormat:@"%0.2f",principalPayment],@"interest":[NSString stringWithFormat:@"%0.2f",interestPayment],@"balance":[NSString stringWithFormat:@"%0.2f",tempLoanAmount]};

        [self.array addObject:dic];
        dic = nil;
    }

    NSLog(@"Array:%@ %ld",self.array,(unsigned long)self.array.count);
}
</code>```

答:
Nothing wrong in the code. Code is perfectly fine. Array contains 360 elements. It's just got clipped on console. If you need to check or print the entire contents on console use any of the below way.</p>

```<code>for (NSDictionary *dict in self.array) {
     NSLog(@"Dict: %@ ",dict);
}

OR

printf("%s", [NSString stringWithFormat: @"%@", array].UTF8String);
</code>```

Body:
Here is the code. We are unable to get complete array elements. It's restricting to 260 elements but there are 360 elements.

-(void)scheduleCal{
    float monthlyPayment = 0.0; //monthly Payment
    float loanAmount = 100000; //Loan Amount
    int years = 30;
    float intRate = 6;
    float i = intRate / 1200;
    int n = years * 12;// 360
    float rPower = pow(1+i, n);

    float mPayment = loanAmount*((i*(pow((1+i), n)))/((pow(1+i, n))-1));

    monthlyPayment = loanAmount * i * rPower / (rPower -1);

    NSLog(@"Monthly Payment:%0.2f %f",mPayment,round(monthlyPayment));

    float tempLoanAmount = loanAmount;

    self.array = [[NSMutableArray alloc] init];

    for (int r = 1; r <= n; r++) {
        float interestPayment = tempLoanAmount *i;
        double principalPayment = mPayment - interestPayment;

        tempLoanAmount -= principalPayment;

        NSDictionary *dic = @{@"sno":[NSString stringWithFormat:@"%d",r],@"principal": [NSString stringWithFormat:@"%0.2f",principalPayment],@"interest":[NSString stringWithFormat:@"%0.2f",interestPayment],@"balance":[NSString stringWithFormat:@"%0.2f",tempLoanAmount]};

        [self.array addObject:dic];
        dic = nil;
    }

    NSLog(@"Array:%@ %ld",self.array,(unsigned long)self.array.count);
}

Body:
Nothing wrong in the code. Code is perfectly fine. Array contains 360 elements. It's just got clipped on console. If you need to check or print the entire contents on console use any of the below way.

for (NSDictionary *dict in self.array) {
     NSLog(@"Dict: %@ ",dict);
}

OR

printf("%s", [NSString stringWithFormat: @"%@", array].UTF8String);


问:
Validate Tier Pricing / Volume pricing using java
I want to validate pricing on Salesforce based on volume using Java.

For example:
Price for 1-1000 quantity is 2.25$ each

Price for 1001-3000 quantity is 2$ each

Price for 3001-5000 quantity is 1.5$ each

So if I purchase 4000 quantity the pricing breakup would be 2.25$ for first 1000, 2$ for next 2000 and remaining 1000 would be priced at 1.5$.

Expected output for 4000 products is = 7750 (2250@2.5$ +4000 @2$ +1500@ 1.5$)

答:
You may do it using conditional statements like if else :</p>

```<code>public class cn {
    public static void main(String arf[])
    {
        Scanner in =new Scanner(System.in);
        int items;
        double sum=0;
        items=in.nextInt();
        if(items<=1000)
        {
            sum=items*2.25;
            System.out.println((int)sum);
        }
        else
        {
            if(items<=3000&&items>1000)
            {sum=2250;
            items-=1000;
                sum+=items*2;
                System.out.println((int)sum);

            }
            else
            {
                if(items<=5000&&items>3000)
                {sum=6250;
                items-=3000;
                    sum+=items*1.5;
                    System.out.println((int)sum);

                }
            }
        }
    }
}
</code>```

Body:
You may do it using conditional statements like if else :

public class cn {
    public static void main(String arf[])
    {
        Scanner in =new Scanner(System.in);
        int items;
        double sum=0;
        items=in.nextInt();
        if(items<=1000)
        {
            sum=items*2.25;
            System.out.println((int)sum);
        }
        else
        {
            if(items<=3000&&items>1000)
            {sum=2250;
            items-=1000;
                sum+=items*2;
                System.out.println((int)sum);

            }
            else
            {
                if(items<=5000&&items>3000)
                {sum=6250;
                items-=3000;
                    sum+=items*1.5;
                    System.out.println((int)sum);

                }
            }
        }
    }
}


问:
Computer Graphics: Math to Code
First, lets start out with my math background. I've taken calculus I - IV and Differential Equations. I've taken a first semester computer graphics course where we implemented pretty much our own graphics pipeline including shading using Phong without any graphics API.

I'm taking a graduate level Advanced Computer Graphics course this semester and when reading the math involved it loses me. This class is basically an image synthesize class. We'll build a ray-tracer in our first project and build on it from there on.

When reading up on advanced computer graphics, I'll usually get a bunch of math. I understand computer graphics is math heavy but I'm having problems when trying to figure out exactly how I'm suppose to implement the math into code. I'm really going to need to get the hang of this in order to excel in CG.

For instance, this article from GPU Gems:
http://http.developer.nvidia.com/GPUGems/gpugems_ch01.html
 There's a bunch of math, but I have no clue where to start implementing the math if I want to.

So, is there something I'm missing?
 Am I suppose to look at the math and be able to derive the code?
 Are there tutorials/books out there that could help me understand what I'm needing to do?

答:
Programming for the sort of math you see in the GPU gems article would generally fall under numerical analysis. The more applied side of numerical analysis would be treated in a course or book on numerical methods or scientific programming. I'd suggest starting from the wikipedia article on numerical analysis and looking at some of the specific linked articles. Once you know the names of some relevant methods, sample code is easy to find. </p>

<p>A tip: a big part of implementing derivatives and integrals is really just learning how to handle limits (in the mathematical sense) in your programs. Often, that's not explicitly stated. </p>

Title: Computer Graphics: Math to Code

Body:
Programming for the sort of math you see in the GPU gems article would generally fall under numerical analysis. The more applied side of numerical analysis would be treated in a course or book on numerical methods or scientific programming. I'd suggest starting from the wikipedia article on numerical analysis and looking at some of the specific linked articles. Once you know the names of some relevant methods, sample code is easy to find.

A tip: a big part of implementing derivatives and integrals is really just learning how to handle limits (in the mathematical sense) in your programs. Often, that's not explicitly stated.


问:
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.change

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

to this

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

2.change

```<code> @Override
public Object getItem(int i) {
    return null;
}

@Override
public long getItemId(int i) {
    return 0;
}
</code>```

to this

```<code>public Object getItem(int i) {
    return i;
}

public long getItemId(int i) {
    return i;
}
</code>```

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.change

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

to this

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

2.change

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

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

to this

public Object getItem(int i) {
    return i;
}

public long getItemId(int i) {
    return i;
}


问:
webpack css-loader localIdent name hash length
I use webpack and css-loader, and in my css-loader config I use these options:

```<code>options: {
    importLoaders: 1,
    modules: true,
    localIdentName: '[hash:base64:3]'
}
</code>```

Just like you see, it is obvious that I desire all of my class name will have 3 characters, and after build absolutely my desire come true but there is a very big issue.

Some class names has same name! (conflict!)

for example:

```<code>._1mk { /*dev name was .home*/
   color: red;
} /*line 90*/
</code>```

and

```<code>._1mk { /*dev name was .news*/
   color: blue;
}
</code>```

This is a big issue, but when I use [hash:base64:5] everything would be ok and each class has its own hash name without any conflict.

I search this issue about 4 hours and saw all developers use number 5 as less of length of hash for their config. I don't know why! I calculate that 64 characters [a-z][A-Z][0-9][-,_] in three length can has 262144 different words, so why it can not some different names?

how can I settle this conflict? Really should I miss the number 3 ? and use 5 like others?

答:
Finally, I find the right way, it is hash, not randomNaming function. this is made to hash so it is so obviously in short length with vast naming maybe it produces a collision. so I write my own Webpack naming function and use the variables and the function top on the Webpack config file. these are the steps of my solution:

At first, two variables for cache and queue. cache for easy accessing to LocalName and its new randomName and queue for holding variable entries that involve all new random names for avoiding a collision.

let q = [],
  cache = {};
```
<p>Second, we declare the <code>randomNaming</code> function. I know, maybe it is not very optimized but it works well. the export file is awesome without any collision.</p>
<pre class="lang-js prettyprint-override"><code>function randomNaming(length, limit) {
  let result = '',
    chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_',
    /*All valid chars*/
    fchars = 'abcdefghjklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_';
  /*All valid first chars*/

  do {
    if (q.length >= 52 * Math.pow(64, limit - 1) && limit >= length) {
      return 'OutOfPossibility';
    } else if (q.length >= 52 * Math.pow(64, limit - 1) && limit < length) {
      ++limit;
    }
    result = '';
    result += fchars[Math.floor(Math.random() * fchars.length)];
    for (let i = limit - 1; i > 0; --i) {
      result += chars[Math.floor(Math.random() * chars.length)];
    }
  } while (q.includes(result));
  q.push(result); /*push for avoiding collision in next time of funtion call*/
  return result;
}
</code>```

At Third, in css-loader scope inside of webpack config I used getLocalIdent not localIdentName.

const getLocalIdent = (loaderContext, localIdentName, localName, options) => {
  var randName = randomNaming(3, 2);
  if (localName.match(/^i-/i)) {
    randName = `i-${randName}`;
  } else if (localName.match(/^i_/i)) {
    randName = `i_`;
  } else {
    randName = `${randName}`;
  }
  if (typeof cache[localName] == 'undefined') {
    cache[localName] = randName;
    return cache[localName];
  } else {
    return cache[localName];
  }
};
```

And now all of the names are hashed and the CSS file is in minimal possible volume size. And the HTML is so lightweight.

Body:
I use webpack and css-loader, and in my css-loader config I use these options:

options: {
    importLoaders: 1,
    modules: true,
    localIdentName: '[hash:base64:3]'
}

Just like you see, it is obvious that I desire all of my class name will have 3 characters, and after build absolutely my desire come true but there is a very big issue.

Some class names has same name! (conflict!)

for example:

._1mk { /*dev name was .home*/
   color: red;
} /*line 90*/

and

._1mk { /*dev name was .news*/
   color: blue;
}

This is a big issue, but when I use [hash:base64:5] everything would be ok and each class has its own hash name without any conflict.

I search this issue about 4 hours and saw all developers use number 5 as less of length of hash for their config. I don't know why! I calculate that 64 characters [a-z][A-Z][0-9][-,_] in three length can has 262144 different words, so why it can not some different names?

how can I settle this conflict? Really should I miss the number 3 ? and use 5 like others?

Body:
Finally, I find the right way, it is hash, not randomNaming function. this is made to hash so it is so obviously in short length with vast naming maybe it produces a collision. so I write my own Webpack naming function and use the variables and the function top on the Webpack config file. these are the steps of my solution:

At first, two variables for cache and queue. cache for easy accessing to LocalName and its new randomName and queue for holding variable entries that involve all new random names for avoiding a collision.

let q = [],
  cache = {};

Second, we declare the randomNaming function. I know, maybe it is not very optimized but it works well. the export file is awesome without any collision.

function randomNaming(length, limit) {
  let result = '',
    chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_',
    /*All valid chars*/
    fchars = 'abcdefghjklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_';
  /*All valid first chars*/

  do {
    if (q.length >= 52 * Math.pow(64, limit - 1) && limit >= length) {
      return 'OutOfPossibility';
    } else if (q.length >= 52 * Math.pow(64, limit - 1) && limit < length) {
      ++limit;
    }
    result = '';
    result += fchars[Math.floor(Math.random() * fchars.length)];
    for (let i = limit - 1; i > 0; --i) {
      result += chars[Math.floor(Math.random() * chars.length)];
    }
  } while (q.includes(result));
  q.push(result); /*push for avoiding collision in next time of funtion call*/
  return result;
}

At Third, in css-loader scope inside of webpack config I used getLocalIdent not localIdentName.

const getLocalIdent = (loaderContext, localIdentName, localName, options) => {
  var randName = randomNaming(3, 2);
  if (localName.match(/^i-/i)) {
    randName = `i-${randName}`;
  } else if (localName.match(/^i_/i)) {
    randName = `i_`;
  } else {
    randName = `${randName}`;
  }
  if (typeof cache[localName] == 'undefined') {
    cache[localName] = randName;
    return cache[localName];
  } else {
    return cache[localName];
  }
};

And now all of the names are hashed and the CSS file is in minimal possible volume size. And the HTML is so lightweight.

ContentLicense: CC BY-SA 4.0


问:
iOS OTA download slow
Our enterprise app can be download and installed through OTA, but the download speed is really slow (about 20K per sec). In the meantime, the Android app deployed to the same server can download up to 150K per sec, not the expressive, but fair enough for most of the users.

I've tried to download the IPA file directly, the download speed is almost even as the Android version, that said, the file server and the bandwidth are fine for file downloading.

So the question is, why the iOS version deploy system (itms-service) is so slow? and how to improve it?

答: OK, finally found that it's bandwidth problem, but still don't know why the download of Android APK still much faster than iOS IPA a lot.</p>

Title: iOS OTA download slow


问:
How to start Windows service of client system from server system?
I have developed a windows service using C#.net. The purpose of this service is block an application. When ever serrvice starts the application will be blocked. Can I operate this service from server to start or stop in client system?</p>

答:
Try 'sc' command from the command prompt. As servers IP and services name use your own.

Starting service:

```<code>sc \\192.168.1.100 start MySQL
</code>```

Stopping service:

```<code>sc \\192.168.1.100 start MySQL
</code>```

More information here.

Body:
Try 'sc' command from the command prompt. As servers IP and services name use your own.

Starting service:

sc \\192.168.1.100 start MySQL

Stopping service:

sc \\192.168.1.100 start MySQL

More information here.


问:
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>```

答:
I changed selector id and it worked as you want. Check out the code below.</p>

```<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-bar').focus().val(jQuery('#search-bar').val());  // changed selector to "search-bar".
                }, 0);
            }
        });
    });
});
</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:
I changed selector id and it worked as you want. Check out the code below.

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-bar').focus().val(jQuery('#search-bar').val());  // changed selector to "search-bar".
                }, 0);
            }
        });
    });
});


问:
Tuple vs Class in Java
Are there any advantages of using Tuples instead of creating a new class in Java?
I've seen something like this a few times
return Pair.of (username, password);. And I've always wondered what kind of advantages it has in relation to something like this return new Credentials (username, password).

答:
As dimo414 says, the Pair class is often encountered in 3rd party libs; it has two advantages:

it makes defining a separate class for each key/value pairing unnecessary; so you don't need to define a Credential class. Of course, this should only be used to temporarily store data, not to be used within your implementation model.

Even if you do have a Credential class already, usually Pair is immutable, while the Credential class may not be. That means that it may provide setUsername() and setPassword() methods which you don't always want; using a Pair class makes sure both key and value remain unchanged.

Title: Tuple vs Class in Java


问:
The contents of a cloud function get request to firestore keep returning undefined
I'm trying to get access to the contents of a firestore document but i keep getting undefined. I suspect i'm referencing the document wrongly.
The variable updateId prints to the console correctly and is the value of a firebase auth id which represents a part of the path in firestore db ie users/fireauth_id.

In the document users/fireauth_id i have a field called token i'm trying to return but doc.data.token is always undefined. I did try using the path with .doc({updateId}) instead of doc(updateId) but no luck.

```<code> exports.updateRequest = functions.firestore
      .document('users/{userId}')
      .onUpdate(event => {

        var newValue = event.data.data();
        var updateId = newValue.update_id;

        return db.collection('users').doc(updateId).get().then(doc => {

              console.log("this doesn't work: %s", doc.data.token)
</code>```

Thanks.

答:
I think "doc.data.token" should be "doc.data().token"

If that's not the case, then I don't think the document you're trying to retrieve exists.

Body:
I'm trying to get access to the contents of a firestore document but i keep getting undefined. I suspect i'm referencing the document wrongly.
The variable updateId prints to the console correctly and is the value of a firebase auth id which represents a part of the path in firestore db ie users/fireauth_id.

In the document users/fireauth_id i have a field called token i'm trying to return but doc.data.token is always undefined. I did try using the path with .doc({updateId}) instead of doc(updateId) but no luck.

 exports.updateRequest = functions.firestore
      .document('users/{userId}')
      .onUpdate(event => {

        var newValue = event.data.data();
        var updateId = newValue.update_id;

        return db.collection('users').doc(updateId).get().then(doc => {

              console.log("this doesn't work: %s", doc.data.token)

Thanks.


问:
Prevent Jquery autocomplete options from closing after each selection
I am using Jquery UI's autocomplete for multiple selectable values. All is good except the list of options closes after each selection. I would like the options to stay open until the user decides they are done making selections. I have looked through the documentation and I don't see any way to keep the options open. Any ideas?</p>

```<code><meta charset="utf-8">

<script>
$(function() {
    var availableTags = [
        "ActionScript",
        "AppleScript",
        "Asp",
        "BASIC",
        "C",
        "C++",
        "Clojure",
        "COBOL",
        "ColdFusion",
        "Erlang",
        "Fortran",
        "Groovy",
        "Haskell",
        "Java",
        "JavaScript",
        "Lisp",
        "Perl",
        "PHP",
        "Python",
        "Ruby",
        "Scala",
        "Scheme"
    ];
    function split( val ) {
        return val.split( /,\s*/ );
    }
    function extractLast( term ) {
        return split( term ).pop();
    }

    $( "#tags" ).autocomplete({
        minLength: 0,
        source: function( request, response ) {
            // delegate back to autocomplete, but extract the last term
            response( $.ui.autocomplete.filter(
                availableTags, extractLast( request.term ) ) );
        },
        focus: function() {
            // prevent value inserted on focus
            return false;
        },
        select: function( event, ui ) {
            var terms = split( this.value );
            // remove the current input
            terms.pop();
            // add the selected item
            terms.push( ui.item.value );
            // add placeholder to get the comma-and-space at the end
            terms.push( "" );
            this.value = terms.join( ", " );
            return false;
        }
    });
});
</script>
</code>```

    Tag programming languages:

答:
i know this is old Question , But it still helpful,

Below is the solution for lattest version of jquery UI.

```<code>$.ui.autocomplete.prototype._close = function(e){
        return false;
};
</code>```

OP can modify this code according to his need.

Body:
I am using Jquery UI's autocomplete for multiple selectable values. All is good except the list of options closes after each selection. I would like the options to stay open until the user decides they are done making selections. I have looked through the documentation and I don't see any way to keep the options open. Any ideas?

<meta charset="utf-8">

    Tag programming languages:

Body:
i know this is old Question , But it still helpful,

Below is the solution for lattest version of jquery UI.

$.ui.autocomplete.prototype._close = function(e){
        return false;
};

OP can modify this code according to his need.


问:
openssl function to define cipher order
I have a light http server (embedded software solution). This http server is calling openssl functions to handle https connexions.

I want to make the https server prioritize some ciphers. because according to the following link, the https connection is more secure when the DH cipher are prioritized:

Instead of using the RSA method for exchanging session keys, you
  should use the Elliptic Curve Diffie-Hellman (ECDHE) key exchange.
  Note that you can still use the RSA public-key cryptosystem as the
  encryption algorithm, just not as the key exchange algorithm. ECDHE is
  much faster than ordinary DH (Diffie-Hellman), but both create session
  keys that only the entities involved in the SSL connection can access.
  Because the session keys are not linked to the server’s key pair, the
  server’s private key alone cannot be used to decrypt any SSL session.

To enable Perfect Forward Secrecy, you must do the following:

1- Reorder your cipher suites to place the ECDHE (Elliptic Curve
  Diffie-Hellman) suites at the top of list, followed by the DHE
  (Diffie-Hellman) suites.

2- Configure servers to enable other non-DH-key-exchange cipher
  suites from the list of cipher suites offered by the SSL Client.

How I can change the cipher order on my openssl server to make the DH ciphers first?

答:
From the OpenSSL documentation, the relevant function call here is SSL_set_cipher_list

The OpenSSL recommended string to use here is HIGH:!aNULL:!kRSA:!PSK:!SRP:!MD5:!RC4, since the !kRSA disables using RSA as the key exchange and forces the use of ephemeral DH, which provides the Perfect Forward Secrecy that you describe in your question.

As a disclaimer, the cipher string above may not be what is recommended today, it is just what is recommended in the OpenSSL documentation.

Title: openssl function to define cipher order


问:
is there any way to execute code before the observable emits any item? (for retrying purposes)
i want to retry an observable with its subscription. it all went good but now I'm trying to execute some code every time i retry this observable. any suggestions? </p>

```<code>observableItem.retry(1).subscribeWith(subscriber);
</code>```

答:
You can use retryWhen instead of retry.

```<code>observableItem
  .retryWhen(attempts -> {
     return attemps.flatMap(error -> {
       // TODO: Do what you want here...

       // If you return an Observable with an `onNext` event => retry
       // else if you return an Observable with an error => no retry
       return Observable.just(new Object());
     })
  })
  .subscribeWith(subscriber);
</code>```

Body:
i want to retry an observable with its subscription. it all went good but now I'm trying to execute some code every time i retry this observable. any suggestions?

observableItem.retry(1).subscribeWith(subscriber);

Body:
You can use retryWhen instead of retry.

observableItem
  .retryWhen(attempts -> {
     return attemps.flatMap(error -> {
       // TODO: Do what you want here...

       // If you return an Observable with an `onNext` event => retry
       // else if you return an Observable with an error => no retry
       return Observable.just(new Object());
     })
  })
  .subscribeWith(subscriber);


问:
WiFi broadcast receiver not delivering in Android 7.1.1
Using Android-7.1.1, SDK-25.3.0

I am having problems with the WiFi-broadcast-receiver. Until Android-7.0.x everything worked well. But now, having updated to Android-7.1.1. with its newest SDK, my WiFi-broadcast-receiver does not return any values anymore.

The List<ScanResult> resultList = wifi.getScanResults(); returns 0 (instead of like before some valuable values). Why is this ??? What could the Android-update have caused or is there any mistake in my code ?? Any help appreciated!

Below is my code:

Setting up the WiFi-broadcast-receiver inside the Fragment (not full fragment but excerts...):

```<code>public class ScanTeachingFragment extends Fragment implements MyWifiReceiver.OnWiFiResultListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        // set up WiFi Manager
        this.wifiManager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
        if (wifiManager.isWifiEnabled()) {
            // register Broadcast-Receiver for WiFi
            receiverWifi = new MyWifiReceiver(this.context);
            IntentFilter filterWiFi = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
            getActivity().registerReceiver(receiverWifi, filterWiFi);
        }
        // setListener necessary otherwise null-pointer occurs in WiFiReceiver
        receiverWifi.setListener(this);
    }

    private void ScanWifi() {

        if (!IndoorNavHelpers.inEmulator()) {
            wifiManager.setWifiEnabled(true);
            wifiManager.startScan();
        }
    }
}
</code>```

Here is the WiFi-broadcast-receiver implementation:

```<code>package com.xxxx.yyyy.broadcast_receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import java.util.List;

public class MyWifiReceiver extends BroadcastReceiver {

    private Context context;
    OnWiFiResultListener resultListener;

    // ScanFragment must implement this interface
    public interface OnWiFiResultListener {
        void scanWiFireceived(List<ScanResult> resultList);
    }
    // create setListener class (otherwise null-pointer occurs)
    public void setListener(OnWiFiResultListener listener) {
        this.resultListener = listener;
    }

    public MyWifiReceiver(Context context)
    {
        this.context = context;
    }
    // This method call when number of wifi connections changed
    public void onReceive(final Context context, Intent intent) {

        WifiManager wifi = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);
        List<ScanResult> resultList = wifi.getScanResults();

        // ???????????????????????????????????????????????????????????
        // Here resultList returns 0, WHY ????????????????????????????
        // ???????????????????????????????????????????????????????????

        // append newly found WiFi-scanResults to WiFiSniffing_File by calling callback-method in MainActivity
        if(resultListener != null) {
            resultListener.scanWiFireceived(resultList);
        }
    }
}
</code>```

Here is my gradle-file:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.xxxx.yyyy"
        minSdkVersion 25
        targetSdkVersion 25
        versionCode 1
        versionName "0.0.2(26)"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:25.3.0'
    compile 'com.android.support:support-v4:25.3.0'
    compile 'com.android.support:design:25.3.0'
    compile files('libs/ftp4j-1.7.2.jar')
    compile 'org.greenrobot:eventbus:3.0.0'
    compile 'com.github.johnkil.print:print:1.2.2'
    compile 'com.github.bmelnychuk:atv:1.2.+'
}
</code>```

Here is my manifest file:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.xxxx.yyyy">

    <uses-permission android:name="android.permission.USE_FINGERPRINT" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

    <uses-permission android:name="android.permission.android.permission.WAKE_LOCK" />

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/yyyy_icon"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:largeHeap="true">
        <activity
            android:name=".activity.MainActivity"
            android:launchMode="singleTop"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar"
            android:screenOrientation="portrait"
            android:excludeFromRecents="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
                <action android:name="android.hardware.usb.action.USB_DEVICE_DETATCHED" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" android:resource="@xml/device_filter" />
            <meta-data android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" android:resource="@xml/device_filter" />
        </activity>
    </application>

</manifest>
</code>```

答:
Turn on your GPS..

For Android 7 the permissions ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION are neccessary to get the Wi-Fi scan results. You also have to turn on location at device.

Body:
Using Android-7.1.1, SDK-25.3.0

I am having problems with the WiFi-broadcast-receiver. Until Android-7.0.x everything worked well. But now, having updated to Android-7.1.1. with its newest SDK, my WiFi-broadcast-receiver does not return any values anymore.

The List<ScanResult> resultList = wifi.getScanResults(); returns 0 (instead of like before some valuable values). Why is this ??? What could the Android-update have caused or is there any mistake in my code ?? Any help appreciated!

Below is my code:

Setting up the WiFi-broadcast-receiver inside the Fragment (not full fragment but excerts...):

public class ScanTeachingFragment extends Fragment implements MyWifiReceiver.OnWiFiResultListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        // set up WiFi Manager
        this.wifiManager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
        if (wifiManager.isWifiEnabled()) {
            // register Broadcast-Receiver for WiFi
            receiverWifi = new MyWifiReceiver(this.context);
            IntentFilter filterWiFi = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
            getActivity().registerReceiver(receiverWifi, filterWiFi);
        }
        // setListener necessary otherwise null-pointer occurs in WiFiReceiver
        receiverWifi.setListener(this);
    }

    private void ScanWifi() {

        if (!IndoorNavHelpers.inEmulator()) {
            wifiManager.setWifiEnabled(true);
            wifiManager.startScan();
        }
    }
}

Here is the WiFi-broadcast-receiver implementation:

package com.xxxx.yyyy.broadcast_receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import java.util.List;

public class MyWifiReceiver extends BroadcastReceiver {

    private Context context;
    OnWiFiResultListener resultListener;

    // ScanFragment must implement this interface
    public interface OnWiFiResultListener {
        void scanWiFireceived(List<ScanResult> resultList);
    }
    // create setListener class (otherwise null-pointer occurs)
    public void setListener(OnWiFiResultListener listener) {
        this.resultListener = listener;
    }

    public MyWifiReceiver(Context context)
    {
        this.context = context;
    }
    // This method call when number of wifi connections changed
    public void onReceive(final Context context, Intent intent) {

        WifiManager wifi = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);
        List<ScanResult> resultList = wifi.getScanResults();

        // ???????????????????????????????????????????????????????????
        // Here resultList returns 0, WHY ????????????????????????????
        // ???????????????????????????????????????????????????????????

        // append newly found WiFi-scanResults to WiFiSniffing_File by calling callback-method in MainActivity
        if(resultListener != null) {
            resultListener.scanWiFireceived(resultList);
        }
    }
}

Here is my gradle-file:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.xxxx.yyyy"
        minSdkVersion 25
        targetSdkVersion 25
        versionCode 1
        versionName "0.0.2(26)"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:25.3.0'
    compile 'com.android.support:support-v4:25.3.0'
    compile 'com.android.support:design:25.3.0'
    compile files('libs/ftp4j-1.7.2.jar')
    compile 'org.greenrobot:eventbus:3.0.0'
    compile 'com.github.johnkil.print:print:1.2.2'
    compile 'com.github.bmelnychuk:atv:1.2.+'
}

Here is my manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.xxxx.yyyy">

    <uses-permission android:name="android.permission.USE_FINGERPRINT" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

    <uses-permission android:name="android.permission.android.permission.WAKE_LOCK" />

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/yyyy_icon"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:largeHeap="true">
        <activity
            android:name=".activity.MainActivity"
            android:launchMode="singleTop"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar"
            android:screenOrientation="portrait"
            android:excludeFromRecents="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
                <action android:name="android.hardware.usb.action.USB_DEVICE_DETATCHED" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" android:resource="@xml/device_filter" />
            <meta-data android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" android:resource="@xml/device_filter" />
        </activity>
    </application>

</manifest>


问:
jquery : show/hide div, timing
I have a pretty standard problem here.

I have an error div that,

when a button is pressed is populated with an error message,
the div is then faded in, after (500*n)ms (where n = number of letters) the div is faded out.

my issue occurs when the user presses the button again before the div has faded out.

while the div is still visible the divs contents are updated with the new error message,

after the initial (500*n)ms the div is faded out, then immediately gets faded back in and is visible for another (500*n)ms.

What I want is.

user clicks button

div contents are updated

div is faded in

user clicks button again

div immediately fades out

content is updated

div is faded in.

How can I achieve this?

My current code is below

```<code>function login_error(message){
        $('form').effect('shake', { times: 1 }, 50);
        $('#error').html(message).fadeIn('fast').delay(500*message.length).fadeOut('fast');
}
</code>```

答: Another solution would be that after clicking the button you can disable it and with the div finishes/the animation is done you can enable it back.</p>

Title: jquery : show/hide div, timing

Body:
I have a pretty standard problem here.

I have an error div that,

when a button is pressed is populated with an error message,
the div is then faded in, after (500*n)ms (where n = number of letters) the div is faded out.

my issue occurs when the user presses the button again before the div has faded out.

while the div is still visible the divs contents are updated with the new error message,

after the initial (500*n)ms the div is faded out, then immediately gets faded back in and is visible for another (500*n)ms.

What I want is.

user clicks button

div contents are updated

div is faded in

user clicks button again

div immediately fades out

content is updated

div is faded in.

How can I achieve this?

My current code is below

function login_error(message){
        $('form').effect('shake', { times: 1 }, 50);
        $('#error').html(message).fadeIn('fast').delay(500*message.length).fadeOut('fast');
}


问:
how to include https to restart service on https ping result
Hi I would like to to a https request on my server.  How can I include https to do get the response?  I want to restart the server if I get a https code result that is not 200. Here is my source code

```<code>@set @x=0 /*
:: ChkHTTP.cmd
@echo off
setlocal
set "URL=https://localhost:8080/ping.xhtml"
cscript /nologo /e:jscript "%~f0" %URL% | find "200"  > nul
echo going to check error
if %ErrorLevel% EQU 0 (
echo Web server ok
) else (
echo Weber server not ok
echo kill task and then restart service
)
JScript */
var x=new ActiveXObject("Msxml2.ServerXMLHTTP.6.0");
x.setOption(2,13056);
x.open("GET",WSH.Arguments(0));x.send();
while (x.ReadyState!=4)  {WSH.Sleep(15000)};
WSH.Echo(x.status);
</code>```

It will wait for 15 seconds before it runs.  But it runs forever if its https?

I want to ignore SSL errors

答: It wont be possible to ignore the SSL Errors due to the fact that it runs on https. Alternative run it on the server with http example: http://localhost</p>

Body:
Hi I would like to to a https request on my server.  How can I include https to do get the response?  I want to restart the server if I get a https code result that is not 200. Here is my source code

@set @x=0 /*
:: ChkHTTP.cmd
@echo off
setlocal
set "URL=https://localhost:8080/ping.xhtml"
cscript /nologo /e:jscript "%~f0" %URL% | find "200"  > nul
echo going to check error
if %ErrorLevel% EQU 0 (
echo Web server ok
) else (
echo Weber server not ok
echo kill task and then restart service
)
JScript */
var x=new ActiveXObject("Msxml2.ServerXMLHTTP.6.0");
x.setOption(2,13056);
x.open("GET",WSH.Arguments(0));x.send();
while (x.ReadyState!=4)  {WSH.Sleep(15000)};
WSH.Echo(x.status);

It will wait for 15 seconds before it runs.  But it runs forever if its https?

I want to ignore SSL errors


问:
after redirect - is there a way to remove the form field from the URL in Django?
After sending a form, i'm redirected to another page.

The URL of that page will contain the URL + form field name + form field value.

Is there a way to redirect (or maybe manipulating data without redirect) in a way that the URL won't show the form field name and value?

my project (no apps):

urls.py

```<code>from django.conf.urls import url
from . import views

urlpatterns = [

url(r'^$', views.home, name='home'),
url(r'^translate/', views.translate, name='translate'),

]
</code>```

views.py

```<code>from django.shortcuts import render

def home(request):
    return render(request, 'hello.html')

def translate(request):

original = request.GET['originaltext'].lower()
translation = ''
for word in original.split():
    if word[0] in ['a','e','i','o','u']:
        translation += word
        translation +='yay '
    else:
        translation += word[1:]
        translation += word[0]
        translation += 'ay '

return render(request, 'translate.html', {'original':original,
'translate':translation})
</code>```

hello.html

```<code><h1> heading title </h1>

<form action="{% url 'translate' %}">
  <input type="text" name="originaltext"/>
  <br/>
  <input type="submit" value="Translate" />
</form>
</code>```

translate.html

```<code>{{ original }} <br>
{{ translate }}
<br><br>
<a href="{% url 'home' %}">Home</a>
</code>```

So whenever i'm sending the form, i'm redirected and the URL becomes:

http://127.0.0.1:8000/translate/?originaltext=user_text

答:
Maybe try to send POST request from your form:

```<code><form action="{% url 'translate' %}" method="POST">{% csrf_token %}
<input type="text" name="originaltext"/>
<br/>
<input type="submit" value="Translate" />
</form>
</code>```

In your view:

```<code>def translate(request):
    context = {}
    if request.method == 'POST':
        original = request.POST.get('originaltext').lower()
        context['original'] = original
        translation = ''
        for word in original.split():
            if word[0] in ['a','e','i','o','u']:
                translation += word
                translation +='yay '
            else:
                translation += word[1:]
                translation += word[0]
                translation += 'ay '
        context['translation'] = translation
    return render(request, 'translate.html', context)
</code>```

Body:
After sending a form, i'm redirected to another page.

The URL of that page will contain the URL + form field name + form field value.

Is there a way to redirect (or maybe manipulating data without redirect) in a way that the URL won't show the form field name and value?

my project (no apps):

urls.py

from django.conf.urls import url
from . import views

urlpatterns = [

url(r'^$', views.home, name='home'),
url(r'^translate/', views.translate, name='translate'),

]

views.py

from django.shortcuts import render

def home(request):
    return render(request, 'hello.html')

def translate(request):

original = request.GET['originaltext'].lower()
translation = ''
for word in original.split():
    if word[0] in ['a','e','i','o','u']:
        translation += word
        translation +='yay '
    else:
        translation += word[1:]
        translation += word[0]
        translation += 'ay '

return render(request, 'translate.html', {'original':original,
'translate':translation})

hello.html

 heading title

<form action="{% url 'translate' %}">
  <input type="text" name="originaltext"/>

  <input type="submit" value="Translate" />
</form>

translate.html

{{ original }}

{{ translate }}

Home

So whenever i'm sending the form, i'm redirected and the URL becomes:

http://127.0.0.1:8000/translate/?originaltext=user_text

Body:
Maybe try to send POST request from your form:

<form action="{% url 'translate' %}" method="POST">{% csrf_token %}
<input type="text" name="originaltext"/>
<br/>
<input type="submit" value="Translate" />
</form>

In your view:

def translate(request):
    context = {}
    if request.method == 'POST':
        original = request.POST.get('originaltext').lower()
        context['original'] = original
        translation = ''
        for word in original.split():
            if word[0] in ['a','e','i','o','u']:
                translation += word
                translation +='yay '
            else:
                translation += word[1:]
                translation += word[0]
                translation += 'ay '
        context['translation'] = translation
    return render(request, 'translate.html', context)


问:
How can I align multiple plots by their titles instead of plot area?
I'm using egg to align multiple plots on a page. I'm wondering if it's possible to align two columns by the titles a) and c) instead of plot area? Thanks!

Code:

```<code>library(egg)
library(grid)

p1 <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) +
  geom_point() + ggtitle("a)")
p1

p2 <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) +
  geom_point() + facet_wrap(~ cyl, ncol = 2, scales = "free") +
  guides(colour = "none") +
  theme() + ggtitle("b)")
p2

p3 <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) +
  geom_point() + facet_grid(. ~ am, scales = "free") + guides(colour="none") +
  ggtitle("c)")
p3

g1 <- ggplotGrob(p1)

g2 <- ggplotGrob(p2)

g3 <- ggplotGrob(p3)

fg1 <- gtable_frame(g1, debug = TRUE)
fg2 <- gtable_frame(g2, debug = TRUE)
fg12 <- gtable_frame(gtable_rbind(fg1, fg2),
                     width = unit(2, "null"),
                     height = unit(1, "null"))
fg3 <-
  gtable_frame(
    g3,
    width = unit(2, "null"),
    height = unit(1, "null"),
    debug = TRUE
  )
grid.newpage()
combined <- gtable_cbind(fg12, fg3)
grid.draw(combined)
</code>```

Plot:

答:
I found another way by using cowplot package

```<code>left_col <- cowplot::plot_grid(p1 + ggtitle(""), p2 + ggtitle(""),
                               labels = c('a)', 'b)'), label_size = 14,
                               ncol = 1, align = 'v', axis = 'lr')
cowplot::plot_grid(left_col, p3 + ggtitle(""),
                   labels = c('', 'c)'), label_size = 14,
                   align = 'h', axis = 'b')
</code>```

See also here

Edit:

A recently developed package patchwork for ggplot2 can also get the job done

```<code>library(patchwork)

{
  p1 + {p2} + patchwork::plot_layout(ncol = 1)
} / p3 + patchwork::plot_layout(ncol = 2)
</code>```

Body:
I'm using egg to align multiple plots on a page. I'm wondering if it's possible to align two columns by the titles a) and c) instead of plot area? Thanks!

Code:

library(egg)
library(grid)

p1 <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) +
  geom_point() + ggtitle("a)")
p1

p2 <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) +
  geom_point() + facet_wrap(~ cyl, ncol = 2, scales = "free") +
  guides(colour = "none") +
  theme() + ggtitle("b)")
p2

p3 <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) +
  geom_point() + facet_grid(. ~ am, scales = "free") + guides(colour="none") +
  ggtitle("c)")
p3

g1 <- ggplotGrob(p1)

g2 <- ggplotGrob(p2)

g3 <- ggplotGrob(p3)

fg1 <- gtable_frame(g1, debug = TRUE)
fg2 <- gtable_frame(g2, debug = TRUE)
fg12 <- gtable_frame(gtable_rbind(fg1, fg2),
                     width = unit(2, "null"),
                     height = unit(1, "null"))
fg3 <-
  gtable_frame(
    g3,
    width = unit(2, "null"),
    height = unit(1, "null"),
    debug = TRUE
  )
grid.newpage()
combined <- gtable_cbind(fg12, fg3)
grid.draw(combined)

Plot:

Body:
I found another way by using cowplot package

left_col <- cowplot::plot_grid(p1 + ggtitle(""), p2 + ggtitle(""),
                               labels = c('a)', 'b)'), label_size = 14,
                               ncol = 1, align = 'v', axis = 'lr')
cowplot::plot_grid(left_col, p3 + ggtitle(""),
                   labels = c('', 'c)'), label_size = 14,
                   align = 'h', axis = 'b')

See also here

Edit:

A recently developed package patchwork for ggplot2 can also get the job done

library(patchwork)

{
  p1 + {p2} + patchwork::plot_layout(ncol = 1)
} / p3 + patchwork::plot_layout(ncol = 2)