Programs & Examples On #Android listview

A subclass of AdapterView which shows items in a vertically scrolling list.

Remove ListView items in Android

            names = db.getSites();
            la = new ArrayAdapter<String>(EditSiteList.this,
                    android.R.layout.simple_list_item_1, names);
            EditSiteList.this.setListAdapter(la);
            listview.invalidateViews();

this code works fine for me.

Focusable EditText inside ListView

In my case, there is 14 input edit text in the list view. The problem I was facing, when the keyboard open, edit text focus lost, scroll the layout, and as soon as focused view not visible to the user keyboard down. It was not good for the user experience. I can't use windowSoftInputMethod="adjustPan". So after so much searching, I found a link that inflates custom layout and sets data on view as an adapter by using LinearLayout and scrollView and work well for my case.

how to implement a long click listener on a listview

You have to set setOnItemLongClickListener() in the ListView:

lv.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                    int pos, long id) {
                // TODO Auto-generated method stub

                Log.v("long clicked","pos: " + pos);

                return true;
            }
        }); 

The XML for each item in the list (should you use a custom XML) must have android:longClickable="true" as well (or you can use the convenience method lv.setLongClickable(true);). This way you can have a list with only some items responding to longclick.

Hope this will help you.

Custom Listview Adapter with filter Android

I hope it will be helpful for others.

// put below code (method) in Adapter class
public void filter(String charText) {
    charText = charText.toLowerCase(Locale.getDefault());
    myList.clear();
    if (charText.length() == 0) {
        myList.addAll(arraylist);
    }
    else
    {
        for (MyBean wp : arraylist) {
            if (wp.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
                myList.add(wp);
            }
        }
    }
    notifyDataSetChanged();
}

declare below code in adapter class

private ArrayList<MyBean> myList;  // for loading main list
private ArrayList<MyBean> arraylist=null;  // for loading  filter data

below code in adapter Constructor

this.arraylist = new ArrayList<MyBean>();
    this.arraylist.addAll(myList);

and below code in your activity class

final EditText searchET = (EditText)findViewById(R.id.search_et);
    // Capture Text in EditText
    searchET.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub
            String text = searchET.getText().toString().toLowerCase(Locale.getDefault());
            adapter.filter(text);
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1,
                                      int arg2, int arg3) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                  int arg3) {
            // TODO Auto-generated method stub
        }
    });

Converting JSONarray to ArrayList

To make it handy, use POJO.

try like this..

List<YourPojoObject> yourPojos = new ArrayList<YourPojoObject>();

JSONObject jsonObject = new JSONObject(jsonString);
YourPojoObject yourPojo = new YourPojoObject();
yourPojo.setId(jsonObject.getString("idName"));
...
...

yourPojos.add(yourPojo);

How can I put a ListView into a ScrollView without it collapsing?

There are plenty of situations where it makes a lot of sense to have ListView's in a ScrollView.

Here's code based on DougW's suggestion... works in a fragment, takes less memory.

public static void setListViewHeightBasedOnChildren(ListView listView) {
    ListAdapter listAdapter = listView.getAdapter();
    if (listAdapter == null) {
        return;
    }
    int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
    int totalHeight = 0;
    View view = null;
    for (int i = 0; i < listAdapter.getCount(); i++) {
        view = listAdapter.getView(i, view, listView);
        if (i == 0) {
            view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, LayoutParams.WRAP_CONTENT));
        }
        view.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
        totalHeight += view.getMeasuredHeight();
    }
    ViewGroup.LayoutParams params = listView.getLayoutParams();
    params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
    listView.setLayoutParams(params);
    listView.requestLayout();
}

call setListViewHeightBasedOnChildren(listview) on each embedded listview.

Android ListView Selector Color

The list selector drawable is a StateListDrawable — it contains reference to multiple drawables for each state the list can be, like selected, focused, pressed, disabled...

While you can retrieve the drawable using getSelector(), I don't believe you can retrieve a specific Drawable from a StateListDrawable, nor does it seem possible to programmatically retrieve the colour directly from a ColorDrawable anyway.

As for setting the colour, you need a StateListDrawable as described above. You can set this on your list using the android:listSelector attribute, defining the drawable in XML like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_enabled="false" android:state_focused="true"
        android:drawable="@drawable/item_disabled" />
  <item android:state_pressed="true"
        android:drawable="@drawable/item_pressed" />
  <item android:state_focused="true"
        android:drawable="@drawable/item_focused" />
</selector>

How to set space between listView Items in Android

<ListView
    android:clipToPadding="false"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:dividerHeight="10dp"
    android:divider="@null"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</ListView>

and set paddingTop, paddingBottom and dividerHeight to the same value to get equal spacing between all elements and space at the top and bottom of the list.

I set clipToPadding to false to let the views be drawn in this padded area.

I set divider to @null to remove the lines between list elements.

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

it sometimes occurs when we use a custom adapter in any activity of fragment . and we return null object i.e null view so the activity gets confused which view to load , so that is why this exception occurs

shows the position where to change the view

android - listview get item view by position

Use this :

public View getViewByPosition(int pos, ListView listView) {
    final int firstListItemPosition = listView.getFirstVisiblePosition();
    final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;

    if (pos < firstListItemPosition || pos > lastListItemPosition ) {
        return listView.getAdapter().getView(pos, null, listView);
    } else {
        final int childIndex = pos - firstListItemPosition;
        return listView.getChildAt(childIndex);
    }
}

Maintain/Save/Restore scroll position when returning to a ListView

If you are saving/restoring scroll position of ListView yourself you are essentially duplicating the functionality already implemented in android framework. The ListView restores fine scroll position just well on its own except one caveat: as @aaronvargas mentioned there is a bug in AbsListView that won't let to restore fine scroll position for the first list item. Nevertheless the best way to restore scroll position is not to restore it. Android framework will do it better for you. Just make sure you have met the following conditions:

  • make sure you have not called setSaveEnabled(false) method and not set android:saveEnabled="false" attribute for the list in the xml layout file
  • for ExpandableListView override long getCombinedChildId(long groupId, long childId) method so that it returns positive long number (default implementation in class BaseExpandableListAdapter returns negative number). Here are examples:

.

@Override
public long getChildId(int groupPosition, int childPosition) {
    return 0L | groupPosition << 12 | childPosition;
}

@Override
public long getCombinedChildId(long groupId, long childId) {
    return groupId << 32 | childId << 1 | 1;
}

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

@Override
public long getCombinedGroupId(long groupId) {
    return (groupId & 0x7FFFFFFF) << 32;
}
  • if ListView or ExpandableListView is used in a fragment do not recreate the fragment on activity recreation (after screen rotation for example). Obtain the fragment with findFragmentByTag(String tag) method.
  • make sure the ListView has an android:id and it is unique.

To avoid aforementioned caveat with first list item you can craft your adapter the way it returns special dummy zero pixels height view for the ListView at position 0. Here is the simple example project shows ListView and ExpandableListView restore their fine scroll positions whereas their scroll positions are not explicitly saved/restored. Fine scroll position is restored perfectly even for the complex scenarios with temporary switching to some other application, double screen rotation and switching back to the test application. Please note, if you are explicitly exiting the application (by pressing the Back button) the scroll position won't be saved (as well as all other Views won't save their state). https://github.com/voromto/RestoreScrollPosition/releases

List View Filter Android

In case anyone are still interested in this subject, I find that the best approach for filtering lists is to create a generic Filter class and use it with some base reflection/generics techniques contained in the Java old school SDK package. Here's what I did:

public class GenericListFilter<T> extends Filter {

    /**
     * Copycat constructor
     * @param list  the original list to be used
     */
    public GenericListFilter (List<T> list, String reflectMethodName, ArrayAdapter<T> adapter) {
        super ();

        mInternalList = new ArrayList<>(list);
        mAdapterUsed  = adapter;

        try {
            ParameterizedType stringListType = (ParameterizedType)
                    getClass().getField("mInternalList").getGenericType();
            mCompairMethod =
                    stringListType.getActualTypeArguments()[0].getClass().getMethod(reflectMethodName);
        }
        catch (Exception ex) {
            Log.w("GenericListFilter", ex.getMessage(), ex);

            try {
                if (mInternalList.size() > 0) {
                    T type = mInternalList.get(0);
                    mCompairMethod = type.getClass().getMethod(reflectMethodName);
                }
            }
            catch (Exception e) {
                Log.e("GenericListFilter", e.getMessage(), e);
            }

        }
    }

    /**
     * Let's filter the data with the given constraint
     * @param constraint
     * @return
     */
    @Override protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults results = new FilterResults();
        List<T> filteredContents = new ArrayList<>();

        if ( constraint.length() > 0 ) {
            try {
                for (T obj : mInternalList) {
                    String result = (String) mCompairMethod.invoke(obj);
                    if (result.toLowerCase().startsWith(constraint.toString().toLowerCase())) {
                        filteredContents.add(obj);
                    }
                }
            }
            catch (Exception ex) {
                Log.e("GenericListFilter", ex.getMessage(), ex);
            }
        }
        else {
            filteredContents.addAll(mInternalList);
        }

        results.values = filteredContents;
        results.count  = filteredContents.size();
        return results;
    }

    /**
     * Publish the filtering adapter list
     * @param constraint
     * @param results
     */
    @Override protected void publishResults(CharSequence constraint, FilterResults results) {
        mAdapterUsed.clear();
        mAdapterUsed.addAll((List<T>) results.values);

        if ( results.count == 0 ) {
            mAdapterUsed.notifyDataSetInvalidated();
        }
        else {
            mAdapterUsed.notifyDataSetChanged();
        }
    }

    // class properties
    private ArrayAdapter<T> mAdapterUsed;
    private List<T> mInternalList;
    private Method  mCompairMethod;
}

And afterwards, the only thing you need to do is to create the filter as a member class (possibly within the View's "onCreate") passing your adapter reference, your list, and the method to be called for filtering:

this.mFilter = new GenericFilter<MyObjectBean> (list, "getName", adapter);

The only thing missing now, is to override the "getFilter" method in the adapter class:

@Override public Filter getFilter () {
     return MyViewClass.this.mFilter;
}

All done! You should successfully filter your list - Of course, you should also implement your filter algorithm the best way that describes your need, the code bellow is just an example.. Hope it helped, take care.

How do I create a ListView with rounded corners in Android?

The other answers are very useful, thanks to the authors!

But I could not see how to customise the rectangle when highlighting an item upon selection rather than disabling the highlighting @alvins @bharat dojeha.

The following works for me to create a rounded list view item container with no outline and a lighter grey when selected of the same shape:

Your xml needs to contain a selector such as e.g. ( in res/drawable/customshape.xml):

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" >
    <shape xmlns:android="http://schemas.android.com/apk/res/android" >
        <stroke android:width="8dp" android:color="@android:color/transparent" />
        <padding android:left="14dp" android:top="14dp"
                android:right="14dp" android:bottom="14dp" />
        <corners android:radius="10dp" />
        <gradient 
             android:startColor="@android:color/background_light"
             android:endColor="@android:color/transparent" 
             android:angle="225"/> 
    </shape>
</item>
<item android:state_pressed="false">
    <shape xmlns:android="http://schemas.android.com/apk/res/android" >
        <stroke android:width="8dp" android:color="@android:color/transparent" />
        <padding android:left="14dp" android:top="14dp"
                android:right="14dp" android:bottom="14dp" />
        <corners android:radius="10dp" />
        <gradient 
             android:startColor="@android:color/darker_gray"
             android:endColor="@android:color/transparent" 
             android:angle="225"/> 
    </shape>        
</item>

Then you need to implement a list adapter and override the getView method to set the custom selector as background

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //snip
        convertView.setBackgroundResource(R.drawable.customshape);
        //snip
    }

and need to also 'hide' the default selector rectangle e.g in onCreate (I also hide my thin grey divider line between the items):

listView.setSelector(android.R.color.transparent);
listview.setDivider(null);

This approach solves a general solution for drawables, not just ListViewItem with various selection states.

how to show progress bar(circle) in an activity having a listview before loading the listview with data

I am using this:

loading = ProgressDialog.show(example.this,"",null, true, true);

How to make android listview scrollable?

Practically its not good to do. But if you want to do like this, just make listview's height fixed to wrap_content.

android:layout_height="wrap_content"

CardView not showing Shadow in Android L

check hardwareAccelerated in manifest make it true , making it false removes shadows , when false shadow appears in xml preview but not in phone .

Android custom Row Item for ListView

Add this row.xml to your layout folder

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
<TextView android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Header"/>

<TextView 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/text"/>
    
    
</LinearLayout>

make your main xml layout as this

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <ListView
        android:id="@+id/listview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
    </ListView>

</LinearLayout>

This is your adapter

class yourAdapter extends BaseAdapter {

    Context context;
    String[] data;
    private static LayoutInflater inflater = null;

    public yourAdapter(Context context, String[] data) {
        // TODO Auto-generated constructor stub
        this.context = context;
        this.data = data;
        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return data.length;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return data[position];
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View vi = convertView;
        if (vi == null)
            vi = inflater.inflate(R.layout.row, null);
        TextView text = (TextView) vi.findViewById(R.id.text);
        text.setText(data[position]);
        return vi;
    }
}

Your java activity

public class StackActivity extends Activity {

    ListView listview;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        listview = (ListView) findViewById(R.id.listview);
        listview.setAdapter(new yourAdapter(this, new String[] { "data1",
                "data2" }));
    }
}

the results

enter image description here

How to refresh Android listview?

You need to use a single object of that list whoose data you are inflating on ListView. If reference is change then notifyDataSetChanged() does't work .Whenever You are deleting elements from list view also delete them from the list you are using whether it is a ArrayList<> or Something else then Call notifyDataSetChanged() on object of Your adapter class.

So here see how i managed it in my adapter see below

public class CountryCodeListAdapter extends BaseAdapter implements OnItemClickListener{

private Context context;
private ArrayList<CountryDataObject> dObj;
private ViewHolder holder;
private Typeface itemFont;
private int selectedPosition=-1;
private ArrayList<CountryDataObject> completeList;

public CountryCodeListAdapter(Context context, ArrayList<CountryDataObject> dObj) {
    this.context = context;
    this.dObj=dObj;
    completeList=new  ArrayList<CountryDataObject>();
    completeList.addAll(dObj);
    itemFont=Typeface.createFromAsset(context.getAssets(), "CaviarDreams.ttf");
}

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

@Override
public Object getItem(int position) {
    return dObj.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
    if(view==null){
        holder = new ViewHolder();
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.states_inflator_layout, null);
        holder.textView = ((TextView)view.findViewById(R.id.stateNameInflator));
        holder.checkImg=(ImageView)view.findViewById(R.id.checkBoxState);
        view.setTag(holder);
    }else{
        holder = (ViewHolder) view.getTag();
    }
    holder.textView.setText(dObj.get(position).getCountryName());
    holder.textView.setTypeface(itemFont);

    if(position==selectedPosition)
     {
         holder.checkImg.setImageResource(R.drawable.check);
     }
     else
     {
         holder.checkImg.setImageResource(R.drawable.uncheck);
     }
    return view;
}
private class ViewHolder{
    private TextView textView;
    private ImageView checkImg;
}

public void getFilter(String name) {
    dObj.clear();
    if(!name.equals("")){
    for (CountryDataObject item : completeList) {
        if(item.getCountryName().toLowerCase().startsWith(name.toLowerCase(),0)){
            dObj.add(item);
        }
    }
    }
    else {
        dObj.addAll(completeList);
    }
    selectedPosition=-1;
    notifyDataSetChanged();
    notifyDataSetInvalidated(); 
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {
    Registration reg=(Registration)context;
    selectedPosition=position;
    reg.setSelectedCountryCode("+"+dObj.get(position).getCountryCode());
    notifyDataSetChanged();
}
}

How can I update a single row in a ListView?

This question has been asked at the Google I/O 2010, you can watch it here:

The world of ListView, time 52:30

Basically what Romain Guy explains is to call getChildAt(int) on the ListView to get the view and (I think) call getFirstVisiblePosition() to find out the correlation between position and index.

Romain also points to the project called Shelves as an example, I think he might mean the method ShelvesActivity.updateBookCovers(), but I can't find the call of getFirstVisiblePosition().

AWESOME UPDATES COMING:

The RecyclerView will fix this in the near future. As pointed out on http://www.grokkingandroid.com/first-glance-androids-recyclerview/, you will be able to call methods to exactly specify the change, such as:

void notifyItemInserted(int position)
void notifyItemRemoved(int position)
void notifyItemChanged(int position)

Also, everyone will want to use the new views based on RecyclerView because they will be rewarded with nicely-looking animations! The future looks awesome! :-)

Using ListView : How to add a header view?

You simply can't use View as a Header of ListView.

Because the view which is being passed in has to be inflated.

Look at my answer at Android ListView addHeaderView() nullPointerException for predefined Views for more info.

EDIT:

Look at this tutorial Android ListView and ListActivity - Tutorial .

EDIT 2: This link is broken Android ListActivity with a header or footer

Your content must have a ListView whose id attribute is 'android.R.id.list'

Exact way I fixed this based on feedback above since I couldn't get it to work at first:

activity_main.xml:

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

MainActivity.java:

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

preferences.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory
    android:key="upgradecategory"
    android:title="Upgrade" >
    <Preference
        android:key="download"
        android:title="Get OnCall Pager Pro"
        android:summary="Touch to download the Pro Version!" />
</PreferenceCategory>
</PreferenceScreen>

ListView with Add and Delete Buttons in each Row in android

You will first need to create a custom layout xml which will represent a single item in your list. You will add your two buttons to this layout along with any other items you want to display from your list.

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

<TextView
    android:id="@+id/list_item_string"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_alignParentLeft="true"
    android:paddingLeft="8dp"
    android:textSize="18sp"
    android:textStyle="bold" /> 

<Button
    android:id="@+id/delete_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:layout_marginRight="5dp"
    android:text="Delete" /> 

<Button
    android:id="@+id/add_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toLeftOf="@id/delete_btn"
    android:layout_centerVertical="true"
    android:layout_marginRight="10dp"
    android:text="Add" />

</RelativeLayout>

Next you will need to create a Custom ArrayAdapter Class which you will use to inflate your xml layout, as well as handle your buttons and on click events.

public class MyCustomAdapter extends BaseAdapter implements ListAdapter { 
private ArrayList<String> list = new ArrayList<String>(); 
private Context context; 



public MyCustomAdapter(ArrayList<String> list, Context context) { 
    this.list = list; 
    this.context = context; 
} 

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

@Override
public Object getItem(int pos) { 
    return list.get(pos); 
} 

@Override
public long getItemId(int pos) { 
    return list.get(pos).getId();
    //just return 0 if your list items do not have an Id variable.
} 

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View view = convertView;
    if (view == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
        view = inflater.inflate(R.layout.my_custom_list_layout, null);
    } 

    //Handle TextView and display string from your list
    TextView listItemText = (TextView)view.findViewById(R.id.list_item_string); 
    listItemText.setText(list.get(position)); 

    //Handle buttons and add onClickListeners
    Button deleteBtn = (Button)view.findViewById(R.id.delete_btn);
    Button addBtn = (Button)view.findViewById(R.id.add_btn);

    deleteBtn.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) { 
            //do something
            list.remove(position); //or some other task
            notifyDataSetChanged();
        }
    });
    addBtn.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) { 
            //do something
            notifyDataSetChanged();
        }
    });

    return view; 
} 
}

Finally, in your activity you can instantiate your custom ArrayAdapter class and set it to your listview.

public class MyActivity extends Activity { 

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

    //generate list
    ArrayList<String> list = new ArrayList<String>();
    list.add("item1");
    list.add("item2");

    //instantiate custom adapter
    MyCustomAdapter adapter = new MyCustomAdapter(list, this);

    //handle listview and assign adapter
    ListView lView = (ListView)findViewById(R.id.my_listview);
    lView.setAdapter(adapter);
}

Hope this helps!

Swipe ListView item From right to left show delete button

Define a ViewPager in your layout .xml:

<android.support.v4.view.ViewPager
    android:id="@+id/example_pager"
    android:layout_width="fill_parent"
    android:layout_height="@dimen/abc_action_bar_default_height" />

And then, in your activity / fragment, set a custom pager adapter:

In an activity:

protected void onCreate(Bundle savedInstanceState) {
    PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager());
    ViewPager pager = (ViewPager) findViewById(R.id.example_pager);

    pager.setAdapter(adapter);
    // pager.setOnPageChangeListener(this); // You can set a page listener here
    pager.setCurrentItem(0);
}

In a fragment:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_layout, container, false);

    if (view != null) {
        PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager());
        ViewPager pager = (ViewPager) view.findViewById(R.id.example_pager);

        pager.setAdapter(adapter);
        // pager.setOnPageChangeListener(this); // You can set a page listener here
        pager.setCurrentItem(0);
    }

    return view;
}

Create our custom pager class:

// setup your PagerAdapter which extends FragmentPagerAdapter
class PagerAdapter extends FragmentPagerAdapter {
    public static final int NUM_PAGES = 2;
    private CustomFragment[] mFragments = new CustomFragment[NUM_PAGES];
    public PagerAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
    }
    @ Override
    public int getCount() {
        return NUM_PAGES;
    }
    @ Override
    public Fragment getItem(int position) {
        if (mFragments[position] == null) {
               // this calls the newInstance from when you setup the ListFragment
            mFragments[position] = new CustomFragment();
        }
        return mFragments[position];
    }
}

Add Items to ListView - Android

public OnClickListener moreListener = new OnClickListener() {

    @Override
      public void onClick(View v) {
          adapter.add("aaaa")
      }
}

How to implement Android Pull-to-Refresh

We should first know what is Pull to refresh layout in android . we can call pull to refresh in android as swipe-to-refresh. when you swipe screen from top to bottom it will do some action based on setOnRefreshListener.

Here's tutorial that demonstrate about how to implement android pull to refresh. I hope this helps.

Android: disabling highlight on listView click

add this also to ur XMl along with listselector..hope it will work

<ListView
android:cacheColorHint="@android:color/transparent"
android:listSelector="@android:color/transparent"/> 

How to create a custom navigation drawer in android

I need to add a header to categorize the list item in Drawer

Customize the listView or use expandableListView

I need a radio button to select some of my options

You can do that without modifying the current implementation of NavigationDrawer, You just need to create a custom adapter for your listView. You can add a parent layout as Drawer then you can do any complex layouts within that as normal.

Programmatically scroll to a specific position in an Android ListView

The Listview scroll will be positioned to top by default, but want to scroll if not visible then use this:

if (listView1.getFirstVisiblePosition() > position || listView1.getLastVisiblePosition() < position)
            listView1.setSelection(position);

Android ListView selected item stay highlighted

I found the proper way. It's very simple. In resource describe following:

android:choiceMode="singleChoice"
android:listSelector="#666666"

(or you may specify a resource link instead of color value)

Programmatical:

listView.setSelector(Drawable selector);
listView.setSelector(int resourceId);
listView.setChoiceMode(int mode);

mode can be one of these: AbsListView.CHOICE_MODE_SINGLE, AbsListView.CHOICE_MODE_MULTIPLE, AbsListView.CHOICE_MODE_NONE (default)

(AbsListView is the abstract ancestor for the ListView class)

P.S. manipulations with onItemClick and changing view background are bankrupt, because a view itself is a temporary object. Hence you must not to track a view.

If our list is long enough, the views associated with scrolled out items will be removed from hierarchy, and will be recreated when those items will shown again (with cached display options, such as background). So, the view we have tracked is now not an actual view of the item, and changing its background does nothing to the actual item view. As a result we have multiple items selected.

Android ListView not refreshing after notifyDataSetChanged

Try like this:

this.notifyDataSetChanged();

instead of:

adapter.notifyDataSetChanged();

You have to notifyDataSetChanged() to the ListView not to the adapter class.

Detect Scroll Up & Scroll down in ListView

            ListView listView = getListView();
            listView.setOnScrollListener(new OnScrollListener() {

                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {

                    view.setOnTouchListener(new OnTouchListener() {
                        private float mInitialX;
                        private float mInitialY;

                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            switch (event.getAction()) {
                                case MotionEvent.ACTION_DOWN:
                                    mInitialX = event.getX();
                                    mInitialY = event.getY();
                                    return true;
                                case MotionEvent.ACTION_MOVE:
                                    final float x = event.getX();
                                    final float y = event.getY();
                                    final float yDiff = y - mInitialY;
                                    if (yDiff > 0.0) {
                                        Log.d(tag, "SCROLL DOWN");
                                        scrollDown = true;
                                        break;

                                    } else if (yDiff < 0.0) {
                                        Log.d(tag, "SCROLL up");
                                        scrollDown = true;
                                        break;

                                    }
                                    break;
                            }
                            return false;
                        }
                    });

How can I parse a local JSON file from assets folder into a ListView?

As Faizan describes in their answer here:

First of all read the Json File from your assests file using below code.

and then you can simply read this string return by this function as

public String loadJSONFromAsset() {
    String json = null;
    try {
        InputStream is = getActivity().getAssets().open("yourfilename.json");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}

and use this method like that

    try {
        JSONObject obj = new JSONObject(loadJSONFromAsset());
        JSONArray m_jArry = obj.getJSONArray("formules");
        ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> m_li;

        for (int i = 0; i < m_jArry.length(); i++) {
            JSONObject jo_inside = m_jArry.getJSONObject(i);
            Log.d("Details-->", jo_inside.getString("formule"));
            String formula_value = jo_inside.getString("formule");
            String url_value = jo_inside.getString("url");

            //Add your values in your `ArrayList` as below:
            m_li = new HashMap<String, String>();
            m_li.put("formule", formula_value);
            m_li.put("url", url_value);

            formList.add(m_li);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

For further details regarding JSON Read HERE

How to change color of Android ListView separator line?

You can also get the colors from your resources by using:

dateView.setDivider(new ColorDrawable(_context.getResources().getColor(R.color.textlight)));
dateView.setDividerHeight(1);

How to add a footer in ListView?

If the ListView is a child of the ListActivity:

getListView().addFooterView(
    getLayoutInflater().inflate(R.layout.footer_view, null)
);

(inside onCreate())

Android: Access child views from a ListView

See: Android ListView: get data index of visible item and combine with part of Feet's answer above, can give you something like:

int wantedPosition = 10; // Whatever position you're looking for
int firstPosition = listView.getFirstVisiblePosition() - listView.getHeaderViewsCount(); // This is the same as child #0
int wantedChild = wantedPosition - firstPosition;
// Say, first visible position is 8, you want position 10, wantedChild will now be 2
// So that means your view is child #2 in the ViewGroup:
if (wantedChild < 0 || wantedChild >= listView.getChildCount()) {
  Log.w(TAG, "Unable to get view for desired position, because it's not being displayed on screen.");
  return;
}
// Could also check if wantedPosition is between listView.getFirstVisiblePosition() and listView.getLastVisiblePosition() instead.
View wantedView = listView.getChildAt(wantedChild);

The benefit is that you aren't iterating over the ListView's children, which could take a performance hit.

How to convert a selection to lowercase or uppercase in Sublime Text

For Windows OS

For Uppercase CTRL + K + U

For Lowercase CTRL + K + L

Error retrieving parent for item: No resource found that matches the given name after upgrading to AppCompat v23

Another solution : navigate to

\sdk\extras\android\m2repository\com\android\support\appcompat-v7\23.x.x

open .aar file with 7-zip or winrar , in res folder remove values-23 folder and save changes .

bootstrap datepicker today as default

I used this code

$('#datePicker').datepicker({
                    format:'mm/dd/yyyy',
                }).datepicker("setDate",'now');

Unresponsive KeyListener for JFrame

Hmm.. what class is your constructor for? Probably some class extending JFrame? The window focus should be at the window, of course but I don't think that's the problem.

I expanded your code, tried to run it and it worked - the key presses resulted as print output. (run with Ubuntu through Eclipse):

public class MyFrame extends JFrame {
    public MyFrame() {
        System.out.println("test");
        addKeyListener(new KeyListener() {
            public void keyPressed(KeyEvent e) {
                System.out.println("tester");
            }

            public void keyReleased(KeyEvent e) {
                System.out.println("2test2");
            }

            public void keyTyped(KeyEvent e) {
                System.out.println("3test3");
            }
        });
    }

    public static void main(String[] args) {
        MyFrame f = new MyFrame();
        f.pack();
        f.setVisible(true);
    }
}

Why won't eclipse switch the compiler to Java 8?

I had the same problem even though I had:

  • a freshly downloaded JDK 1.8.0

  • JAVA_HOME is set

  • java -version on command line reports 1.8

  • Java in control panel is set to 1.8

  • downloaded Eclipse Mars

Eclipse only let me choose a compiler compliance level op to 1.7 in the compiler preferences, even though my installed JRE is 1.8.0. I also couldn't see a 1.8 in the Execution Environments underneath Installed JREs, only a JavaSE-1.7 (which I haven't even got installed!). When I clicked on that, it shows "jdk1.8.0" as a compatible JRE, so I selected that, but still no change.

Then I unzipped Eclipse Mars into a brand new directory, created a new project, and now I can select 1.8, hurrah! That greatly reduced the "Duplicate methods named spliterator..." errors I was getting when compiling my code under Java 1.8, however, there is still one left:

Duplicate default methods named spliterator with the parameters () and () are inherited from the types List and Set.

However, that's likely because I'm extending AbstractList and implementing Set, so I've fixed that for now by removing the implements Set because it doesn't really add anything in my case (other than signifying that my collection has only unique elements)

Div vertical scrollbar show

Have you tried overflow-y:auto ? It is not exactly what you want, as the scrollbar will appear only when needed.

dplyr mutate with conditional values

With dplyr 0.7.2, you can use the very useful case_when function :

x=read.table(
 text="V1 V2 V3 V4
 1  1  2  3  5
 2  2  4  4  1
 3  1  4  1  1
 4  4  5  1  3
 5  5  5  5  4")
x$V5 = case_when(x$V1==1 & x$V2!=4 ~ 1,
                 x$V2==4 & x$V3!=1 ~ 2,
                 TRUE ~ 0)

Expressed with dplyr::mutate, it gives:

x = x %>% mutate(
     V5 = case_when(
         V1==1 & V2!=4 ~ 1,
         V2==4 & V3!=1 ~ 2,
         TRUE ~ 0
     )
)

Please note that NA are not treated specially, as it can be misleading. The function will return NA only when no condition is matched. If you put a line with TRUE ~ ..., like I did in my example, the return value will then never be NA.

Therefore, you have to expressively tell case_when to put NA where it belongs by adding a statement like is.na(x$V1) | is.na(x$V3) ~ NA_integer_. Hint: the dplyr::coalesce() function can be really useful here sometimes!

Moreover, please note that NA alone will usually not work, you have to put special NA values : NA_integer_, NA_character_ or NA_real_.

Python For loop get index

Do you want to iterate over characters or words?

For words, you'll have to split the words first, such as

for index, word in enumerate(loopme.split(" ")):
    print "CURRENT WORD IS", word, "AT INDEX", index

This prints the index of the word.

For the absolute character position you'd need something like

chars = 0
for index, word in enumerate(loopme.split(" ")):
    print "CURRENT WORD IS", word, "AT INDEX", index, "AND AT CHARACTER", chars
    chars += len(word) + 1

Flexbox: center horizontally and vertically

diplay: flex; for it's container and margin:auto; for it's item works perfect.

NOTE: You have to setup the width and height to see the effect.

_x000D_
_x000D_
#container{_x000D_
  width: 100%; /*width needs to be setup*/_x000D_
  height: 150px; /*height needs to be setup*/_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.item{_x000D_
  margin: auto; /*These will make the item in center*/_x000D_
  background-color: #CCC;_x000D_
}
_x000D_
<div id="container">_x000D_
   <div class="item">CENTER</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jQuery Scroll to bottom of page/iframe

The scripts mentioned in previous answers, like:

$("body, html").animate({
    scrollTop: $(document).height()
}, 400)

or

$(window).scrollTop($(document).height());

will not work in Chrome and will be jumpy in Safari in case html tag in CSS has overflow: auto; property set. It took me nearly an hour to figure out.

Why is document.write considered a "bad practice"?

Browser Violation

.write is considered a browser violation as it halts the parser from rendering the page. The parser receives the message that the document is being modified; hence, it gets blocked until JS has completed its process. Only at this time will the parser resume.

Performance

The biggest consequence of employing such a method is lowered performance. The browser will take longer to load page content. The adverse reaction on load time depends on what is being written to the document. You won't see much of a difference if you are adding a <p> tag to the DOM as opposed to passing an array of 50-some references to JavaScript libraries (something which I have seen in working code and resulted in an 11 second delay - of course, this also depends on your hardware).

All in all, it's best to steer clear of this method if you can help it.

For more info see Intervening against document.write()

How to destroy a DOM element with jQuery?

Is $target.remove(); what you're looking for?

https://api.jquery.com/remove/

How to select all textareas and textboxes using jQuery?

Simply use $(":input")

Example disabling all inputs (textarea, input text, etc):

_x000D_
_x000D_
$(":input").prop("disabled", true);
_x000D_
<form>_x000D_
  <textarea>Tetarea</textarea>_x000D_
  <input type="text" value="Text">_x000D_
  <label><input type="checkbox"> Checkbox</label>_x000D_
</form>_x000D_
_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

VBA EXCEL To Prompt User Response to Select Folder and Return the Path as String Variable

Consider:

Function GetFolder() As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

This code was adapted from Ozgrid

and as jkf points out, from Mr Excel

Spring Data JPA map the native query result to Non-Entity POJO

Use the default method in the interface and get the EntityManager to get the opportunity to set the ResultTransformer, then you can return the pure POJO, like this:

final String sql = "SELECT g.*, gm.* FROM group g LEFT JOIN group_members gm ON g.group_id = gm.group_id and gm.user_id = ? WHERE g.group_id = ?";
default GroupDetails getGroupDetails(Integer userId, Integer groupId) {
    return BaseRepository.getInstance().uniqueResult(sql, GroupDetails.class, userId, groupId);
}

And the BaseRepository.java is like this:

@PersistenceContext
public EntityManager em;

public <T> T uniqueResult(String sql, Class<T> dto, Object... params) {
    Session session = em.unwrap(Session.class);
    NativeQuery q = session.createSQLQuery(sql);
    if(params!=null){
        for(int i=0,len=params.length;i<len;i++){
            Object param=params[i];
            q.setParameter(i+1, param);
        }
    }
    q.setResultTransformer(Transformers.aliasToBean(dto));
    return (T) q.uniqueResult();
}

This solution does not impact any other methods in repository interface file.

How to get form input array into PHP array

They are already in arrays: $name is an array, as is $email

So all you need to do is add a bit of processing to attack both arrays:

$name = $_POST['name'];
$email = $_POST['account'];

foreach( $name as $key => $n ) {
  print "The name is ".$n." and email is ".$email[$key].", thank you\n";
}

To handle more inputs, just extend the pattern:

$name = $_POST['name'];
$email = $_POST['account'];
$location = $_POST['location'];

foreach( $name as $key => $n ) {
  print "The name is ".$n.", email is ".$email[$key].
        ", and location is ".$location[$key].". Thank you\n";
}

How to install packages offline?

If you want install python libs and their dependencies offline, finish following these steps on a machine with the same os, network connected, and python installed:

1) Create a requirements.txt file with similar content (Note - these are the libraries you wish to download):

Flask==0.12
requests>=2.7.0
scikit-learn==0.19.1
numpy==1.14.3
pandas==0.22.0

One option for creating the requirements file is to use pip freeze > requirements.txt. This will list all libraries in your environment. Then you can go in to requirements.txt and remove un-needed ones.

2) Execute command mkdir wheelhouse && pip download -r requirements.txt -d wheelhouse to download libs and their dependencies to directory wheelhouse

3) Copy requirements.txt into wheelhouse directory

4) Archive wheelhouse into wheelhouse.tar.gz with tar -zcf wheelhouse.tar.gz wheelhouse

Then upload wheelhouse.tar.gz to your target machine:

1) Execute tar -zxf wheelhouse.tar.gz to extract the files

2) Execute pip install -r wheelhouse/requirements.txt --no-index --find-links wheelhouse to install the libs and their dependencies

Confirm postback OnClientClick button ASP.NET

The code is like this:

In Aspx:

<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" CausesValidation=true />

in Cs:

protected void Page_Load(object sender, System.EventArgs e)
{
     if (!IsPostBack)
     {
         btnSave.Attributes["Onclick"] = "return confirm('Do you really want to save?')";          
     }
}

protected void btnSave_Click(object sender, EventArgs e){
    Page.Validate();
    if (Page.IsValid)
    {
       //Update the database
         lblMessage.Text = "Saved Successfully";
    }
}

Convert Python dictionary to JSON array

If you use Python 2, don't forget to add the UTF-8 file encoding comment on the first line of your script.

# -*- coding: UTF-8 -*-

This will fix some Unicode problems and make your life easier.

Select values of checkbox group with jQuery

With map in instead of each it is possible to avoid the array creation step:

var checkedCheckboxesValues = 
    $('input:checkbox[name="groupName"]:checked')
        .map(function() {
            return $(this).val();
        }).get();

From the map() page of the docs:

Pass each element in the current matched set through a function, producing a new jQuery object containing the return values

get() turns those values into an array.

Is it possible to use an input value attribute as a CSS selector?

As mentioned before, you need more than a css selector because it doesn't access the stored value of the node, so javascript is definitely needed. Heres another possible solution:

<style>
input:not([value=""]){
border:2px solid red;
}
</style>

<input type="text" onkeyup="this.setAttribute('value', this.value);"/>

How do I mock an autowired @Value field in Spring with Mockito?

You can use this magic Spring Test annotation :

@TestPropertySource(properties = { "my.spring.property=20" }) 

see org.springframework.test.context.TestPropertySource

For example, this is the test class :

@ContextConfiguration(classes = { MyTestClass.Config.class })
@TestPropertySource(properties = { "my.spring.property=20" })
public class MyTestClass {

  public static class Config {
    @Bean
    MyClass getMyClass() {
      return new MyClass ();
    }
  }

  @Resource
  private MyClass myClass ;

  @Test
  public void myTest() {
   ...

And this is the class with the property :

@Component
public class MyClass {

  @Value("${my.spring.property}")
  private int mySpringProperty;
   ...

What is the best way to manage a user's session in React?

There is a React module called react-client-session that makes storing client side session data very easy. The git repo is here.

This is implemented in a similar way as the closure approach in my other answer, however it also supports persistence using 3 different persistence stores. The default store is memory(not persistent).

  1. Cookie
  2. localStorage
  3. sessionStorage

After installing, just set the desired store type where you mount the root component ...

import ReactSession from 'react-client-session';

ReactSession.setStoreType("localStorage");

... and set/get key value pairs from anywhere in your app:

import ReactSession from 'react-client-session';

ReactSession.set("username", "Bob");
ReactSession.get("username");  // Returns "Bob"

ENOENT, no such file or directory

I believe the previous answer is the correct answer to this problem but I was getting this error when I tried installing npm package (see below) :

enter image description here

The fix for me was : npm init --yes

enter image description here

How do I clone a specific Git branch?

git clone --single-branch --branch <branchname> <remote-repo>

The --single-branch option is valid from version 1.7.10 and later.

Please see also the other answer which many people prefer.

You may also want to make sure you understand the difference. And the difference is: by invoking git clone --branch <branchname> url you're fetching all the branches and checking out one. That may, for instance, mean that your repository has a 5kB documentation or wiki branch and 5GB data branch. And whenever you want to edit your frontpage, you may end up cloning 5GB of data.

Again, that is not to say git clone --branch is not the way to accomplish that, it's just that it's not always what you want to accomplish, when you're asking about cloning a specific branch.

Getting results between two dates in PostgreSQL

You have to use the date part fetching method:

SELECT * FROM testbed WHERE start_date  ::date >= to_date('2012-09-08' ,'YYYY-MM-DD') and date::date <= to_date('2012-10-09' ,'YYYY-MM-DD')

NoClassDefFoundError in Java: com/google/common/base/Function

I got the same error, but it was resolved if you add the libraries of selenium (again if you haven't), if you are using INTELIJ

project>projectStructure>Module>+>add the selenium jars (both from lib folder and outside ones.).

Same needs to be done for other IDE's as well, like eclipse.

How should I call 3 functions in order to execute them one after the other?

I use a 'waitUntil' function based on javascript's setTimeout

/*
    funcCond : function to call to check whether a condition is true
    readyAction : function to call when the condition was true
    checkInterval : interval to poll <optional>
    timeout : timeout until the setTimeout should stop polling (not 100% accurate. It was accurate enough for my code, but if you need exact milliseconds, please refrain from using Date <optional>
    timeoutfunc : function to call on timeout <optional>
*/
function waitUntil(funcCond, readyAction, checkInterval, timeout, timeoutfunc) {
    if (checkInterval == null) {
        checkInterval = 100; // checkinterval of 100ms by default
    }
    var start = +new Date(); // use the + to convert it to a number immediatly
    if (timeout == null) {
        timeout = Number.POSITIVE_INFINITY; // no timeout by default
    }
    var checkFunc = function() {
        var end = +new Date(); // rough timeout estimations by default

        if (end-start > timeout) {
            if (timeoutfunc){ // if timeout function was defined
                timeoutfunc(); // call timeout function
            }
        } else {
            if(funcCond()) { // if condition was met
                readyAction(); // perform ready action function
            } else {
                setTimeout(checkFunc, checkInterval); // else re-iterate
            }
        }
    };
    checkFunc(); // start check function initially
};

This would work perfectly if your functions set a certain condition to true, which you would be able to poll. Plus it comes with timeouts, which offers you alternatives in case your function failed to do something (even within time-range. Think about user feedback!)

eg

doSomething();
waitUntil(function() { return doSomething_value===1;}, doSomethingElse);
waitUntil(function() { return doSomethingElse_value===1;}, doSomethingUseful);

Notes

Date causes rough timeout estimates. For greater precision, switch to functions such as console.time(). Do take note that Date offers greater cross-browser and legacy support. If you don't need exact millisecond measurements; don't bother, or, alternatively, wrap it, and offer console.time() when the browser supports it

Javascript: console.log to html

You can override the default implementation of console.log()

(function () {
    var old = console.log;
    var logger = document.getElementById('log');
    console.log = function (message) {
        if (typeof message == 'object') {
            logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify(message) : message) + '<br />';
        } else {
            logger.innerHTML += message + '<br />';
        }
    }
})();

Demo: Fiddle

Why is there no String.Empty in Java?

If you really want a String.EMPTY constant, you can create an utility static final class named "Constants" (for example) in your project. This class will maintain your constants, including the empty String...

In the same idea, you can create ZERO, ONE int constants... that don't exist in the Integer class, but like I commented, it would be a pain to write and to read :

for(int i=Constants.ZERO; ...) {
    if(myArray.length > Constants.ONE) {
        System.out.println("More than one element");
    }
}

Etc.

How to get the nth element of a python list or a default if not available

Just discovered that :

next(iter(myList), 5)

iter(l) returns an iterator on myList, next() consumes the first element of the iterator, and raises a StopIteration error except if called with a default value, which is the case here, the second argument, 5

This only works when you want the 1st element, which is the case in your example, but not in the text of you question, so...

Additionally, it does not need to create temporary lists in memory and it works for any kind of iterable, even if it does not have a name (see Xiong Chiamiov's comment on gruszczy's answer)

How do I use cx_freeze?

I'm really not sure what you're doing to get that error, it looks like you're trying to run cx_Freeze on its own, without arguments. So here is a short step-by-step guide on how to do it in windows (Your screenshot looks rather like the windows command line, so I'm assuming that's your platform)

  1. Write your setup.py file. Your script above looks correct so it should work, assuming that your script exists.

  2. Open the command line (Start -> Run -> "cmd")

  3. Go to the location of your setup.py file and run python setup.py build

Notes:

  1. There may be a problem with the name of your script. "Main.py" contains upper case letters, which might cause confusion since windows' file names are not case sensitive, but python is. My approach is to always use lower case for scripts to avoid any conflicts.

  2. Make sure that python is on your PATH (read http://docs.python.org/using/windows.html)1

  3. Make sure are are looking at the new cx_Freeze documentation. Google often seems to bring up the old docs.

How to make join queries using Sequelize on Node.js

Model1.belongsTo(Model2, { as: 'alias' })

Model1.findAll({include: [{model: Model2  , as: 'alias'  }]},{raw: true}).success(onSuccess).error(onError);

How to Correctly handle Weak Self in Swift Blocks with Arguments

**EDITED for Swift 4.2:

As @Koen commented, swift 4.2 allows:

guard let self = self else {
   return // Could not get a strong reference for self :`(
}

// Now self is a strong reference
self.doSomething()

P.S.: Since I am having some up-votes, I would like to recommend the reading about escaping closures.

EDITED: As @tim-vermeulen has commented, Chris Lattner said on Fri Jan 22 19:51:29 CST 2016, this trick should not be used on self, so please don't use it. Check the non escaping closures info and the capture list answer from @gbk.**

For those who use [weak self] in capture list, note that self could be nil, so the first thing I do is check that with a guard statement

guard let `self` = self else {
   return
}
self.doSomething()

If you are wondering what the quote marks are around self is a pro trick to use self inside the closure without needing to change the name to this, weakSelf or whatever.

How to use nan and inf in C?

There is no compiler independent way of doing this, as neither the C (nor the C++) standards say that the floating point math types must support NAN or INF.

Edit: I just checked the wording of the C++ standard, and it says that these functions (members of the templated class numeric_limits):

quiet_NaN() 
signalling_NaN()

wiill return NAN representations "if available". It doesn't expand on what "if available" means, but presumably something like "if the implementation's FP rep supports them". Similarly, there is a function:

infinity() 

which returns a positive INF rep "if available".

These are both defined in the <limits> header - I would guess that the C standard has something similar (probably also "if available") but I don't have a copy of the current C99 standard.

How to set underline text on textview?

Need not to use HTML properties, let's focus on java xD I had the same problem, i found the way to do it in java:

String text="Hide post";
TextView tvHide=(TextView)findViewById(R.id.text);
SpannableString spanString = new SpannableString(text);
spanString.setSpan(new UnderlineSpan(), 0, spanString.length(), 0);
tvHide.setText(spanString );

Trying to SSH into an Amazon Ec2 instance - permission error

Ok man, the only thing that worked for me was:

  1. Change permissions of the key

    chmod 400 mykey.pem

  2. Make sure to log in using ec2-user, and the correct ec2-99... address. The ec2-99 address is at the bottom of the aws console when you're logged in and seeing your instance listed

    ssh -i mykey.pem [email protected]

Sum values in a column based on date

If the second row has the same pattern as the first row, you just need edit first row manually, then you position your mouse pointer to the bottom-right corner, in the mean time, press ctrl key to drag the cell down. the pattern should be copied automatically.

css selector to match an element without attribute x

:not selector:

input:not([type]), input[type='text'], input[type='password'] {
    /* style here */
}

Support: in Internet Explorer 9 and higher

Difference between natural join and inner join

difference is that int the inner(equi/default)join and natural join that in the natuarl join common column win will be display in single time but inner/equi/default/simple join the common column will be display double time.

How do we count rows using older versions of Hibernate (~2009)?

It's very easy, just run the following JPQL query:

int count = (
(Number)
    entityManager
    .createQuery(
        "select count(b) " +
        "from Book b")
    .getSingleResult()
).intValue();

The reason we are casting to Number is that some databases will return Long while others will return BigInteger, so for portability sake you are better off casting to a Number and getting an int or a long, depending on how many rows you are expecting to be counted.

Java ArrayList replace at specific index

You can replace the items at specific position using set method of ArrayList as below:

list.set( your_index, your_item );

But the element should be present at the index you are passing inside set() method else it will throw exception.

Online code beautifier and formatter

For PHP, Java, C++, C, Perl, JavaScript, CSS you can try:

http://www.prettyprinter.de/index.php

Am I trying to connect to a TLS-enabled daemon without TLS?

The underlining problem is simple – lack of permission to /var/run/docker.sock unix domain socket.

From Daemon socket option chapter of Docker Command Line reference for Docker 1.6.0:

By default, a unix domain socket (or IPC socket) is created at /var/run/docker.sock, requiring either root permission, or docker group membership.

Steps necessary to grant rights to users are nicely described in Docker installation instructions for Fedora:

Granting rights to users to use Docker

The docker command line tool contacts the docker daemon process via a socket file /var/run/docker.sock owned by root:root. Though it's recommended to use sudo for docker commands, if users wish to avoid it, an administrator can create a docker group, have it own /var/run/docker.sock, and add users to this group.

$ sudo groupadd docker
$ sudo chown root:docker /var/run/docker.sock
$ sudo usermod -a -G docker $USERNAME

Log out and log back in for above changes to take effect. Please note that Docker packages of some Linux distributions (Ubuntu) do already place /var/run/docker.sock in the docker group making the first two of above steps unnecessary.

In case of OS X and boot2docker the situation is different; the Docker daemon runs inside a VM so the DOCKER_HOST environment variable must be set to this VM so that the Docker client could find the Docker daemon. This is done by running $(boot2docker shellinit) in the shell.

How to specify more spaces for the delimiter using cut?

If you want to pick columns from a ps output, any reason to not use -o?

e.g.

ps ax -o pid,vsz
ps ax -o pid,cmd

Minimum column width allocated, no padding, only single space field separator.

ps ax --no-headers -o pid:1,vsz:1,cmd

3443 24600 -bash
8419 0 [xfsalloc]
8420 0 [xfs_mru_cache]
8602 489316 /usr/sbin/apache2 -k start
12821 497240 /usr/sbin/apache2 -k start
12824 497132 /usr/sbin/apache2 -k start

Pid and vsz given 10 char width, 1 space field separator.

ps ax --no-headers -o pid:10,vsz:10,cmd

  3443      24600 -bash
  8419          0 [xfsalloc]
  8420          0 [xfs_mru_cache]
  8602     489316 /usr/sbin/apache2 -k start
 12821     497240 /usr/sbin/apache2 -k start
 12824     497132 /usr/sbin/apache2 -k start

Used in a script:-

oldpid=12824
echo "PID: ${oldpid}"
echo "Command: $(ps -ho cmd ${oldpid})"

What are good grep tools for Windows?

It may not exactly fall into the 'grep' category, but I couldn't get by on Windows without a utility called AgentRansack. It's a gui-based "find in files" utility with regex support. It's dead simple to right-click on a folder, hit "ransack.." and find files containing what you're looking for. Extremely fast too.

Getting the "real" Facebook profile picture URL from graph API

ImageView user_picture;
userpicture=(ImageView)findViewById(R.id.userpicture);
URL img_value = null;
img_value = new URL("http://graph.facebook.com/"+id+"/picture?type=large");
Bitmap mIcon1 = BitmapFactory.decodeStream(img_value.openConnection().getInputStream());
userpicture.setImageBitmap(mIcon1);

Where ID is one your profile ID.

Identify if a string is a number

If you want to catch a broader spectrum of numbers, à la PHP's is_numeric, you can use the following:

// From PHP documentation for is_numeric
// (http://php.net/manual/en/function.is-numeric.php)

// Finds whether the given variable is numeric.

// Numeric strings consist of optional sign, any number of digits, optional decimal part and optional
// exponential part. Thus +0123.45e6 is a valid numeric value.

// Hexadecimal (e.g. 0xf4c3b00c), Binary (e.g. 0b10100111001), Octal (e.g. 0777) notation is allowed too but
// only without sign, decimal and exponential part.
static readonly Regex _isNumericRegex =
    new Regex(  "^(" +
                /*Hex*/ @"0x[0-9a-f]+"  + "|" +
                /*Bin*/ @"0b[01]+"      + "|" + 
                /*Oct*/ @"0[0-7]*"      + "|" +
                /*Dec*/ @"((?!0)|[-+]|(?=0+\.))(\d*\.)?\d+(e\d+)?" + 
                ")$" );
static bool IsNumeric( string value )
{
    return _isNumericRegex.IsMatch( value );
}

Unit Test:

static void IsNumericTest()
{
    string[] l_unitTests = new string[] { 
        "123",      /* TRUE */
        "abc",      /* FALSE */
        "12.3",     /* TRUE */
        "+12.3",    /* TRUE */
        "-12.3",    /* TRUE */
        "1.23e2",   /* TRUE */
        "-1e23",    /* TRUE */
        "1.2ef",    /* FALSE */
        "0x0",      /* TRUE */
        "0xfff",    /* TRUE */
        "0xf1f",    /* TRUE */
        "0xf1g",    /* FALSE */
        "0123",     /* TRUE */
        "0999",     /* FALSE (not octal) */
        "+0999",    /* TRUE (forced decimal) */
        "0b0101",   /* TRUE */
        "0b0102"    /* FALSE */
    };

    foreach ( string l_unitTest in l_unitTests )
        Console.WriteLine( l_unitTest + " => " + IsNumeric( l_unitTest ).ToString() );

    Console.ReadKey( true );
}

Keep in mind that just because a value is numeric doesn't mean it can be converted to a numeric type. For example, "999999999999999999999999999999.9999999999" is a perfeclty valid numeric value, but it won't fit into a .NET numeric type (not one defined in the standard library, that is).

How to add a ScrollBar to a Stackpanel

It works like this:

<ScrollViewer VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Disabled" Width="340" HorizontalAlignment="Left" Margin="12,0,0,0">
        <StackPanel Name="stackPanel1" Width="311">

        </StackPanel>
</ScrollViewer>

TextBox tb = new TextBox();
tb.TextChanged += new TextChangedEventHandler(TextBox_TextChanged);
stackPanel1.Children.Add(tb);

Find out how much memory is being used by an object in Python

For big objects you may use a somewhat crude but effective method: check how much memory your Python process occupies in the system, then delete the object and compare.

This method has many drawbacks but it will give you a very fast estimate for very big objects.

535-5.7.8 Username and Password not accepted

UPDATE:

Notice: This setting is not available for accounts with 2-Step Verification enabled, which mean you have to disable 2 factor authentication.

enter image description here

If you disable the 2-Step Verification:

enter image description here

Android How to adjust layout in Full Screen Mode when softkeyboard is visible

1) Create KeyboardHeightHelper:

public class KeyboardHeightHelper {

    private final View decorView;
    private int lastKeyboardHeight = -1;

    public KeyboardHeightHelper(Activity activity, View activityRootView, OnKeyboardHeightChangeListener listener) {
        this.decorView = activity.getWindow().getDecorView();
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
            int keyboardHeight = getKeyboardHeight();
            if (lastKeyboardHeight != keyboardHeight) {
                lastKeyboardHeight = keyboardHeight;
                listener.onKeyboardHeightChange(keyboardHeight);
            }
        });
    }

    private int getKeyboardHeight() {
        Rect rect = new Rect();
        decorView.getWindowVisibleDisplayFrame(rect);
        return decorView.getHeight() - rect.bottom;
    }

    public interface OnKeyboardHeightChangeListener {
        void onKeyboardHeightChange(int keyboardHeight);
    }
}

2) Let your activity be full screen:

activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

3) Listen for keyboard height changes and add bottom padding for your view:

View rootView = activity.findViewById(R.id.root); // your root view or any other you want to resize
KeyboardHeightHelper effectiveHeightHelper = new KeyboardHeightHelper(
        activity, 
        rootView,
        keyboardHeight -> rootView.setPadding(0, 0, 0, keyboardHeight));

So, each time keyboard will appear on the screen - bottom padding for your view will change, and content will be rearranged.

ascending/descending in LINQ - can one change the order via parameter?

In terms of how this is implemented, this changes the method - from OrderBy/ThenBy to OrderByDescending/ThenByDescending. However, you can apply the sort separately to the main query...

var qry = from .... // or just dataList.AsEnumerable()/AsQueryable()

if(sortAscending) {
    qry = qry.OrderBy(x=>x.Property);
} else {
    qry = qry.OrderByDescending(x=>x.Property);
}

Any use? You can create the entire "order" dynamically, but it is more involved...

Another trick (mainly appropriate to LINQ-to-Objects) is to use a multiplier, of -1/1. This is only really useful for numeric data, but is a cheeky way of achieving the same outcome.

git: 'credential-cache' is not a git command

Looks like git now comes with wincred out-of-the-box on Windows (msysgit):

git config --global credential.helper wincred

Reference: https://github.com/msysgit/git/commit/e2770979fec968a25ac21e34f9082bc17a71a780

Constructor in an Interface?

Generally constructors are for initializing non-static members of particular class with respect to object.

There is no object creation for interface as there is only declared methods but not defined methods. Why we can’t create object to declared methods is-object creation is nothing but allocating some memory (in heap memory) for non-static members.

JVM will create memory for members which are fully developed and ready to use.Based on those members , JVM calculates how much of memory required for them and creates memory.

Incase of declared methods, JVM is unable to calculate the how much memory will required to these declared methods as the implementation will be in future which is not done by this time. so object creation is not possible for interface.

conclusion:

without object creation, there is no chance to initialize non-static members through a constructor.That is why constructor is not allowed inside a interface.(as there is no use of constructor inside a interface)

Adding a library/JAR to an Eclipse Android project

First, the problem of the missing prefix.

If you consume something in your layout file that comes from a third party, you may need to consume its prefix as well, something like "droidfu:" which occurs in several places in the XML construct below:

<com.github.droidfu.widgets.WebImageView android:id="@+id/webimage"
          android:layout_width="75dip"
          android:layout_height="75dip"
          android:background="#CCC"
          droidfu:autoLoad="true"
          droidfu:imageUrl="http://www.android.com/images/opensourceprojec.gif"
          droidfu:progressDrawable="..."
          />

This comes out of the JAR, but you'll also need to add the new "xmlns:droidfu"

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:droidfu="http://github.com/droidfu/schema"
      ...>

or you get the unbound prefix error. For me, this was a failure to copy and paste all of the supplied example from the third-party library's pages.

Convert a list of characters into a string

You could also use operator.concat() like this:

>>> from operator import concat
>>> a = ['a', 'b', 'c', 'd']
>>> reduce(concat, a)
'abcd'

If you're using Python 3 you need to prepend:

>>> from functools import reduce

since the builtin reduce() has been removed from Python 3 and now lives in functools.reduce().

Filter rows which contain a certain string

Solution

It is possible to use str_detect of the stringr package included in the tidyverse package. str_detect returns True or False as to whether the specified vector contains some specific string. It is possible to filter using this boolean value. See Introduction to stringr for details about stringr package.

library(tidyverse)
# - Attaching packages -------------------- tidyverse 1.2.1 -
# ? ggplot2 2.2.1     ? purrr   0.2.4
# ? tibble  1.4.2     ? dplyr   0.7.4
# ? tidyr   0.7.2     ? stringr 1.2.0
# ? readr   1.1.1     ? forcats 0.3.0
# - Conflicts --------------------- tidyverse_conflicts() -
# ? dplyr::filter() masks stats::filter()
# ? dplyr::lag()    masks stats::lag()

mtcars$type <- rownames(mtcars)
mtcars %>%
  filter(str_detect(type, 'Toyota|Mazda'))
# mpg cyl  disp  hp drat    wt  qsec vs am gear carb           type
# 1 21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4      Mazda RX4
# 2 21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4  Mazda RX4 Wag
# 3 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1 Toyota Corolla
# 4 21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1  Toyota Corona

The good things about Stringr

We should use rather stringr::str_detect() than base::grepl(). This is because there are the following reasons.

  • The functions provided by the stringr package start with the prefix str_, which makes the code easier to read.
  • The first argument of the functions of stringr package is always the data.frame (or value), then comes the parameters.(Thank you Paolo)
object <- "stringr"
# The functions with the same prefix `str_`.
# The first argument is an object.
stringr::str_count(object) # -> 7
stringr::str_sub(object, 1, 3) # -> "str"
stringr::str_detect(object, "str") # -> TRUE
stringr::str_replace(object, "str", "") # -> "ingr"
# The function names without common points.
# The position of the argument of the object also does not match.
base::nchar(object) # -> 7
base::substr(object, 1, 3) # -> "str"
base::grepl("str", object) # -> TRUE
base::sub("str", "", object) # -> "ingr"

Benchmark

The results of the benchmark test are as follows. For large dataframe, str_detect is faster.

library(rbenchmark)
library(tidyverse)

# The data. Data expo 09. ASA Statistics Computing and Graphics 
# http://stat-computing.org/dataexpo/2009/the-data.html
df <- read_csv("Downloads/2008.csv")
print(dim(df))
# [1] 7009728      29

benchmark(
  "str_detect" = {df %>% filter(str_detect(Dest, 'MCO|BWI'))},
  "grepl" = {df %>% filter(grepl('MCO|BWI', Dest))},
  replications = 10,
  columns = c("test", "replications", "elapsed", "relative", "user.self", "sys.self"))
# test replications elapsed relative user.self sys.self
# 2      grepl           10  16.480    1.513    16.195    0.248
# 1 str_detect           10  10.891    1.000     9.594    1.281

Need to list all triggers in SQL Server database with table name and table's schema

If you are looking for ALL triggers, remember MS-SQL has both SQL-based triggers (sysobjects.type = 'TR') and CLR-based triggers (sysobjects.type = 'TA').

Cheap way to search a large text file for a string

If there is no way to tell where the string will be (first half, second half, etc) then there is really no optimized way to do the search other than the builtin "find" function. You could reduce the I/O time and memory consumption by not reading the file all in one shot, but at 4kb blocks (which is usually the size of an hard disk block). This will not make the search faster, unless the string is in the first part of the file, but in all case will reduce memory consumption which might be a good idea if the file is huge.

Could not reserve enough space for object heap

32-bit Java requires contiguous free space in memory to run. If you specify a large heap size, there may not be so much contiguous free space in memory even if you have much more free space available than necessary.

Installing a 64-bit version of Java helps in these cases, the contiguous memory requirements only applies to 32-bit Java.

Convert java.time.LocalDate into java.util.Date type

java.util.Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());

Getting user input

To supplement the above answers into something a little more re-usable, I've come up with this, which continues to prompt the user if the input is considered invalid.

try:
    input = raw_input
except NameError:
    pass

def prompt(message, errormessage, isvalid):
    """Prompt for input given a message and return that value after verifying the input.

    Keyword arguments:
    message -- the message to display when asking the user for the value
    errormessage -- the message to display when the value fails validation
    isvalid -- a function that returns True if the value given by the user is valid
    """
    res = None
    while res is None:
        res = input(str(message)+': ')
        if not isvalid(res):
            print str(errormessage)
            res = None
    return res

It can be used like this, with validation functions:

import re
import os.path

api_key = prompt(
        message = "Enter the API key to use for uploading", 
        errormessage= "A valid API key must be provided. This key can be found in your user profile",
        isvalid = lambda v : re.search(r"(([^-])+-){4}[^-]+", v))

filename = prompt(
        message = "Enter the path of the file to upload", 
        errormessage= "The file path you provided does not exist",
        isvalid = lambda v : os.path.isfile(v))

dataset_name = prompt(
        message = "Enter the name of the dataset you want to create", 
        errormessage= "The dataset must be named",
        isvalid = lambda v : len(v) > 0)

Single quotes vs. double quotes in Python

Triple quoted comments are an interesting subtopic of this question. PEP 257 specifies triple quotes for doc strings. I did a quick check using Google Code Search and found that triple double quotes in Python are about 10x as popular as triple single quotes -- 1.3M vs 131K occurrences in the code Google indexes. So in the multi line case your code is probably going to be more familiar to people if it uses triple double quotes.

JSON order mixed up

The main intention here is to send an ordered JSON object as response. We don't need javax.json.JsonObject to achieve that. We could create the ordered json as a string. First create a LinkedHashMap with all key value pairs in required order. Then generate the json in string as shown below. Its much easier with Java 8.

public Response getJSONResponse() {
    Map<String, String> linkedHashMap = new LinkedHashMap<>();
    linkedHashMap.put("A", "1");
    linkedHashMap.put("B", "2");
    linkedHashMap.put("C", "3");

    String jsonStr = linkedHashMap.entrySet().stream()
            .map(x -> "\"" + x.getKey() + "\":\"" + x.getValue() + "\"")
            .collect(Collectors.joining(",", "{", "}"));
    return Response.ok(jsonStr).build();
}

The response return by this function would be following: {"A":"1","B":"2","C":"3"}

What is the recommended way to make a numeric TextField in JavaFX?

In recent updates of JavaFX, you have to set new text in Platform.runLater method just like this:

    private void set_normal_number(TextField textField, String oldValue, String newValue) {
    try {
        int p = textField.getCaretPosition();
        if (!newValue.matches("\\d*")) {
            Platform.runLater(() -> {
                textField.setText(newValue.replaceAll("[^\\d]", ""));
                textField.positionCaret(p);
            });
        }
    } catch (Exception e) {
    }
}

It's a good idea to set caret position too.

When should I use double or single quotes in JavaScript?

I think it's important not to forget that while Internet Explorer might have zero extensions/toolbars installed, Firefox might have some extensions installed (I'm just thinking of Firebug for instance). Those extensions will have an influence on the benchmark result.

Not that it really matters since browser X is faster in getting elementstyles, while browser Y might be faster in rendering a canvas element (hence why a browser "manufacturer" always has the fastest JavaScript engine).

Getting the filenames of all files in a folder

Create a File object, passing the directory path to the constructor. Use the listFiles() to retrieve an array of File objects for each file in the directory, and then call the getName() method to get the filename.

List<String> results = new ArrayList<String>();


File[] files = new File("/path/to/the/directory").listFiles();
//If this pathname does not denote a directory, then listFiles() returns null. 

for (File file : files) {
    if (file.isFile()) {
        results.add(file.getName());
    }
}

`require': no such file to load -- mkmf (LoadError)

This is the answer that worked for me. Was in the comments above, but deserves its rightful place as answer for ubuntu 12.04 ruby 1.8.7

sudo apt-get install ruby-dev
# if above doesnt work make sure you have build essential
sudo apt-get install build-essential

Facebook Open Graph not clearing cache

Really easy solve. Tested and working. You just need to generate a new url when you update your meta tags. It's as simple as adding a "&cacheBuster=1" to your url. If you change the meta tags, just increment the "&cacheBuster=2"

Orginal URL

www.example.com

URL when og meta tags are updated:

www.example.com?cacheBuster=1

URL when og meta tags are updated again:

www.example.com?cacheBuster=2

Facebook will treat each like a new url and get fresh meta data.

The server committed a protocol violation. Section=ResponseStatusLine ERROR

Many solutions talk about a workaround, but not about the actual cause of the error.

One possible cause of this error is if the webserver uses an encoding other than ASCII or ISO-8859-1 to output the header response section. The reason to use ISO-8859-1 would be if the Response-Phrase contains extended Latin characters.

Another possible cause of this error is if a webserver uses UTF-8 that outputs the byte-order-marker (BOM). For example, the default constant Encoding.UTF8 outputs the BOM, and it's easy to forget this. The webpages will work correctly in Firefox and Chrome, but HttpWebRequest will bomb :). A quick fix is to change the webserver to use the UTF-8 encoding that doesn't output the BOM, e.g. new UTF8Encoding(false) (which is OK as long as the Response-Phrase only contains ASCII characters, but really it should use ASCII or ISO-8859-1 for the headers, and then UTF-8 or some other encoding for the response).

Convert dictionary values into array

// dict is Dictionary<string, Foo>

Foo[] foos = new Foo[dict.Count];
dict.Values.CopyTo(foos, 0);

// or in C# 3.0:
var foos = dict.Values.ToArray();

How do you easily horizontally center a <div> using CSS?

In the case of a non-fixed width div (i.e. you don't know how much space the div will occupy).

_x000D_
_x000D_
#wrapper {_x000D_
  background-color: green; /* for visualization purposes */_x000D_
  text-align: center;_x000D_
}_x000D_
#yourdiv {_x000D_
  background-color: red; /* for visualization purposes */_x000D_
  display: inline-block;_x000D_
}
_x000D_
<div id="wrapper">    _x000D_
    <div id="yourdiv">Your text</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Keep in mind that the width of #yourdiv is dynamic -> it will grow and shrink to accommodate the text inside it.

You can check browser compatibility on Caniuse

How to insert values in two dimensional array programmatically?

Think about it as array of array.

If you do this str[x][y], then there is array of length x where each element in turn contains array of length y. In java its not necessary for second dimension to have same length. So for x=i you can have y=m and x=j you can have y=n

For this your declaration looks like

String[][] test = new String[4][]; test[0] = new String[3]; test[1] = new String[2];

etc..

Maven: repository element was not specified in the POM inside distributionManagement?

You can also override the deployment repository on the command line: -Darguments=-DaltDeploymentRepository=myreposid::default::http://my/url/releases

Why my regexp for hyphenated words doesn't work?

This regex should do it.

\b[a-z]+-[a-z]+\b 

\b indicates a word-boundary.

How to run a shell script at startup

This is the way I do it on Red Hat Linux systems.

Put your script in /etc/init.d, owned by root and executable. At the top of the script, you can give a directive for chkconfig. Example, the following script is used to start a Java application as user oracle.

The name of the script is /etc/init.d/apex

#!/bin/bash
# chkconfig: 345 99 10
# Description: auto start apex listener
#
case "$1" in
 'start')
   su - oracle -c "cd /opt/apex ; java -jar apex.war > logs/apex.log 2>logs/apex_error.log &";;
 'stop')
   echo "put something to shutdown or kill the process here";;
esac

This says that the script must run at levels 3, 4, and 5, and the priority for start/stop is 99 and 10.

Then, as user root you can use chkconfig to enable or disable the script at startup:

chkconfig --list apex
chkconfig --add apex

And you can use service start/stop apex.

Find the division remainder of a number

We can solve this by using modulus operator (%)

26 % 7 = 5;

but 26 / 7 = 3 because it will give quotient but % operator will give remainder.

Remove Item from ArrayList

Try it this way,

ArrayList<String> List_Of_Array = new ArrayList<String>();
List_Of_Array.add("A");
List_Of_Array.add("B");
List_Of_Array.add("C");
List_Of_Array.add("D");
List_Of_Array.add("E");
List_Of_Array.add("F");
List_Of_Array.add("G");
List_Of_Array.add("H");

int i[] = {5,3,1};

for (int j = 0; j < i.length; j++) {
    List_Of_Array.remove(i[j]);
}

How to retrieve Request Payload

If I understand the situation correctly, you are just passing json data through the http body, instead of application/x-www-form-urlencoded data.

You can fetch this data with this snippet:

$request_body = file_get_contents('php://input');

If you are passing json, then you can do:

$data = json_decode($request_body);

$data then contains the json data is php array.

php://input is a so called wrapper.

php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".

How to use Redirect in the new react-router-dom of Reactjs

React Router v5 now allows you to simply redirect using history.push() thanks to the useHistory() hook:

import { useHistory } from "react-router"

function HomeButton() {
  let history = useHistory()

  function handleClick() {
    history.push("/home")
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  )
}

Delete file from internal storage

This is an old topic, but I will add my experience, maybe someone finds this helpful

>     2019-11-12 20:05:50.178 27764-27764/com.strba.myapplicationx I/File: /storage/emulated/0/Android/data/com.strba.myapplicationx/files/Readings/JPEG_20191112_200550_4444350520538787768.jpg//file when it was created

2019-11-12 20:05:58.801 27764-27764/com.strba.myapplicationx I/File: content://com.strba.myapplicationx.fileprovider/my_images/JPEG_20191112_200550_4444350520538787768.jpg //same file when trying to delete it

solution1:

              Uri uriDelete=Uri.parse (adapter.getNoteAt (viewHolder.getAdapterPosition ()).getImageuri ());//getter getImageuri on my object from adapter that returns String with content uri

here I initialize Content resolver and delete it with a passed parameter of that URI

            ContentResolver contentResolver = getContentResolver ();
            contentResolver.delete (uriDelete,null ,null );

solution2(my first solution-from head in this time I do know that ): content resolver exists...

              String path = "/storage/emulated/0/Android/data/com.strba.myapplicationx/files/Readings/" +
                    adapter.getNoteAt (viewHolder.getAdapterPosition ()).getImageuri ().substring (58);

            File file = new File (path);
            if (file != null) {
                file.delete ();
            }

Hope that this will be helpful to someone happy coding

Extract directory path and filename

dirname "/usr/home/theconjuring/music/song.mp3" will yield /usr/home/theconjuring/music.

Keep SSH session alive

We can keep our ssh connection alive by having following Global configurations

Add the following line to the /etc/ssh/ssh_config file:

ServerAliveInterval 60

Best way to remove an event handler in jQuery?

All the approaches described did not work for me because I was adding the click event with on() to the document where the element was created at run-time:

$(document).on("click", ".button", function() {
    doSomething();
});


My workaround:

As I could not unbind the ".button" class I just assigned another class to the button that had the same CSS styles. By doing so the live/on-event-handler ignored the click finally:

// prevent another click on the button by assigning another class
$(".button").attr("class","buttonOff");

Hope that helps.

Best C/C++ Network Library

Aggregated List of Libraries

How do I capture the output into a variable from an external process in PowerShell?

I use the following:

Function GetProgramOutput([string]$exe, [string]$arguments)
{
    $process = New-Object -TypeName System.Diagnostics.Process
    $process.StartInfo.FileName = $exe
    $process.StartInfo.Arguments = $arguments
    
    $process.StartInfo.UseShellExecute = $false
    $process.StartInfo.RedirectStandardOutput = $true
    $process.StartInfo.RedirectStandardError = $true
    $process.Start()
    
    $output = $process.StandardOutput.ReadToEnd()   
    $err = $process.StandardError.ReadToEnd()
    
    $process.WaitForExit()
    
    $output
    $err
}
    
$exe = "C:\Program Files\7-Zip\7z.exe"
$arguments = "i"
    
$runResult = (GetProgramOutput $exe $arguments)
$stdout = $runResult[-2]
$stderr = $runResult[-1]
    
[System.Console]::WriteLine("Standard out: " + $stdout)
[System.Console]::WriteLine("Standard error: " + $stderr)

Integration Testing POSTing an entire object to Spring MVC controller

I ran into the same issue a while ago and did solve it by using reflection with some help from Jackson.

First populate a map with all the fields on an Object. Then add those map entries as parameters to the MockHttpServletRequestBuilder.

In this way you can use any Object and you are passing it as request parameters. I'm sure there are other solutions out there but this one worked for us:

    @Test
    public void testFormEdit() throws Exception {
        getMockMvc()
                .perform(
                        addFormParameters(post(servletPath + tableRootUrl + "/" + POST_FORM_EDIT_URL).servletPath(servletPath)
                                .param("entityID", entityId), validEntity)).andDo(print()).andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON)).andExpect(content().string(equalTo(entityId)));
    }

    private MockHttpServletRequestBuilder addFormParameters(MockHttpServletRequestBuilder builder, Object object)
            throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {

        SimpleDateFormat dateFormat = new SimpleDateFormat(applicationSettings.getApplicationDateFormat());

        Map<String, ?> propertyValues = getPropertyValues(object, dateFormat);

        for (Entry<String, ?> entry : propertyValues.entrySet()) {
            builder.param(entry.getKey(),
                    Util.prepareDisplayValue(entry.getValue(), applicationSettings.getApplicationDateFormat()));
        }

        return builder;
    }

    private Map<String, ?> getPropertyValues(Object object, DateFormat dateFormat) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setDateFormat(dateFormat);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mapper.registerModule(new JodaModule());

        TypeReference<HashMap<String, ?>> typeRef = new TypeReference<HashMap<String, ?>>() {};

        Map<String, ?> returnValues = mapper.convertValue(object, typeRef);

        return returnValues;

    }

How to execute only one test spec with angular-cli

You can test only specific file with the Angular CLI (the ng command) like this:

ng test --main ./path/to/test.ts

Further docs are at https://angular.io/cli/test

Note that while this works for standalone library files, it will not work for angular components/services/etc. This is because angular files have dependencies on other files (namely src/test.ts in Angular 7). Sadly the --main flag doesn't take multiple arguments.

TypeError: 'list' object cannot be interpreted as an integer

Error messages usually mean precisely what they say. So they must be read very carefully. When you do that, you'll see that this one is not actually complaining, as you seem to have assumed, about what sort of object your list contains, but rather about what sort of object it is. It's not saying it wants your list to contain integers (plural)—instead, it seems to want your list to be an integer (singular) rather than a list of anything. And since you can't convert a list into a single integer (at least, not in a way that is meaningful in this context) you shouldn't be trying.

So the question is: why does the interpreter seem to want to interpret your list as an integer? The answer is that you are passing your list as the input argument to range, which expects an integer. Don't do that. Say for i in myList instead.

How can I check for NaN values?

for strings in panda take pd.isnull:

if not pd.isnull(atext):
  for word in nltk.word_tokenize(atext):

the function as feature extraction for NLTK

def act_features(atext):
features = {}
if not pd.isnull(atext):
  for word in nltk.word_tokenize(atext):
    if word not in default_stopwords:
      features['cont({})'.format(word.lower())]=True
return features

How to set margin of ImageView using code, not xml

    image = (ImageView) findViewById(R.id.imageID);
    MarginLayoutParams marginParams = new MarginLayoutParams(image.getLayoutParams());
    marginParams.setMargins(left_margin, top_margin, right_margin, bottom_margin);
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(marginParams);
    image.setLayoutParams(layoutParams);

Java JDBC - How to connect to Oracle using Service Name instead of SID

http://download.oracle.com/docs/cd/B28359_01/java.111/b31224/urls.htm#BEIDHCBA

Thin-style Service Name Syntax

Thin-style service names are supported only by the JDBC Thin driver. The syntax is:

@//host_name:port_number/service_name

For example:

jdbc:oracle:thin:scott/tiger@//myhost:1521/myservicename

So I would try:

jdbc:oracle:thin:@//oracle.hostserver2.mydomain.ca:1522/ABCD

Also, per Robert Greathouse's answer, you can also specify the TNS name in the JDBC URL as below:

jdbc:oracle:thin:@(DESCRIPTION =(ADDRESS_LIST =(ADDRESS =(PROTOCOL=TCP)(HOST=blah.example.com)(PORT=1521)))(CONNECT_DATA=(SID=BLAHSID)(GLOBAL_NAME=BLAHSID.WORLD)(SERVER=DEDICATED)))

python selenium click on button

try this:

download firefox, add the plugin "firebug" and "firepath"; after install them go to your webpage, start firebug and find the xpath of the element, it unique in the page so you can't make any mistake.

See picture: instruction

browser.find_element_by_xpath('just copy and paste the Xpath').click()

How to cin to a vector

These were two methods I tried. Both are fine to use.

int main() {
       
        int size,temp;
        cin>>size;
        vector<int> ar(size);
    //method 1 
      for(auto i=0;i<size;i++)
          {   cin>>temp;
              ar.insert(ar.begin()+i,temp);
          }
          for (auto i:ar) 
            cout <<i<<" "; 
            
     //method 2
     for(int i=0;i<size;i++)
     {
        cin>>ar[i];
     }
     
     for (auto i:ar) 
            cout <<i<<" "; 
        return 0;
    }

How to fix C++ error: expected unqualified-id

For what it's worth, I had the same problem but it wasn't because of an extra semicolon, it was because I'd forgotten a semicolon on the previous statement.

My situation was something like

mynamespace::MyObject otherObject

for (const auto& element: otherObject.myVector) {
  // execute arbitrary code on element
  //...
  //...
} 

From this code, my compiler kept telling me:

error: expected unqualified-id before for (const auto& element: otherObject.myVector) { etc... which I'd taken to mean I'd writtten the for loop wrong. Nope! I'd simply forgotten a ; after declaring otherObject.

Get gateway ip address in android

This seems to work well for me. Tested on Touchwiz 5.1, LineageOS 7.1, and CyanogenMod 11.

ip route list match 0 table all scope global

Gives output similar to this:

default via 192.168.1.1 dev wlan0  table wlan0  proto static

Is it possible to insert multiple rows at a time in an SQLite database?

update

As BrianCampbell points out here, SQLite 3.7.11 and above now supports the simpler syntax of the original post. However, the approach shown is still appropriate if you want maximum compatibility across legacy databases.

original answer

If I had privileges, I would bump river's reply: You can insert multiple rows in SQLite, you just need different syntax. To make it perfectly clear, the OPs MySQL example:

INSERT INTO 'tablename' ('column1', 'column2') VALUES
  ('data1', 'data2'),
  ('data1', 'data2'),
  ('data1', 'data2'),
  ('data1', 'data2');

This can be recast into SQLite as:

     INSERT INTO 'tablename'
          SELECT 'data1' AS 'column1', 'data2' AS 'column2'
UNION ALL SELECT 'data1', 'data2'
UNION ALL SELECT 'data1', 'data2'
UNION ALL SELECT 'data1', 'data2'

a note on performance

I originally used this technique to efficiently load large datasets from Ruby on Rails. However, as Jaime Cook points out, it's not clear this is any faster wrapping individual INSERTs within a single transaction:

BEGIN TRANSACTION;
INSERT INTO 'tablename' table VALUES ('data1', 'data2');
INSERT INTO 'tablename' table VALUES ('data3', 'data4');
...
COMMIT;

If efficiency is your goal, you should try this first.

a note on UNION vs UNION ALL

As several people commented, if you use UNION ALL (as shown above), all rows will be inserted, so in this case, you'd get four rows of data1, data2. If you omit the ALL, then duplicate rows will be eliminated (and the operation will presumably be a bit slower). We're using UNION ALL since it more closely matches the semantics of the original post.

in closing

P.S.: Please +1 river's reply, as it presented the solution first.

How do you compare two version Strings in Java?

Using Java 8 Stream to replace leading zeroes in components. This code passed all tests on interviewbit.com

public int compareVersion(String A, String B) {
    List<String> strList1 = Arrays.stream(A.split("\\."))
                                           .map(s -> s.replaceAll("^0+(?!$)", ""))
                                           .collect(Collectors.toList());
    List<String> strList2 = Arrays.stream(B.split("\\."))
                                           .map(s -> s.replaceAll("^0+(?!$)", ""))
                                           .collect(Collectors.toList());
    int len1 = strList1.size();
    int len2 = strList2.size();
    int i = 0;
    while(i < len1 && i < len2){
        if (strList1.get(i).length() > strList2.get(i).length()) return 1;
        if (strList1.get(i).length() < strList2.get(i).length()) return -1;
        int result = new Long(strList1.get(i)).compareTo(new Long(strList2.get(i)));
        if (result != 0) return result;
        i++;
    }
    while (i < len1){
        if (!strList1.get(i++).equals("0")) return 1;
    }
    while (i < len2){
        if (!strList2.get(i++).equals("0")) return -1;
    }
    return 0;
}

How can I read the contents of an URL with Python?

from urllib.request import urlopen

# if has Chinese, apply decode()
html = urlopen("https://blog.csdn.net/qq_39591494/article/details/83934260").read().decode('utf-8')
print(html)

Print all properties of a Python Class

Another way is to call the dir() function (see https://docs.python.org/2/library/functions.html#dir).

a = Animal()
dir(a)   
>>>
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__',
 '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', 
 '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 
 '__weakref__', 'age', 'color', 'kids', 'legs', 'name', 'smell']

Note, that dir() tries to reach any attribute that is possible to reach.

Then you can access the attributes e.g. by filtering with double underscores:

attributes = [attr for attr in dir(a) 
              if not attr.startswith('__')]

This is just an example of what is possible to do with dir(), please check the other answers for proper way of doing this.

How can I create a simple message box in Python?

Not the best, here is my basic Message box using only tkinter.

#Python 3.4
from    tkinter import  messagebox  as  msg;
import  tkinter as      tk;

def MsgBox(title, text, style):
    box = [
        msg.showinfo,       msg.showwarning,    msg.showerror,
        msg.askquestion,    msg.askyesno,       msg.askokcancel,        msg.askretrycancel,
];

tk.Tk().withdraw(); #Hide Main Window.

if style in range(7):
    return box[style](title, text);

if __name__ == '__main__':

Return = MsgBox(#Use Like This.
    'Basic Error Exemple',

    ''.join( [
        'The Basic Error Exemple a problem with test',                      '\n',
        'and is unable to continue. The application must close.',           '\n\n',
        'Error code Test',                                                  '\n',
        'Would you like visit http://wwww.basic-error-exemple.com/ for',    '\n',
        'help?',
    ] ),

    2,
);

print( Return );

"""
Style   |   Type        |   Button      |   Return
------------------------------------------------------
0           Info            Ok              'ok'
1           Warning         Ok              'ok'
2           Error           Ok              'ok'
3           Question        Yes/No          'yes'/'no'
4           YesNo           Yes/No          True/False
5           OkCancel        Ok/Cancel       True/False
6           RetryCancal     Retry/Cancel    True/False
"""

Named placeholders in string formatting

Thanks for all your help! Using all your clues, I've written routine to do exactly what I want -- python-like string formatting using dictionary. Since I'm Java newbie, any hints are appreciated.

public static String dictFormat(String format, Hashtable<String, Object> values) {
    StringBuilder convFormat = new StringBuilder(format);
    Enumeration<String> keys = values.keys();
    ArrayList valueList = new ArrayList();
    int currentPos = 1;
    while (keys.hasMoreElements()) {
        String key = keys.nextElement(),
        formatKey = "%(" + key + ")",
        formatPos = "%" + Integer.toString(currentPos) + "$";
        int index = -1;
        while ((index = convFormat.indexOf(formatKey, index)) != -1) {
            convFormat.replace(index, index + formatKey.length(), formatPos);
            index += formatPos.length();
        }
        valueList.add(values.get(key));
        ++currentPos;
    }
    return String.format(convFormat.toString(), valueList.toArray());
}

Failed to load resource 404 (Not Found) - file location error?

Looks like the path you gave doesn't have any bootstrap files in them.

href="~/lib/bootstrap/dist/css/bootstrap.min.css"

Make sure the files exist over there , else point the files to the correct path, which should be in your case

href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"

CSS background image in :after element

A couple things

(a) you cant have both background-color and background, background will always win. in the example below, i combined them through shorthand, but this will produce the color only as a fallback method when the image does not show.

(b) no-scroll does not work, i don't believe it is a valid property of a background-image. try something like fixed:

.button:after {
    content: "";
    width: 30px;
    height: 30px;
    background:red url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") no-repeat -30px -50px fixed;
    top: 10px;
    right: 5px;
    position: absolute;
    display: inline-block;
}

I updated your jsFiddle to this and it showed the image.

Laravel 5 call a model function in a blade view

want to use model in view as:

{{ Product::find($id) }}

you can use in view:

<?php
$tmp = \App\Product::find($id);
?>
{{ $tmp->name }}

Hope this will help you

Node.js fs.readdir recursive directory search

There is a new module called cup-readdir that recursively searches directories very fast. It uses asynchronous promises and outperforms many popular modules when dealing with deep directory structures.

It can return all files in an array and sort them by their properties, but lacks features like file filtering and entering symlinked directories. This could be useful for large projects where you simply want to get every file from a directory. Here is a link to their project homepage.

How to check if a value exists in a dictionary (python)

In Python 3, you can use

"one" in d.values()

to test if "one" is among the values of your dictionary.

In Python 2, it's more efficient to use

"one" in d.itervalues()

instead.

Note that this triggers a linear scan through the values of the dictionary, short-circuiting as soon as it is found, so this is a lot less efficient than checking whether a key is present.

Get property value from string using reflection

public static List<KeyValuePair<string, string>> GetProperties(object item) //where T : class
    {
        var result = new List<KeyValuePair<string, string>>();
        if (item != null)
        {
            var type = item.GetType();
            var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (var pi in properties)
            {
                var selfValue = type.GetProperty(pi.Name).GetValue(item, null);
                if (selfValue != null)
                {
                    result.Add(new KeyValuePair<string, string>(pi.Name, selfValue.ToString()));
                }
                else
                {
                    result.Add(new KeyValuePair<string, string>(pi.Name, null));
                }
            }
        }
        return result;
    }

This is a way to get all properties with their values in a List.

error running apache after xampp install

I had the same problem, I solved changing the ports.

-> Clicked button Config front of Apache.
1) Select Apache (httpd.conf)
2) searched for this line: Listen 80
3) changed for this: Listen 8081
4) saved file
-> Click Config button front of Apache.
1) Select Apache (httpd-ssl.conf)
2) searched for this line: Listen 443
3) changed for this: Listen 444
4) saved file
I can run xammp from port 8081
http://localhost:8081/
You have to give port number you gave to enter the localhost
Hope this helps you to understand what is happening.

Vim 80 column layout concerns

Newer versions of vim allow a :set numberwidth=x value, which sets the width of the line number display. I don't really use folding etc, so I wouldn't know about that though. Drawing a thin vertical line is beyond the abilities of a console application though. GVim may allow this (I don't use it, so can't comment there).

Pandas: Return Hour from Datetime Column Directly

Since the quickest, shortest answer is in a comment (from Jeff) and has a typo, here it is corrected and in full:

sales['time_hour'] = pd.DatetimeIndex(sales['timestamp']).hour

How can I fix assembly version conflicts with JSON.NET after updating NuGet package references in a new ASP.NET MVC 5 project?

No one mentioned the following, which in my understanding is the correct solution:

Go the csproj of the project where the nuget is installed, and set the AutoGEneratedBindingRedirects to false.

<AutoGenerateBindingRedirects>false</AutoGenerateBindingRedirects>

Full article in MSDN.

How to style UITextview to like Rounded Rect text field?

If you want to keep your controller code clean, you can subclass UITextView like below, and change the class name in the Interface Builder.

RoundTextView.h

#import <UIKit/UIKit.h>
@interface RoundTextView : UITextView
@end

RoundTextView.m

#import "RoundTextView.h"
#import <QuartzCore/QuartzCore.h>
@implementation RoundTextView
-(id) initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self.layer setBorderColor:[[[UIColor grayColor] colorWithAlphaComponent:0.333] CGColor]];
        [self.layer setBorderWidth:1.0];
        self.layer.cornerRadius = 5;
        self.clipsToBounds = YES;
    }
    return self;
}
@end

C# How to change font of a label

You can't change a Font once it's created - so you need to create a new one:

  mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);

Reactjs: Unexpected token '<' Error

Here is a working example from your jsbin:

HTML:

<!DOCTYPE html>
<html>
<head>
<script src="//fb.me/react-with-addons-0.9.0.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <div id="main-content"></div>
</body>
</html>

jsx:

<script type="text/jsx">
/** @jsx React.DOM */
var LikeOrNot = React.createClass({
    render: function () {
      return (
        <p>Like</p>
      );
    }
});

React.renderComponent(<LikeOrNot />, document.getElementById('main-content'));
</script>

Run this code from a single file and your it should work.

Ruby replace string with captured regex pattern

\1 in double quotes needs to be escaped. So you want either

"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/, "\\1")

or

"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/, '\1')

see the docs on gsub where it says "If it is a double-quoted string, both back-references must be preceded by an additional backslash."

That being said, if you just want the result of the match you can do:

"Z_sdsd: sdsd".scan(/^Z_.*(?=:)/)

or

"Z_sdsd: sdsd"[/^Z_.*(?=:)/]

Note that the (?=:) is a non-capturing group so that the : doesn't show up in your match.

CSS 3 slide-in from left transition

Use CSS3 2D transform to avoid performance issues (mobile)

A common pitfall is to animate left/top/right/bottom properties instead of using to achieve the same effect. For a variety of reasons, the semantics of transforms make them easier to offload, but left/top/right/bottom are much more difficult.

Source: Mozilla Developer Network (MDN)


Demo:

_x000D_
_x000D_
var $slider = document.getElementById('slider');
var $toggle = document.getElementById('toggle');

$toggle.addEventListener('click', function() {
    var isOpen = $slider.classList.contains('slide-in');

    $slider.setAttribute('class', isOpen ? 'slide-out' : 'slide-in');
});
_x000D_
#slider {
    position: absolute;
    width: 100px;
    height: 100px;
    background: blue;
    transform: translateX(-100%);
    -webkit-transform: translateX(-100%);
}

.slide-in {
    animation: slide-in 0.5s forwards;
    -webkit-animation: slide-in 0.5s forwards;
}

.slide-out {
    animation: slide-out 0.5s forwards;
    -webkit-animation: slide-out 0.5s forwards;
}
    
@keyframes slide-in {
    100% { transform: translateX(0%); }
}

@-webkit-keyframes slide-in {
    100% { -webkit-transform: translateX(0%); }
}
    
@keyframes slide-out {
    0% { transform: translateX(0%); }
    100% { transform: translateX(-100%); }
}

@-webkit-keyframes slide-out {
    0% { -webkit-transform: translateX(0%); }
    100% { -webkit-transform: translateX(-100%); }
}
_x000D_
<div id="slider" class="slide-in">
    <ul>
        <li>Lorem</li>
        <li>Ipsum</li>
        <li>Dolor</li>
    </ul>
</div>

<button id="toggle" style="position:absolute; top: 120px;">Toggle</button>
_x000D_
_x000D_
_x000D_

How can I limit possible inputs in a HTML5 "number" element?

Or if your max value is for example 99 and minimum 0, you can add this to input element (your value will be rewrited by your max value etc.)

<input type="number" min="0" max="99" 
   onKeyUp="if(this.value>99){this.value='99';}else if(this.value<0){this.value='0';}"
id="yourid">

Then (if you want), you could check if is input really number

gitbash command quick reference

from within the git bash shell type:

>cd /bin
>ls -l

You will then see a long listing of all the unix-like commands available. There are lots of goodies in there.

Width equal to content

I set width as max-content and it worked for me.

width: max-content;

Trigger function when date is selected with jQuery UI datepicker

Use the following code:

$(document).ready(function() {
    $('.date-pick').datepicker( {
     onSelect: function(date) {
        alert(date)
     },
    selectWeek: true,
    inline: true,
    startDate: '01/01/2000',
    firstDay: 1,
  });
});

You can adjust the parameters yourself :-)

Calculate compass bearing / heading to location in Android

The formula will give the bearing using the coordinates of the start point to the end point see

The following code will give you the bearing (angle between 0-360)

private double bearing(Location startPoint, Location endPoint) {
    double longitude1 = startPoint.getLongitude();
    double latitude1 = Math.toRadians(startPoint.getLatitude());

    double longitude2 = endPoint.getLongitude();        
    double latitude2 = Math.toRadians(endPoint.getLatitude());

    double longDiff = Math.toRadians(longitude2 - longitude1);

    double y = Math.sin(longDiff) * Math.cos(latitude2);
    double x = Math.cos(latitude1) * Math.sin(latitude2) - Math.sin(latitude1) * Math.cos(latitude2) * Math.cos(longDiff);

    return Math.toDegrees(Math.atan2(y, x));

}

This works for me hope it will work others as well

How to obtain Signing certificate fingerprint (SHA1) for OAuth 2.0 on Android?

  1. Open your command prompt
  2. Navigate working directory to 1.8.0/bin
  3. paste keytool -list -v -alias androiddebugkey -keystore %USERPROFILE%\.android\debug.keystore
  4. Press enter if it ask you a password

Finding the indices of matching elements in list in Python

You are using .index() which will only find the first occurrence of your value in the list. So if you have a value 1.0 at index 2, and at index 9, then .index(1.0) will always return 2, no matter how many times 1.0 occurs in the list.

Use enumerate() to add indices to your loop instead:

def find(lst, a, b):
    result = []
    for i, x in enumerate(lst):
        if x<a or x>b:
            result.append(i)
    return result

You can collapse this into a list comprehension:

def find(lst, a, b):
    return [i for i, x in enumerate(lst) if x<a or x>b]

Excel Reference To Current Cell

I found the best way to handle this (for me) is to use the following:

Dim MyString as String
MyString = Application.ThisCell.Address
Range(MyString).Select

Hope this helps.

Get visible items in RecyclerView

You can find the first and last visible children of the recycle view and check if the view you're looking for is in the range:

var visibleChild: View = rv.getChildAt(0)
val firstChild: Int = rv.getChildAdapterPosition(visibleChild)
visibleChild = rv.getChildAt(rv.childCount - 1)
val lastChild: Int = rv.getChildAdapterPosition(visibleChild)
println("first visible child is: $firstChild")
println("last visible child is: $lastChild")

List all liquibase sql types

I've found the liquibase.database.typeconversion.core.AbstractTypeConverter class. It lists all types that can be used:

protected DataType getDataType(String columnTypeString, Boolean autoIncrement, String dataTypeName, String precision, String additionalInformation) {
    // Translate type to database-specific type, if possible
    DataType returnTypeName = null;
    if (dataTypeName.equalsIgnoreCase("BIGINT")) {
        returnTypeName = getBigIntType();
    } else if (dataTypeName.equalsIgnoreCase("NUMBER") || dataTypeName.equalsIgnoreCase("NUMERIC")) {
        returnTypeName = getNumberType();
    } else if (dataTypeName.equalsIgnoreCase("BLOB")) {
        returnTypeName = getBlobType();
    } else if (dataTypeName.equalsIgnoreCase("BOOLEAN")) {
        returnTypeName = getBooleanType();
    } else if (dataTypeName.equalsIgnoreCase("CHAR")) {
        returnTypeName = getCharType();
    } else if (dataTypeName.equalsIgnoreCase("CLOB")) {
        returnTypeName = getClobType();
    } else if (dataTypeName.equalsIgnoreCase("CURRENCY")) {
        returnTypeName = getCurrencyType();
    } else if (dataTypeName.equalsIgnoreCase("DATE") || dataTypeName.equalsIgnoreCase(getDateType().getDataTypeName())) {
        returnTypeName = getDateType();
    } else if (dataTypeName.equalsIgnoreCase("DATETIME") || dataTypeName.equalsIgnoreCase(getDateTimeType().getDataTypeName())) {
        returnTypeName = getDateTimeType();
    } else if (dataTypeName.equalsIgnoreCase("DOUBLE")) {
        returnTypeName = getDoubleType();
    } else if (dataTypeName.equalsIgnoreCase("FLOAT")) {
        returnTypeName = getFloatType();
    } else if (dataTypeName.equalsIgnoreCase("INT")) {
        returnTypeName = getIntType();
    } else if (dataTypeName.equalsIgnoreCase("INTEGER")) {
        returnTypeName = getIntType();
    } else if (dataTypeName.equalsIgnoreCase("LONGBLOB")) {
        returnTypeName = getLongBlobType();
    } else if (dataTypeName.equalsIgnoreCase("LONGVARBINARY")) {
        returnTypeName = getBlobType();
    } else if (dataTypeName.equalsIgnoreCase("LONGVARCHAR")) {
        returnTypeName = getClobType();
    } else if (dataTypeName.equalsIgnoreCase("SMALLINT")) {
        returnTypeName = getSmallIntType();
    } else if (dataTypeName.equalsIgnoreCase("TEXT")) {
        returnTypeName = getClobType();
    } else if (dataTypeName.equalsIgnoreCase("TIME") || dataTypeName.equalsIgnoreCase(getTimeType().getDataTypeName())) {
        returnTypeName = getTimeType();
    } else if (dataTypeName.toUpperCase().contains("TIMESTAMP")) {
        returnTypeName = getDateTimeType();
    } else if (dataTypeName.equalsIgnoreCase("TINYINT")) {
        returnTypeName = getTinyIntType();
    } else if (dataTypeName.equalsIgnoreCase("UUID")) {
        returnTypeName = getUUIDType();
    } else if (dataTypeName.equalsIgnoreCase("VARCHAR")) {
        returnTypeName = getVarcharType();
    } else if (dataTypeName.equalsIgnoreCase("NVARCHAR")) {
        returnTypeName = getNVarcharType();
    } else {
        return new CustomType(columnTypeString,0,2);
    }

How can I access Oracle from Python?

Here's what worked for me. My Python and Oracle versions are slightly different from yours, but the same approach should apply. Just make sure the cx_Oracle binary installer version matches your Oracle client and Python versions.

My versions:

  • Python 2.7
  • Oracle Instant Client 11G R2
  • cx_Oracle 5.0.4 (Unicode, Python 2.7, Oracle 11G)
  • Windows XP SP3

Steps:

  1. Download the Oracle Instant Client package. I used instantclient-basic-win32-11.2.0.1.0.zip. Unzip it to C:\your\path\to\instantclient_11_2
  2. Download and run the cx_Oracle binary installer. I used cx_Oracle-5.0.4-11g-unicode.win32-py2.7.msi. I installed it for all users and pointed it to the Python 2.7 location it found in the registry.
  3. Set the ORACLE_HOME and PATH environment variables via a batch script or whatever mechanism makes sense in your app context, so that they point to the Oracle Instant Client directory. See oracle_python.bat source below. I'm sure there must be a more elegant solution for this, but I wanted to limit my system-wide changes as much as possible. Make sure you put the targeted Oracle Instant Client directory at the beginning of the PATH (or at least ahead of any other Oracle client directories). Right now, I'm only doing command-line stuff so I just run oracle_python.bat in the shell before running any programs that require cx_Oracle.
  4. Run regedit and check to see if there's an NLS_LANG key set at \HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE. If so, rename the key (I changed it to NLS_LANG_OLD) or unset it. This key should only be used as the default NLS_LANG value for Oracle 7 client, so it's safe to remove it unless you happen to be using Oracle 7 client somewhere else. As always, be sure to backup your registry before making changes.
  5. Now, you should be able to import cx_Oracle in your Python program. See the oracle_test.py source below. Note that I had to set the connection and SQL strings to Unicode for my version of cx_Oracle.

Source: oracle_python.bat

@echo off
set ORACLE_HOME=C:\your\path\to\instantclient_11_2
set PATH=%ORACLE_HOME%;%PATH%

Source: oracle_test.py

import cx_Oracle

conn_str = u'user/password@host:port/service'
conn = cx_Oracle.connect(conn_str)
c = conn.cursor()
c.execute(u'select your_col_1, your_col_2 from your_table')
for row in c:
    print row[0], "-", row[1]
conn.close()

Possible Issues:

  • "ORA-12705: Cannot access NLS data files or invalid environment specified" - I ran into this before I made the NLS_LANG registry change.
  • "TypeError: argument 1 must be unicode, not str" - if you need to set the connection string to Unicode.
  • "TypeError: expecting None or a string" - if you need to set the SQL string to Unicode.
  • "ImportError: DLL load failed: The specified procedure could not be found." - may indicate that cx_Oracle can't find the appropriate Oracle client DLL.

Can I disable a CSS :hover effect via JavaScript?

This is similar to aSeptik's answer, but what about this approach? Wrap the CSS code which you want to disable using JavaScript in <noscript> tags. That way if javaScript is off, the CSS :hover will be used, otherwise the JavaScript effect will be used.

Example:

<noscript>
<style type="text/css">
ul#mainFilter a:hover {
  /* some CSS attributes here */
}
</style>
</noscript>
<script type="text/javascript">
$("ul#mainFilter a").hover(
     function(o){ /* ...do your stuff... */ }, 
     function(o){ /* ...do your stuff... */ });
</script>

What integer hash function are good that accepts an integer hash key?

Fast and good hash functions can be composed from fast permutations with lesser qualities, like

  • multiplication with an uneven integer
  • binary rotations
  • xorshift

To yield a hashing function with superior qualities, like demonstrated with PCG for random number generation.

This is in fact also the recipe rrxmrrxmsx_0 and murmur hash are using, knowingly or unknowingly.

I personally found

uint64_t xorshift(const uint64_t& n,int i){
  return n^(n>>i);
}
uint64_t hash(const uint64_t& n){
  uint64_t p = 0x5555555555555555ull; // pattern of alternating 0 and 1
  uint64_t c = 17316035218449499591ull;// random uneven integer constant; 
  return c*xorshift(p*xorshift(n,32),32);
}

to be good enough.

A good hash function should

  1. be bijective to not loose information, if possible and have the least collisions
  2. cascade as much and as evenly as possible, i.e. each input bit should flip every output bit with probability 0.5.

Let's first look at the identity function. It satisfies 1. but not 2. :

identity function

Input bit n determines output bit n with a correlation of 100% (red) and no others, they are therefore blue, giving a perfect red line across.

A xorshift(n,32) is not much better, yielding one and half a line. Still satisfying 1., because it is invertible with a second application.

xorshift

A multiplication with an unsigned integer ("Knuth's multiplicative method") is much better, cascading more strongly and flipping more output bits with a probability of 0.5, which is what you want, in green. It satisfies 1. as for each uneven integer there is a multiplicative inverse.

knuth

Combining the two gives the following output, still satisfying 1. as the composition of two bijective functions yields another bijective function.

knuth•xorshift

A second application of multiplication and xorshift will yield the following:

proposed hash

Or you can use Galois field multiplications like GHash, they have become reasonably fast on modern CPUs and have superior qualities in one step.

   uint64_t const inline gfmul(const uint64_t& i,const uint64_t& j){           
     __m128i I{};I[0]^=i;                                                          
     __m128i J{};J[0]^=j;                                                          
     __m128i M{};M[0]^=0xb000000000000000ull;                                      
     __m128i X = _mm_clmulepi64_si128(I,J,0);                                      
     __m128i A = _mm_clmulepi64_si128(X,M,0);                                      
     __m128i B = _mm_clmulepi64_si128(A,M,0);                                      
     return A[0]^A[1]^B[1]^X[0]^X[1];                                              
   }

Git: add vs push vs commit

  • git add adds files to the Git index, which is a staging area for objects prepared to be commited.
  • git commit commits the files in the index to the repository, git commit -a is a shortcut to add all the modified tracked files to the index first.
  • git push sends all the pending changes to the remote repository to which your branch is mapped (eg. on GitHub).

In order to understand Git you would need to invest more effort than just glancing over the documentation, but it's definitely worth it. Just don't try to map Git commands directly to Subversion, as most of them don't have a direct counterpart.

How to restart ADB manually from Android Studio

I do not find a perfect way in Android Studio, get the process id and kill it from terminal:

ps -e | grep adb
kill -9 pid_adb

Git On Custom SSH Port

(Update: a few years later Google and Qwant "airlines" still send me here when searching for "git non-default ssh port") A probably better way in newer git versions is to use the GIT_SSH_COMMAND ENV.VAR like:

GIT_SSH_COMMAND="ssh -oPort=1234 -i ~/.ssh/myPrivate_rsa.key" \ git clone myuser@myGitRemoteServer:/my/remote/git_repo/path

This has the added advantage of allowing any other ssh suitable option (port, priv.key, IPv6, PKCS#11 device, ...).

How to check if object property exists with a variable holding the property name?

For own property :

var loan = { amount: 150 };
if(Object.prototype.hasOwnProperty.call(loan, "amount")) 
{ 
   //will execute
}

Note: using Object.prototype.hasOwnProperty is better than loan.hasOwnProperty(..), in case a custom hasOwnProperty is defined in the prototype chain (which is not the case here), like

var foo = {
      hasOwnProperty: function() {
        return false;
      },
      bar: 'Here be dragons'
    };

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

To include inherited properties in the finding use the in operator: (but you must place an object at the right side of 'in', primitive values will throw error, e.g. 'length' in 'home' will throw error, but 'length' in new String('home') won't)

const yoshi = { skulk: true };
const hattori = { sneak: true };
const kuma = { creep: true };
if ("skulk" in yoshi) 
    console.log("Yoshi can skulk");

if (!("sneak" in yoshi)) 
    console.log("Yoshi cannot sneak");

if (!("creep" in yoshi)) 
    console.log("Yoshi cannot creep");

Object.setPrototypeOf(yoshi, hattori);

if ("sneak" in yoshi)
    console.log("Yoshi can now sneak");
if (!("creep" in hattori))
    console.log("Hattori cannot creep");

Object.setPrototypeOf(hattori, kuma);

if ("creep" in hattori)
    console.log("Hattori can now creep");
if ("creep" in yoshi)
    console.log("Yoshi can also creep");

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in

Note: One may be tempted to use typeof and [ ] property accessor as the following code which doesn't work always ...

var loan = { amount: 150 };

loan.installment = undefined;

if("installment" in loan) // correct
{
    // will execute
}

if(typeof loan["installment"] !== "undefined") // incorrect
{
    // will not execute
}

Missing Push Notification Entitlement

I got this message for a different reason -- I submitted an app via Xcode without first creating an App Store Distribution Profile specifically for the app. I believe Xcode automatically uses a wildcard App Store profile if you have one installed. But an app uses Push Notifications requires its own profile.

The fix is to create a new App Store Distribution profile for the app. Then you download it, drag it onto Xcode, and modify your project Build Settings > Code Signing > Release to use the new profile.

How to create a temporary directory/folder in Java?

As you can see in the other answers, no standard approach has arisen. Hence you already mentioned Apache Commons, I propose the following approach using FileUtils from Apache Commons IO:

/**
 * Creates a temporary subdirectory in the standard temporary directory.
 * This will be automatically deleted upon exit.
 * 
 * @param prefix
 *            the prefix used to create the directory, completed by a
 *            current timestamp. Use for instance your application's name
 * @return the directory
 */
public static File createTempDirectory(String prefix) {

    final File tmp = new File(FileUtils.getTempDirectory().getAbsolutePath()
            + "/" + prefix + System.currentTimeMillis());
    tmp.mkdir();
    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {

            try {
                FileUtils.deleteDirectory(tmp);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    return tmp;

}

This is preferred since apache commons the library that comes as closest to the asked "standard" and works with both JDK 7 and older versions. This also returns an "old" File instance (which is stream based) and not a "new" Path instance (which is buffer based and would be the result of JDK7's getTemporaryDirectory() method) -> Therefore it returns what most people need when they want to create a temporary directory.

Setting WPF image source in code

I am a new to WPF, but not in .NET.

I have spent five hours trying to add a PNG file to a "WPF Custom Control Library Project" in .NET 3.5 (Visual Studio 2010) and setting it as a background of an image-inherited control.

Nothing relative with URIs worked. I can not imagine why there is no method to get a URI from a resource file, through IntelliSense, maybe as:

Properties.Resources.ResourceManager.GetURI("my_image");

I've tried a lot of URIs and played with ResourceManager, and Assembly's GetManifest methods, but all there were exceptions or NULL values.

Here I pot the code that worked for me:

// Convert the image in resources to a Stream
Stream ms = new MemoryStream()
Properties.Resources.MyImage.Save(ms, ImageFormat.Png);

// Create a BitmapImage with the stream.
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = ms;
bitmap.EndInit();

// Set as source
Source = bitmap;

How to get time (hour, minute, second) in Swift 3 using NSDate?

In Swift 3 you can do this,

let date = Date()
let hour = Calendar.current.component(.hour, from: date)

PHP: Update multiple MySQL fields in single query

If you are using pdo, it will look like

$sql = "UPDATE users SET firstname = :firstname, lastname = :lastname WHERE id= :id";
$query = $this->pdo->prepare($sql);
$result = $query->execute(array(':firstname' => $firstname, ':lastname' => $lastname, ':id' => $id));

How to call VS Code Editor from terminal / command line

In windows you can add following path to environment variable

C:\Users\username\AppData\Local\Programs\Microsoft VS Code\bin

MSVCP120d.dll missing

I have the same problem with you when I implement OpenCV 2.4.11 on VS 2015. I tried to solve this problem by three methods one by one but they didn't work:

  1. download MSVCP120.DLL online and add it to windows path and OpenCV bin file path
  2. install Visual C++ Redistributable Packages for Visual Studio 2013 both x86 and x86
  3. adjust Debug mode. Go to configuration > C/C++ > Code Generation > Runtime Library and select Multi-threaded Debug (/MTd)

Finally I solved this problem by reinstalling VS2015 with selecting all the options that can be installed, it takes a lot space but it really works.

jQuery: get parent tr for selected radio button

Try this.

You don't need to prefix attribute name by @ in jQuery selector. Use closest() method to get the closest parent element matching the selector.

$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');

You can simplify your method like this

function getSelectedRowGuid() {
    return GetRowGuid(
      $("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}

closest() - Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.

Node.js: How to send headers with form data using request module?

I think it's just because you have forgot HTTP METHOD. The default HTTP method of request is GET.

You should add method: 'POST' and your code will work if your backend receive the post method.

var req = require('request');

req.post({
   url: 'someUrl',
   form: { username: 'user', password: '', opaque: 'someValue', logintype: '1'},
   headers: { 
      'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36',
      'Content-Type' : 'application/x-www-form-urlencoded' 
   },
   method: 'POST'
  },

  function (e, r, body) {
      console.log(body);
  });

How to send post request to the below post method using postman rest client

1.Open postman app 2.Enter the URL in the URL bar in postman app along with the name of the design.Use slash(/) after URL to give the design name. 3.Select POST from the dropdown list from URL textbox. 4.Select raw from buttons available below the URL textbox. 5.Select JSON from the dropdown. 6.In the text area enter your data to be updated and enter send. 7.Select GET from dropdown list from URL textbox and enter send to see the updated result.

Equivalent of typedef in C#

Both C++ and C# are missing easy ways to create a new type which is semantically identical to an exisiting type. I find such 'typedefs' totally essential for type-safe programming and its a real shame c# doesn't have them built-in. The difference between void f(string connectionID, string username) to void f(ConID connectionID, UserName username) is obvious ...

(You can achieve something similar in C++ with boost in BOOST_STRONG_TYPEDEF)

It may be tempting to use inheritance but that has some major limitations:

  • it will not work for primitive types
  • the derived type can still be casted to the original type, ie we can send it to a function receiving our original type, this defeats the whole purpose
  • we cannot derive from sealed classes (and ie many .NET classes are sealed)

The only way to achieve a similar thing in C# is by composing our type in a new class:

Class SomeType { 
  public void Method() { .. }
}

sealed Class SomeTypeTypeDef {
  public SomeTypeTypeDef(SomeType composed) { this.Composed = composed; }

  private SomeType Composed { get; }

  public override string ToString() => Composed.ToString();
  public override int GetHashCode() => HashCode.Combine(Composed);
  public override bool Equals(object obj) => obj is TDerived o && Composed.Equals(o.Composed); 
  public bool Equals(SomeTypeTypeDefo) => object.Equals(this, o);

  // proxy the methods we want
  public void Method() => Composed.Method();
}

While this will work it is very verbose for just a typedef. In addition we have a problem with serializing (ie to Json) as we want to serialize the class through its Composed property.

Below is a helper class that uses the "Curiously Recurring Template Pattern" to make this much simpler:

namespace Typedef {

  [JsonConverter(typeof(JsonCompositionConverter))]
  public abstract class Composer<TDerived, T> : IEquatable<TDerived> where TDerived : Composer<TDerived, T> {
    protected Composer(T composed) { this.Composed = composed; }
    protected Composer(TDerived d) { this.Composed = d.Composed; }

    protected T Composed { get; }

    public override string ToString() => Composed.ToString();
    public override int GetHashCode() => HashCode.Combine(Composed);
    public override bool Equals(object obj) => obj is Composer<TDerived, T> o && Composed.Equals(o.Composed); 
    public bool Equals(TDerived o) => object.Equals(this, o);
  }

  class JsonCompositionConverter : JsonConverter {
    static FieldInfo GetCompositorField(Type t) {
      var fields = t.BaseType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy);
      if (fields.Length!=1) throw new JsonSerializationException();
      return fields[0];
    }

    public override bool CanConvert(Type t) {
      var fields = t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy);
      return fields.Length == 1;
    }

    // assumes Compositor<T> has either a constructor accepting T or an empty constructor
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
      while (reader.TokenType == JsonToken.Comment && reader.Read()) { };
      if (reader.TokenType == JsonToken.Null) return null; 
      var compositorField = GetCompositorField(objectType);
      var compositorType = compositorField.FieldType;
      var compositorValue = serializer.Deserialize(reader, compositorType);
      var ctorT = objectType.GetConstructor(new Type[] { compositorType });
      if (!(ctorT is null)) return Activator.CreateInstance(objectType, compositorValue);
      var ctorEmpty = objectType.GetConstructor(new Type[] { });
      if (ctorEmpty is null) throw new JsonSerializationException();
      var res = Activator.CreateInstance(objectType);
      compositorField.SetValue(res, compositorValue);
      return res;
    }

    public override void WriteJson(JsonWriter writer, object o, JsonSerializer serializer) {
      var compositorField = GetCompositorField(o.GetType());
      var value = compositorField.GetValue(o);
      serializer.Serialize(writer, value);
    }
  }

}

With Composer the above class becomes simply:

sealed Class SomeTypeTypeDef : Composer<SomeTypeTypeDef, SomeType> {
   public SomeTypeTypeDef(SomeType composed) : base(composed) {}

   // proxy the methods we want
   public void Method() => Composed.Method();
}

And in addition the SomeTypeTypeDef will serialize to Json in the same way that SomeType does.

Hope this helps !

How can I get a count of the total number of digits in a number?

int i = 855865264;
int NumLen = i.ToString().Length;

PHP - iterate on string characters

Iterate string:

for ($i = 0; $i < strlen($str); $i++){
    echo $str[$i];
}

What does `m_` variable prefix mean?

To complete the current answers and as the question is not language specific, some C-project use the prefix m_ to define global variables that are specific to a file - and g_ for global variables that have a scoped larger than the file they are defined.
In this case global variables defined with prefix m_ should be defined as static.

See EDK2 (a UEFI Open-Source implementation) coding convention for an example of project using this convention.

.attr('checked','checked') does not work

$('.checkbox').prop('checked',true); 
$('.checkbox').prop('checked',false);

... works perfectly with jquery1.9.1

Sticky and NON-Sticky sessions

When your website is served by only one web server, for each client-server pair, a session object is created and remains in the memory of the web server. All the requests from the client go to this web server and update this session object. If some data needs to be stored in the session object over the period of interaction, it is stored in this session object and stays there as long as the session exists.

However, if your website is served by multiple web servers which sit behind a load balancer, the load balancer decides which actual (physical) web-server should each request go to. For example, if there are 3 web servers A, B and C behind the load balancer, it is possible that www.mywebsite.com/index.jsp is served from server A, www.mywebsite.com/login.jsp is served from server B and www.mywebsite.com/accoutdetails.php are served from server C.

Now, if the requests are being served from (physically) 3 different servers, each server has created a session object for you and because these session objects sit on three independent boxes, there's no direct way of one knowing what is there in the session object of the other. In order to synchronize between these server sessions, you may have to write/read the session data into a layer which is common to all - like a DB. Now writing and reading data to/from a db for this use-case may not be a good idea. Now, here comes the role of sticky-session.

If the load balancer is instructed to use sticky sessions, all of your interactions will happen with the same physical server, even though other servers are present. Thus, your session object will be the same throughout your entire interaction with this website.

To summarize, In case of Sticky Sessions, all your requests will be directed to the same physical web server while in case of a non-sticky loadbalancer may choose any webserver to serve your requests.

As an example, you may read about Amazon's Elastic Load Balancer and sticky sessions here : http://aws.typepad.com/aws/2010/04/new-elastic-load-balancing-feature-sticky-sessions.html

count files in specific folder and display the number into 1 cel

Try below code :

Assign the path of the folder to variable FolderPath before running the below code.

Sub sample()

    Dim FolderPath As String, path As String, count As Integer
    FolderPath = "C:\Documents and Settings\Santosh\Desktop"

    path = FolderPath & "\*.xls"

    Filename = Dir(path)

    Do While Filename <> ""
       count = count + 1
        Filename = Dir()
    Loop

    Range("Q8").Value = count
    'MsgBox count & " : files found in folder"
End Sub

How to take MySQL database backup using MySQL Workbench?

  1. On ‘HOME’ page -- > select 'Manage Import / Export' under 'Server Administration'

  2. A box comes up... choose which server holds the data you want to back up.

  3. On the 'Export to Disk' tab, then select which databases you want to export.

  4. If you want all the tables, select option ‘Export to self-contained file’, otherwise choose the other option for a selective restore

  5. If you need advanced options, see other post, otherwise then click ‘Start Export’

Entity Framework Join 3 Tables

I think it will be easier using syntax-based query:

var entryPoint = (from ep in dbContext.tbl_EntryPoint
                 join e in dbContext.tbl_Entry on ep.EID equals e.EID
                 join t in dbContext.tbl_Title on e.TID equals t.TID
                 where e.OwnerID == user.UID
                 select new {
                     UID = e.OwnerID,
                     TID = e.TID,
                     Title = t.Title,
                     EID = e.EID
                 }).Take(10);

And you should probably add orderby clause, to make sure Top(10) returns correct top ten items.

proper way to logout from a session in PHP

From the session_destroy() page in the PHP manual:

<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();

// Unset all of the session variables.
$_SESSION = array();

// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

// Finally, destroy the session.
session_destroy();
?>

Is there a maximum number you can set Xmx to when trying to increase jvm memory?

Yes, there is a maximum, but it's system dependent. Try it and see, doubling until you hit a limit then searching down. At least with Sun JRE 1.6 on linux you get interesting if not always informative error messages (peregrino is netbook running 32 bit ubuntu with 2G RAM and no swap):

peregrino:$ java -Xmx4096M -cp bin WheelPrimes 
Invalid maximum heap size: -Xmx4096M
The specified size exceeds the maximum representable size.
Could not create the Java virtual machine.

peregrino:$ java -Xmx4095M -cp bin WheelPrimes 
Error occurred during initialization of VM
Incompatible minimum and maximum heap sizes specified

peregrino:$ java -Xmx4092M -cp bin WheelPrimes 
Error occurred during initialization of VM
The size of the object heap + VM data exceeds the maximum representable size

peregrino:$ java -Xmx4000M -cp bin WheelPrimes 
Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.

(experiment reducing from 4000M until)

peregrino:$ java -Xmx2686M -cp bin WheelPrimes 
(normal execution)

Most are self explanatory, except -Xmx4095M which is rather odd (maybe a signed/unsigned comparison?), and that it claims to reserve 2686M on a 2GB machine with no swap. But it does hint that the maximum size is 4G not 2G for a 32 bit VM, if the OS allows you to address that much.

Bootstrap Modal Backdrop Remaining

This is for someone who cannot get it fixed after trying almost everything listed above. Please go and do some basic checking like the order of scripts, referencing them and stuff. Personally, I used a bundle from bootstrap that did not let it work for some reason. Switching to separate scripts made my life a lot easier. So yeah! Just-in-case.

How to export table data in MySql Workbench to csv?

MySQL Workbench 6.3.6

Export the SELECT result

  • After you run a SELECT: Query > Export Results...

    Query Export Results

Export table data

  • In the Navigator, right click on the table > Table Data Export Wizard

    Table Data Export

  • All columns and rows are included by default, so click on Next.

  • Select File Path, type, Field Separator (by default it is ;, not ,!!!) and click on Next.

    CSV

  • Click Next > Next > Finish and the file is created in the specified location

C# How can I check if a URL exists/is valid?

Here is another implementation of this solution:

using System.Net;

///
/// Checks the file exists or not.
///
/// The URL of the remote file.
/// True : If the file exits, False if file not exists
private bool RemoteFileExists(string url)
{
    try
    {
        //Creating the HttpWebRequest
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        //Setting the Request method HEAD, you can also use GET too.
        request.Method = "HEAD";
        //Getting the Web Response.
        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
        //Returns TRUE if the Status code == 200
        response.Close();
        return (response.StatusCode == HttpStatusCode.OK);
    }
    catch
    {
        //Any exception will returns false.
        return false;
    }
}

From: http://www.dotnetthoughts.net/2009/10/14/how-to-check-remote-file-exists-using-c/

UNION with WHERE clause

i think it will depend on many things - run EXPLAIN PLAN on each one to see what your optimizer selects. Otherwise - as @rayman suggests - run them both and time them.

JSON array get length

have you tried size() ? Something like :

jar.size();

Hope it helps.

Bootstrap 4 datapicker.js not included

You can use this and then you can add just a class form from bootstrap. (does not matter which version)

<div class="form-group">
 <label >Begin voorverkoop periode</label>
 <input type="date" name="bday" max="3000-12-31" 
        min="1000-01-01" class="form-control">
</div>
<div class="form-group">
 <label >Einde voorverkoop periode</label>
 <input type="date" name="bday" min="1000-01-01"
        max="3000-12-31" class="form-control">
</div>

How to tell if a string is not defined in a Bash shell script

A summary of tests.

[ -n "$var" ] && echo "var is set and not empty"
[ -z "$var" ] && echo "var is unset or empty"
[ "${var+x}" = "x" ] && echo "var is set"  # may or may not be empty
[ -n "${var+x}" ] && echo "var is set"  # may or may not be empty
[ -z "${var+x}" ] && echo "var is unset"
[ -z "${var-x}" ] && echo "var is set and empty"

Converting a SimpleXML Object to an Array

I found this in the PHP manual comments:

/**
 * function xml2array
 *
 * This function is part of the PHP manual.
 *
 * The PHP manual text and comments are covered by the Creative Commons 
 * Attribution 3.0 License, copyright (c) the PHP Documentation Group
 *
 * @author  k dot antczak at livedata dot pl
 * @date    2011-04-22 06:08 UTC
 * @link    http://www.php.net/manual/en/ref.simplexml.php#103617
 * @license http://www.php.net/license/index.php#doc-lic
 * @license http://creativecommons.org/licenses/by/3.0/
 * @license CC-BY-3.0 <http://spdx.org/licenses/CC-BY-3.0>
 */
function xml2array ( $xmlObject, $out = array () )
{
    foreach ( (array) $xmlObject as $index => $node )
        $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;

    return $out;
}

It could help you. However, if you convert XML to an array you will loose all attributes that might be present, so you cannot go back to XML and get the same XML.

PHP read and write JSON from file

The clue is in the error message - if you look at the documentation for json_decode note that it can take a second param, which controls whether it returns an array or an object - it defaults to object.

So change your call to

$json = json_decode(file_get_contents($file), true);

And it'll return an associative array and your code should work fine.

installing apache: no VCRUNTIME140.dll

Problem: Wamp Won't Turn Green & VCRUNTIME140.dll error

Solved:)

You need C++ Redistributable for Visual Studio 2015 RC. Try to download the file, vc_redist.x64.exe from here, https://www.microsoft.com/en-us/download/details.aspx?id=48145

if you already installed then uninstalled it first

  1. I installed the vc_redist.x64.exe (if you OS is 32 bit then you should download vc_redist.x86.exe)
  2. then installed the wampserver (if you already installed then unsintalled it first)

Sort divs in jQuery based on attribute 'data-sort'?

Answered the same question here:

To repost:

After searching through many solutions I decided to blog about how to sort in jquery. In summary, steps to sort jquery "array-like" objects by data attribute...

  1. select all object via jquery selector
  2. convert to actual array (not array-like jquery object)
  3. sort the array of objects
  4. convert back to jquery object with the array of dom objects

Html

<div class="item" data-order="2">2</div>
<div class="item" data-order="1">1</div>
<div class="item" data-order="4">4</div>
<div class="item" data-order="3">3</div>

Plain jquery selector

$('.item');
[<div class="item" data-order="2">2</div>,
 <div class="item" data-order="1">1</div>,
 <div class="item" data-order="4">4</div>,
 <div class="item" data-order="3">3</div>
]

Lets sort this by data-order

function getSorted(selector, attrName) {
    return $($(selector).toArray().sort(function(a, b){
        var aVal = parseInt(a.getAttribute(attrName)),
            bVal = parseInt(b.getAttribute(attrName));
        return aVal - bVal;
    }));
}
> getSorted('.item', 'data-order')
[<div class="item" data-order="1">1</div>,
 <div class="item" data-order="2">2</div>,
 <div class="item" data-order="3">3</div>,
 <div class="item" data-order="4">4</div>
]

See how getSorted() works.

Hope this helps!

phpMyAdmin on MySQL 8.0

 mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'rootpassword';

Login through the command line, it will work after that.

Visual Studio 2015 doesn't have cl.exe

Visual Studio 2015 doesn't install C++ by default. You have to rerun the setup, select Modify and then check Programming Language -> C++

How to create an Oracle sequence starting with max value from a table?

DECLARE
    v_max NUMBER;
BEGIN
    SELECT (NVL (MAX (<COLUMN_NAME>), 0) + 1) INTO v_max FROM <TABLE_NAME>;
    EXECUTE IMMEDIATE 'CREATE SEQUENCE <SEQUENCE_NAME> INCREMENT BY 1 START WITH ' || v_max || ' NOCYCLE CACHE 20 NOORDER';
END;

Windows XP or later Windows: How can I run a batch file in the background with no window displayed?

I think this is the easiest and shortest solution to running a batch file without opening the DOS window, it can be very distracting when you want to schedule a set of commands to run periodically, so the DOS window keeps poping up, here is your solution. Use a VBS Script to call the batch file ...

Set WshShell = CreateObject("WScript.Shell" ) 
WshShell.Run chr(34) & "C:\Batch Files\ mycommands.bat" & Chr(34), 0 
Set WshShell = Nothing 

Copy the lines above to an editor and save the file with .VBS extension. Edit the .BAT file name and path accordingly.

Draw path between two points using Google Maps Android API v2

Try below solution to draw path with animation and also get time and distance between two points.

DirectionHelper.java

public class DirectionHelper {

    public List<List<HashMap<String, String>>> parse(JSONObject jObject) {

        List<List<HashMap<String, String>>> routes = new ArrayList<>();
        JSONArray jRoutes;
        JSONArray jLegs;
        JSONArray jSteps;
        JSONObject jDistance = null;
        JSONObject jDuration = null;

        try {

            jRoutes = jObject.getJSONArray("routes");

            /** Traversing all routes */
            for (int i = 0; i < jRoutes.length(); i++) {
                jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
                List path = new ArrayList<>();

                /** Traversing all legs */
                for (int j = 0; j < jLegs.length(); j++) {

                    /** Getting distance from the json data */
                    jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
                    HashMap<String, String> hmDistance = new HashMap<String, String>();
                    hmDistance.put("distance", jDistance.getString("text"));

                    /** Getting duration from the json data */
                    jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
                    HashMap<String, String> hmDuration = new HashMap<String, String>();
                    hmDuration.put("duration", jDuration.getString("text"));

                    /** Adding distance object to the path */
                    path.add(hmDistance);

                    /** Adding duration object to the path */
                    path.add(hmDuration);

                    jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");

                    /** Traversing all steps */
                    for (int k = 0; k < jSteps.length(); k++) {
                        String polyline = "";
                        polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
                        List<LatLng> list = decodePoly(polyline);

                        /** Traversing all points */
                        for (int l = 0; l < list.size(); l++) {
                            HashMap<String, String> hm = new HashMap<>();
                            hm.put("lat", Double.toString((list.get(l)).latitude));
                            hm.put("lng", Double.toString((list.get(l)).longitude));
                            path.add(hm);
                        }
                    }
                    routes.add(path);
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
        }


        return routes;
    }

    //Method to decode polyline points
    private List<LatLng> decodePoly(String encoded) {

        List<LatLng> poly = new ArrayList<>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;

        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng p = new LatLng((((double) lat / 1E5)),
                    (((double) lng / 1E5)));
            poly.add(p);
        }

        return poly;
    }
}

GetPathFromLocation.java

public class GetPathFromLocation extends AsyncTask<String, Void, List<List<HashMap<String, String>>>> {

    private Context context;
    private String TAG = "GetPathFromLocation";
    private LatLng source, destination;
    private ArrayList<LatLng> wayPoint;
    private GoogleMap mMap;
    private boolean animatePath, repeatDrawingPath;
    private DirectionPointListener resultCallback;
    private ProgressDialog progressDialog;

    //https://www.mytrendin.com/draw-route-two-locations-google-maps-android/
    //https://www.androidtutorialpoint.com/intermediate/google-maps-draw-path-two-points-using-google-directions-google-map-android-api-v2/

    public GetPathFromLocation(Context context, LatLng source, LatLng destination, ArrayList<LatLng> wayPoint, GoogleMap mMap, boolean animatePath, boolean repeatDrawingPath, DirectionPointListener resultCallback) {
        this.context = context;
        this.source = source;
        this.destination = destination;
        this.wayPoint = wayPoint;
        this.mMap = mMap;
        this.animatePath = animatePath;
        this.repeatDrawingPath = repeatDrawingPath;
        this.resultCallback = resultCallback;
    }

    synchronized public String getUrl(LatLng source, LatLng dest, ArrayList<LatLng> wayPoint) {

        String url = "https://maps.googleapis.com/maps/api/directions/json?sensor=false&mode=driving&origin="
                + source.latitude + "," + source.longitude + "&destination=" + dest.latitude + "," + dest.longitude;
        for (int centerPoint = 0; centerPoint < wayPoint.size(); centerPoint++) {
            if (centerPoint == 0) {
                url = url + "&waypoints=optimize:true|" + wayPoint.get(centerPoint).latitude + "," + wayPoint.get(centerPoint).longitude;
            } else {
                url = url + "|" + wayPoint.get(centerPoint).latitude + "," + wayPoint.get(centerPoint).longitude;
            }
        }
        url = url + "&key=" + context.getResources().getString(R.string.google_api_key);

        return url;
    }

    public int getRandomColor() {
        Random rnd = new Random();
        return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("Please wait...");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected List<List<HashMap<String, String>>> doInBackground(String... url) {

        String data;

        try {
            InputStream inputStream = null;
            HttpURLConnection connection = null;
            try {
                URL directionUrl = new URL(getUrl(source, destination, wayPoint));
                connection = (HttpURLConnection) directionUrl.openConnection();
                connection.connect();
                inputStream = connection.getInputStream();

                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer stringBuffer = new StringBuffer();

                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line);
                }

                data = stringBuffer.toString();
                bufferedReader.close();

            } catch (Exception e) {
                Log.e(TAG, "Exception : " + e.toString());
                return null;
            } finally {
                inputStream.close();
                connection.disconnect();
            }
            Log.e(TAG, "Background Task data : " + data);

            //Second AsyncTask

            JSONObject jsonObject;
            List<List<HashMap<String, String>>> routes = null;

            try {
                jsonObject = new JSONObject(data);
                // Starts parsing data
                DirectionHelper helper = new DirectionHelper();
                routes = helper.parse(jsonObject);
                Log.e(TAG, "Executing Routes : "/*, routes.toString()*/);

                return routes;

            } catch (Exception e) {
                Log.e(TAG, "Exception in Executing Routes : " + e.toString());
                return null;
            }

        } catch (Exception e) {
            Log.e(TAG, "Background Task Exception : " + e.toString());
            return null;
        }
    }

    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {
        super.onPostExecute(result);

        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

        ArrayList<LatLng> points;
        PolylineOptions lineOptions = null;
        String distance = "";
        String duration = "";

        // Traversing through all the routes
        for (int i = 0; i < result.size(); i++) {
            points = new ArrayList<>();
            lineOptions = new PolylineOptions();

            // Fetching i-th route
            List<HashMap<String, String>> path = result.get(i);

            // Fetching all the points in i-th route
            for (int j = 0; j < path.size(); j++) {
                HashMap<String, String> point = path.get(j);

                if (j == 0) {    // Get distance from the list
                    distance = (String) point.get("distance");
                    continue;
                } else if (j == 1) { // Get duration from the list
                    duration = (String) point.get("duration");
                    continue;
                }

                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);

                points.add(position);
            }

            // Adding all the points in the route to LineOptions
            lineOptions.addAll(points);
            lineOptions.width(8);
            lineOptions.color(Color.RED);
            //lineOptions.color(getRandomColor());

            if (animatePath) {
                final ArrayList<LatLng> finalPoints = points;
                ((AppCompatActivity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        PolylineOptions polylineOptions;
                        final Polyline greyPolyLine, blackPolyline;
                        final ValueAnimator polylineAnimator;

                        LatLngBounds.Builder builder = new LatLngBounds.Builder();
                        for (LatLng latLng : finalPoints) {
                            builder.include(latLng);
                        }
                        polylineOptions = new PolylineOptions();
                        polylineOptions.color(Color.RED);
                        polylineOptions.width(8);
                        polylineOptions.startCap(new SquareCap());
                        polylineOptions.endCap(new SquareCap());
                        polylineOptions.jointType(ROUND);
                        polylineOptions.addAll(finalPoints);
                        greyPolyLine = mMap.addPolyline(polylineOptions);

                        polylineOptions = new PolylineOptions();
                        polylineOptions.width(8);
                        polylineOptions.color(Color.WHITE);
                        polylineOptions.startCap(new SquareCap());
                        polylineOptions.endCap(new SquareCap());
                        polylineOptions.zIndex(5f);
                        polylineOptions.jointType(ROUND);

                        blackPolyline = mMap.addPolyline(polylineOptions);
                        polylineAnimator = ValueAnimator.ofInt(0, 100);
                        polylineAnimator.setDuration(5000);
                        polylineAnimator.setInterpolator(new LinearInterpolator());
                        polylineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                            @Override
                            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                                List<LatLng> points = greyPolyLine.getPoints();
                                int percentValue = (int) valueAnimator.getAnimatedValue();
                                int size = points.size();
                                int newPoints = (int) (size * (percentValue / 100.0f));
                                List<LatLng> p = points.subList(0, newPoints);
                                blackPolyline.setPoints(p);
                            }
                        });

                        polylineAnimator.addListener(new Animator.AnimatorListener() {
                            @Override
                            public void onAnimationStart(Animator animation) {

                            }

                            @Override
                            public void onAnimationEnd(Animator animation) {
                                if (repeatDrawingPath) {
                                    List<LatLng> greyLatLng = greyPolyLine.getPoints();
                                    if (greyLatLng != null) {
                                        greyLatLng.clear();

                                    }
                                    polylineAnimator.start();
                                }
                            }

                            @Override
                            public void onAnimationCancel(Animator animation) {
                                polylineAnimator.cancel();
                            }

                            @Override
                            public void onAnimationRepeat(Animator animation) {
                            }
                        });
                        polylineAnimator.start();
                    }
                });
            }

            Log.e(TAG, "PolylineOptions Decoded");
        }

        // Drawing polyline in the Google Map for the i-th route
        if (resultCallback != null && lineOptions != null)
            resultCallback.onPath(lineOptions, distance, duration);
    }
}

DirectionPointListener

public interface DirectionPointListener {
    public void onPath(PolylineOptions polyLine,String distance,String duration);
}

Now draw path using below code in your Activity

private GoogleMap mMap;
private ArrayList<LatLng> wayPoint = new ArrayList<>();
private SupportMapFragment mapFragment;

mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

@Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                LatLngBounds.Builder builder = new LatLngBounds.Builder();

                /*Add Source Marker*/
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(source);
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
                mMap.addMarker(markerOptions);
                builder.include(source);

                /*Add Destination Marker*/
                markerOptions = new MarkerOptions();
                markerOptions.position(destination);
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
                mMap.addMarker(markerOptions);
                builder.include(destination);

                LatLngBounds bounds = builder.build();

                int width = mapFragment.getView().getMeasuredWidth();
                int height = mapFragment.getView().getMeasuredHeight();
                int padding = (int) (width * 0.15); // offset from edges of the map 10% of screen

                CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);

                mMap.animateCamera(cu);

                new GetPathFromLocation(context, source, destination, wayPoint, mMap, true, false, new DirectionPointListener() {
                    @Override
                    public void onPath(PolylineOptions polyLine, String distance, String duration) {
                        mMap.addPolyline(polyLine);
                        Log.e(TAG, "onPath :: Distance :: " + distance + " Duration :: " + duration);

                        binding.txtDistance.setText(String.format(" %s", distance));
                        binding.txtDuration.setText(String.format(" %s", duration));
                    }
                }).execute();
            }
        });
    }

OutPut

enter image description here

I hope this can help you!

Thank You.

How to replace negative numbers in Pandas Data Frame by zero

Another clean option that I have found useful is pandas.DataFrame.mask which will "replace values where the condition is true."

Create the DataFrame:

In [2]: import pandas as pd

In [3]: df = pd.DataFrame({'a': [0, -1, 2], 'b': [-3, 2, 1]})

In [4]: df
Out[4]: 
   a  b
0  0 -3
1 -1  2
2  2  1

Replace negative numbers with 0:

In [5]: df.mask(df < 0, 0)
Out[5]: 
   a  b
0  0  0
1  0  2
2  2  1

Or, replace negative numbers with NaN, which I frequently need:

In [7]: df.mask(df < 0)
Out[7]: 
     a    b
0  0.0  NaN
1  NaN  2.0
2  2.0  1.0

Using multiple .cpp files in c++ program?

You should have header files (.h) that contain the function's declaration, then a corresponding .cpp file that contains the definition. You then include the header file everywhere you need it. Note that the .cpp file that contains the definitions also needs to include (it's corresponding) header file.

// main.cpp
#include "second.h"
int main () {
    secondFunction();
}

// second.h
void secondFunction();

// second.cpp
#include "second.h"
void secondFunction() {
   // do stuff
}

Get the device width in javascript

I think using window.devicePixelRatio is more elegant than the window.matchMedia solution:

if (window.innerWidth*window.devicePixelRatio <= 960 
    && window.innerHeight*window.devicePixelRatio <= 640) { 
    ... 
}

UITableView, Separator color where to set?

Now you should be able to do it directly in the IB.

Not sure though, if this was available when the question was posted originally.

enter image description here

How to show disable HTML select option in by default?

Electron + React Let your two first options be like this

<option hidden="true>Choose Tagging</option>
<option disabled="disabled" default="true">Choose Tagging</option>

First to display when closed Second to display first when the list opens

Swift - encode URL

Swift 4:

It depends by the encoding rules followed by your server.

Apple offer this class method, but it don't report wich kind of RCF protocol it follows.

var escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!

Following this useful tool you should guarantee the encoding of these chars for your parameters:

  • $ (Dollar Sign) becomes %24
  • & (Ampersand) becomes %26
  • + (Plus) becomes %2B
  • , (Comma) becomes %2C
  • : (Colon) becomes %3A
  • ; (Semi-Colon) becomes %3B
  • = (Equals) becomes %3D
  • ? (Question Mark) becomes %3F
  • @ (Commercial A / At) becomes %40

In other words, speaking about URL encoding, you should following the RFC 1738 protocol.

And Swift don't cover the encoding of the + char for example, but it works well with these three @ : ? chars.

So, to correctly encoding each your parameter , the .urlHostAllowed option is not enough, you should add also the special chars as for example:

encodedParameter = parameter.replacingOccurrences(of: "+", with: "%2B")

Hope this helps someone who become crazy to search these informations.

REST API using POST instead of GET

POST is valid to use instead of GET if you have specific reasons for doing so and process it properly. I understand it's not specifically RESTy, but if you have a bunch of spaces and ampersands and slashes and so on in your data [eg a product model like Amazon] then trying to encode and decode this can be more trouble than it's worth instead of just pre-jsonifying it. Make sure though that you return the proper response codes and heavily comment what you're doing because it's not a typical use case of POST.

What is the purpose for using OPTION(MAXDOP 1) in SQL Server?

As Kaboing mentioned, MAXDOP(n) actually controls the number of CPU cores that are being used in the query processor.

On a completely idle system, SQL Server will attempt to pull the tables into memory as quickly as possible and join between them in memory. It could be that, in your case, it's best to do this with a single CPU. This might have the same effect as using OPTION (FORCE ORDER) which forces the query optimizer to use the order of joins that you have specified. IN some cases, I have seen OPTION (FORCE PLAN) reduce a query from 26 seconds to 1 second of execution time.

Books Online goes on to say that possible values for MAXDOP are:

0 - Uses the actual number of available CPUs depending on the current system workload. This is the default value and recommended setting.

1 - Suppresses parallel plan generation. The operation will be executed serially.

2-64 - Limits the number of processors to the specified value. Fewer processors may be used depending on the current workload. If a value larger than the number of available CPUs is specified, the actual number of available CPUs is used.

I'm not sure what the best usage of MAXDOP is, however I would take a guess and say that if you have a table with 8 partitions on it, you would want to specify MAXDOP(8) due to I/O limitations, but I could be wrong.

Here are a few quick links I found about MAXDOP:

Books Online: Degree of Parallelism

General guidelines to use to configure the MAXDOP option

How to run mvim (MacVim) from Terminal?

This works for me:

? brew link --overwrite macvim
Linking /usr/local/Cellar/macvim/8.0-146_1... 12 symlinks created

Android Studio Run/Debug configuration error: Module not specified

I struggled with this because I'm developing a library, and every now and then want to run it as an application.

From app/build.gradle, check that you have apply plugin: 'com.android.application' instead of apply plugin: 'com.android.library'.

You should also have this in app/build.gradle:

defaultConfig { applicationId "com.your_company.your_application" ... }

Finally run Gradle sync.

MongoError: connect ECONNREFUSED 127.0.0.1:27017

I was having the same problem today.. and has been searching for answers.. I am on Ubuntu... however, I could not find the correct one that works on this thread.. after much research the following worked for me finally!! :)

First, after running

mongod dbpath

if appeared that mongodb was looking for the data/db directory.. which was missing in my installed mongodb app.. so I ran the following commands:

$ sudo mkdir -p /data/db

then run,

$ sudo chown -R $USER /data/db

chown - changes ownership of files/dirs. Ie. owner of the file/dir changes to the specified one, but it doesn't modify permissions. As detailed here: https://unix.stackexchange.com/questions/402062/how-are-chown-and-chmod-command-different-in-the-given-operation

Finally, run

`$ sudo systemctl enable mongod.service

It will give a message: Created symlink /etc/systemd/system/multi-user.target.wants/mongod.service ? /lib/systemd/system/mongod.service and started the service.

What is the best way to repeatedly execute a function every x seconds?

import time, traceback

def every(delay, task):
  next_time = time.time() + delay
  while True:
    time.sleep(max(0, next_time - time.time()))
    try:
      task()
    except Exception:
      traceback.print_exc()
      # in production code you might want to have this instead of course:
      # logger.exception("Problem while executing repetitive task.")
    # skip tasks if we are behind schedule:
    next_time += (time.time() - next_time) // delay * delay + delay

def foo():
  print("foo", time.time())

every(5, foo)

If you want to do this without blocking your remaining code, you can use this to let it run in its own thread:

import threading
threading.Thread(target=lambda: every(5, foo)).start()

This solution combines several features rarely found combined in the other solutions:

  • Exception handling: As far as possible on this level, exceptions are handled properly, i. e. get logged for debugging purposes without aborting our program.
  • No chaining: The common chain-like implementation (for scheduling the next event) you find in many answers is brittle in the aspect that if anything goes wrong within the scheduling mechanism (threading.Timer or whatever), this will terminate the chain. No further executions will happen then, even if the reason of the problem is already fixed. A simple loop and waiting with a simple sleep() is much more robust in comparison.
  • No drift: My solution keeps an exact track of the times it is supposed to run at. There is no drift depending on the execution time (as in many other solutions).
  • Skipping: My solution will skip tasks if one execution took too much time (e. g. do X every five seconds, but X took 6 seconds). This is the standard cron behavior (and for a good reason). Many other solutions then simply execute the task several times in a row without any delay. For most cases (e. g. cleanup tasks) this is not wished. If it is wished, simply use next_time += delay instead.

Laravel 5.5 ajax call 419 (unknown status)

just serialize the form data and get your problem solved.

data: $('#form_id').serialize(),

How to close Browser Tab After Submitting a Form?

<?php    
    /* ... SQL EXECUTION TO UPDATE DB ... */

    echo "<script>window.close();</script>";
?>

and Remove the window.close() from the form onsubmit event

using stored procedure in entity framework

You need to create a model class that contains all stored procedure properties like below. Also because Entity Framework model class needs primary key, you can create a fake key by using Guid.

public class GetFunctionByID
{
    [Key]
    public Guid? GetFunctionByID { get; set; }

    // All the other properties.
}

then register the GetFunctionByID model class in your DbContext.

public class FunctionsContext : BaseContext<FunctionsContext>
{
    public DbSet<App_Functions> Functions { get; set; }
    public DbSet<GetFunctionByID> GetFunctionByIds {get;set;}
}

When you call your stored procedure, just see below:

var functionId = yourIdParameter;
var result =  db.Database.SqlQuery<GetFunctionByID>("GetFunctionByID @FunctionId", new SqlParameter("@FunctionId", functionId)).ToList());

How can I remove the last character of a string in python?

You could use String.rstrip.

result = string.rstrip('/')

Center align "span" text inside a div

If you know the width of the span you could just stuff in a left margin.

Try this:

.center { text-align: center}
div.center span { display: table; }

Add the "center: class to your .

If you want some spans centered, but not others, replace the "div.center span" in your style sheet to a class (e.g "center-span") and add that class to the span.

Get loop count inside a Python FOR loop

Try using itertools.count([n])

Open a new tab in the background?

Here is a complete example for navigating valid URL on a new tab with focused.

HTML:

<div class="panel">
  <p>
    Enter Url: 
    <input type="text" id="txturl" name="txturl" size="30" class="weburl" />
    &nbsp;&nbsp;    
    <input type="button" id="btnopen"  value="Open Url in New Tab" onclick="openURL();"/>
  </p>
</div>

CSS:

.panel{
  font-size:14px;
}
.panel input{
  border:1px solid #333;
}

JAVASCRIPT:

function isValidURL(url) {
    var RegExp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;

    if (RegExp.test(url)) {
        return true;
    } else {
        return false;
    }
}

function openURL() {
    var url = document.getElementById("txturl").value.trim();
    if (isValidURL(url)) {
        var myWindow = window.open(url, '_blank');
        myWindow.focus();
        document.getElementById("txturl").value = '';
    } else {
        alert("Please enter valid URL..!");
        return false;
    }
}

I have also created a bin with the solution on http://codebins.com/codes/home/4ldqpbw

Has anyone ever got a remote JMX JConsole to work?

There are already some great answers here, but, there is a slightly simpler approach that I think it is worth sharing.

sushicutta's approach is good, but is very manual as you have to get the RMI Port every time. Thankfully, we can work around that by using a SOCKS proxy rather than explicitly opening the port tunnels. The downside of this approach is JMX app you run on your machine needs to be able to be configured to use a Proxy. Most processes you can do this from adding java properties, but, some apps don't support this.

Steps:

  1. Add the JMX options to the startup script for your remote Java service:

    -Dcom.sun.management.jmxremote=true
    -Dcom.sun.management.jmxremote.port=8090
    -Dcom.sun.management.jmxremote.ssl=false
    -Dcom.sun.management.jmxremote.authenticate=false
    
  2. Set up a SOCKS proxy connection to your remote machine:

    ssh -D 9696 [email protected]
    
  3. Configure your local Java monitoring app to use the SOCKS proxy (localhost:9696). Note: You can sometimes do this from the command line, i.e.:

    jconsole -J-DsocksProxyHost=localhost -J-DsocksProxyPort=9696
    

"Cannot send session cache limiter - headers already sent"

"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.

Check that you don't send ANY content before calling session_start. Better yet, just make session_start the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).

How do I list all the columns in a table?

The following code worked very well for me:

SELECT
       o.name as tableName,
       c.name as columnName,
       o.[type],
       s.name as schemaName,
       o.type_desc
FROM
       sys.objects AS o
       INNER JOIN sys.[columns] AS c ON c.[object_id] = o.[object_id]
       INNER JOIN sys.schemas AS s ON o.[schema_id] = s.[schema_id]
WHERE
       o.type_desc='USER_TABLE' 
       AND c.name='YourColumnName' --if comment this line,show all columns
ORDER BY
        o.name,
        c.column_id

you just replace your Column name with 'YourColumnName'. then run query

Show loading screen when navigating between routes in Angular 2

UPDATE:3 Now that I have upgraded to new Router, @borislemke's approach will not work if you use CanDeactivate guard. I'm degrading to my old method, ie: this answer

UPDATE2: Router events in new-router look promising and the answer by @borislemke seems to cover the main aspect of spinner implementation, I havent't tested it but I recommend it.

UPDATE1: I wrote this answer in the era of Old-Router, when there used to be only one event route-changed notified via router.subscribe(). I also felt overload of the below approach and tried to do it using only router.subscribe(), and it backfired because there was no way to detect canceled navigation. So I had to revert back to lengthy approach(double work).


If you know your way around in Angular2, this is what you'll need


Boot.ts

import {bootstrap} from '@angular/platform-browser-dynamic';
import {MyApp} from 'path/to/MyApp-Component';
import { SpinnerService} from 'path/to/spinner-service';

bootstrap(MyApp, [SpinnerService]);

Root Component- (MyApp)

import { Component } from '@angular/core';
import { SpinnerComponent} from 'path/to/spinner-component';
@Component({
  selector: 'my-app',
  directives: [SpinnerComponent],
  template: `
     <spinner-component></spinner-component>
     <router-outlet></router-outlet>
   `
})
export class MyApp { }

Spinner-Component (will subscribe to Spinner-service to change the value of active accordingly)

import {Component} from '@angular/core';
import { SpinnerService} from 'path/to/spinner-service';
@Component({
  selector: 'spinner-component',
  'template': '<div *ngIf="active" class="spinner loading"></div>'
})
export class SpinnerComponent {
  public active: boolean;

  public constructor(spinner: SpinnerService) {
    spinner.status.subscribe((status: boolean) => {
      this.active = status;
    });
  }
}

Spinner-Service (bootstrap this service)

Define an observable to be subscribed by spinner-component to change the status on change, and function to know and set the spinner active/inactive.

import {Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';
import 'rxjs/add/operator/share';

@Injectable()
export class SpinnerService {
  public status: Subject<boolean> = new Subject();
  private _active: boolean = false;

  public get active(): boolean {
    return this._active;
  }

  public set active(v: boolean) {
    this._active = v;
    this.status.next(v);
  }

  public start(): void {
    this.active = true;
  }

  public stop(): void {
    this.active = false;
  }
}

All Other Routes' Components

(sample):

import { Component} from '@angular/core';
import { SpinnerService} from 'path/to/spinner-service';
@Component({
   template: `<div *ngIf="!spinner.active" id="container">Nothing is Loading Now</div>`
})
export class SampleComponent {

  constructor(public spinner: SpinnerService){} 

  ngOnInit(){
    this.spinner.stop(); // or do it on some other event eg: when xmlhttp request completes loading data for the component
  }

  ngOnDestroy(){
    this.spinner.start();
  }
}

Excel to CSV with UTF8 encoding

Easiest way: No need Open office and google docs

  1. Save your file as "Unicode text file";
  2. now you have an unicode text file
  3. open it with "notepad" and "Save as" it with selecting "utf-8" or other code page that you want
  4. rename file extension from "txt" to "csv". This will result in a tab-delimited UTF-8 csv file.
  5. If you want a comma-delimited file, open the csv file you just renamed and replace all tabs with commas. To do this in Notepad on Win 10, simply select one tab field then click Ctrl+H. In the window that opens, type a comma , in the "Replace with" field then click "Replace All". Save your file. The result will be a comma-delimited UTF-8 csv file.

Don't open it with MS-Office anyway!!! Now you have a tab delimited CSV file. Or, a comma-delimited one if you applied step number 5.