Programs & Examples On #Emv

EMV stands for Europay, MasterCard and VISA, a global standard for inter-operation of integrated circuit cards (ICC or "chip cards") and ICC capable point of sale (POS) terminals and automated teller machines (ATMs), for authenticating credit and debit card transactions. It's the application structure inside your smart card that handles requests for protected data and communicates with the issuing bank to confirm the authenticity of the card user.

ASP.NET Core - Swashbuckle not creating swagger.json file

I am moving my comment to an answer since it appears to be helpful.


To avoid issues with IIS aliases, remove /swagger/ from the URL path. It should look like this:

app.UseSwaggerUI(c => { c.SwaggerEndpoint("v1/swagger.json", "API name"); });

How to enable CORS in ASP.net Core WebAPI

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
                .AddJsonOptions(options => {
                    var resolver = options.SerializerSettings.ContractResolver;
                    if (resolver != null)
                        (resolver as DefaultContractResolver).NamingStrategy = null;
                });

            services.AddDbContext<PaymentDetailContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DevConnection"))); //Dependency Injection
            // options => options.UseSqlServer() Lamda Expression

            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                    builder =>
                    {
                        builder.WithOrigins("http://localhost:4200").AllowAnyHeader()
                                .AllowAnyMethod(); ;
                    });
            });

Changing background color of selected item in recyclerview

I managed to do this from my Activity where i'm setting my Rv and not from the adapter

If someone need to do something similar here's the code

In this case the color changes on a logClick

           @Override
        public void onLongClick(View view, int position) {
            Toast.makeText(UltimasConsultasActivity.this, "Item agregado a la lista de mails",
                    Toast.LENGTH_SHORT).show();

            sendMultipleMails.setVisibility(View.VISIBLE);
            valueEmail.setVisibility(View.VISIBLE);
            itemsSeleccionados.setVisibility(View.VISIBLE);

            listaEmails.add(superListItems.get(position));
            listaItems ="";
            NameOfyourRecyclerInActivity.findViewHolderForAdapterPosition(position).NameOfYourViewInTheViewholder.setBackgroundColor((Color.parseColor("#336F0D")));

            for(int itemsSelect = 0; itemsSelect <= listaEmails.size() -1; itemsSelect++){

             listaItems  +=  "*"+listaEmails.get(itemsSelect).getDescripcion() + "\n";
            }

            itemsSeleccionados.setText("Items Seleccionados : "+  "\n" + listaItems);


        }


    }));

How do I access Configuration in any class in ASP.NET Core?

I know this is old but given the IOptions patterns is relatively simple to implement:

  1. Class with public get/set properties that match the settings in the configuration

    public class ApplicationSettings
    {
        public string UrlBasePath { get; set; }
    }
    
  2. register your settings

    public void ConfigureServices(IServiceCollection services)
    {
     ...
     services.Configure<ApplicationSettings>(Configuration.GetSection("ApplicationSettings"));
    ...
    }
    
  3. inject via IOptions

    public class HomeController
    {
       public HomeController(IOptions<ApplicationSettings> appSettings)
       { ...
        appSettings.Value.UrlBasePath
        ...
        // or better practice create a readonly private reference
        }
     }
    

I'm not sure why you wouldn't just do this.

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.

The error message says your DbContext(LogManagerContext ) needs a constructor which accepts a DbContextOptions. But i couldn't find such a constructor in your DbContext. So adding below constructor probably solves your problem.

    public LogManagerContext(DbContextOptions options) : base(options)
    {
    }

Edit for comment

If you don't register IHttpContextAccessor explicitly, use below code:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); 

How to add a recyclerView inside another recyclerView

you can use LayoutInflater to inflate your dynamic data as a layout file.

UPDATE : first create a LinearLayout inside your CardView's layout and assign an ID for it. after that create a layout file that you want to inflate. at last in your onBindViewHolder method in your "RAdaper" class. write these codes :

  mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

  view = mInflater.inflate(R.layout.my_list_custom_row, parent, false);

after that you can initialize data and ClickListeners with your RAdapter Data. hope it helps.

this and this may useful :)

Npm install cannot find module 'semver'

Having just encountered this on Arch Linux 4.13.3, I solved the issue by simply reinstalling semver:

pacman -S semver

How to update/refresh specific item in RecyclerView

The problem is RecyclerView.Adatper does not provide any methods that return the index of element

public abstract static class Adapter<VH extends ViewHolder> {
  /**
   * returns index of the given element in adapter, return -1 if not exist
   */
  public int indexOf(Object elem);
}

My workaround is to create a map instance for (element, position)s

public class FriendAdapter extends RecyclerView.Adapter<MyViewHolder> {
  private Map<Friend, Integer> posMap ;
  private List<Friend> friends;

  public FriendAdapter(List<Friend> friends ) {
    this.friends = new ArrayList<>(friends);
    this.posMap = new HashMap<>();
    for(int i = 0; i < this.friends.size(); i++) {
      posMap.put(this.friends.get(i), i);
    }
  }

  public int indexOf(Friend friend) {
    Integer position = this.posMap.get(elem);
    return position == null ? -1 : position;
  }
  // skip other methods in class Adapter
}
  • the element type(here class Friend) should implements hashCode() and equals() because it is key in hashmap.

when an element changed,

  void someMethod() {
    Friend friend = ...;
    friend.setPhoneNumber('xxxxx');

    int position = friendAdapter.indexOf(friend);
    friendAdapter.notifyItemChanged(position);

  }

It is good to define an helper method

public class FriendAdapter extends extends RecyclerView.Adapter<MyViewHolder> {

  public void friendUpdated(Friend friend) {
    int position = this.indexOf(friend);
    this.notifyItemChanged(position);
  }
}

Map instance(Map<Friend, Integer> posMap) is not necessarily required. If map is not used, looping throughout list can find the position of an element.

RecyclerView and java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder in Samsung devices

This problem is caused by RecyclerView Data modified in different thread

Can confirm threading as one problem and since I ran into the issue and RxJava is becoming increasingly popular: make sure that you are using .observeOn(AndroidSchedulers.mainThread()) whenever you're calling notify[whatever changed]

code example from adapter:

myAuxDataStructure.getChangeObservable().observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<AuxDataStructure>() {

    [...]

    @Override
    public void onNext(AuxDataStructure o) {
        [notify here]
    }
});

How to update RecyclerView Adapter Data?

This is a general answer for future visitors. The various ways to update the adapter data are explained. The process includes two main steps every time:

  1. Update the data set
  2. Notify the adapter of the change

#Insert single item

Add "Pig" at index 2.

Insert single item
String item = "Pig";
int insertIndex = 2;
data.add(insertIndex, item);
adapter.notifyItemInserted(insertIndex);

#Insert multiple items

Insert three more animals at index 2.

Insert multiple items
ArrayList<String> items = new ArrayList<>();
items.add("Pig");
items.add("Chicken");
items.add("Dog");
int insertIndex = 2;
data.addAll(insertIndex, items);
adapter.notifyItemRangeInserted(insertIndex, items.size());

#Remove a single item

Remove "Pig" from the list.

Remove single item
int removeIndex = 2;
data.remove(removeIndex);
adapter.notifyItemRemoved(removeIndex);

#Remove multiple items

Remove "Camel" and "Sheep" from the list.

Remove multiple items
int startIndex = 2; // inclusive
int endIndex = 4;   // exclusive
int count = endIndex - startIndex; // 2 items will be removed
data.subList(startIndex, endIndex).clear();
adapter.notifyItemRangeRemoved(startIndex, count);

#Remove all items

Clear the whole list.

Remove all items
data.clear();
adapter.notifyDataSetChanged();

#Replace old list with the new list

Clear the old list then add a new one.

Replace old list with new list
// clear old list
data.clear();

// add new list
ArrayList<String> newList = new ArrayList<>();
newList.add("Lion");
newList.add("Wolf");
newList.add("Bear");
data.addAll(newList);

// notify adapter
adapter.notifyDataSetChanged();

The adapter has a reference to data, so it is important that I didn't set data to a new object. Instead, I cleared the old items from data and then added the new ones.

#Update single item

Change the "Sheep" item so that it says "I like sheep."

Update single item
String newValue = "I like sheep.";
int updateIndex = 3;
data.set(updateIndex, newValue);
adapter.notifyItemChanged(updateIndex);

#Move single item

Move "Sheep" from position 3 to position 1.

Move single item
int fromPosition = 3;
int toPosition = 1;

// update data array
String item = data.get(fromPosition);
data.remove(fromPosition);
data.add(toPosition, item);

// notify adapter
adapter.notifyItemMoved(fromPosition, toPosition);

#Code

Here is the project code for your reference. The RecyclerView Adapter code can be found at this answer.

MainActivity.java

public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {

    List<String> data;
    MyRecyclerViewAdapter adapter;

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

        // data to populate the RecyclerView with
        data = new ArrayList<>();
        data.add("Horse");
        data.add("Cow");
        data.add("Camel");
        data.add("Sheep");
        data.add("Goat");

        // set up the RecyclerView
        RecyclerView recyclerView = findViewById(R.id.rvAnimals);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
                layoutManager.getOrientation());
        recyclerView.addItemDecoration(dividerItemDecoration);
        adapter = new MyRecyclerViewAdapter(this, data);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onItemClick(View view, int position) {
        Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
    }

    public void onButtonClick(View view) {
        insertSingleItem();
    }

    private void insertSingleItem() {
        String item = "Pig";
        int insertIndex = 2;
        data.add(insertIndex, item);
        adapter.notifyItemInserted(insertIndex);
    }

    private void insertMultipleItems() {
        ArrayList<String> items = new ArrayList<>();
        items.add("Pig");
        items.add("Chicken");
        items.add("Dog");
        int insertIndex = 2;
        data.addAll(insertIndex, items);
        adapter.notifyItemRangeInserted(insertIndex, items.size());
    }

    private void removeSingleItem() {
        int removeIndex = 2;
        data.remove(removeIndex);
        adapter.notifyItemRemoved(removeIndex);
    }

    private void removeMultipleItems() {
        int startIndex = 2; // inclusive
        int endIndex = 4;   // exclusive
        int count = endIndex - startIndex; // 2 items will be removed
        data.subList(startIndex, endIndex).clear();
        adapter.notifyItemRangeRemoved(startIndex, count);
    }

    private void removeAllItems() {
        data.clear();
        adapter.notifyDataSetChanged();
    }

    private void replaceOldListWithNewList() {
        // clear old list
        data.clear();

        // add new list
        ArrayList<String> newList = new ArrayList<>();
        newList.add("Lion");
        newList.add("Wolf");
        newList.add("Bear");
        data.addAll(newList);

        // notify adapter
        adapter.notifyDataSetChanged();
    }

    private void updateSingleItem() {
        String newValue = "I like sheep.";
        int updateIndex = 3;
        data.set(updateIndex, newValue);
        adapter.notifyItemChanged(updateIndex);
    }

    private void moveSingleItem() {
        int fromPosition = 3;
        int toPosition = 1;

        // update data array
        String item = data.get(fromPosition);
        data.remove(fromPosition);
        data.add(toPosition, item);

        // notify adapter
        adapter.notifyItemMoved(fromPosition, toPosition);
    }
}

#Notes

  • If you use notifyDataSetChanged(), then no animation will be performed. This can also be an expensive operation, so it is not recommended to use notifyDataSetChanged() if you are only updating a single item or a range of items.
  • Check out DiffUtil if you are making large or complex changes to a list.

#Further study

How to filter a RecyclerView with a SearchView

Introduction

Since it is not really clear from your question what exactly you are having trouble with, I wrote up this quick walkthrough about how to implement this feature; if you still have questions feel free to ask.

I have a working example of everything I am talking about here in this GitHub Repository.
If you want to know more about the example project visit the project homepage.

In any case the result should looks something like this:

demo image

If you first want to play around with the demo app you can install it from the Play Store:

Get it on Google Play

Anyway lets get started.


Setting up the SearchView

In the folder res/menu create a new file called main_menu.xml. In it add an item and set the actionViewClass to android.support.v7.widget.SearchView. Since you are using the support library you have to use the namespace of the support library to set the actionViewClass attribute. Your xml file should look something like this:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">

    <item android:id="@+id/action_search"
          android:title="@string/action_search"
          app:actionViewClass="android.support.v7.widget.SearchView"
          app:showAsAction="always"/>

</menu>

In your Fragment or Activity you have to inflate this menu xml like usual, then you can look for the MenuItem which contains the SearchView and implement the OnQueryTextListener which we are going to use to listen for changes to the text entered into the SearchView:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);

    final MenuItem searchItem = menu.findItem(R.id.action_search);
    final SearchView searchView = (SearchView) searchItem.getActionView();
    searchView.setOnQueryTextListener(this);

    return true;
}

@Override
public boolean onQueryTextChange(String query) {
    // Here is where we are going to implement the filter logic
    return false;
}

@Override
public boolean onQueryTextSubmit(String query) {
    return false;
}

And now the SearchView is ready to be used. We will implement the filter logic later on in onQueryTextChange() once we are finished implementing the Adapter.


Setting up the Adapter

First and foremost this is the model class I am going to use for this example:

public class ExampleModel {

    private final long mId;
    private final String mText;

    public ExampleModel(long id, String text) {
        mId = id;
        mText = text;
    }

    public long getId() {
        return mId;
    }

    public String getText() {
        return mText;
    }
}

It's just your basic model which will display a text in the RecyclerView. This is the layout I am going to use to display the text:

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

    <data>

        <variable
            name="model"
            type="com.github.wrdlbrnft.searchablerecyclerviewdemo.ui.models.ExampleModel"/>

    </data>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/selectableItemBackground"
        android:clickable="true">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="8dp"
            android:text="@{model.text}"/>

    </FrameLayout>

</layout>

As you can see I use Data Binding. If you have never worked with data binding before don't be discouraged! It's very simple and powerful, however I can't explain how it works in the scope of this answer.

This is the ViewHolder for the ExampleModel class:

public class ExampleViewHolder extends RecyclerView.ViewHolder {

    private final ItemExampleBinding mBinding;

    public ExampleViewHolder(ItemExampleBinding binding) {
        super(binding.getRoot());
        mBinding = binding;
    }

    public void bind(ExampleModel item) {
        mBinding.setModel(item);
    }
}

Again nothing special. It just uses data binding to bind the model class to this layout as we have defined in the layout xml above.

Now we can finally come to the really interesting part: Writing the Adapter. I am going to skip over the basic implementation of the Adapter and am instead going to concentrate on the parts which are relevant for this answer.

But first there is one thing we have to talk about: The SortedList class.


SortedList

The SortedList is a completely amazing tool which is part of the RecyclerView library. It takes care of notifying the Adapter about changes to the data set and does so it a very efficient way. The only thing it requires you to do is specify an order of the elements. You need to do that by implementing a compare() method which compares two elements in the SortedList just like a Comparator. But instead of sorting a List it is used to sort the items in the RecyclerView!

The SortedList interacts with the Adapter through a Callback class which you have to implement:

private final SortedList.Callback<ExampleModel> mCallback = new SortedList.Callback<ExampleModel>() {

    @Override
    public void onInserted(int position, int count) {
         mAdapter.notifyItemRangeInserted(position, count);
    }

    @Override
    public void onRemoved(int position, int count) {
        mAdapter.notifyItemRangeRemoved(position, count);
    }

    @Override
    public void onMoved(int fromPosition, int toPosition) {
        mAdapter.notifyItemMoved(fromPosition, toPosition);
    }

    @Override
    public void onChanged(int position, int count) {
        mAdapter.notifyItemRangeChanged(position, count);
    }

    @Override
    public int compare(ExampleModel a, ExampleModel b) {
        return mComparator.compare(a, b);
    }

    @Override
    public boolean areContentsTheSame(ExampleModel oldItem, ExampleModel newItem) {
        return oldItem.equals(newItem);
    }

    @Override
    public boolean areItemsTheSame(ExampleModel item1, ExampleModel item2) {
        return item1.getId() == item2.getId();
    }
}

In the methods at the top of the callback like onMoved, onInserted, etc. you have to call the equivalent notify method of your Adapter. The three methods at the bottom compare, areContentsTheSame and areItemsTheSame you have to implement according to what kind of objects you want to display and in what order these objects should appear on the screen.

Let's go through these methods one by one:

@Override
public int compare(ExampleModel a, ExampleModel b) {
    return mComparator.compare(a, b);
}

This is the compare() method I talked about earlier. In this example I am just passing the call to a Comparator which compares the two models. If you want the items to appear in alphabetical order on the screen. This comparator might look like this:

private static final Comparator<ExampleModel> ALPHABETICAL_COMPARATOR = new Comparator<ExampleModel>() {
    @Override
    public int compare(ExampleModel a, ExampleModel b) {
        return a.getText().compareTo(b.getText());
    }
};

Now let's take a look at the next method:

@Override
public boolean areContentsTheSame(ExampleModel oldItem, ExampleModel newItem) {
    return oldItem.equals(newItem);
}

The purpose of this method is to determine if the content of a model has changed. The SortedList uses this to determine if a change event needs to be invoked - in other words if the RecyclerView should crossfade the old and new version. If you model classes have a correct equals() and hashCode() implementation you can usually just implement it like above. If we add an equals() and hashCode() implementation to the ExampleModel class it should look something like this:

public class ExampleModel implements SortedListAdapter.ViewModel {

    private final long mId;
    private final String mText;

    public ExampleModel(long id, String text) {
        mId = id;
        mText = text;
    }

    public long getId() {
        return mId;
    }

    public String getText() {
        return mText;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        ExampleModel model = (ExampleModel) o;

        if (mId != model.mId) return false;
        return mText != null ? mText.equals(model.mText) : model.mText == null;

    }

    @Override
    public int hashCode() {
        int result = (int) (mId ^ (mId >>> 32));
        result = 31 * result + (mText != null ? mText.hashCode() : 0);
        return result;
    }
}

Quick side note: Most IDE's like Android Studio, IntelliJ and Eclipse have functionality to generate equals() and hashCode() implementations for you at the press of a button! So you don't have to implement them yourself. Look up on the internet how it works in your IDE!

Now let's take a look at the last method:

@Override
public boolean areItemsTheSame(ExampleModel item1, ExampleModel item2) {
    return item1.getId() == item2.getId();
}

The SortedList uses this method to check if two items refer to the same thing. In simplest terms (without explaining how the SortedList works) this is used to determine if an object is already contained in the List and if either an add, move or change animation needs to be played. If your models have an id you would usually compare just the id in this method. If they don't you need to figure out some other way to check this, but however you end up implementing this depends on your specific app. Usually it is the simplest option to give all models an id - that could for example be the primary key field if you are querying the data from a database.

With the SortedList.Callback correctly implemented we can create an instance of the SortedList:

final SortedList<ExampleModel> list = new SortedList<>(ExampleModel.class, mCallback);

As the first parameter in the constructor of the SortedList you need to pass the class of your models. The other parameter is just the SortedList.Callback we defined above.

Now let's get down to business: If we implement the Adapter with a SortedList it should look something like this:

public class ExampleAdapter extends RecyclerView.Adapter<ExampleViewHolder> {

    private final SortedList<ExampleModel> mSortedList = new SortedList<>(ExampleModel.class, new SortedList.Callback<ExampleModel>() {
        @Override
        public int compare(ExampleModel a, ExampleModel b) {
            return mComparator.compare(a, b);
        }

        @Override
        public void onInserted(int position, int count) {
            notifyItemRangeInserted(position, count);
        }

        @Override
        public void onRemoved(int position, int count) {
            notifyItemRangeRemoved(position, count);
        }

        @Override
        public void onMoved(int fromPosition, int toPosition) {
            notifyItemMoved(fromPosition, toPosition);
        }

        @Override
        public void onChanged(int position, int count) {
            notifyItemRangeChanged(position, count);
        }

        @Override
        public boolean areContentsTheSame(ExampleModel oldItem, ExampleModel newItem) {
            return oldItem.equals(newItem);
        }

        @Override
        public boolean areItemsTheSame(ExampleModel item1, ExampleModel item2) {
            return item1.getId() == item2.getId();
        }
    });

    private final LayoutInflater mInflater;
    private final Comparator<ExampleModel> mComparator;

    public ExampleAdapter(Context context, Comparator<ExampleModel> comparator) {
        mInflater = LayoutInflater.from(context);
        mComparator = comparator;
    }

    @Override
    public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        final ItemExampleBinding binding = ItemExampleBinding.inflate(inflater, parent, false);
        return new ExampleViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(ExampleViewHolder holder, int position) {
        final ExampleModel model = mSortedList.get(position);
        holder.bind(model);
    }

    @Override
    public int getItemCount() {
        return mSortedList.size();
    }
}

The Comparator used to sort the item is passed in through the constructor so we can use the same Adapter even if the items are supposed to be displayed in a different order.

Now we are almost done! But we first need a way to add or remove items to the Adapter. For this purpose we can add methods to the Adapter which allow us to add and remove items to the SortedList:

public void add(ExampleModel model) {
    mSortedList.add(model);
}

public void remove(ExampleModel model) {
    mSortedList.remove(model);
}

public void add(List<ExampleModel> models) {
    mSortedList.addAll(models);
}

public void remove(List<ExampleModel> models) {
    mSortedList.beginBatchedUpdates();
    for (ExampleModel model : models) {
        mSortedList.remove(model);
    }
    mSortedList.endBatchedUpdates();
}

We don't need to call any notify methods here because the SortedList already does this for through the SortedList.Callback! Aside from that the implementation of these methods is pretty straight forward with one exception: the remove method which removes a List of models. Since the SortedList has only one remove method which can remove a single object we need to loop over the list and remove the models one by one. Calling beginBatchedUpdates() at the beginning batches all the changes we are going to make to the SortedList together and improves performance. When we call endBatchedUpdates() the RecyclerView is notified about all the changes at once.

Additionally what you have to understand is that if you add an object to the SortedList and it is already in the SortedList it won't be added again. Instead the SortedList uses the areContentsTheSame() method to figure out if the object has changed - and if it has the item in the RecyclerView will be updated.

Anyway, what I usually prefer is one method which allows me to replace all items in the RecyclerView at once. Remove everything which is not in the List and add all items which are missing from the SortedList:

public void replaceAll(List<ExampleModel> models) {
    mSortedList.beginBatchedUpdates();
    for (int i = mSortedList.size() - 1; i >= 0; i--) {
        final ExampleModel model = mSortedList.get(i);
        if (!models.contains(model)) {
            mSortedList.remove(model);
        }
    }
    mSortedList.addAll(models);
    mSortedList.endBatchedUpdates();
}

This method again batches all updates together to increase performance. The first loop is in reverse since removing an item at the start would mess up the indexes of all items that come up after it and this can lead in some instances to problems like data inconsistencies. After that we just add the List to the SortedList using addAll() to add all items which are not already in the SortedList and - just like I described above - update all items that are already in the SortedList but have changed.

And with that the Adapter is complete. The whole thing should look something like this:

public class ExampleAdapter extends RecyclerView.Adapter<ExampleViewHolder> {

    private final SortedList<ExampleModel> mSortedList = new SortedList<>(ExampleModel.class, new SortedList.Callback<ExampleModel>() {
        @Override
        public int compare(ExampleModel a, ExampleModel b) {
            return mComparator.compare(a, b);
        }

        @Override
        public void onInserted(int position, int count) {
            notifyItemRangeInserted(position, count);
        }

        @Override
        public void onRemoved(int position, int count) {
            notifyItemRangeRemoved(position, count);
        }

        @Override
        public void onMoved(int fromPosition, int toPosition) {
            notifyItemMoved(fromPosition, toPosition);
        }

        @Override
        public void onChanged(int position, int count) {
            notifyItemRangeChanged(position, count);
        }

        @Override
        public boolean areContentsTheSame(ExampleModel oldItem, ExampleModel newItem) {
            return oldItem.equals(newItem);
        }

        @Override
        public boolean areItemsTheSame(ExampleModel item1, ExampleModel item2) {
            return item1 == item2;
        }
    });

    private final Comparator<ExampleModel> mComparator;
    private final LayoutInflater mInflater;

    public ExampleAdapter(Context context, Comparator<ExampleModel> comparator) {
        mInflater = LayoutInflater.from(context);
        mComparator = comparator;
    }

    @Override
    public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        final ItemExampleBinding binding = ItemExampleBinding.inflate(mInflater, parent, false);
        return new ExampleViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(ExampleViewHolder holder, int position) {
        final ExampleModel model = mSortedList.get(position);
        holder.bind(model);
    }

    public void add(ExampleModel model) {
        mSortedList.add(model);
    }

    public void remove(ExampleModel model) {
        mSortedList.remove(model);
    }

    public void add(List<ExampleModel> models) {
        mSortedList.addAll(models);
    }

    public void remove(List<ExampleModel> models) {
        mSortedList.beginBatchedUpdates();
        for (ExampleModel model : models) {
            mSortedList.remove(model);
        }
        mSortedList.endBatchedUpdates();
    }

    public void replaceAll(List<ExampleModel> models) {
        mSortedList.beginBatchedUpdates();
        for (int i = mSortedList.size() - 1; i >= 0; i--) {
            final ExampleModel model = mSortedList.get(i);
            if (!models.contains(model)) {
                mSortedList.remove(model);
            }
        }
        mSortedList.addAll(models);
        mSortedList.endBatchedUpdates();
    }

    @Override
    public int getItemCount() {
        return mSortedList.size();
    }
}

The only thing missing now is to implement the filtering!


Implementing the filter logic

To implement the filter logic we first have to define a List of all possible models. For this example I create a List of ExampleModel instances from an array of movies:

private static final String[] MOVIES = new String[]{
        ...
};

private static final Comparator<ExampleModel> ALPHABETICAL_COMPARATOR = new Comparator<ExampleModel>() {
    @Override
    public int compare(ExampleModel a, ExampleModel b) {
        return a.getText().compareTo(b.getText());
    }
};

private ExampleAdapter mAdapter;
private List<ExampleModel> mModels;
private RecyclerView mRecyclerView;

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);

    mAdapter = new ExampleAdapter(this, ALPHABETICAL_COMPARATOR);

    mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
    mBinding.recyclerView.setAdapter(mAdapter);

    mModels = new ArrayList<>();
    for (String movie : MOVIES) {
        mModels.add(new ExampleModel(movie));
    }
    mAdapter.add(mModels);
}

Nothing special going on here, we just instantiate the Adapter and set it to the RecyclerView. After that we create a List of models from the movie names in the MOVIES array. Then we add all the models to the SortedList.

Now we can go back to onQueryTextChange() which we defined earlier and start implementing the filter logic:

@Override
public boolean onQueryTextChange(String query) {
    final List<ExampleModel> filteredModelList = filter(mModels, query);
    mAdapter.replaceAll(filteredModelList);
    mBinding.recyclerView.scrollToPosition(0);
    return true;
}

This is again pretty straight forward. We call the method filter() and pass in the List of ExampleModels as well as the query string. We then call replaceAll() on the Adapter and pass in the filtered List returned by filter(). We also have to call scrollToPosition(0) on the RecyclerView to ensure that the user can always see all items when searching for something. Otherwise the RecyclerView might stay in a scrolled down position while filtering and subsequently hide a few items. Scrolling to the top ensures a better user experience while searching.

The only thing left to do now is to implement filter() itself:

private static List<ExampleModel> filter(List<ExampleModel> models, String query) {
    final String lowerCaseQuery = query.toLowerCase();

    final List<ExampleModel> filteredModelList = new ArrayList<>();
    for (ExampleModel model : models) {
        final String text = model.getText().toLowerCase();
        if (text.contains(lowerCaseQuery)) {
            filteredModelList.add(model);
        }
    }
    return filteredModelList;
}

The first thing we do here is call toLowerCase() on the query string. We don't want our search function to be case sensitive and by calling toLowerCase() on all strings we compare we can ensure that we return the same results regardless of case. It then just iterates through all the models in the List we passed into it and checks if the query string is contained in the text of the model. If it is then the model is added to the filtered List.

And that's it! The above code will run on API level 7 and above and starting with API level 11 you get item animations for free!

I realize that this is a very detailed description which probably makes this whole thing seem more complicated than it really is, but there is a way we can generalize this whole problem and make implementing an Adapter based on a SortedList much simpler.


Generalizing the problem and simplifying the Adapter

In this section I am not going to go into much detail - partly because I am running up against the character limit for answers on Stack Overflow but also because most of it already explained above - but to summarize the changes: We can implemented a base Adapter class which already takes care of dealing with the SortedList as well as binding models to ViewHolder instances and provides a convenient way to implement an Adapter based on a SortedList. For that we have to do two things:

  • We need to create a ViewModel interface which all model classes have to implement
  • We need to create a ViewHolder subclass which defines a bind() method the Adapter can use to bind models automatically.

This allows us to just focus on the content which is supposed to be displayed in the RecyclerView by just implementing the models and there corresponding ViewHolder implementations. Using this base class we don't have to worry about the intricate details of the Adapter and its SortedList.

SortedListAdapter

Because of the character limit for answers on StackOverflow I can't go through each step of implementing this base class or even add the full source code here, but you can find the full source code of this base class - I called it SortedListAdapter - in this GitHub Gist.

To make your life simple I have published a library on jCenter which contains the SortedListAdapter! If you want to use it then all you need to do is add this dependency to your app's build.gradle file:

compile 'com.github.wrdlbrnft:sorted-list-adapter:0.2.0.1'

You can find more information about this library on the library homepage.

Using the SortedListAdapter

To use the SortedListAdapter we have to make two changes:

  • Change the ViewHolder so that it extends SortedListAdapter.ViewHolder. The type parameter should be the model which should be bound to this ViewHolder - in this case ExampleModel. You have to bind data to your models in performBind() instead of bind().

    public class ExampleViewHolder extends SortedListAdapter.ViewHolder<ExampleModel> {
    
        private final ItemExampleBinding mBinding;
    
        public ExampleViewHolder(ItemExampleBinding binding) {
            super(binding.getRoot());
            mBinding = binding;
        }
    
        @Override
        protected void performBind(ExampleModel item) {
            mBinding.setModel(item);
        }
    }
    
  • Make sure that all your models implement the ViewModel interface:

    public class ExampleModel implements SortedListAdapter.ViewModel {
        ...
    }
    

After that we just have to update the ExampleAdapter to extend SortedListAdapter and remove everything we don't need anymore. The type parameter should be the type of model you are working with - in this case ExampleModel. But if you are working with different types of models then set the type parameter to ViewModel.

public class ExampleAdapter extends SortedListAdapter<ExampleModel> {

    public ExampleAdapter(Context context, Comparator<ExampleModel> comparator) {
        super(context, ExampleModel.class, comparator);
    }

    @Override
    protected ViewHolder<? extends ExampleModel> onCreateViewHolder(LayoutInflater inflater, ViewGroup parent, int viewType) {
        final ItemExampleBinding binding = ItemExampleBinding.inflate(inflater, parent, false);
        return new ExampleViewHolder(binding);
    }

    @Override
    protected boolean areItemsTheSame(ExampleModel item1, ExampleModel item2) {
        return item1.getId() == item2.getId();
    }

    @Override
    protected boolean areItemContentsTheSame(ExampleModel oldItem, ExampleModel newItem) {
        return oldItem.equals(newItem);
    }
}

After that we are done! However one last thing to mention: The SortedListAdapter does not have the same add(), remove() or replaceAll() methods our original ExampleAdapter had. It uses a separate Editor object to modify the items in the list which can be accessed through the edit() method. So if you want to remove or add items you have to call edit() then add and remove the items on this Editor instance and once you are done, call commit() on it to apply the changes to the SortedList:

mAdapter.edit()
        .remove(modelToRemove)
        .add(listOfModelsToAdd)
        .commit();

All changes you make this way are batched together to increase performance. The replaceAll() method we implemented in the chapters above is also present on this Editor object:

mAdapter.edit()
        .replaceAll(mModels)
        .commit();

If you forget to call commit() then none of your changes will be applied!

How to open a different activity on recyclerView item onclick

This question has been asked long ago but none of the answers above helped me out, though Milad Moosavi`s answer was very close. To open a new activity from a certain position on the recycler view, the following code may help:


    @Override
    public void onBindViewHolder(@NonNull TripViewHolder holder, int position) {
        Trip currentTrip = trips.get(position);

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(v.getContext(), EditTrip.class);
                v.getContext().startActivity(intent);
            }
        });

        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Intent intent = new Intent(v.getContext(), ReadTripActivity.class);
                v.getContext().startActivity(intent);

                return false;
            }
        });
    }

Add a new item to recyclerview programmatically?

if you are adding multiple items to the list use this:

mAdapter.notifyItemRangeInserted(startPosition, itemcount);

This notify any registered observers that the currently reflected itemCount items starting at positionStart have been newly inserted. The item previously located at positionStart and beyond can now be found starting at position positinStart+itemCount

existing item in the dataset still considered up to date.

How to properly highlight selected item on RecyclerView?

there is no selector in RecyclerView like ListView and GridView but you try below thing it worked for me

create a selector drawable as below

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
<item android:state_pressed="true">
   <shape>
         <solid android:color="@color/blue" />
   </shape>
</item>

<item android:state_pressed="false">
    <shape>
       <solid android:color="@android:color/transparent" />
    </shape>
</item>
</selector>

then set this drawable as background of your RecyclerView row layout as

android:background="@drawable/selector"

How do I get the position selected in a RecyclerView?

Set your onClickListeners on onBindViewHolder() and you can access the position from there. If you set them in your ViewHolder you won't know what position was clicked unless you also pass the position into the ViewHolder

EDIT

As pskink pointed out ViewHolder has a getPosition() so the way you were originally doing it was correct.

When the view is clicked you can use getPosition() in your ViewHolder and it returns the position

Update

getPosition() is now deprecated and replaced with getAdapterPosition()

Update 2020

getAdapterPosition() is now deprecated and replaced with getAbsoluteAdapterPosition() or getBindingAdapterPosition()

Kotlin code:

override fun onBindViewHolder(holder: MyHolder, position: Int) {
        // - get element from your dataset at this position
        val item = myDataset.get(holder.absoluteAdapterPosition)
    }

How do I resolve `The following packages have unmet dependencies`

I came to this situation when I installed node js from the latest stable release.

curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -

It seems this version already comes with a prepackaged NPM. So when I tried to install NPM again, I got this error. If anyone is installing Nodejs in this manner then, it's not needed to install NPM separately.

The following packages have unmet dependencies:
 npm : Depends: nodejs but it is not going to be installed
       Depends: node-abbrev (>= 1.0.4) but it is not going to be installed
       Depends: node-ansi (>= 0.3.0-2) but it is not going to be installed
       Depends: node-ansi-color-table but it is not going to be installed
       Depends: node-archy but it is not going to be installed
       Depends: node-block-stream but it is not going to be installed
       Depends: node-fstream (>= 0.1.22) but it is not going to be installed
       Depends: node-fstream-ignore but it is not going to be installed
       Depends: node-github-url-from-git but it is not going to be installed
       Depends: node-glob (>= 3.1.21) but it is not going to be installed
       Depends: node-graceful-fs (>= 2.0.0) but it is not going to be installed
       Depends: node-inherits but it is not going to be installed
       Depends: node-ini (>= 1.1.0) but it is not going to be installed
       Depends: node-lockfile but it is not going to be installed
       Depends: node-lru-cache (>= 2.3.0) but it is not going to be installed
       Depends: node-minimatch (>= 0.2.11) but it is not going to be installed
       Depends: node-mkdirp (>= 0.3.3) but it is not going to be installed
       Depends: node-gyp (>= 0.10.9) but it is not going to be installed
       Depends: node-nopt (>= 3.0.1) but it is not going to be installed
       Depends: node-npmlog but it is not going to be installed
       Depends: node-once but it is not going to be installed
       Depends: node-osenv but it is not going to be installed
       Depends: node-read but it is not going to be installed
       Depends: node-read-package-json (>= 1.1.0) but it is not going to be installed
       Depends: node-request (>= 2.25.0) but it is not going to be installed
       Depends: node-retry but it is not going to be installed
       Depends: node-rimraf (>= 2.2.2) but it is not going to be installed
       Depends: node-semver (>= 2.1.0) but it is not going to be installed
       Depends: node-sha but it is not going to be installed
       Depends: node-slide but it is not going to be installed
       Depends: node-tar (>= 0.1.18) but it is not going to be installed
       Depends: node-underscore but it is not going to be installed
       Depends: node-which but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

Is there an addHeaderView equivalent for RecyclerView?

There is one more solution that covers all the use cases above: CompoundAdapter: https://github.com/negusoft/CompoundAdapter-android

You can create a AdapterGroup that holds your Adapter as it is, along with an adapter with a single item to represent the header. The code is easy and readable:

AdapterGroup adapterGroup = new AdapterGroup();
adapterGroup.addAdapter(SingleAdapter.create(R.layout.header));
adapterGroup.addAdapter(new CommentAdapter(...));

recyclerView.setAdapter(adapterGroup);

AdapterGroup allows nesting too, so for a adapter with sections, you may create a AdapterGroup per section. Then put all the sections in a root AdapterGroup.

UIAlertController custom font, size, color

There is a problem with setting the tint color on the view after presenting; even if you do it in the completion block of presentViewController:animated:completion:, it causes a flicker effect on the color of the button titles. This is sloppy, unprofessional and completely unacceptable.

Other solutions presented depend on the view hierarchy remaining static, something that Apple is loathe to do. Expect those solutions to fail in future releases of iOS.

The one sure-fire way to solve this problem and to do it everywhere, is via adding a category to UIAlertController and swizzling the viewWillAppear.

The header:

//
//  UIAlertController+iOS9TintFix.h
//
//  Created by Flor, Daniel J on 11/2/15.
//

#import <UIKit/UIKit.h>

@interface UIAlertController (iOS9TintFix)

+ (void)tintFix;

- (void)swizzledViewWillAppear:(BOOL)animated;

@end

The implementation:

//
//  UIAlertController+iOS9TintFix.m
//
//  Created by Flor, Daniel J on 11/2/15.
//

#import "UIAlertController+iOS9TintFix.h"
#import <objc/runtime.h>

@implementation UIAlertController (iOS9TintFix)

+ (void)tintFix {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Method method  = class_getInstanceMethod(self, @selector(viewWillAppear:));
        Method swizzle = class_getInstanceMethod(self, @selector(swizzledViewWillAppear:));
        method_exchangeImplementations(method, swizzle);});
}

- (void)swizzledViewWillAppear:(BOOL)animated {
    [self swizzledViewWillAppear:animated];
    for (UIView *view in self.view.subviews) {
        if (view.tintColor == self.view.tintColor) {
            //only do those that match the main view, so we don't strip the red-tint from destructive buttons.
            self.view.tintColor = [UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0];
            [view setNeedsDisplay];
        }
    }
}

@end

Add a .pch (precompiled header) to your project and include the category:

#import "UIAlertController+iOS9TintFix.h"

Make sure you register your pch in the project properly, and it will include the category methods in every class that uses the UIAlertController.

Then, in your app delegates didFinishLaunchingWithOptions method, import your category and call

[UIAlertController tintFix];

and it will automatically propagate to every single instance of UIAlertController within your app, whether launched by your code or anyone else's.

This solution works for both iOS 8.X and iOS 9.X and lacks the flicker of the tint change post-presentation approach. It is also completely agnostic with respect to the view hierarchy of the sub-views of the UIAlertController.

Happy hacking!

Recyclerview and handling different type of row inflation

Handling the rows / sections logic similar to iOS's UITableView is not as simple in Android as it is in iOS, however, when you use RecyclerView - the flexibility of what you can do is far greater.

In the end, it's all about how you figure out what type of view you're displaying in the Adapter. Once you got that figured out, it should be easy sailing (not really, but at least you'll have that sorted).

The Adapter exposes two methods which you should override:

getItemViewType(int position)

This method's default implementation will always return 0, indicating that there is only 1 type of view. In your case, it is not so, and so you will need find a way to assert which row corresponds to which view type. Unlike iOS, which manages this for you with rows and sections, here you will have only one index to rely on, and you'll need to use your developer skills to know when a position correlates to a section header, and when it correlates to a normal row.

createViewHolder(ViewGroup parent, int viewType)

You need to override this method anyway, but usually people just ignore the viewType parameter. According to the view type, you'll need to inflate the correct layout resource and create your view holder accordingly. The RecyclerView will handle recycling different view types in a way which avoids clashing of different view types.

If you're planning on using a default LayoutManager, such as LinearLayoutManager, you should be good to go. If you're planning on making your own LayoutManager implementation, you'll need to work a bit harder. The only API you really have to work with is findViewByPosition(int position) which gives a given view at a certain position. Since you'll probably want to lay it out differently depending on what type this view is, you have a few options:

  1. Usually when using the ViewHolder pattern, you set the view's tag with the view holder. You could use this during runtime in the layout manager to find out what type the view is by adding a field in the view holder which expresses this.

  2. Since you'll need a function which determines which position correlates to which view type, you might as well make this method globally accessible somehow (maybe a singleton class which manages the data?), and then you can simply query the same method according to the position.

Here's a code sample:

// in this sample, I use an object array to simulate the data of the list. 
// I assume that if the object is a String, it means I should display a header with a basic title.
// If not, I assume it's a custom model object I created which I will use to bind my normal rows.
private Object[] myData;

public static final int ITEM_TYPE_NORMAL = 0;
public static final int ITEM_TYPE_HEADER = 1;

public class MyAdapter extends Adapter<ViewHolder> {

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        if (viewType == ITEM_TYPE_NORMAL) {
            View normalView = LayoutInflater.from(getContext()).inflate(R.layout.my_normal_row, null);
            return new MyNormalViewHolder(normalView); // view holder for normal items
        } else if (viewType == ITEM_TYPE_HEADER) {
            View headerRow = LayoutInflater.from(getContext()).inflate(R.layout.my_header_row, null);
            return new MyHeaderViewHolder(headerRow); // view holder for header items
        }
    }


    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        final int itemType = getItemViewType(position);

        if (itemType == ITEM_TYPE_NORMAL) {
            ((MyNormalViewHolder)holder).bindData((MyModel)myData[position]);
        } else if (itemType == ITEM_TYPE_HEADER) {
            ((MyHeaderViewHolder)holder).setHeaderText((String)myData[position]);
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (myData[position] instanceof String) {
            return ITEM_TYPE_HEADER;
        } else {
            return ITEM_TYPE_NORMAL;
        }
    }

    @Override
    public int getItemCount() {
        return myData.length;
    }
}

Here's a sample of how these view holders should look like:

public MyHeaderViewHolder extends ViewHolder {

    private TextView headerLabel;    

    public MyHeaderViewHolder(View view) {
        super(view);

        headerLabel = (TextView)view.findViewById(R.id.headerLabel);
    }

    public void setHeaderText(String text) {
        headerLabel.setText(text);
    }    
}


public MyNormalViewHolder extends ViewHolder {

    private TextView titleLabel;
    private TextView descriptionLabel;    

    public MyNormalViewHolder(View view) {
        super(view);

        titleLabel = (TextView)view.findViewById(R.id.titleLabel);
        descriptionLabel = (TextView)view.findViewById(R.id.descriptionLabel);
    }

    public void bindData(MyModel model) {
        titleLabel.setText(model.getTitle());
        descriptionLabel.setText(model.getDescription());
    }    
}

Of course, this sample assumes you've constructed your data source (myData) in a way that makes it easy to implement an adapter in this way. As an example, I'll show you how I'd construct a data source which shows a list of names, and a header for every time the 1st letter of the name changes (assume the list is alphabetized) - similar to how a contacts list would look like:

// Assume names & descriptions are non-null and have the same length.
// Assume names are alphabetized
private void processDataSource(String[] names, String[] descriptions) {
    String nextFirstLetter = "";
    String currentFirstLetter;

    List<Object> data = new ArrayList<Object>();

    for (int i = 0; i < names.length; i++) {
        currentFirstLetter = names[i].substring(0, 1); // get the 1st letter of the name

        // if the first letter of this name is different from the last one, add a header row
        if (!currentFirstLetter.equals(nextFirstLetter)) {
            nextFirstLetter = currentFirstLetter;
            data.add(nextFirstLetter);
        }

        data.add(new MyModel(names[i], descriptions[i]));
    }

    myData = data.toArray();
}

This example comes to solve a fairly specific issue, but I hope this gives you a good overview on how to handle different row types in a recycler, and allows you make the necessary adaptations in your own code to fit your needs.

Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 3876877096_Portrait_iPhone-Simple-Pad_Default

The emulator tries to find a numeric keypad on the mac, but this is not found (MacBook Pro, MacBook Air and "normal/small" keyboard do not have it). You can deselect the option Connect Hardware Keyboard or just ignore the error message, it will have no negative effect on application.

Gulp command not found after install

I realize that this is an old thread, but for Future-Me, and posterity, I figured I should add my two-cents around the "running npm as sudo" discussion. Disclaimer: I do not use Windows. These steps have only been proven on non-windows machines, both virtual and physical.

You can avoid the need to use sudo by changing the permission to npm's default directory.


How to: change permissions in order to run npm without sudo

Step 1: Find out where npm's default directory is.

  • To do this, open your terminal and run:
    npm config get prefix

Step 2: Proceed, based on the output of that command:

  • Scenario One: npm's default directory is /usr/local
    For most users, your output will show that npm's default directory is /usr/local, in which case you can skip to step 4 to update the permissions for the directory.
  • Scenario Two: npm's default directory is /usr or /Users/YOURUSERNAME/node_modules or /Something/Else/FishyLooking
    If you find that npm's default directory is not /usr/local, but is instead something you can't explain or looks fishy, you should go to step 3 to change the default directory for npm, or you risk messing up your permissions on a much larger scale.

Step 3: Change npm's default directory:

  • There are a couple of ways to go about this, including creating a directory specifically for global installations and then adding that directory to your $PATH, but since /usr/local is probably already in your path, I think it's simpler to just change npm's default directory to that. Like so: npm config set prefix /usr/local
    • For more info on the other approaches I mentioned, see the npm docs here.

Step 4: Update the permissions on npm's default directory:

  • Once you've verified that npm's default directory is in a sensible location, you can update the permissions on it using the command:
    sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share}

Now you should be able to run npm <whatever> without sudo. Note: You may need to restart your terminal in order for these changes to take effect.

registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later

Swift 2.0

// Checking if app is running iOS 8
    if application.respondsToSelector("isRegisteredForRemoteNotifications") {

        print("registerApplicationForPushNotifications - iOS 8")

        application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil));
        application.registerForRemoteNotifications()

    } else {
        // Register for Push Notifications before iOS 8
        print("registerApplicationForPushNotifications - <iOS 8")
        application.registerForRemoteNotificationTypes([UIRemoteNotificationType.Alert, UIRemoteNotificationType.Badge, UIRemoteNotificationType.Sound])

    }

How to change MenuItem icon in ActionBar programmatically

Kotlin version:

toolbar.menu.findItem(R.id.notification).icon =
                    ContextCompat.getDrawable(requireContext(), R.drawable.ic_notification)

toolbar.menu.findItem(R.id.notification).isVisible = true

Android - java.lang.SecurityException: Permission Denial: starting Intent

Add android:exported="true" in your 'com.example.lib.MainActivity' activity tag.

From the android:exported documentation,

android:exported Whether or not the activity can be launched by components of other applications — "true" if it can be, and "false" if not. If "false", the activity can be launched only by components of the same application or applications with the same user ID.

From your logcat output, clearly a mismatch in uid is causing the issue. So adding the android:exported="true" should do the trick.

How to change the background color of Action Bar's Option Menu in Android 4.2?

Add following to your Styles.xml

<style name="Custom_Theme" parent="Theme.AppCompat.Light.DarkActionBar">

    <item name="android:itemBackground">@color/white</item>
    <item name="android:textColor">@color/colorPrimaryDark</item>

</style>

Change theme in activity_main.xml only.

android:theme="@style/Custom_Theme"

How to test if JSON object is empty in Java

For this case, I do something like this:

_x000D_
_x000D_
var obj = {};_x000D_
_x000D_
if(Object.keys(obj).length == 0){_x000D_
        console.log("The obj is null")_x000D_
}
_x000D_
_x000D_
_x000D_

Indexing vectors and arrays with +:

This is another way to specify the range of the bit-vector.

x +: N, The start position of the vector is given by x and you count up from x by N.

There is also

x -: N, in this case the start position is x and you count down from x by N.

N is a constant and x is an expression that can contain iterators.

It has a couple of benefits -

  1. It makes the code more readable.

  2. You can specify an iterator when referencing bit-slices without getting a "cannot have a non-constant value" error.

Can't install any package with node npm

The problem is with ssl

you should use sudo. Follow below method to resolve the issue.

if you are getting this issue enter sudo npm config set strict-ssl false password: Enter current username password

then now run all ur command wit sudo sudo npm npm install -g underscore password: Enter current username password

Even after if your getting error. Your proxy will be problem. few corporate proxy will be blocked, so you should use wifi or open network to fix this issue.

Primefaces valueChangeListener or <p:ajax listener not firing for p:selectOneMenu

If you want to use valueChangeListener, you need to submit the form every time a new option is chosen. Something like this:

<p:selectOneMenu value="#{mymb.employee}" onchange="submit()"
                 valueChangeListener="#{mymb.handleChange}" >
    <f:selectItems value="#{mymb.employeesList}" var="emp"
                   itemLabel="#{emp.employeeName}" itemValue="#{emp.employeeID}" />
</p:selectOneMenu>

public void handleChange(ValueChangeEvent event){  
    System.out.println("New value: " + event.getNewValue());
}

Or else, if you want to use <p:ajax>, it should look like this:

<p:selectOneMenu value="#{mymb.employee}" >
    <p:ajax listener="#{mymb.handleChange}" />
    <f:selectItems value="#{mymb.employeesList}" var="emp"
                   itemLabel="#{emp.employeeName}" itemValue="#{emp.employeeID}" />
</p:selectOneMenu>

private String employeeID;

public void handleChange(){  
    System.out.println("New value: " + employee);
}

One thing to note is that in your example code, I saw that the value attribute of your <p:selectOneMenu> is #{mymb.employeesList} which is the same as the value of <f:selectItems>. The value of your <p:selectOneMenu> should be similar to my examples above which point to a single employee, not a list of employees.

Android ListView not refreshing after notifyDataSetChanged

adpter.notifyDataSetInvalidated();

Try this in onPause() method of Activity class.

setValue:forUndefinedKey: this class is not key value coding-compliant for the key

In my case I have IBOutlet UILabel *description in .h, it was with yellow /!\ - "will not synthesized", as I remember. Dunno what is it and why only this label.

But I got this crash and error like above. Deleted *description and recreate *description2. No crash in result.

Node package ( Grunt ) installed but not available

There is one more way to run grunt on windows, without adding anything globally. This is a case when you don't have to do anything with %PATH%

if you have grunt and grunt-cli installed (without -g switch). Either by:

npm install grunt-cli
npm install [email protected]

Or by having that in your packages.json file like:

"devDependencies": {
    "grunt-cli": "^1.2.0",
    "grunt": "^0.4.5",

You can call grunt from your local installation by:

node node_modules\grunt-cli\bin\grunt --version

This is a solution for those who for some reasons don't want to or can't play with PATH, or have something else messing it all the time, for instance on a build agent.

Edit: Added versions as the grunt-cli works with grunt > 0.3

How to convert image into byte array and byte array to base64 String in android?

They have wrapped most stuff need to solve your problem, one of the tests looks like this:

String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " ");
String code = "background: url(folder.png);";

StringWriter writer = new StringWriter();
embedder = new CSSURLEmbedder(new StringReader(code), true);
embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1));

String result = writer.toString();
assertEquals("background: url(" + folderDataURI + ");", result);

Get the position of a spinner in Android

if (position ==0) {
    if (rYes.isChecked()) {
        Toast.makeText(SportActivity.this, "yes ur answer is right", Toast.LENGTH_LONG).show();
    } else if (rNo.isChecked()) {
        Toast.makeText(SportActivity.this, "no.ur answer is wrong", Toast.LENGTH_LONG).show();
    }
}

This code is supposed to select both check boxes.
Is there a problem with it?

How to get the width and height of an android.widget.ImageView?

The simplest way is to get the width and height of an ImageView in onWindowFocusChanged method of the activity

 @Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);

    height = mImageView.getHeight();
    width = mImageView.getWidth();

}

DataGridView.Clear()

Try this Method

dataGridView1.DataSource = dt;
dt.Rows.Clear();

Count the number of items in my array list

The number of itemIds in your list will be the same as the number of elements in your list:

int itemCount = list.size();

However, if you're looking to count the number of unique itemIds (per @pst) then you should use a set to keep track of them.

Set<String> itemIds = new HashSet<String>();

//...
itemId = p.getItemId();
itemIds.add(itemId);

//... later ...
int uniqueItemIdCount = itemIds.size();

How to check iOS version?

Using the refered recommended way... if there is no definition in the header files, you can always get the versión printing it on console with a device of the desired IOS versión.

- (BOOL) isIOS8OrAbove{
    float version802 = 1140.109985;
    float version8= 1139.100000; // there is no def like NSFoundationVersionNumber_iOS_7_1 for ios 8 yet?
    NSLog(@"la version actual es [%f]", NSFoundationVersionNumber);
    if (NSFoundationVersionNumber >= version8){
        return true;
    }
    return false;
}

MySQL - Rows to Columns

I figure out one way to make my reports converting rows to columns almost dynamic using simple querys. You can see and test it online here.

The number of columns of query is fixed but the values are dynamic and based on values of rows. You can build it So, I use one query to build the table header and another one to see the values:

SELECT distinct concat('<th>',itemname,'</th>') as column_name_table_header FROM history order by 1;

SELECT
     hostid
    ,(case when itemname = (select distinct itemname from history a order by 1 limit 0,1) then itemvalue else '' end) as col1
    ,(case when itemname = (select distinct itemname from history a order by 1 limit 1,1) then itemvalue else '' end) as col2
    ,(case when itemname = (select distinct itemname from history a order by 1 limit 2,1) then itemvalue else '' end) as col3
    ,(case when itemname = (select distinct itemname from history a order by 1 limit 3,1) then itemvalue else '' end) as col4
FROM history order by 1;

You can summarize it, too:

SELECT
     hostid
    ,sum(case when itemname = (select distinct itemname from history a order by 1 limit 0,1) then itemvalue end) as A
    ,sum(case when itemname = (select distinct itemname from history a order by 1 limit 1,1) then itemvalue end) as B
    ,sum(case when itemname = (select distinct itemname from history a order by 1 limit 2,1) then itemvalue end) as C
FROM history group by hostid order by 1;
+--------+------+------+------+
| hostid | A    | B    | C    |
+--------+------+------+------+
|      1 |   10 |    3 | NULL |
|      2 |    9 | NULL |   40 |
+--------+------+------+------+

Results of RexTester:

Results of RexTester

http://rextester.com/ZSWKS28923

For one real example of use, this report bellow show in columns the hours of departures arrivals of boat/bus with a visual schedule. You will see one additional column not used at the last col without confuse the visualization: sistema venda de passagens online e consumidor final e controle de frota - xsl tecnologia - xsl.com.br ** ticketing system to of sell ticket online and presential

dyld: Library not loaded: /usr/local/lib/libpng16.16.dylib with anything php related

Just in case someone else runs into this problem I solved it by the following

brew update && brew upgrade # installs libpng 1.6

This caused an error with other packages requiring 1.5 which they were built with, so I linked it:

cd /usr/local/lib/
ln -s ../Cellar/libpng/1.5.18/lib/libpng15.15.dylib

Now they are both living in harmony and side by side for the different packages. It would be better to rebuild the packages that depend on 1.5, but this works as a quick bandage fix.

How do I "Add Existing Item" an entire directory structure in Visual Studio?

What worked for me was to drag the folder into Visual Studio, then right click the folder and select "Open Folder in File Explorer". Then select all and drag them into the folder in Visual Studio.

pandas groupby sort descending order

Do your groupby, and use reset_index() to make it back into a DataFrame. Then sort.

grouped = df.groupby('mygroups').sum().reset_index()
grouped.sort_values('mygroups', ascending=False)

How to give a pattern for new line in grep?

As for the workaround (without using non-portable -P), you can temporary replace a new-line character with the different one and change it back, e.g.:

grep -o "_foo_" <(paste -sd_ file) | tr -d '_'

Basically it's looking for exact match _foo_ where _ means \n (so __ = \n\n). You don't have to translate it back by tr '_' '\n', as each pattern would be printed in the new line anyway, so removing _ is enough.

Carriage Return\Line feed in Java

Encapsulate your writer to provide char replacement, like this:

public class WindowsFileWriter extends Writer {

    private Writer writer;

    public WindowsFileWriter(File file) throws IOException {
        try {
            writer = new OutputStreamWriter(new FileOutputStream(file), "ISO-8859-15");
        } catch (UnsupportedEncodingException e) {
            writer = new FileWriter(logfile);
        }
    }

    @Override
    public void write(char[] cbuf, int off, int len) throws IOException {
        writer.write(new String(cbuf, off, len).replace("\n", "\r\n"));
    }

    @Override
    public void flush() throws IOException {
        writer.flush();
    }

    @Override
    public void close() throws IOException {
        writer.close();
    }

}

Phone validation regex

enter image description hereThis solution actually validates the numbers and the format. For example: 123-456-7890 is a valid format but is NOT a valid US number and this answer bears that out where others here do not.


If you do not want the extension capability remove the following including the parenthesis: (?:\s*(?:#|x.?|ext.?|extension)\s*(\d+)\s*)? :)

edit (addendum) I needed this in a client side only application so I converted it. Here it is for the javascript folks:

var myPhoneRegex = /(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]??)\s*)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)([2-9]1[02-9]??|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})\s*(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+)\s*)?$/i;
if (myPhoneRegex.test(phoneVar)) {
    // Successful match
} else {
    // Match attempt failed
}

hth. end edit

This allows extensions or not and works with .NET

(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]??)\s*)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)([2-9]1[02-9]??|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$

To validate with or without trailing spaces. Perhaps when using .NET validators and trimming server side use this slightly different regex:

(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]??)\s*)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)([2-9]1[02-9]??|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})\s*(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+)\s*)?$

All valid:

1 800 5551212

800 555 1212

8005551212

18005551212

+1800 555 1212 extension65432

800 5551212 ext3333

Invalid #s

234-911-5678

314-159-2653

123-234-5678


EDIT: Based on Felipe's comment I have updated this for international.

Based on what I could find out from here and here regarding valid global numbers

This is tested as a first line of defense of course. An overarching element of the international number is that it is no longer than 15 characters. I did not write a replace for all the non digits and sum the result. It should be done for completeness. Also, you may notice that I have not combined the North America regex with this one. The reason is that this international regex will match North American numbers, however, it will also accept known invalid # such as +1 234-911-5678. For more accurate results you should separate them as well.

Pauses and other dialing instruments are not mentioned and therefore invalid per E.164

\(?\+[0-9]{1,3}\)? ?-?[0-9]{1,3} ?-?[0-9]{3,5} ?-?[0-9]{4}( ?-?[0-9]{3})?

With 1-10 letter word for extension and 1-6 digit extension:

\(?\+[0-9]{1,3}\)? ?-?[0-9]{1,3} ?-?[0-9]{3,5} ?-?[0-9]{4}( ?-?[0-9]{3})? ?(\w{1,10}\s?\d{1,6})?

Valid International: Country name for ref its not a match.

+55 11 99999-5555 Brazil

+593 7 282-3889 Ecuador

(+44) 0848 9123 456 UK

+1 284 852 5500 BVI

+1 345 9490088 Grand Cayman

+32 2 702-9200 Belgium

+65 6511 9266 Asia Pacific

+86 21 2230 1000 Shanghai

+9124 4723300 India

+821012345678 South Korea

And for your extension pleasure

+55 11 99999-5555 ramal 123 Brazil

+55 11 99999-5555 foo786544 Brazil

Enjoy

Web-scraping JavaScript page with Python

I personally prefer using scrapy and selenium and dockerizing both in separate containers. This way you can install both with minimal hassle and crawl modern websites that almost all contain javascript in one form or another. Here's an example:

Use the scrapy startproject to create your scraper and write your spider, the skeleton can be as simple as this:

import scrapy


class MySpider(scrapy.Spider):
    name = 'my_spider'
    start_urls = ['https://somewhere.com']

    def start_requests(self):
        yield scrapy.Request(url=self.start_urls[0])


    def parse(self, response):

        # do stuff with results, scrape items etc.
        # now were just checking everything worked

        print(response.body)

The real magic happens in the middlewares.py. Overwrite two methods in the downloader middleware, __init__ and process_request, in the following way:

# import some additional modules that we need
import os
from copy import deepcopy
from time import sleep

from scrapy import signals
from scrapy.http import HtmlResponse
from selenium import webdriver

class SampleProjectDownloaderMiddleware(object):

def __init__(self):
    SELENIUM_LOCATION = os.environ.get('SELENIUM_LOCATION', 'NOT_HERE')
    SELENIUM_URL = f'http://{SELENIUM_LOCATION}:4444/wd/hub'
    chrome_options = webdriver.ChromeOptions()

    # chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
    self.driver = webdriver.Remote(command_executor=SELENIUM_URL,
                                   desired_capabilities=chrome_options.to_capabilities())


def process_request(self, request, spider):

    self.driver.get(request.url)

    # sleep a bit so the page has time to load
    # or monitor items on page to continue as soon as page ready
    sleep(4)

    # if you need to manipulate the page content like clicking and scrolling, you do it here
    # self.driver.find_element_by_css_selector('.my-class').click()

    # you only need the now properly and completely rendered html from your page to get results
    body = deepcopy(self.driver.page_source)

    # copy the current url in case of redirects
    url = deepcopy(self.driver.current_url)

    return HtmlResponse(url, body=body, encoding='utf-8', request=request)

Dont forget to enable this middlware by uncommenting the next lines in the settings.py file:

DOWNLOADER_MIDDLEWARES = {
'sample_project.middlewares.SampleProjectDownloaderMiddleware': 543,}

Next for dockerization. Create your Dockerfile from a lightweight image (I'm using python Alpine here), copy your project directory to it, install requirements:

# Use an official Python runtime as a parent image
FROM python:3.6-alpine

# install some packages necessary to scrapy and then curl because it's  handy for debugging
RUN apk --update add linux-headers libffi-dev openssl-dev build-base libxslt-dev libxml2-dev curl python-dev

WORKDIR /my_scraper

ADD requirements.txt /my_scraper/

RUN pip install -r requirements.txt

ADD . /scrapers

And finally bring it all together in docker-compose.yaml:

version: '2'
services:
  selenium:
    image: selenium/standalone-chrome
    ports:
      - "4444:4444"
    shm_size: 1G

  my_scraper:
    build: .
    depends_on:
      - "selenium"
    environment:
      - SELENIUM_LOCATION=samplecrawler_selenium_1
    volumes:
      - .:/my_scraper
    # use this command to keep the container running
    command: tail -f /dev/null

Run docker-compose up -d. If you're doing this the first time it will take a while for it to fetch the latest selenium/standalone-chrome and the build your scraper image as well.

Once it's done, you can check that your containers are running with docker ps and also check that the name of the selenium container matches that of the environment variable that we passed to our scraper container (here, it was SELENIUM_LOCATION=samplecrawler_selenium_1).

Enter your scraper container with docker exec -ti YOUR_CONTAINER_NAME sh , the command for me was docker exec -ti samplecrawler_my_scraper_1 sh, cd into the right directory and run your scraper with scrapy crawl my_spider.

The entire thing is on my github page and you can get it from here

How to call one shell script from another shell script?

Depends on. Briefly... If you want load variables on current console and execute you may use source myshellfile.sh on your code. Example:

!#/bin/bash
set -x
echo "This is an example of run another INTO this session."
source my_lib_of_variables_and_functions.sh
echo "The function internal_function() is defined into my lib."
returned_value=internal_function()
echo $this_is_an_internal_variable

set +x

If you just want to execute a file and the only thing intersting for you is the result, you can do:

!#/bin/bash
set -x
./executing_only.sh
sh i_can_execute_this_way_too.sh
bash or_this_way.sh
set +x

I hope helps you. Thanks.

How can I customize the tab-to-space conversion factor?

There are already lots of good answers provided by our beloved community members. I actually wanted to add the C# code tabSize and found this thread. There are many solutions I found and official VS Code docs is awesome. I just want to share my C# setting:

"[csharp]": {
    "editor.insertSpaces": true,
    "editor.tabSize": 4
},

just copy and paste above code to your settings.json file and save. thanks

how to prevent "directory already exists error" in a makefile when using mkdir

It works under mingw32/msys/cygwin/linux

ifeq "$(wildcard .dep)" ""
-include $(shell mkdir .dep) $(wildcard .dep/*)
endif

How can I select from list of values in SQL Server

Available only on SQL Server 2008 and over is row-constructor in this form:
You could use

SELECT DISTINCT * FROM (VALUES (1), (1), (1), (2), (5), (1), (6)) AS X(a)

Many wrote about, among them:

How to install python modules without root access?

You can run easy_install to install python packages in your home directory even without root access. There's a standard way to do this using site.USER_BASE which defaults to something like $HOME/.local or $HOME/Library/Python/2.7/bin and is included by default on the PYTHONPATH

To do this, create a .pydistutils.cfg in your home directory:

cat > $HOME/.pydistutils.cfg <<EOF
[install]
user=1
EOF

Now you can run easy_install without root privileges:

easy_install boto

Alternatively, this also lets you run pip without root access:

pip install boto

This works for me.

Source from Wesley Tanaka's blog : http://wtanaka.com/node/8095

How to open a website when a Button is clicked in Android application?

you can use this on your button click activity

Intent webOpen = new Intent(android.content.Intent.ACTION_VIEW);
            WebOpen.setData(Uri.parse("http://www.google.com"));
                startActivity(myWebLink);

and import this on your code

import android.net.Uri;

How to scroll the page when a modal dialog is longer than the screen?

just use

.modal-body {
    max-height: calc(100vh - 210px);
    overflow-y: auto;
}

it will arrange your modal and then give it an vertical scroll

Responsive background image in div full width

When you use background-size: cover the background image will automatically be stretched to cover the entire container. Aspect ratio is maintained however, so you will always lose part of the image, unless the aspect ratio of the image and the element it is applied to are identical.

I see two ways you could solve this:

  • Do not maintain the aspect ratio of the image by setting background-size: 100% 100% This will also make the image cover the entire container, but the ratio will not be maintained. Disadvantage is that this distorts your image, and therefore may look very weird, depending on the image. With the image you are using in the fiddle, I think you could get away with it though.

  • You could also calculate and set the height of the element with javascript, based on its width, so it gets the same ratio as the image. This calculation would have to be done on load and on resize. It should be easy enough with a few lines of code (feel free to ask if you want an example). Disadvantage of this method is that your width may become very small (on mobile devices), and therfore the calculated height also, which may cause the content of the container to overflow. This could be solved by changing the size of the content as well or something, but it adds some complexity to the solution/

Developing C# on Linux

You can also install it using conda (tested on Ubuntu):

conda create --name csharp
conda activate csharp
conda install -c conda-forge mono

Twitter bootstrap 3 two columns full height

Modern and very simple solution:

HTML:

<div class="container">
  <div class="row">
    <div class="col-md-3"></div>
    <div class="col-md-9"></div>
  </div>
</div>

CSS:

.row{
    display: flex;
}

alter the size of column in table containing data

Case 1 : Yes, this works fine.

Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.

Share and enjoy.

get all the elements of a particular form

It is also possible to use this:

var user_name = document.forms[0].elements[0];
var user_email = document.forms[0].elements[1];
var user_message = document.forms[0].elements[2];

All the elements of forms are stored in an array by Javascript. This takes the elements from the first form and stores each value into a unique variable.

n-grams in python, four, five, six grams?

If efficiency is an issue and you have to build multiple different n-grams (up to a hundred as you say), but you want to use pure python I would do:

from itertools import chain

def n_grams(seq, n=1):
    """Returns an itirator over the n-grams given a listTokens"""
    shiftToken = lambda i: (el for j,el in enumerate(seq) if j>=i)
    shiftedTokens = (shiftToken(i) for i in range(n))
    tupleNGrams = zip(*shiftedTokens)
    return tupleNGrams # if join in generator : (" ".join(i) for i in tupleNGrams)

def range_ngrams(listTokens, ngramRange=(1,2)):
    """Returns an itirator over all n-grams for n in range(ngramRange) given a listTokens."""
    return chain(*(n_grams(listTokens, i) for i in range(*ngramRange)))

Usage :

>>> input_list = input_list = 'test the ngrams generator'.split()
>>> list(range_ngrams(input_list, ngramRange=(1,3)))
[('test',), ('the',), ('ngrams',), ('generator',), ('test', 'the'), ('the', 'ngrams'), ('ngrams', 'generator'), ('test', 'the', 'ngrams'), ('the', 'ngrams', 'generator')]

~Same speed as NLTK:

import nltk
%%timeit
input_list = 'test the ngrams interator vs nltk '*10**6
nltk.ngrams(input_list,n=5)
# 7.02 ms ± 79 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%%timeit
input_list = 'test the ngrams interator vs nltk '*10**6
n_grams(input_list,n=5)
# 7.01 ms ± 103 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%%timeit
input_list = 'test the ngrams interator vs nltk '*10**6
nltk.ngrams(input_list,n=1)
nltk.ngrams(input_list,n=2)
nltk.ngrams(input_list,n=3)
nltk.ngrams(input_list,n=4)
nltk.ngrams(input_list,n=5)
# 7.32 ms ± 241 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%%timeit
input_list = 'test the ngrams interator vs nltk '*10**6
range_ngrams(input_list, ngramRange=(1,6))
# 7.13 ms ± 165 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Repost from my previous answer.

npm can't find package.json

I'll be brief but deadly. :) install -d will not work for you. It's simple. Try

$ npm install -g express

Event on a disabled input

suggestion here looks like a good candidate for this question as well

Performing click event on a disabled element? Javascript jQuery

jQuery('input#submit').click(function(e) {
    if ( something ) {        
        return false;
    } 
});

How to overcome "'aclocal-1.15' is missing on your system" warning?

2017 - High Sierra

It is really hard to get autoconf 1.15 working on Mac. We hired an expert to get it working. Everything worked beautifully.

Later I happened to upgrade a Mac to High Sierra.

The Docker pipeline stopped working!

Even though autoconf 1.15 is working fine on the Mac.

How to fix,

Short answer, I simply trashed the local repo, and checked out the repo again.

This suggestion is noted in the mix on this QA page and elsewhere.

It then worked fine!

It likely has something to do with the aclocal.m4 and similar files. (But who knows really). I endlessly massaged those files ... but nothing.

For some unknown reason if you just scratch your repo and get the repo again: everything works!

I tried for hours every combo of touching/deleting etc etc the files in question, but no. Just check out the repo from scratch!

SpringMVC RequestMapping for GET parameters

If you are willing to change your uri, you could also use PathVariable.

@RequestMapping(value="/mapping/foo/{foo}/{bar}", method=RequestMethod.GET)
public String process(@PathVariable String foo,@PathVariable String bar) {
    //Perform logic with foo and bar
}

NB: The first foo is part of the path, the second one is the PathVariable

How to yum install Node.JS on Amazon Linux

I just came across this. I tried a few of the more popular answers, but in the end, what worked for me was Amazon's quick setup guide.

Tutorial: Setting Up Node.js on an Amazon EC2 Instance

The gist of the tutorial is:

  1. Make sure you are ssh'd onto the instance.
  2. Grab nvm: curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.0/install.sh | bash
  3. Active . ~/.nvm/nvm.sh
  4. Install node using nvm nvm install 4.4.5 (NOTE: You can choose a different version. Check out the remote versions first by running $ nvm ls-remote)
  5. Finally, test that you have installed node Node correctly by running $ node -e "console.log('Running Node.js' + process.version)"

Hopefully this helps the next person.

Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?

If you are into following Google's style guide:

Test, [ and [[

[[ ... ]] reduces errors as no path name expansion or word splitting takes place between [[ and ]], and [[ ... ]] allows for regular expression matching where [ ... ] does not.

# This ensures the string on the left is made up of characters in the
# alnum character class followed by the string name.
# Note that the RHS should not be quoted here.
# For the gory details, see
# E14 at https://tiswww.case.edu/php/chet/bash/FAQ
if [[ "filename" =~ ^[[:alnum:]]+name ]]; then
  echo "Match"
fi

# This matches the exact pattern "f*" (Does not match in this case)
if [[ "filename" == "f*" ]]; then
  echo "Match"
fi

# This gives a "too many arguments" error as f* is expanded to the
# contents of the current directory
if [ "filename" == f* ]; then
  echo "Match"
fi

Google Play Services Missing in Emulator (Android 4.4.2)

Setp 1 : Download the following apk files. 1)com.google.android.gms.apk (https://androidfilehost.com/?fid=95916177934534438) 2)com.android.vending-4.4.22.apk (https://androidfilehost.com/?fid=23203820527945795)

Step 2 : Create a new AVD without the google API's

Step 3 : Run the AVD (Start the emulator)

Step 4 : Install the downloaded apks using adb .

     1)adb install com.google.android.gms-6.7.76_\(1745988-038\)-6776038-minAPI9.apk  
     2)adb install com.android.vending-4.4.22.apk

adb come up with android sdks/studio

Step 5 : Create the application in google developer console

Step 6 : Configure the api key in your Androidmanifest.xml and google api version.

Note : In step1 you need to download the apk based on your Android API level(..18,19,21..) and google play services version (5,5.1,6,6.5......)

This will work 100%.

No line-break after a hyphen

You could also wrap the relevant text with

<span style="white-space: nowrap;"></span>

How to Auto resize HTML table cell to fit the text size

If you want the cells to resize depending on the content, then you must not specify a width to the table, the rows, or the cells.

If you don't want word wrap, assign the CSS style white-space: nowrap to the cells.

How to display HTML in TextView?

I know this question is old. Other answers here suggesting Html.fromHtml() method. I suggest you to use HtmlCompat.fromHtml() from androidx.core.text.HtmlCompat package. As this is backward compatible version of Html class.

Sample code:

import androidx.core.text.HtmlCompat;
import android.text.Spanned;
import android.widget.TextView;

String htmlString = "<h1>Hello World!</h1>";

Spanned spanned = HtmlCompat.fromHtml(htmlString, HtmlCompat.FROM_HTML_MODE_COMPACT);

TextView tvOutput = (TextView) findViewById(R.id.text_view_id);

tvOutput.setText(spanned);

By this way you can avoid Android API version check and it's easy to use (single line solution).

How to force an entire layout View refresh?

If you are going to create a custom view, make sure it is extending SurfaceView then, you can redraw it with method getHolder().lockCanvas(). Here is an example:

Canvas c = getHolder().lockCanvas();
c.drawText("Text", x, y, paint);
getHolder().unlockCanvasAndPost(c);

How do I make a splash screen?

Splash screens should not be loaded from a layout file, there might still be some lag when loading it.

The best way is to create a Theme just for your SplashScreenActivity and set the android:windowBackground to a drawable ressource.

https://www.bignerdranch.com/blog/splash-screens-the-right-way/

In a nutshell:

Declare your SplashScreenActivity in the manifest:

<activity
        android:name=".activities.SplashScreenActivity"
        android:theme="@style/SplashTheme"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

In your SplashScreenActivity.java:

@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent intent = new Intent(this, MainActivity_.class);
    startActivity(intent);
    finish();

}

Next create the ressource for the background window of your theme:

<style name="SplashTheme" parent="Theme.Bumpfie.Base">
    <item name="android:windowBackground">@drawable/splash</item>
</style>

Drawable file splash.xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@android:color/white"/>
    <item>
        <bitmap
            android:gravity="center"
            android:src="@drawable/app_logo"/>
    </item>
</layer-list>

bootstrap responsive table content wrapping

The behaviour is on purpose:

Create responsive tables by wrapping any .table in .table-responsive to make them scroll horizontally on small devices (under 768px). When viewing on anything larger than 768px wide, you will not see any difference in these tables.

Which means tables are responsive by default (are adjusting their size). But only if you wish to not break your table's lines and add scrollbar when there is not enough room use .table-responsive class.

If you take a look at bootstrap's source you will notice there is media query that only activates on XS screen size and it sets text of table to white-space: nowrap which causes it to not breaking.

TL;DR; Solution

Simply remove .table-responsive element/class from your html code.

List of all special characters that need to be escaped in a regex

although the answer is for Java, but the code can be easily adapted from this Kotlin String extension I came up with (adapted from that @brcolow provided):

private val escapeChars = charArrayOf(
    '<',
    '(',
    '[',
    '{',
    '\\',
    '^',
    '-',
    '=',
    '$',
    '!',
    '|',
    ']',
    '}',
    ')',
    '?',
    '*',
    '+',
    '.',
    '>'
)

fun String.escapePattern(): String {
    return this.fold("") {
      acc, chr ->
        acc + if (escapeChars.contains(chr)) "\\$chr" else "$chr"
    }
}

fun main() {
    println("(.*)".escapePattern())
}

prints \(\.\*\)

check it in action here https://pl.kotl.in/h-3mXZkNE

How can I get the active screen dimensions?

You can use this to get desktop workspace bounds of the primary screen:

System.Windows.SystemParameters.WorkArea

This is also useful for getting just the size of the primary screen:

System.Windows.SystemParameters.PrimaryScreenWidth System.Windows.SystemParameters.PrimaryScreenHeight

Excel: Can I create a Conditional Formula based on the Color of a Cell?

You can use this function (I found it here: http://excelribbon.tips.net/T010780_Colors_in_an_IF_Function.html):

Function GetFillColor(Rng As Range) As Long
    GetFillColor = Rng.Interior.ColorIndex
End Function

Here is an explanation, how to create user-defined functions: http://www.wikihow.com/Create-a-User-Defined-Function-in-Microsoft-Excel

In your worksheet, you can use the following: =GetFillColor(B5)

Unlink of file Failed. Should I try again?

If you're using Docker and running Windows 10, you may want to stop the container(s) where the file may be running at. To show the statuses of your containers, run

docker ps -a

To stop them, simply run

docker stop <container name or container id>

This worked for me as I am running my local files using a .sh file

Lumen: get URL parameter in a Blade view

The shortest way i have used

{{ Request::get('a') }}

How to keep the spaces at the end and/or at the beginning of a String?

Even if you use string formatting, sometimes you still need white spaces at the beginning or the end of your string. For these cases, neither escaping with \, nor xml:space attribute helps. You must use HTML entity &#160; for a whitespace.

Use &#160; for non-breakable whitespace.
Use &#032; for regular space.

What Content-Type value should I send for my XML sitemap?

Other answers here address the general question of what the proper Content-Type for an XML response is, and conclude (as with What's the difference between text/xml vs application/xml for webservice response) that both text/xml and application/xml are permissible. However, none address whether there are any rules specific to sitemaps.

Answer: there aren't. The sitemap spec is https://www.sitemaps.org, and using Google site: searches you can confirm that it does not contain the words or phrases mime, mimetype, content-type, application/xml, or text/xml anywhere. In other words, it is entirely silent on the topic of what Content-Type should be used for serving sitemaps.

In the absence of any commentary in the sitemap spec directly addressing this question, we can safely assume that the same rules apply as when choosing the Content-Type of any other XML document - i.e. that it may be either text/xml or application/xml.

Disable browser cache for entire ASP.NET website

HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
HttpContext.Current.Response.Cache.SetValidUntilExpires(false);
HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();

All requests get routed through default.aspx first - so assuming you can just pop in code behind there.

How to edit the legend entry of a chart in Excel?

The data series names are defined by the column headers. Add the names to the column headers that you would like to use as titles for each of your data series, select all of the data (including the headers), then re-generate your graph. The names in the headers should then appear as the names in the legend for each series.

Column headers become data series titles in graph legend

How do you get a list of the names of all files present in a directory in Node.js?

I made a node module to automate this task: mddir

Usage

node mddir "../relative/path/"

To install: npm install mddir -g

To generate markdown for current directory: mddir

To generate for any absolute path: mddir /absolute/path

To generate for a relative path: mddir ~/Documents/whatever.

The md file gets generated in your working directory.

Currently ignores node_modules, and .git folders.

Troubleshooting

If you receive the error 'node\r: No such file or directory', the issue is that your operating system uses different line endings and mddir can't parse them without you explicitly setting the line ending style to Unix. This usually affects Windows, but also some versions of Linux. Setting line endings to Unix style has to be performed within the mddir npm global bin folder.

Line endings fix

Get npm bin folder path with:

npm config get prefix

Cd into that folder

brew install dos2unix

dos2unix lib/node_modules/mddir/src/mddir.js

This converts line endings to Unix instead of Dos

Then run as normal with: node mddir "../relative/path/".

Example generated markdown file structure 'directoryList.md'

    |-- .bowerrc
    |-- .jshintrc
    |-- .jshintrc2
    |-- Gruntfile.js
    |-- README.md
    |-- bower.json
    |-- karma.conf.js
    |-- package.json
    |-- app
        |-- app.js
        |-- db.js
        |-- directoryList.md
        |-- index.html
        |-- mddir.js
        |-- routing.js
        |-- server.js
        |-- _api
            |-- api.groups.js
            |-- api.posts.js
            |-- api.users.js
            |-- api.widgets.js
        |-- _components
            |-- directives
                |-- directives.module.js
                |-- vendor
                    |-- directive.draganddrop.js
            |-- helpers
                |-- helpers.module.js
                |-- proprietary
                    |-- factory.actionDispatcher.js
            |-- services
                |-- services.cardTemplates.js
                |-- services.cards.js
                |-- services.groups.js
                |-- services.posts.js
                |-- services.users.js
                |-- services.widgets.js
        |-- _mocks
            |-- mocks.groups.js
            |-- mocks.posts.js
            |-- mocks.users.js
            |-- mocks.widgets.js

Check if an element contains a class in JavaScript?

This is a little old, but maybe someone will find my solution helpfull:

// Fix IE's indexOf Array
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement) {
        if (this == null) throw new TypeError();
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) return -1;
        var n = 0;
        if (arguments.length > 0) {
            n = Number(arguments[1]);
            if (n != n) n = 0;
            else if (n != 0 && n != Infinity && n != -Infinity) n = (n > 0 || -1) * Math.floor(Math.abs(n));
        }
        if (n >= len) return -1;
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k < len; k++) if (k in t && t[k] === searchElement) return k;
        return -1;
    }
}
// add hasClass support
if (!Element.prototype.hasClass) {
    Element.prototype.hasClass = function (classname) {
        if (this == null) throw new TypeError();
        return this.className.split(' ').indexOf(classname) === -1 ? false : true;
    }
}

Having a UITextField in a UITableViewCell

This should not be difficult. When creating a cell for your table, add a UITextField object to the cell's content view

UITextField *txtField = [[UITextField alloc] initWithFrame....]
...
[cell.contentView addSubview:txtField]

Set the delegate of the UITextField as self (ie your viewcontroller) Give a tag to the text field so you can identify which textfield was edited in your delegate methods. The keyboard should pop up when the user taps the text field. I got it working like this. Hope it helps.

Android SQLite SELECT Query

Try trimming the string to make sure there is no extra white space:

Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);

Also use c.moveToFirst() like @thinksteep mentioned.


This is a complete code for select statements.

SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
    do {
        // Passing values 
        String column1 = c.getString(0);
        String column2 = c.getString(1);
        String column3 = c.getString(2); 
        // Do something Here with values
    } while(c.moveToNext());
}
c.close();
db.close();

How to show changed file name only with git log?

If you need just file names like:

dir/subdir/file1.txt
dir/subdir2/file2.sql
dir2/subdir3/file6.php

(which I use as a source for tar command) you will also need to filter out commit messages.

In order to do this I use following command:

git log --name-only --oneline | grep -v '.{7} '

Grep command excludes (-v param) every line which starts with seven symbols (which is the length of my git hash for git log command) followed by space. So it filters out every git hash message line and leave only lines with file names.

One useful improvement is to append uniq to remove duplicate lines so it will looks as follow:

git log --name-only --oneline | grep -v '.{7} ' | uniq

Directly export a query to CSV using SQL Developer

Click in the grid so it has focus.

Ctrl+End

This will force the rest of the records back into the grid.

All credit to http://www.thatjeffsmith.com/archive/2012/03/how-to-export-sql-developer-query-results-without-re-running-the-query/

PHP & MySQL: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given

$dbc is returning false. Your query has an error in it:

SELECT users.*, profile.* --You do not join with profile anywhere.
                                 FROM users 
                                 INNER JOIN contact_info 
                                 ON contact_info.user_id = users.user_id 
                                 WHERE users.user_id=3");

The fix for this in general has been described by Raveren.

Add new row to dataframe, at specific row-index, not appended?

You should try dplyr package

library(dplyr)
a <- data.frame(A = c(1, 2, 3, 4),
               B = c(11, 12, 13, 14))


system.time({
for (i in 50:1000) {
    b <- data.frame(A = i, B = i * i)
    a <- bind_rows(a, b)
}

})

Output

   user  system elapsed 
   0.25    0.00    0.25

In contrast with using rbind function

a <- data.frame(A = c(1, 2, 3, 4),
                B = c(11, 12, 13, 14))


system.time({
    for (i in 50:1000) {
        b <- data.frame(A = i, B = i * i)
        a <- rbind(a, b)
    }

})

Output

   user  system elapsed 
   0.49    0.00    0.49 

There is some performance gain.

fork() child and parent processes

This is the correct way for getting the correct output.... However, childs parent id maybe sometimes printed as 1 because parent process gets terminated and the root process with pid = 1 controls this orphan process.

 pid_t  pid;
 pid = fork();
 if (pid == 0) 
    printf("This is the child process. My pid is %d and my parent's id 
      is %d.\n", getpid(), getppid());
 else 
     printf("This is the parent process. My pid is %d and my parent's 
         id is %d.\n", getpid(), pid);

Simple parse JSON from URL on Android and display in listview

I would suggest using the JSONParser class. It's very easy to use.

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) throws IOException {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);

            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }           


    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (Exception ex) {
        Log.d("Networking", ex.getLocalizedMessage());
        throw new IOException("Error connecting");
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

Then in your application, create an instance of this class. You may want to pass the constructor 'GET' or 'POST' if desired.

public JSONParser jsonParser = new JSONParser();

try {

    // Building Parameters ( you can pass as many parameters as you want)
    List<NameValuePair> params = new ArrayList<NameValuePair>();

    params.add(new BasicNameValuePair("name", name));
    params.add(new BasicNameValuePair("age", 25));

    // Getting JSON Object
    JSONObject json = jsonParser.makeHttpRequest(YOUR_URL, "POST", params);
} catch (JSONException e) {
    e.printStackTrace();
}

Assign result of dynamic sql to variable

You could use sp_executesql instead of exec. That allows you to specify an output parameter.

declare @out_var varchar(max);
execute sp_executesql 
    N'select @out_var = ''hello world''', 
    N'@out_var varchar(max) OUTPUT', 
    @out_var = @out_var output;
select @out_var;

This prints "hello world".

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

I am having the same issue here is my scenario

i put empty('') where value is NULL now this '' value does not match with the parent table's id

here is things need to check , all value with presented in parent table otherwise remove data from parent table then try enter image description here

enter image description here enter image description here

How do you strip a character out of a column in SQL Server?

UPDATE [TableName]
SET [ColumnName] = Replace([ColumnName], '[StringToRemove]', '[Replacement]')

In your instance it would be

UPDATE [TableName]
SET [ColumnName] = Replace([ColumnName], '[StringToRemove]', '')

Because there is no replacement (you want to get rid of it).

This will run on every row of the specified table. No need for a WHERE clause unless you want to specify only certain rows.

Selecting a row of pandas series/dataframe by integer index

The primary purpose of the DataFrame indexing operator, [] is to select columns.

When the indexing operator is passed a string or integer, it attempts to find a column with that particular name and return it as a Series.

So, in the question above: df[2] searches for a column name matching the integer value 2. This column does not exist and a KeyError is raised.


The DataFrame indexing operator completely changes behavior to select rows when slice notation is used

Strangely, when given a slice, the DataFrame indexing operator selects rows and can do so by integer location or by index label.

df[2:3]

This will slice beginning from the row with integer location 2 up to 3, exclusive of the last element. So, just a single row. The following selects rows beginning at integer location 6 up to but not including 20 by every third row.

df[6:20:3]

You can also use slices consisting of string labels if your DataFrame index has strings in it. For more details, see this solution on .iloc vs .loc.

I almost never use this slice notation with the indexing operator as its not explicit and hardly ever used. When slicing by rows, stick with .loc/.iloc.

How to do an update + join in PostgreSQL?

Here we go:

update vehicles_vehicle v
set price=s.price_per_vehicle
from shipments_shipment s
where v.shipment_id=s.id;

Simple as I could make it. Thanks guys!

Can also do this:

-- Doesn't work apparently
update vehicles_vehicle 
set price=s.price_per_vehicle
from vehicles_vehicle v
join shipments_shipment s on v.shipment_id=s.id;

But then you've got the vehicle table in there twice, and you're only allowed to alias it once, and you can't use the alias in the "set" portion.

In Oracle, is it possible to INSERT or UPDATE a record through a view?

YES, you can Update and Insert into view and that edit will be reflected on the original table....
BUT
1-the view should have all the NOT NULL values on the table
2-the update should have the same rules as table... "updating primary key related to other foreign key.. etc"...

load json into variable

_x000D_
_x000D_
var itens = null;_x000D_
$.getJSON("yourfile.json", function(data) {_x000D_
  itens = data;_x000D_
  itens.forEach(function(item) {_x000D_
    console.log(item);_x000D_
  });_x000D_
});_x000D_
console.log(itens);
_x000D_
<html>_x000D_
<head>_x000D_
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

What are Maven goals and phases and what is their difference?

The definitions are detailed at the Maven site's page Introduction to the Build Lifecycle, but I have tried to summarize:

Maven defines 4 items of a build process:

  1. Lifecycle

    Three built-in lifecycles (aka build lifecycles): default, clean, site. (Lifecycle Reference)

  2. Phase

    Each lifecycle is made up of phases, e.g. for the default lifecycle: compile, test, package, install, etc.

  3. Plugin

    An artifact that provides one or more goals.

    Based on packaging type (jar, war, etc.) plugins' goals are bound to phases by default. (Built-in Lifecycle Bindings)

  4. Goal

    The task (action) that is executed. A plugin can have one or more goals.

    One or more goals need to be specified when configuring a plugin in a POM. Additionally, in case a plugin does not have a default phase defined, the specified goal(s) can be bound to a phase.

Maven can be invoked with:

  1. a phase (e.g clean, package)
  2. <plugin-prefix>:<goal> (e.g. dependency:copy-dependencies)
  3. <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal> (e.g. org.apache.maven.plugins:maven-compiler-plugin:3.7.0:compile)

with one or more combinations of any or all, e.g.:

mvn clean dependency:copy-dependencies package

Vagrant shared and synced folders

shared folders VS synced folders

Basically shared folders are renamed to synced folder from v1 to v2 (docs), under the bonnet it is still using vboxsf between host and guest (there is known performance issues if there are large numbers of files/directories).

Vagrantfile directory mounted as /vagrant in guest

Vagrant is mounting the current working directory (where Vagrantfile resides) as /vagrant in the guest, this is the default behaviour.

See docs

NOTE: By default, Vagrant will share your project directory (the directory with the Vagrantfile) to /vagrant.

You can disable this behaviour by adding cfg.vm.synced_folder ".", "/vagrant", disabled: true in your Vagrantfile.

Why synced folder is not working

Based on the output /tmp on host was NOT mounted during up time.

Use VAGRANT_INFO=debug vagrant up or VAGRANT_INFO=debug vagrant reload to start the VM for more output regarding why the synced folder is not mounted. Could be a permission issue (mode bits of /tmp on host should be drwxrwxrwt).

I did a test quick test using the following and it worked (I used opscode bento raring vagrant base box)

config.vm.synced_folder "/tmp", "/tmp/src"

output

$ vagrant reload
[default] Attempting graceful shutdown of VM...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) eth0
2) vmnet8
3) lxcbr0
4) vmnet1
What interface should the network bridge to? 1
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Configuring and enabling network interfaces...
[default] Mounting shared folders...
[default] -- /vagrant
[default] -- /tmp/src

Within the VM, you can see the mount info /tmp/src on /tmp/src type vboxsf (uid=900,gid=900,rw).

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test

please follow this tutorial: https://www.petrikainulainen.net/programming/maven/creating-code-coverage-reports-for-unit-and-integration-tests-with-the-jacoco-maven-plugin/

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.15</version>
<configuration>
    <!-- Sets the VM argument line used when unit tests are run. -->
    <argLine>${surefireArgLine}</argLine>
    <!-- Skips unit tests if the value of skip.unit.tests property is true -->
    <skipTests>${skip.unit.tests}</skipTests>
    <!-- Excludes integration tests when unit tests are run. -->
    <excludes>
        <exclude>**/IT*.java</exclude>
    </excludes>
</configuration>

Import Error: No module named numpy

For installing NumPy via Anaconda(use below commands):

  • conda install -c conda-forge numpy
  • conda install -c conda-forge/label/broken numpy

what is trailing whitespace and how can I handle this?

This is just a warning and it doesn't make problem for your project to run, you can just ignore it and continue coding. But if you're obsessed about clean coding, same as me, you have two options:

  1. Hover the mouse on warning in VS Code or any IDE and use quick fix to remove white spaces.
  2. Press f1 then type trim trailing whitespace.

Laravel: Validation unique on update

You can try this.

protected $rules_update = [
    'email_address' => 'required|email|unique:users,email_address,'. $this->id,
    'first_name' => "required",
    'last_name' => "required",
    'password' => "required|min:6|same:password_confirm",
    'password_confirm' => "required:min:6|same:password",
    'password_current' => "required:min:6"
];

Remove "Using default security password" on Spring Boot

I came across the same problem and adding this line to my application.properties solved the issue.

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration

It's one of the Spring's Automatic stuffs which you exclude it like excluding other stuffs such as actuators. I recommend looking at this link

How to add "active" class to Html.ActionLink in ASP.NET MVC

ASP.NET Core & Bootstrap 4

Most up-to-date answer

I have re-worked @crush's neat solution for an updated, ASP.NET Core and Bootstrap 4 compatible way to solve this problem based on an IHtmlHelper extension method:

public static class LinkExtensions
{
    public static IHtmlContent ActiveActionLink(this IHtmlHelper html, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes)
    {
        return ActiveActionLink(html, linkText, actionName, controllerName, new RouteValueDictionary(routeValues), HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
    }

    public static IHtmlContent ActiveActionLink(this IHtmlHelper html, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes)
    {
        var routeData = html.ViewContext.RouteData;
        var routeAction = (string)routeData.Values["action"];
        var routeController = (string)routeData.Values["controller"];

        var active = controllerName.Equals(routeController) && actionName.Equals(routeAction);

        using (var writer = new StringWriter())
        {
            writer.WriteLine($"<li class='nav-item {(active ? "active" : "")}'>");
            html.ActionLink(linkText, actionName, controllerName, routeValues, htmlAttributes).WriteTo(writer, HtmlEncoder.Default);
            writer.WriteLine("</li>");
            return new HtmlString(writer.ToString());
        }
    }
}

Usage

<nav class="navbar">
    <div class="collapse navbar-collapse">
        <ul class="navbar-nav">
            @Html.ActiveActionLink("Home", "Index", "Home", null, new { @class = "nav-link" })
            @Html.ActiveActionLink("About", "About", "Home", null, new { @class = "nav-link" })
            @Html.ActiveActionLink("Contact", "Contact", "TimeTracking", null, new { @class = "nav-link" })
        </ul>
    </div>
</nav>

Float and double datatype in Java

The Wikipedia page on it is a good place to start.

To sum up:

  • float is represented in 32 bits, with 1 sign bit, 8 bits of exponent, and 23 bits of the significand (or what follows from a scientific-notation number: 2.33728*1012; 33728 is the significand).

  • double is represented in 64 bits, with 1 sign bit, 11 bits of exponent, and 52 bits of significand.

By default, Java uses double to represent its floating-point numerals (so a literal 3.14 is typed double). It's also the data type that will give you a much larger number range, so I would strongly encourage its use over float.

There may be certain libraries that actually force your usage of float, but in general - unless you can guarantee that your result will be small enough to fit in float's prescribed range, then it's best to opt with double.

If you require accuracy - for instance, you can't have a decimal value that is inaccurate (like 1/10 + 2/10), or you're doing anything with currency (for example, representing $10.33 in the system), then use a BigDecimal, which can support an arbitrary amount of precision and handle situations like that elegantly.

How to Change color of Button in Android when Clicked?

you can try this code to solve your problem

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_pressed="true"
   android:drawable="@drawable/login_selected" /> <!-- pressed -->
  <item android:state_focused="true"
   android:drawable="@drawable/login_mouse_over" /> <!-- focused -->
  <item android:drawable="@drawable/login" /> <!-- default -->
</selector>

write this code in your drawable make a new resource and name it what you want and then write the name of this drwable in the button same as we refer to image src in android

Adding double quote delimiters into csv file

Here's a way to do it without formulas or macros:

  1. Save your CSV as Excel
  2. Select any cells that might have commas
  3. Open to the Format menu and click on Cells
  4. Pick the Custom format
  5. Enter this => \"@\"
  6. Click OK
  7. Save the file as CSV

(from http://www.lenashore.com/2012/04/how-to-add-quotes-to-your-cells-in-excel-automatically/)

WRONGTYPE Operation against a key holding the wrong kind of value php

I faced this issue when trying to set something to redis. The problem was that I previously used "set" method to set data with a certain key, like

$redis->set('persons', $persons)

Later I decided to change to "hSet" method, and I tried it this way

foreach($persons as $person){
    $redis->hSet('persons', $person->id, $person);
}

Then I got the aforementioned error. So, what I had to do is to go to redis-cli and manually delete "persons" entry with

del persons

It simply couldn't write different data structure under existing key, so I had to delete the entry and hSet then.

How do I modify fields inside the new PostgreSQL JSON datatype?

The following plpython snippet might come in handy.

CREATE EXTENSION IF NOT EXISTS plpythonu;
CREATE LANGUAGE plpythonu;

CREATE OR REPLACE FUNCTION json_update(data json, key text, value text)
 RETURNS json
 AS $$
    import json
    json_data = json.loads(data)
    json_data[key] = value
    return json.dumps(json_data, indent=4)
 $$ LANGUAGE plpythonu;

-- Check how JSON looks before updating

SELECT json_update(content::json, 'CFRDiagnosis.mod_nbs', '1')
FROM sc_server_centre_document WHERE record_id = 35 AND template = 'CFRDiagnosis';

-- Once satisfied update JSON inplace

UPDATE sc_server_centre_document SET content = json_update(content::json, 'CFRDiagnosis.mod_nbs', '1')
WHERE record_id = 35 AND template = 'CFRDiagnosis';

CSV new-line character seen in unquoted field error

If this happens to you on mac (as it did to me):

  1. Save the file as CSV (MS-DOS Comma-Separated)
  2. Run the following script

    with open(csv_filename, 'rU') as csvfile:
        csvreader = csv.reader(csvfile)
        for row in csvreader:
            print ', '.join(row)
    

FFmpeg on Android

The most easy to build, easy to use implementation I have found is made by theguardianproject team: https://github.com/guardianproject/android-ffmpeg

How to swap two variables in JavaScript

Destructing assignment is the best way to solve your problem.

_x000D_
_x000D_
var a = 1;
var b = 2;

[a, b] = [b, a];

console.log("After swap a =", a, " and b =", b);
_x000D_
_x000D_
_x000D_

How to hide keyboard in swift on pressing return key?

Here's the Swift 3.0 update to peacetype's comment:

textField.addTarget(nil, action:Selector(("firstResponderAction:")), for:.editingDidEndOnExit)

"An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP

Windows Firewall was creating this error for me. SMTP was trying to post to GMAIL at port 587. Adding port 587 to the Outbound rule [Outbound HTTP/SMTP/RDP] resolved the issue.

Android: show/hide status bar/power bar

with this method, using SYSTEM_UI_FLAG_IMMERSIVE_STICKY the full screen come back with one tap without any implementation. Just copy past this method below and call it where you want in your activity. More details here

private void hideSystemUI() {
    getWindow().getDecorView().setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_IMMERSIVE
                    // Set the content to appear under the system bars so that the
                    // content doesn't resize when the system bars hide and show.
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    // Hide the nav bar and status bar
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN);
}

Cannot connect to Database server (mysql workbench)

My problem was that the MySQL server wasn't actually installed. I had run the MySQL Installer, but it didn't install the MySQL server.

I reran the installer, click "Add", and then added MySQL server to the list. Now it works fine.

When should I write the keyword 'inline' for a function/method?

  • When will the the compiler not know when to make a function/method 'inline'?

This depends on the compiler used. Do not blindly trust that nowadays compilers know better then humans how to inline and you should never use it for performance reasons, because it's linkage directive rather than optimization hint. While I agree that ideologically are these arguments correct encountering reality might be a different thing.

After reading multiple threads around I tried out of curiosity the effects of inline on the code I'm just working and the results were that I got measurable speedup for GCC and no speed up for Intel compiler.

(More detail: math simulations with few critical functions defined outside class, GCC 4.6.3 (g++ -O3), ICC 13.1.0 (icpc -O3); adding inline to critical points caused +6% speedup with GCC code).

So if you qualify GCC 4.6 as a modern compiler the result is that inline directive still matters if you write CPU intensive tasks and know where exactly is the bottleneck.

Automating the InvokeRequired code pattern

Here's the form I've been using in all my code.

private void DoGUISwitch()
{ 
    Invoke( ( MethodInvoker ) delegate {
        object1.Visible = true;
        object2.Visible = false;
    });
} 

I've based this on the blog entry here. I have not had this approach fail me, so I see no reason to complicate my code with a check of the InvokeRequired property.

Hope this helps.

jQuery hyperlinks - href value?

You should really put a real link in there. I don't want to sound like a pedant, but that's a fairly bad habit to get into. JQuery and Ajax should always be the last thing you implement. If you have a link that goes no-where, you're not doing it right.

I'm not busting your balls, I mean that with all the best intention.

React.js create loop through Array

In CurrentGame component you need to change initial state because you are trying use loop for participants but this property is undefined that's why you get error.,

getInitialState: function(){
    return {
       data: {
          participants: [] 
       }
    };
},

also, as player in .map is Object you should get properties from it

this.props.data.participants.map(function(player) {
   return <li key={player.championId}>{player.summonerName}</li>
   // -------------------^^^^^^^^^^^---------^^^^^^^^^^^^^^
})

Example

Is it possible to create static classes in PHP (like in C#)?

object cannot be defined staticly but this works

final Class B{
  static $var;
  static function init(){
    self::$var = new A();
}
B::init();

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.

Java Regex to Validate Full Name allow only Spaces and Letters

please try this regex (allow only Alphabets and space)

"[a-zA-Z][a-zA-Z ]*"

if you want it for IOS then,

NSString *yourstring = @"hello";

NSString *Regex = @"[a-zA-Z][a-zA-Z ]*";
NSPredicate *TestResult = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",Regex];

if ([TestResult evaluateWithObject:yourstring] == true)
{
    // validation passed
}
else
{
    // invalid name
}

Mysql Compare two datetime fields

Do you want to order it?

Select * From temp where mydate > '2009-06-29 04:00:44' ORDER BY mydate;

AngularJS does not send hidden field value

I've found a nice solution written by Mike on sapiensworks. It is as simple as using a directive that watches for changes on your model:

.directive('ngUpdateHidden',function() {
    return function(scope, el, attr) {
        var model = attr['ngModel'];
        scope.$watch(model, function(nv) {
            el.val(nv);
        });
    };
})

and then bind your input:

<input type="hidden" name="item.Name" ng-model="item.Name" ng-update-hidden />

But the solution provided by tymeJV could be better as input hidden doesn't fire change event in javascript as yycorman told on this post, so when changing the value through a jQuery plugin will still work.

Edit I've changed the directive to apply the a new value back to the model when change event is triggered, so it will work as an input text.

.directive('ngUpdateHidden', function () {
    return {
        restrict: 'AE', //attribute or element
        scope: {},
        replace: true,
        require: 'ngModel',
        link: function ($scope, elem, attr, ngModel) {
            $scope.$watch(ngModel, function (nv) {
                elem.val(nv);
            });
            elem.change(function () { //bind the change event to hidden input
                $scope.$apply(function () {
                    ngModel.$setViewValue(  elem.val());
                });
            });
        }
    };
})

so when you trigger $("#yourInputHidden").trigger('change') event with jQuery, it will update the binded model as well.

How to define dimens.xml for every different screen size in android?

You have to create a different values folder for different screens and put dimens.xml file according to densities.

1) values

2) values-hdpi (320x480 ,480x800)

3) values-large-hdpi (600x1024)

4) values-xlarge (720x1280 ,768x1280 ,800x1280 ,Nexus7 ,Nexus10)

5) values-sw480dp (5.1' WVGA screen)

6) values-xhdpi (Nexus4 , Galaxy Nexus)

How to count the number of occurrences of an element in a List

Simple Way to find the occurrence of string value in an array using Java 8 features.

public void checkDuplicateOccurance() {
        List<String> duplicateList = new ArrayList<String>();
        duplicateList.add("Cat");
        duplicateList.add("Dog");
        duplicateList.add("Cat");
        duplicateList.add("cow");
        duplicateList.add("Cow");
        duplicateList.add("Goat");          
        Map<String, Long> couterMap = duplicateList.stream().collect(Collectors.groupingBy(e -> e.toString(),Collectors.counting()));
        System.out.println(couterMap);
    }

Output : {Cat=2, Goat=1, Cow=1, cow=1, Dog=1}

You can notice "Cow" and cow are not considered as same string, in case you required it under same count, use .toLowerCase(). Please find the snippet below for the same.

Map<String, Long> couterMap = duplicateList.stream().collect(Collectors.groupingBy(e -> e.toString().toLowerCase(),Collectors.counting()));

Output : {cat=2, cow=2, goat=1, dog=1}

ORACLE IIF Statement

Two other alternatives:

  1. a combination of NULLIF and NVL2. You can only use this if emp_id is NOT NULL, which it is in your case:

    select nvl2(nullif(emp_id,1),'False','True') from employee;
    
  2. simple CASE expression (Mt. Schneiders used a so-called searched CASE expression)

    select case emp_id when 1 then 'True' else 'False' end from employee;
    

ASP.NET file download from server

Try this set of code to download a CSV file from the server.

byte[] Content= File.ReadAllBytes(FilePath); //missing ;
Response.ContentType = "text/csv";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".csv");
Response.BufferOutput = true;
Response.OutputStream.Write(Content, 0, Content.Length);
Response.End();

How do you list the primary key of a SQL Server table?

Sys.Objects Table contains row for each user-defined, schema-scoped object .

Constraints created like Primary Key or others will be the object and Table name will be the parent_object

Query sys.Objects and collect the Object's Ids of Required Type

declare @TableName nvarchar(50)='TblInvoice' -- your table name
declare @TypeOfKey nvarchar(50)='PK' -- For Primary key

SELECT Name FROM sys.objects
WHERE type = @TypeOfKey 
AND  parent_object_id = OBJECT_ID (@TableName)

Check if a string contains a number

Simpler way to solve is as

s = '1dfss3sw235fsf7s'
count = 0
temp = list(s)
for item in temp:
    if(item.isdigit()):
        count = count + 1
    else:
        pass
print count

Convert pandas timezone-aware DateTimeIndex to naive timestamp, but in certain timezone

I think you can't achieve what you want in a more efficient manner than you proposed.

The underlying problem is that the timestamps (as you seem aware) are made up of two parts. The data that represents the UTC time, and the timezone, tz_info. The timezone information is used only for display purposes when printing the timezone to the screen. At display time, the data is offset appropriately and +01:00 (or similar) is added to the string. Stripping off the tz_info value (using tz_convert(tz=None)) doesn't doesn't actually change the data that represents the naive part of the timestamp.

So, the only way to do what you want is to modify the underlying data (pandas doesn't allow this... DatetimeIndex are immutable -- see the help on DatetimeIndex), or to create a new set of timestamp objects and wrap them in a new DatetimeIndex. Your solution does the latter:

pd.DatetimeIndex([i.replace(tzinfo=None) for i in t])

For reference, here is the replace method of Timestamp (see tslib.pyx):

def replace(self, **kwds):
    return Timestamp(datetime.replace(self, **kwds),
                     offset=self.offset)

You can refer to the docs on datetime.datetime to see that datetime.datetime.replace also creates a new object.

If you can, your best bet for efficiency is to modify the source of the data so that it (incorrectly) reports the timestamps without their timezone. You mentioned:

I want to work with timezone naive timeseries (to avoid the extra hassle with timezones, and I do not need them for the case I am working on)

I'd be curious what extra hassle you are referring to. I recommend as a general rule for all software development, keep your timestamp 'naive values' in UTC. There is little worse than looking at two different int64 values wondering which timezone they belong to. If you always, always, always use UTC for the internal storage, then you will avoid countless headaches. My mantra is Timezones are for human I/O only.

Restoring database from .mdf and .ldf files of SQL Server 2008

First google search yielded me this answer. So I thought of updating this with newer version of attach, detach.

Create database dbname 
On 
(   
Filename= 'path where you copied files',   
Filename ='path where you copied log'
)
For attach; 

Further,if your database is cleanly shutdown(there are no active transactions while database was shutdown) and you dont have log file,you can use below method,SQL server will create a new transaction log file..

Create database dbname 
    On 
    (   
    Filename= 'path where you copied files'   
    )
    For attach; 

if you don't specify transaction log file,SQL will try to look in the default path and will try to use it irrespective of whether database was cleanly shutdown or not..

Here is what MSDN has to say about this..

If a read-write database has a single log file and you do not specify a new location for the log file, the attach operation looks in the old location for the file. If it is found, the old log file is used, regardless of whether the database was shut down cleanly. However, if the old log file is not found and if the database was shut down cleanly and has no active log chain, the attach operation attempts to build a new log file for the database.

There are some restrictions with this approach and some side affects too..

1.attach-and-detach operations both disable cross-database ownership chaining for the database
2.Database trustworthy is set to off
3.Detaching a read-only database loses information about the differential bases of differential backups.

Most importantly..you can't attach a database with recent versions to an earlier version

References:
https://msdn.microsoft.com/en-in/library/ms190794.aspx

How to convert JSON to string?

You can use the JSON stringify method.

JSON.stringify({x: 5, y: 6}); // '{"x":5,"y":6}' or '{"y":6,"x":5}'

There is pretty good support for this across the board when it comes to browsers, as shown on http://caniuse.com/#search=JSON. You will note, however, that versions of IE earlier than 8 do not support this functionality natively.

If you wish to cater to those users as well you will need a shim. Douglas Crockford has provided his own JSON Parser on github.

What is (x & 1) and (x >>= 1)?

It is similar to x = (x >> 1).

(operand1)(operator)=(operand2)  implies(=>)  (operand1)=(operand1)(operator)(operand2) 

It shifts the binary value of x by one to the right.

E.g.

int x=3;    // binary form (011) 
x = x >> 1; // zero shifted in from the left, 1 shifted out to the right:
            // x=1, binary form (001)

Change link color of the current page with CSS

a:active : when you click on the link and hold it (active!).
a:visited : when the link has already been visited.

If you want the link corresponding to the current page to be highlighted, you can define some specific style to the link -

.currentLink {
   color: #640200;
   background-color: #000000;
}

Add this new class only to the corresponding li (link), either on server-side or on client-side (using JavaScript).

how to get multiple checkbox value using jquery

$('input:checked').map(function(i, e) {return e.value}).toArray();

How to set image for bar button with swift?

Just choose Original image option when adding an image to assets in Xcode

enter image description here

How to debug Google Apps Script (aka where does Logger.log log to?)

If you have the script editor open you will see the logs under View->Logs. If your script has an onedit trigger, make a change to the spreadsheet which should trigger the function with the script editor opened in a second tab. Then go to the script editor tab and open the log. You will see whatever your function passes to the logger.

Basically as long as the script editor is open, the event will write to the log and show it for you. It will not show if someone else is in the file elsewhere.

compare two files in UNIX

There are 3 basic commands to compare files in unix:

  1. cmp : This command is used to compare two files byte by byte and as any mismatch occurs,it echoes it on the screen.if no mismatch occurs i gives no response. syntax:$cmp file1 file2.

  2. comm : This command is used to find out the records available in one but not in another

  3. diff

How to change the default encoding to UTF-8 for Apache?

<meta charset='utf-8'> overrides the apache default charset (cf /etc/apache2/conf.d/charset)

If this is not enough, then you probably created your original file with iso-8859-1 encoding character set. You have to convert it to the proper character set:

iconv -f ISO-8859-1 -t UTF-8 source_file.php -o new file.php

Filtering a list of strings based on contents

Tried this out quickly in the interactive shell:

>>> l = ['a', 'ab', 'abc', 'bac']
>>> [x for x in l if 'ab' in x]
['ab', 'abc']
>>>

Why does this work? Because the in operator is defined for strings to mean: "is substring of".

Also, you might want to consider writing out the loop as opposed to using the list comprehension syntax used above:

l = ['a', 'ab', 'abc', 'bac']
result = []
for s in l:
   if 'ab' in s:
       result.append(s)

Android Service needs to run always (Never pause or stop)

If you already have a service and want it to work all the time, you need to add 2 things:

  1. in the service itself:

    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }
    
  2. In the manifest:

    android:launchMode="singleTop"
    

No need to add bind unless you need it in the service.

rails bundle clean

Honestly, I had problems with bundler circular dependencies and the best way to go is rm -rf .bundle. Save yourselves the headache and just use the hammer.

Where can I get a list of Countries, States and Cities?

The UN maintains a list of countries and "states" / regions for economic trade. That DB is available here: http://www.unece.org/cefact/locode/welcome.html

How can you print a variable name in python?

Will something like this work for you?

>>> def namestr(**kwargs):
...     for k,v in kwargs.items():
...       print "%s = %s" % (k, repr(v))
...
>>> namestr(a=1, b=2)
a = 1
b = 2

And in your example:

>>> choice = {'key': 24; 'data': None}
>>> namestr(choice=choice)
choice = {'data': None, 'key': 24}
>>> printvars(**globals())
__builtins__ = <module '__builtin__' (built-in)>
__name__ = '__main__'
__doc__ = None
namestr = <function namestr at 0xb7d8ec34>
choice = {'data': None, 'key': 24}

Java: recommended solution for deep cloning/copying an instance

For deep cloning (clones the entire object hierarchy):

  • commons-lang SerializationUtils - using serialization - if all classes are in your control and you can force implementing Serializable.

  • Java Deep Cloning Library - using reflection - in cases when the classes or the objects you want to clone are out of your control (a 3rd party library) and you can't make them implement Serializable, or in cases you don't want to implement Serializable.

For shallow cloning (clones only the first level properties):

I deliberately omitted the "do-it-yourself" option - the API's above provide a good control over what to and what not to clone (for example using transient, or String[] ignoreProperties), so reinventing the wheel isn't preferred.

Converting int to string in C

You can make your own itoa, with this function:

void my_utoa(int dataIn, char* bffr, int radix){
int temp_dataIn;
temp_dataIn = dataIn;
int stringLen=1;

while ((int)temp_dataIn/radix != 0){
    temp_dataIn = (int)temp_dataIn/radix;
    stringLen++;
}
//printf("stringLen = %d\n", stringLen);
temp_dataIn = dataIn;
do{
    *(bffr+stringLen-1) = (temp_dataIn%radix)+'0';
    temp_dataIn = (int) temp_dataIn / radix;
}while(stringLen--);}

and this is example:

char buffer[33];
int main(){
  my_utoa(54321, buffer, 10);
  printf(buffer);
  printf("\n");

  my_utoa(13579, buffer, 10);
  printf(buffer);
  printf("\n");
}

What is InputStream & Output Stream? Why and when do we use them?

Stream: In laymen terms stream is data , most generic stream is binary representation of data.

Input Stream : If you are reading data from a file or any other source , stream used is input stream. In a simpler terms input stream acts as a channel to read data.

Output Stream : If you want to read and process data from a source (file etc) you first need to save the data , the mean to store data is output stream .

Display rows with one or more NaN values in pandas dataframe

Suppose gamma1 and gamma2 are two such columns for which df.isnull().any() gives True value , the following code can be used to print the rows.

bool1 = pd.isnull(df['gamma1'])
bool2 = pd.isnull(df['gamma2'])
df[bool1]
df[bool2]

What is the best way to iterate over a dictionary?

Using C# 7, add this extension method to any project of your solution:

public static class IDictionaryExtensions
{
    public static IEnumerable<(TKey, TValue)> Tuples<TKey, TValue>(
        this IDictionary<TKey, TValue> dict)
    {
        foreach (KeyValuePair<TKey, TValue> kvp in dict)
            yield return (kvp.Key, kvp.Value);
    }
}


And use this simple syntax

foreach (var(id, value) in dict.Tuples())
{
    // your code using 'id' and 'value'
}


Or this one, if you prefer

foreach ((string id, object value) in dict.Tuples())
{
    // your code using 'id' and 'value'
}


In place of the traditional

foreach (KeyValuePair<string, object> kvp in dict)
{
    string id = kvp.Key;
    object value = kvp.Value;

    // your code using 'id' and 'value'
}


The extension method transforms the KeyValuePair of your IDictionary<TKey, TValue> into a strongly typed tuple, allowing you to use this new comfortable syntax.

It converts -just- the required dictionary entries to tuples, so it does NOT converts the whole dictionary to tuples, so there are no performance concerns related to that.

There is a only minor cost calling the extension method for creating a tuple in comparison with using the KeyValuePair directly, which should NOT be an issue if you are assigning the KeyValuePair's properties Key and Value to new loop variables anyway.

In practice, this new syntax suits very well for most cases, except for low-level ultra-high performance scenarios, where you still have the option to simply not use it on that specific spot.

Check this out: MSDN Blog - New features in C# 7

Change Text Color of Selected Option in a Select Box

JQuery Code:

$('#mySelect').change(function () {
    $('#mySelect').css("background", $("select option:selected").css("background-color"));
});

This will replace the select's background-color with selected option's background-color.

Here is an example fiddle.

How can I enable MySQL's slow query log without restarting MySQL?

These work

SET GLOBAL LOG_SLOW_TIME = 1;
SET GLOBAL LOG_QUERIES_NOT_USING_INDEXES = ON;

Broken on my setup 5.1.42

SET GLOBAL LOG_SLOW_QUERIES = ON;
SET GLOBAL SLOW_QUERY_LOG = ON;
set @@global.log_slow_queries=1;

http://bugs.mysql.com/bug.php?id=32565

Looks like the best way to do this is set log_slow_time very high thus "turning off" the slow query log. Lower log_slow_time to enable it. Use the same trick (set to OFF) for log_queries_not_using_indexes.

How to add a new line in textarea element?

<textarea cols='60' rows='8'>This is my statement one.

This is my statement2</textarea>

Fiddle showing that it works: http://jsfiddle.net/trott/5vu28/.

If you really want this to be on a single line in the source file, you could insert the HTML character references for a line feed and a carriage return as shown in the answer from @Bakudan:

_x000D_
_x000D_
  <textarea cols='60' rows='8'>This is my statement one.&#13;&#10;This is my statement2</textarea>
_x000D_
_x000D_
_x000D_

Decode HTML entities in Python string?

Beautiful Soup handles entity conversion. In Beautiful Soup 3, you'll need to specify the convertEntities argument to the BeautifulSoup constructor (see the 'Entity Conversion' section of the archived docs). In Beautiful Soup 4, entities get decoded automatically.

Beautiful Soup 3

>>> from BeautifulSoup import BeautifulSoup
>>> BeautifulSoup("<p>&pound;682m</p>", 
...               convertEntities=BeautifulSoup.HTML_ENTITIES)
<p>£682m</p>

Beautiful Soup 4

>>> from bs4 import BeautifulSoup
>>> BeautifulSoup("<p>&pound;682m</p>")
<html><body><p>£682m</p></body></html>

UICollectionView auto scroll to cell at IndexPath

I've found that scrolling in viewWillAppear may not work reliably because the collection view hasn't finished it's layout yet; you may scroll to the wrong item.

I've also found that scrolling in viewDidAppear will cause a momentary flash of the unscrolled view to be visible.

And, if you scroll every time through viewDidLayoutSubviews, the user won't be able to manually scroll because some collection layouts cause subview layout every time you scroll.

Here's what I found works reliably:

Objective C :

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    // If we haven't done the initial scroll, do it once.
    if (!self.initialScrollDone) {
        self.initialScrollDone = YES;

        [self.collectionView scrollToItemAtIndexPath:self.myInitialIndexPath
                                    atScrollPosition:UICollectionViewScrollPositionRight animated:NO];
    }
}

Swift :

 override func viewWillLayoutSubviews() {

    super.viewWillLayoutSubviews()

      if (!self.initialScrollDone) {

         self.initialScrollDone = true
         self.testNameCollectionView.scrollToItem(at:selectedIndexPath, at: .centeredHorizontally, animated: true)
    }

}

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

You always need to check for XACT_STATE(), irrelevant of the XACT_ABORT setting. I have an example of a template for stored procedures that need to handle transactions in the TRY/CATCH context at Exception handling and nested transactions:

create procedure [usp_my_procedure_name]
as
begin
    set nocount on;
    declare @trancount int;
    set @trancount = @@trancount;
    begin try
        if @trancount = 0
            begin transaction
        else
            save transaction usp_my_procedure_name;

        -- Do the actual work here

lbexit:
        if @trancount = 0   
            commit;
    end try
    begin catch
        declare @error int, @message varchar(4000), @xstate int;
        select @error = ERROR_NUMBER(),
               @message = ERROR_MESSAGE(), 
               @xstate = XACT_STATE();
        if @xstate = -1
            rollback;
        if @xstate = 1 and @trancount = 0
            rollback
        if @xstate = 1 and @trancount > 0
            rollback transaction usp_my_procedure_name;

        raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
    end catch   
end

Nginx: stat() failed (13: permission denied)

I faced this problem, I solved it to give permissions to nginx user and group something like this:

chown -R nginx:nginx /username/test/static

Change a Nullable column to NOT NULL with Default Value

If its SQL Server you can do it on the column properties within design view

Try this?:

ALTER TABLE dbo.TableName 
  ADD CONSTRAINT DF_TableName_ColumnName
    DEFAULT '01/01/2000' FOR ColumnName

Android: remove notification from notification bar

Just call ID:

public void delNoti(int id) {((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancel(id);}

when I try to open an HTML file through `http://localhost/xampp/htdocs/index.html` it says unable to connect to localhost

I just put an index.html file in /htdocs and type in http://127.0.0.1/index.html - and up comes the html.

Add a folder "named Forum" and type in 127.0.0.1/forum/???.???

Cordova : Requirements check failed for JDK 1.8 or greater

I was running into the same problem yesterday with my new laptop (all new installation), with the only execption that for me Cordova said:

Requirements check failed for JDK 8 ('1.8.*')! Detected version: null

That Detected version: null was the actual problem for me!

When looking into the check_reqs.js (as mentioned in a post above) you will notice that this is where the magic happens: It contains a function "check_java" that, at some point, uses "execa" to retrieve the installed version of Java:

return execa('javac', ['-version'], { all: true })
    .then(({ all: output }) => {
        // Java <= 8 writes version info to stderr, Java >= 9 to stdout
        const match = /javac\s+([\d.]+)/i.exec(output);
        return match && match[1];
    }

The problem for me was that, for whatever reason, I had an outdated version of "execa" which does not contain the "all" property that was used for the output. Hence, the retrieved version of Java was always undefined. By adding "execa": "^4.0.2" to my dependencies in the package.json and running "npm i" again I was able to fix this problem.

Just wanted to share this insight.

How can I stop redis-server?

On MacOSX,

This is what worked for me

/etc/init.d/redis restart

/etc/init.d/redis stop

/etc/init.d/redis start

DisplayName attribute from Resources?

If you open your resource file and change the access modifier to public or internal it will generate a class from your resource file which allows you to create strongly typed resource references.

Option for resource file code generation

Which means you can do something like this instead (using C# 6.0). Then you dont have to remember if firstname was lowercased or camelcased. And you can see if other properties use the same resource value with a find all references.

[Display(Name = nameof(PropertyNames.FirstName), ResourceType = typeof(PropertyNames))]
public string FirstName { get; set; }

How to clean up R memory (without the need to restart my PC)?

An example under Linux (Fedora 16) shows that memory is freed when R is closed:

$ free -m                                                                                                                                                                                                                                    
             total       used       free     shared    buffers     cached                                                                                                                                                                    
Mem:          3829       2854        974          0        344       1440                                                                                                                                                                    
-/+ buffers/cache:       1069       2759                                                                                                                                                                                                     
Swap:         4095         85       4010     

2854 megabytes is used. Next I open an R session and create a large matrix of random numbers:

m = matrix(runif(10e7), 10000, 1000)

when the matrix is created, 3714 MB is used:

$ free -m                                                                                                                                                                                                                                    
             total       used       free     shared    buffers     cached                                                                                                                                                                    
Mem:          3829       3714        115          0        344       1442                                                                                                                                                                    
-/+ buffers/cache:       1927       1902                                                                                                                                                                                                     
Swap:         4095         85       4010     

After closing the R session, I nicely get back the memory I used (2856 MB free):

$ free -m                                                                                                                                                                                                                                    
             total       used       free     shared    buffers     cached                                                                                                                                                                    
Mem:          3829       2856        972          0        344       1442                                                                                                                                                                    
-/+ buffers/cache:       1069       2759                                                                                                                                                                                                     
Swap:         4095         85       4010   

Ofcourse you use Windows, but you could repeat this excercise in Windows and report how the available memory develops before and after you create this large dataset in R.

Reactive forms - disabled attribute

Use [attr.disabled] instead [disabled], in my case it works ok

Calling the base constructor in C#

From Framework Design Guidelines and FxCop rules.:

1. Custom Exception should have a name that ends with Exception

    class MyException : Exception

2. Exception should be public

    public class MyException : Exception

3. CA1032: Exception should implements standard constructors.

  • A public parameterless constructor.
  • A public constructor with one string argument.
  • A public constructor with one string and Exception (as it can wrap another Exception).
  • A serialization constructor protected if the type is not sealed and private if the type is sealed. Based on MSDN:

    [Serializable()]
    public class MyException : Exception
    {
      public MyException()
      {
         // Add any type-specific logic, and supply the default message.
      }
    
      public MyException(string message): base(message) 
      {
         // Add any type-specific logic.
      }
      public MyException(string message, Exception innerException): 
         base (message, innerException)
      {
         // Add any type-specific logic for inner exceptions.
      }
      protected MyException(SerializationInfo info, 
         StreamingContext context) : base(info, context)
      {
         // Implement type-specific serialization constructor logic.
      }
    }  
    

or

    [Serializable()]
    public sealed class MyException : Exception
    {
      public MyException()
      {
         // Add any type-specific logic, and supply the default message.
      }

      public MyException(string message): base(message) 
      {
         // Add any type-specific logic.
      }
      public MyException(string message, Exception innerException): 
         base (message, innerException)
      {
         // Add any type-specific logic for inner exceptions.
      }
      private MyException(SerializationInfo info, 
         StreamingContext context) : base(info, context)
      {
         // Implement type-specific serialization constructor logic.
      }
    }  

Changing the browser zoom level

I would say not possible in most browsers, at least not without some additional plugins. And in any case I would try to avoid relying on the browser's zoom as the implementations vary (some browsers only zoom the fonts, others zoom the images, too etc). Unless you don't care much about user experience.

If you need a more reliable zoom, then consider zooming the page fonts and images with JavaScript and CSS, or possibly on the server side. The image and layout scaling issues could be addressed this way. Of course, this requires a bit more work.

Serialize an object to XML

You can use the function like below to get serialized XML from any object.

public static bool Serialize<T>(T value, ref string serializeXml)
{
    if (value == null)
    {
        return false;
    }
    try
    {
        XmlSerializer xmlserializer = new XmlSerializer(typeof(T));
        StringWriter stringWriter = new StringWriter();
        XmlWriter writer = XmlWriter.Create(stringWriter);

        xmlserializer.Serialize(writer, value);

        serializeXml = stringWriter.ToString();

        writer.Close();
        return true;
    }
    catch (Exception ex)
    {
        return false;
    }
}

You can call this from the client.

Array versus List<T>: When to use which?

Another situation not yet mentioned is when one will have a large number of items, each of which consists of a fixed bunch of related-but-independent variables stuck together (e.g. the coordinates of a point, or the vertices of a 3d triangle). An array of exposed-field structures will allow the its elements to be efficiently modified "in place"--something which is not possible with any other collection type. Because an array of structures holds its elements consecutively in RAM, sequential accesses to array elements can be very fast. In situations where code will need to make many sequential passes through an array, an array of structures may outperform an array or other collection of class object references by a factor of 2:1; further, the ability to update elements in place may allow an array of structures to outperform any other kind of collection of structures.

Although arrays are not resizable, it is not difficult to have code store an array reference along with the number of elements that are in use, and replace the array with a larger one as required. Alternatively, one could easily write code for a type which behaved much like a List<T> but exposed its backing store, thus allowing one to say either MyPoints.Add(nextPoint); or MyPoints.Items[23].X += 5;. Note that the latter would not necessarily throw an exception if code tried to access beyond the end of the list, but usage would otherwise be conceptually quite similar to List<T>.

HEAD and ORIG_HEAD in Git

HEAD is (direct or indirect, i.e. symbolic) reference to the current commit. It is a commit that you have checked in the working directory (unless you made some changes, or equivalent), and it is a commit on top of which "git commit" would make a new one. Usually HEAD is symbolic reference to some other named branch; this branch is currently checked out branch, or current branch. HEAD can also point directly to a commit; this state is called "detached HEAD", and can be understood as being on unnamed, anonymous branch.

And @ alone is a shortcut for HEAD, since Git 1.8.5

ORIG_HEAD is previous state of HEAD, set by commands that have possibly dangerous behavior, to be easy to revert them. It is less useful now that Git has reflog: HEAD@{1} is roughly equivalent to ORIG_HEAD (HEAD@{1} is always last value of HEAD, ORIG_HEAD is last value of HEAD before dangerous operation).

For more information read git(1) manpage / [gitrevisions(7) manpage][git-revisions], Git User's Manual, the Git Community Book and Git Glossary

How to split and modify a string in NodeJS?

Use split and map function:

var str = "123, 124, 234,252";
var arr = str.split(",");
arr = arr.map(function (val) { return +val + 1; });

Notice +val - string is casted to a number.

Or shorter:

var str = "123, 124, 234,252";
var arr = str.split(",").map(function (val) { return +val + 1; });

edit 2015.07.29

Today I'd advise against using + operator to cast variable to a number. Instead I'd go with a more explicit but also more readable Number call:

_x000D_
_x000D_
var str = "123, 124, 234,252";_x000D_
var arr = str.split(",").map(function (val) {_x000D_
  return Number(val) + 1;_x000D_
});_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

edit 2017.03.09

ECMAScript 2015 introduced arrow function so it could be used instead to make the code more concise:

_x000D_
_x000D_
var str = "123, 124, 234,252";_x000D_
var arr = str.split(",").map(val => Number(val) + 1);_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

Start/Stop and Restart Jenkins service on Windows

To Start Jenkins through Command Line

  1. Run CMD with admin

  2. You can run following commands

    "net start servicename" to start

    "net restart servicename" to restart

    "net stop servicename" to stop service

for more reference https://www.windows-commandline.com/start-stop-service-command-line/

Set value for particular cell in pandas DataFrame with iloc

You can use:

df.set_value('Row_index', 'Column_name', value)

set_valye is ~100 times faster than .ix method. It also better then use df['Row_index']['Column_name'] = value.

But since set_value is deprecated now so .iat/.at are good replacements.

For example if we have this data_frame

   A   B   C
0  1   8   4 
1  3   9   6
2  22 33  52

if we want to modify the value of the cell [0,"A"] we can do

df.iat[0,0] = 2

or df.at[0,'A'] = 2

How to use <sec:authorize access="hasRole('ROLES)"> for checking multiple Roles?

i used hasAnyRole('ROLE_ADMIN','ROLE_USER') but i was getting bean creation below error

Error creating bean with name     'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0': Cannot create inner bean '(inner bean)' of type [org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource] while setting bean property 'securityMetadataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#2': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Expected a single expression attribute for [/user/*]

then i tried

access="hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')" and it's working fine for me.

as one of my user is admin as well as user.

for this you need to add use-expressions="true" auto-config="true" followed by http tag

<http use-expressions="true" auto-config="true" >.....</http>

How to get the size of the current screen in WPF?

I also needed the current screen dimension, specifically the Work-area, which returned the rectangle excluding the Taskbar width.

I used it in order to reposition a window, which is opened to the right and down to where the mouse is positioned. Since the window is fairly large, in many cases it got out of the screen bounds. The following code is based on @e-j answer: This will give you the current screen.... The difference is that I also show my repositioning algorithm, which I assume is actually the point.

The code:

using System.Windows;
using System.Windows.Forms;

namespace MySample
{

    public class WindowPostion
    {
        /// <summary>
        /// This method adjust the window position to avoid from it going 
        /// out of screen bounds.
        /// </summary>
        /// <param name="topLeft">The requiered possition without its offset</param>
        /// <param name="maxSize">The max possible size of the window</param>
        /// <param name="offset">The offset of the topLeft postion</param>
        /// <param name="margin">The margin from the screen</param>
        /// <returns>The adjusted position of the window</returns>
        System.Drawing.Point Adjust(System.Drawing.Point topLeft, System.Drawing.Point maxSize, int offset, int margin)
        {
            Screen currentScreen = Screen.FromPoint(topLeft);
            System.Drawing.Rectangle rect = currentScreen.WorkingArea;

            // Set an offset from mouse position.
            topLeft.Offset(offset, offset);

            // Check if the window needs to go above the task bar, 
            // when the task bar shadows the HUD window.
            int totalHight = topLeft.Y + maxSize.Y + margin;

            if (totalHight > rect.Bottom)
            {
                topLeft.Y -= (totalHight - rect.Bottom);

                // If the screen dimensions exceed the hight of the window
                // set it just bellow the top bound.
                if (topLeft.Y < rect.Top)
                {
                    topLeft.Y = rect.Top + margin;
                }
            }

            int totalWidth = topLeft.X + maxSize.X + margin;
            // Check if the window needs to move to the left of the mouse, 
            // when the HUD exceeds the right window bounds.
            if (totalWidth > rect.Right)
            {
                // Since we already set an offset remove it and add the offset 
                // to the other side of the mouse (2x) in addition include the 
                // margin.
                topLeft.X -= (maxSize.X + (2 * offset + margin));

                // If the screen dimensions exceed the width of the window
                // don't exceed the left bound.
                if (topLeft.X < rect.Left)
                {
                    topLeft.X = rect.Left + margin;
                }
            }

            return topLeft;
        }
    }
}

Some explanations:

1) topLeft - position of the top left at the desktop (works                     
   for multi screens - with different aspect ratio).                            
            Screen1              Screen2                                        
        -  +-------------------++-------------------+ Screen3                   
        ?  ¦                   ¦¦                   ¦+-----------------+  -     
        ¦  ¦                   ¦¦                   ¦¦   ?-            ¦  ?     
   1080 ¦  ¦                   ¦¦                   ¦¦                 ¦  ¦     
        ¦  ¦                   ¦¦                   ¦¦                 ¦  ¦ 900 
        ?  ¦                   ¦¦                   ¦¦                 ¦  ?     
        -  +-------------------++-------------------++-----------------+  -     
                 ---------            ---------            --------             
           ¦?-----------------?¦¦?-----------------?¦¦?---------------?¦        
                   1920                 1920                1440                
   If the mouse is in Screen3 a possible value might be:                        
   topLeft.X=4140 topLeft.Y=195                                                 
2) offset - the offset from the top left, one value for both                    
   X and Y directions.                                                          
3) maxSize - the maximal size of the window - including its                     
   size when it is expanded - from the following example                        
   we need maxSize.X = 200, maxSize.Y = 150 - To avoid the expansion            
   being out of bound.                                                          

   Non expanded window:                                                         
   +------------------------------+ -                                           
   ¦ Window Name               [X]¦ ?                                           
   +------------------------------¦ ¦                                           
   ¦         +-----------------+  ¦ ¦ 100                                       
   ¦  Text1: ¦                 ¦  ¦ ¦                                           
   ¦         +-----------------+  ¦ ¦                                           
   ¦                         [?]  ¦ ?                                           
   +------------------------------+ -                                           
   ¦?----------------------------?¦                                             
                 200                                                            

   Expanded window:                                                             
   +------------------------------+ -                                           
   ¦ Window Name               [X]¦ ?                                           
   +------------------------------¦ ¦                                           
   ¦         +-----------------+  ¦ ¦                                           
   ¦  Text1: ¦                 ¦  ¦ ¦                                           
   ¦         +-----------------+  ¦ ¦ 150                                       
   ¦                         [?]  ¦ ¦                                           
   ¦         +-----------------+  ¦ ¦                                           
   ¦  Text2: ¦                 ¦  ¦ ¦                                           
   ¦         +-----------------+  ¦ ?                                           
   +------------------------------+ -                                           
   ¦?----------------------------?¦                                             
                 200                                                            
4) margin - The distance the window should be from the screen                   
   work-area - Example:                                                          
   +-------------------------------------------------------------+ -            
   ¦                                                             ¦ ? Margin     
   ¦                                                             ¦ -            
   ¦                                                             ¦              
   ¦                                                             ¦              
   ¦                                                             ¦              
   ¦                          +------------------------------+   ¦              
   ¦                          ¦ Window Name               [X]¦   ¦              
   ¦                          +------------------------------¦   ¦              
   ¦                          ¦         +-----------------+  ¦   ¦              
   ¦                          ¦  Text1: ¦                 ¦  ¦   ¦              
   ¦                          ¦         +-----------------+  ¦   ¦              
   ¦                          ¦                         [?]  ¦   ¦              
   ¦                          ¦         +-----------------+  ¦   ¦              
   ¦                          ¦  Text2: ¦                 ¦  ¦   ¦              
   ¦                          ¦         +-----------------+  ¦   ¦              
   ¦                          +------------------------------+   ¦ -            
   ¦                                                             ¦ ? Margin     
   +-------------------------------------------------------------¦ -            
   ¦[start] [?][?][?][?]                              ¦en¦ 12:00 ¦              
   +-------------------------------------------------------------+              
   ¦?-?¦                                                     ¦?-?¦              
    Margin                                                    Margin            

* Note that this simple algorithm will always want to leave the cursor          
  out of the window, therefor the window will jumps to its left:                
  +---------------------------------+        +---------------------------------+
  ¦                  ?-+--------------+      ¦  +--------------+?-             ¦
  ¦                    ¦ Window    [X]¦      ¦  ¦ Window    [X]¦               ¦
  ¦                    +--------------¦      ¦  +--------------¦               ¦
  ¦                    ¦       +---+  ¦      ¦  ¦       +---+  ¦               ¦
  ¦                    ¦  Val: ¦   ¦  ¦ ->   ¦  ¦  Val: ¦   ¦  ¦               ¦
  ¦                    ¦       +---+  ¦      ¦  ¦       +---+  ¦               ¦
  ¦                    +--------------+      ¦  +--------------+               ¦
  ¦                                 ¦        ¦                                 ¦
  +---------------------------------¦        +---------------------------------¦
  ¦[start] [?][?][?]     ¦en¦ 12:00 ¦        ¦[start] [?][?][?]     ¦en¦ 12:00 ¦
  +---------------------------------+        +---------------------------------+
  If this is not a requirement, you can add a parameter to just use             
  the margin:                                                                   
  +---------------------------------+        +---------------------------------+
  ¦                  ?-+--------------+      ¦                +-?------------+ ¦
  ¦                    ¦ Window    [X]¦      ¦                ¦ Window    [X]¦ ¦
  ¦                    +--------------¦      ¦                +--------------¦ ¦
  ¦                    ¦       +---+  ¦      ¦                ¦       +---+  ¦ ¦
  ¦                    ¦  Val: ¦   ¦  ¦ ->   ¦                ¦  Val: ¦   ¦  ¦ ¦
  ¦                    ¦       +---+  ¦      ¦                ¦       +---+  ¦ ¦
  ¦                    +--------------+      ¦                +--------------+ ¦
  ¦                                 ¦        ¦                                 ¦
  +---------------------------------¦        +---------------------------------¦
  ¦[start] [?][?][?]     ¦en¦ 12:00 ¦        ¦[start] [?][?][?]     ¦en¦ 12:00 ¦
  +---------------------------------+        +---------------------------------+
* Supports also the following scenarios:
  1) Screen over screen:
       +-----------------+  
       ¦                 ¦
       ¦                 ¦
       ¦                 ¦
       ¦                 ¦
       +-----------------+
     +-------------------+ 
     ¦                   ¦ 
     ¦  ?-               ¦ 
     ¦                   ¦ 
     ¦                   ¦ 
     ¦                   ¦ 
     +-------------------+ 
           ---------       
  2) Window bigger than screen hight or width
     +---------------------------------+        +---------------------------------+ 
     ¦                                 ¦        ¦ +--------------+                ¦
     ¦                                 ¦        ¦ ¦ Window    [X]¦                ¦
     ¦                  ?-+------------¦-+      ¦ +--------------¦ ?-             ¦
     ¦                    ¦ Window    [¦]¦      ¦ ¦       +---+  ¦                ¦
     ¦                    +------------¦-¦ ->   ¦ ¦  Val: ¦   ¦  ¦                ¦ 
     ¦                    ¦       +---+¦ ¦      ¦ ¦       +---+  ¦                ¦
     ¦                    ¦  Val: ¦   ¦¦ ¦      ¦ ¦       +---+  ¦                ¦
     ¦                    ¦       +---+¦ ¦      ¦ ¦  Val: ¦   ¦  ¦                ¦
     +---------------------------------¦ ¦      +---------------------------------¦
     ¦[start] [?][?][?]     ¦en¦ 12:00 ¦ ¦      ¦[start] [?][?][?]     ¦en¦ 12:00 ¦
     +---------------------------------+ ¦      +---------------------------------+
                          ¦       +---+  ¦        ¦       +---+  ¦
                          ¦  Val: ¦   ¦  ¦        +--------------+
                          ¦       +---+  ¦
                          +--------------+


     +---------------------------------+             +---------------------------------+     
     ¦                                 ¦             ¦                                 ¦ 
     ¦                                 ¦             ¦ +-------------------------------¦---+
     ¦    ?-+--------------------------¦--------+    ¦ ¦ W?-dow                        ¦[X]¦
     ¦      ¦ Window                   ¦     [X]¦    ¦ +-------------------------------¦---¦
     ¦      +--------------------------¦--------¦    ¦ ¦       +---+      +---+      +-¦-+ ¦
     ¦      ¦       +---+      +---+   ¦  +---+ ¦ -> ¦ ¦  Val: ¦   ¦ Val: ¦   ¦ Val: ¦ ¦ ¦ ¦
     ¦      ¦  Val: ¦   ¦ Val: ¦   ¦ Va¦: ¦   ¦ ¦    ¦ ¦       +---+      +---+      +-¦-+ ¦
     ¦      ¦       +---+      +---+   ¦  +---+ ¦    ¦ +-------------------------------¦---+
     +---------------------------------¦--------+    +---------------------------------¦
     ¦[start] [?][?][?]     ¦en¦ 12:00 ¦             ¦[start] [?][?][?]     ¦en¦ 12:00 ¦     
     +---------------------------------+             +---------------------------------+     
  • I had no choice but using the code format (otherwise the white spaces would have been lost).
  • Originally this appeared in the code above as a <remark><code>...</code></remark>

How to sort an object array by date property?

If like me you have an array with dates formatted like YYYY[-MM[-DD]] where you'd like to order more specific dates before less specific ones, I came up with this handy function:

function sortByDateSpecificity(a, b) {
  const aLength = a.date.length
  const bLength = b.date.length
  const aDate = a.date + (aLength < 10 ? '-12-31'.slice(-10 + aLength) : '')
  const bDate = b.date + (bLength < 10 ? '-12-31'.slice(-10 + bLength) : '')
  return new Date(aDate) - new Date(bDate)
}

Include .so library in apk in android studio

To include native libraries you need:

  1. create "jar" file with special structure containing ".so" files;
  2. include that file in dependencies list.

To create jar file, use the following snippet:

task nativeLibsToJar(type: Zip, description: 'create a jar archive of the native libs') {
    destinationDir file("$buildDir/native-libs")
    baseName 'native-libs'
    extension 'jar'
    from fileTree(dir: 'libs', include: '**/*.so')
    into 'lib/'
}

tasks.withType(Compile) {
    compileTask -> compileTask.dependsOn(nativeLibsToJar)
}

To include resulting file, paste the following line into "dependencies" section in "build.gradle" file:

compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')

Temporarily change current working directory in bash to run a command

bash has a builtin

pushd SOME_PATH
run_stuff
...
...
popd 

How to access local files of the filesystem in the Android emulator?

In addition to the accepted answer, if you are using Android Studio you can

  1. invoke Android Device Monitor,
  2. select the device in the Devices tab on the left,
  3. select File Explorer tab on the right,
  4. navigate to the file you want, and
  5. click the Pull a file from the device button to save it to your local file system

Taken from Working with an emulator or device's file system

How to secure phpMyAdmin

One of my concerns with phpMyAdmin was that by default, all MySQL users can access the db. If DB's root password is compromised, someone can wreck havoc on the db. I wanted to find a way to avoid that by restricting which MySQL user can login to phpMyAdmin.

I have found using AllowDeny configuration in PhpMyAdmin to be very useful. http://wiki.phpmyadmin.net/pma/Config#AllowDeny_.28rules.29

AllowDeny lets you configure access to phpMyAdmin in a similar way to Apache. If you set the 'order' to explicit, it will only grant access to users defined in 'rules' section. In the rules, section you restrict MySql users who can access use the phpMyAdmin.

$cfg['Servers'][$i]['AllowDeny']['order'] = 'explicit'
$cfg['Servers'][$i]['AllowDeny']['rules'] = array('pma-user from all')

Now you have limited access to the user named pma-user in MySQL, you can grant limited privilege to that user.

grant select on db_name.some_table to 'pma-user'@'app-server'

Difference between app.use and app.get in express.js

Simply app.use means “Run this on ALL requests”
app.get means “Run this on a GET request, for the given URL”

How to check if a string is null in python

In python, bool(sequence) is False if the sequence is empty. Since strings are sequences, this will work:

cookie = ''
if cookie:
    print "Don't see this"
else:
    print "You'll see this"

How to dynamically insert a <script> tag via jQuery after page load?

A simpler way is:

$('head').append('<script type="text/javascript" src="your.js"></script>');

You can also use this form to load css.

How to require a controller in an angularjs directive

There is a good stackoverflow answer here by Mark Rajcok:

AngularJS directive controllers requiring parent directive controllers?

with a link to this very clear jsFiddle: http://jsfiddle.net/mrajcok/StXFK/

<div ng-controller="MyCtrl">
    <div screen>
        <div component>
            <div widget>
                <button ng-click="widgetIt()">Woo Hoo</button>
            </div>
        </div>
    </div>
</div>

JavaScript

var myApp = angular.module('myApp',[])

.directive('screen', function() {
    return {
        scope: true,
        controller: function() {
            this.doSomethingScreeny = function() {
                alert("screeny!");
            }
        }
    }
})

.directive('component', function() {
    return {
        scope: true,
        require: '^screen',
        controller: function($scope) {
            this.componentFunction = function() {
                $scope.screenCtrl.doSomethingScreeny();
            }
        },
        link: function(scope, element, attrs, screenCtrl) {
            scope.screenCtrl = screenCtrl
        }
    }
})

.directive('widget', function() {
    return {
        scope: true,
        require: "^component",
        link: function(scope, element, attrs, componentCtrl) {
            scope.widgetIt = function() {
                componentCtrl.componentFunction();
            };
        }
    }
})


//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
    $scope.name = 'Superhero';
}

Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate

Old post but as you said "why is it not using the correct certificate" I would like to offer an way to find out which SSL certificate is used for SMTP (see here) which required openssl:

openssl s_client -connect exchange01.int.contoso.com:25 -starttls smtp

This will outline the used SSL certificate for the SMTP service. Based on what you see here you can replace the wrong certificate (like you already did) with a correct one (or trust the certificate manually).

How can I install pip on Windows?

-- Outdated -- use distribute, not setuptools as described here. --
-- Outdated #2 -- use setuptools as distribute is deprecated.

As you mentioned pip doesn't include an independent installer, but you can install it with its predecessor easy_install.

So:

  1. Download the last pip version from here: http://pypi.python.org/pypi/pip#downloads
  2. Uncompress it
  3. Download the last easy installer for Windows: (download the .exe at the bottom of http://pypi.python.org/pypi/setuptools ). Install it.
  4. copy the uncompressed pip folder content into C:\Python2x\ folder (don't copy the whole folder into it, just the content), because python command doesn't work outside C:\Python2x folder and then run: python setup.py install
  5. Add your python C:\Python2x\Scripts to the path

You are done.

Now you can use pip install package to easily install packages as in Linux :)

How to print time in format: 2009-08-10 18:17:54.811

time.h defines a strftime function which can give you a textual representation of a time_t using something like:

#include <stdio.h>
#include <time.h>
int main (void) {
    char buff[100];
    time_t now = time (0);
    strftime (buff, 100, "%Y-%m-%d %H:%M:%S.000", localtime (&now));
    printf ("%s\n", buff);
    return 0;
}

but that won't give you sub-second resolution since that's not available from a time_t. It outputs:

2010-09-09 10:08:34.000

If you're really constrained by the specs and do not want the space between the day and hour, just remove it from the format string.

How to use HttpWebRequest (.NET) asynchronously?

Use HttpWebRequest.BeginGetResponse()

HttpWebRequest webRequest;

void StartWebRequest()
{
    webRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), null);
}

void FinishWebRequest(IAsyncResult result)
{
    webRequest.EndGetResponse(result);
}

The callback function is called when the asynchronous operation is complete. You need to at least call EndGetResponse() from this function.

Is there a way to get the XPath in Google Chrome?

Just right-click on the element you want the xpath for and you will see a menu item to copy it. This may not have existed when the OP made his post but it's certainly there now.

How do I find files that do not contain a given string pattern?

The following command could help you to filter the lines which include the substring "foo".

cat file | grep -v "foo"

Setting a minimum/maximum character count for any character using a regular expression

Like this: .

The . means any character except newline (which sometimes is but often isn't included, check your regex flavour).

You can rewrite your expression as ^.{1,35}$, which should match any line of length 1-35.

System.Net.Http: missing from namespace? (using .net 4.5)

I had this issue after upgrading to .NET Framework 4.7.2. I found out that Nuget package for System.Net.Http is no longer recommended. Here are workarounds:

How to iterate through a table rows and get the cell values using jQuery

You got your answer, but why iterate over the tr when you can go straight for the inputs? That way you can store them easier into an array and it reduce the number of CSS queries. Depends what you want to do of course, but for collecting data it is a more flexible approach.

http://jsfiddle.net/zqpgq/

var array = [];

$("tr.item input").each(function() {
    array.push({
        name: $(this).attr('class'),
        value: $(this).val()
    });
});

console.log(array);?

Split string in JavaScript and detect line break

You can use the split() function to break input on the basis of line break.

yourString.split("\n")

Can you autoplay HTML5 videos on the iPad?

Just set

webView.mediaPlaybackRequiresUserAction = NO;

The autoplay works for me on iOS.

How to compare dates in c#

Firstly, understand that DateTime objects aren't formatted. They just store the Year, Month, Day, Hour, Minute, Second, etc as a numeric value and the formatting occurs when you want to represent it as a string somehow. You can compare DateTime objects without formatting them.

To compare an input date with DateTime.Now, you need to first parse the input into a date and then compare just the Year/Month/Day portions:

DateTime inputDate;
if(!DateTime.TryParse(inputString, out inputDate))
    throw new ArgumentException("Input string not in the correct format.");

if(inputDate.Date == DateTime.Now.Date) {
    // Same date!
}

How to change line width in ggplot?

If you want to modify the line width flexibly you can use "scale_size_manual," this is the same procedure for picking the color, fill, alpha, etc.

library(ggplot2)
library(tidyr)

x = seq(0,10,0.05)

df <- data.frame(A = 2 * x + 10,
                 B = x**2 - x*6,
                 C = 30 - x**1.5,
                 X = x)


df = gather(df,A,B,C,key="Model",value="Y")


ggplot( df, aes (x=X, y=Y, size=Model, colour=Model ))+
  geom_line()+
  scale_size_manual( values = c(4,2,1) ) +
  scale_color_manual( values = c("orange","red","navy") ) 

While loop in batch

I have a trick for doing this!

I came up with this method because while on the CLI, it's not possible to use the methods provided in the other answers here and it had always bugged me.

I call this the "Do Until Break" or "Infinite" Loop:

Basic Example

FOR /L %L IN (0,0,1) DO @(
 ECHO. Counter always 0, See "%L" = "0" - Waiting a split second&ping -n 1 127.0.0.1>NUL )

This is truly an infinite loop!

This is useful for monitoring something in a CMD window, and allows you to use CTRL+C to break it when you're done.

Want to Have a counter?

Either use SET /A OR You can modify the FOR /L Loop to do the counting and still be infinite (Note, BOTH of these methods have a 32bit integer overflow)

SET /A Method:

FOR /L %L IN (0,0,1) DO @(
 SET /A "#+=1"&ECHO. L Still equals 0, See "%L = 0"!  - Waiting a split second &ping -n 1 127.0.0.1>NUL  )

Native FOR /L Counter:

FOR /L %L IN (-2147483648,1,2147483648) DO @(
 ECHO.Current value of L: %L - Waiting a split second &ping -n 1 127.0.0.1>NUL  )

Counting Sets of 4294967295 and Showing Current Value of L:

FOR /L %L IN (1,1,2147483648) DO @(
 (
  IF %L EQU 0 SET /A "#+=1">NUL
 )&SET /A "#+=0"&ECHO. Sets of 4294967295 - Current value of L: %L - Waiting a split second &ping -n 1 127.0.0.1>NUL )

However, what if:

  • You're interested in reviewing the output of the monitor, and concerned that I will pass the 9999 line buffer limit before I check it after it has completed.
  • You'd like to take some additional actions once the Thing I am monitoring is finished.

For this, I determined how to use a couple methods to break the FOR Loop prematurely effectively turning it into a "DO WHILE" or "DO UNTIL" Loop, which is otherwise sorely lacking in CMD.

NOTE: Most of the time a loop will continue to iterate past the condition you checked for, often this is a wanted behavior, but not in our case.

Turn the "infinite Loop" into a "DO WHILE" / "DO UNTIL" Loop

UPDATE: Due to wanting to use this code in CMD Scripts (and have them persist!) as well as CLI, and on thinking if there might be a "more Correct" method to achieve this I recommend using the New method!

New Method (Can be used inside CMD Scripts without exiting the script):

FOR /F %%A IN ('
  CMD /C "FOR /L %%L IN (0,1,2147483648) DO @( ECHO.%%L & IF /I %%L EQU 10 ( exit /b  ) )"
') DO @(
  ECHO %%~A
)

At CLI:

FOR /F %A IN ('
  CMD /C "FOR /L %L IN (0,1,2147483648) DO @( ECHO.%L & IF /I %L EQU 10 ( exit /b  ) )"
') DO @(
  ECHO %~A
)

Original Method (Will work on CLI just fine, but will kill a script.)

FOR /L %L IN (0,1,2147483648) DO @(
  ECHO.Current value of L: %L - Waiting a split second &ping -n 1 127.0.0.1>NUL&(
    IF /I %L EQU 10 (
      ECHO.Breaking the Loop! Because We have matched the condition!&DIR >&0
    )
  )
) 2>NUL

Older Post Stuff

Through chance I had hit upon some ways to exit loops prematurely that did not close the CMD prompt when trying to do other things which gave me this Idea.

NOTE:

While ECHO.>&3 >NUL had worked for me in some scenarios, I have played with this off and on over the years and found that DIR >&0 >NUL was much more consistent.

I am re-writing this answer from here forward to use that method instead as I recently found the old note to myself to use this method instead.

Edited Post with better Method Follows:

DIR >&0 >NUL

The >NUL is optional, I just prefer not to have it output the error.

I prefer to match inLine when possible, as you can see in this sanitized example of a Command I use to monitor LUN Migrations on our VNX.

for /l %L IN (0,0,1) DO @(
   ECHO.& ECHO.===========================================& (
     [VNX CMD] | FINDSTR /R /C:"Source LU Name" /C:"State:" /C:"Time " || DIR >&0 >NUL
   ) & Ping -n 10 1.1.1.1 -w 1000>NUL )

Also, I have another method I found in that note to myself which I just re-tested to confirm works just as well at the CLI as the other method.

Apparently, when I first posted here I posted an older iteration I was playing with instead of the two newer ones which work better:

In this method, we use EXIT /B to exit the For Loop, but we don't want to exit the CLI so we wrap it in a CMD session:

FOR /F %A IN ('CMD /C "FOR /L %L IN (0,1,10000000) DO @( ECHO.%L & IF /I %L EQU 10 ( exit /b  ) )" ') DO @(ECHO %~A)

Because the loop itself happens in the CMD session, we can use EXIT /B to exit the iteration of the loop without losing our CMD Session, and without waiting for the loop to complete, much the same as with the other method.

I would go so far as to say that this method is likely the "intended" method for the sort of scenario where you want to break a for loop at the CLI, as using CMD session is also the only way to get Delayed expansion working at the CLI for your loops, and the behavior and such behavior is clearly an intended workflow to leave a CMD session.

IE: Microsoft clearly made an intentional effort to have CMD Exit /B For loops behave this way, while the "Intended" way of doing this, as my other method, relies on having accidentally created just the right error to kick you out of the loop without letting the loop finish processing, which I only happenstantially discovered, and seems to only reliably work when using the DIR command which is fairly strange.

So that said, I think it's probably a better practice to use Method 2:

FOR /F %A IN ('CMD /C "FOR /L %L IN (0,1,10000000) DO @( ECHO.%L & IF /I %L EQU 10 ( exit /b  ) )" ') DO @(ECHO %~A)

Although I suspect Method 1 is going to be slightly faster:

FOR /L %L IN (0,1,10000000) DO @( ECHO.%L & IF /I %L EQU 10 ( DIR >&) >NUL ) )

And in either case, both should allow DO-While loops as you need for your purposes.

How to reload a page using Angularjs?

$scope.rtGo = function(){
            $window.sessionStorage.removeItem('message');
            $window.sessionStorage.removeItem('status');
        }

What is the most efficient way to create a dictionary of two pandas Dataframe columns?

I found a faster way to solve the problem, at least on realistically large datasets using: df.set_index(KEY).to_dict()[VALUE]

Proof on 50,000 rows:

df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB'))
df['A'] = df['A'].apply(chr)

%timeit dict(zip(df.A,df.B))
%timeit pd.Series(df.A.values,index=df.B).to_dict()
%timeit df.set_index('A').to_dict()['B']

Output:

100 loops, best of 3: 7.04 ms per loop  # WouterOvermeire
100 loops, best of 3: 9.83 ms per loop  # Jeff
100 loops, best of 3: 4.28 ms per loop  # Kikohs (me)

PHP: If internet explorer 6, 7, 8 , or 9

PHP has a function called get_browser() that will return an object (or array if you so choose) with details about the users' browser and what it can do.

A simple look through gave me this code:

$browser = get_browser( null, true );
if( $browser['name'] == "Firefox" )
    if( $browser['majorversion'] == 4 )
        echo "You're using Firefox version 4!";

This is not a surefire way (as it reads from HTTP_USER_AGENT, which can be spoofed, and will sometimes be analyzed wrong by php), but it's the easiest one that you can find as far as I know.

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.

This solved my issue. It was 2.10 in my POM, just updated to 2.19.1 and refresh the POM

Add to your pom :

 <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.19.1</version>
        </plugin>
  </plugins>

In your error code he didn't find surefire plugin so add it

How do I write a compareTo method which compares objects?

You're almost all the way there.

Your first few lines, comparing the last name, are right on track. The compareTo() method on string will return a negative number for a string in alphabetical order before, and a positive number for one in alphabetical order after.

Now, you just need to do the same thing for your first name and score.

In other words, if Last Name 1 == Last Name 2, go on a check your first name next. If the first name is the same, check your score next. (Think about nesting your if/then blocks.)

Getting all types that implement an interface

Edit: I've just seen the edit to clarify that the original question was for the reduction of iterations / code and that's all well and good as an exercise, but in real-world situations you're going to want the fastest implementation, regardless of how cool the underlying LINQ looks.

Here's my Utils method for iterating through the loaded types. It handles regular classes as well as interfaces, and the excludeSystemTypes option speeds things up hugely if you are looking for implementations in your own / third-party codebase.

public static List<Type> GetSubclassesOf(this Type type, bool excludeSystemTypes) {
    List<Type> list = new List<Type>();
    IEnumerator enumerator = Thread.GetDomain().GetAssemblies().GetEnumerator();
    while (enumerator.MoveNext()) {
        try {
            Type[] types = ((Assembly) enumerator.Current).GetTypes();
            if (!excludeSystemTypes || (excludeSystemTypes && !((Assembly) enumerator.Current).FullName.StartsWith("System."))) {
                IEnumerator enumerator2 = types.GetEnumerator();
                while (enumerator2.MoveNext()) {
                    Type current = (Type) enumerator2.Current;
                    if (type.IsInterface) {
                        if (current.GetInterface(type.FullName) != null) {
                            list.Add(current);
                        }
                    } else if (current.IsSubclassOf(type)) {
                        list.Add(current);
                    }
                }
            }
        } catch {
        }
    }
    return list;
}

It's not pretty, I'll admit.

Getting a count of rows in a datatable that meet certain criteria

int numberOfRecords = 0;

numberOfRecords = dtFoo.Select().Length;

MessageBox.Show(numberOfRecords.ToString());

How to set width of a div in percent in JavaScript?

document.getElementById('header').style.width = '50%';

If you are using Firebug or the Chrome/Safari Developer tools, execute the above in the console, and you'll see the Stack Overflow header shrink by 50%.

How to convert date in to yyyy-MM-dd Format?

String s;
Format formatter;
Date date = new Date();

// 2012-12-01
formatter = new SimpleDateFormat("yyyy-MM-dd");
s = formatter.format(date);
System.out.println(s);

how to load CSS file into jsp

I had the same problem too. Then i realized that in the MainPageServlet the urlPatterns parameter in @WebServlet annotation contained "/", because i wanted to forward to the MainPage if the user entered the section www.site.com/ . When i tried to open the css file from the browser, the url was www.site.com/css/desktop.css, but the page content was THE PAGE MainPage.jsp. So, i removed the "/" urlPattern and now i can use CSS files in my jsp file using one of the most common solutions (${pageContext.request.contextPath}/css/desktop.css). Make sure your servlet doesn't contain the "/" urlPattern. I hope this worked for u too, - Axel Montini

Simplest way to detect keypresses in javascript

Don't over complicate.

  document.addEventListener('keydown', logKey);
    function logKey(e) {
      if (`${e.code}` == "ArrowRight") {
        //code here
      }
          if (`${e.code}` == "ArrowLeft") {
        //code here
      }
          if (`${e.code}` == "ArrowDown") {
        //code here
      }
          if (`${e.code}` == "ArrowUp") {
        //code here
      }
    }

How to extend available properties of User.Identity

For anyone that finds this question looking for how to access custom properties in ASP.NET Core 2.1 - it's much easier: You'll have a UserManager, e.g. in _LoginPartial.cshtml, and then you can simply do (assuming "ScreenName" is a property that you have added to your own AppUser which inherits from IdentityUser):

@using Microsoft.AspNetCore.Identity

@using <namespaceWhereYouHaveYourAppUser>

@inject SignInManager<AppUser> SignInManager
@inject UserManager<AppUser> UserManager

@if (SignInManager.IsSignedIn(User)) {
    <form asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="@Url.Action("Index", "Home", new { area = "" })" 
          method="post" id="logoutForm" 
          class="form-inline my-2 my-lg-0">

        <ul class="nav navbar-nav ml-auto">
            <li class="nav-item">
                <a class="nav-link" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">
                    Hello @((await UserManager.GetUserAsync(User)).ScreenName)!
                    <!-- Original code, shows Email-Address: @UserManager.GetUserName(User)! -->
                </a>
            </li>
            <li class="nav-item">
                <button type="submit" class="btn btn-link nav-item navbar-link nav-link">Logout</button>
            </li>
        </ul>

    </form>
} else {
    <ul class="navbar-nav ml-auto">
        <li class="nav-item"><a class="nav-link" asp-area="Identity" asp-page="/Account/Register">Register</a></li>
        <li class="nav-item"><a class="nav-link" asp-area="Identity" asp-page="/Account/Login">Login</a></li>
    </ul>
}

Running script upon login mac

  1. Create your shell script as login.sh in your $HOME folder.

  2. Paste the following one-line script into Script Editor:

    do shell script "$HOME/login.sh"

  3. Then save it as an application.

  4. Finally add the application to your login items.

If you want to make the script output visual, you can swap step 2 for this:

tell application "Terminal"
  activate
  do script "$HOME/login.sh"
end tell

If multiple commands are needed something like this can be used:

tell application "Terminal"
  activate
  do script "cd $HOME"
  do script "./login.sh" in window 1
end tell

Set a:hover based on class

Set a:hover based on class you can simply try:

a.main-nav-item:hover { }

How to get the previous URL in JavaScript?

If you want to go to the previous page without knowing the url, you could use the new History api.

history.back(); //Go to the previous page
history.forward(); //Go to the next page in the stack
history.go(index); //Where index could be 1, -1, 56, etc.

But you can't manipulate the content of the history stack on browser that doesn't support the HTML5 History API

For more information see the doc

How do I calculate square root in Python?

Perhaps a simple way to remember: add a dot after the numerator (or denominator)

16 ** (1. / 2)   # 4
289 ** (1. / 2)  # 17
27 ** (1. / 3)   # 3

Is it possible to modify a registry entry via a .bat/.cmd script?

You can use the REG command. From http://www.ss64.com/nt/reg.html:

Syntax:

   REG QUERY [ROOT\]RegKey /v ValueName [/s]
   REG QUERY [ROOT\]RegKey /ve  --This returns the (default) value

   REG ADD [ROOT\]RegKey /v ValueName [/t DataType] [/S Separator] [/d Data] [/f]
   REG ADD [ROOT\]RegKey /ve [/d Data] [/f]  -- Set the (default) value

   REG DELETE [ROOT\]RegKey /v ValueName [/f]
   REG DELETE [ROOT\]RegKey /ve [/f]  -- Remove the (default) value
   REG DELETE [ROOT\]RegKey /va [/f]  -- Delete all values under this key

   REG COPY  [\\SourceMachine\][ROOT\]RegKey [\\DestMachine\][ROOT\]RegKey

   REG EXPORT [ROOT\]RegKey FileName.reg
   REG IMPORT FileName.reg
   REG SAVE [ROOT\]RegKey FileName.hiv
   REG RESTORE \\MachineName\[ROOT]\KeyName FileName.hiv

   REG LOAD FileName KeyName
   REG UNLOAD KeyName

   REG COMPARE [ROOT\]RegKey [ROOT\]RegKey [/v ValueName] [Output] [/s]
   REG COMPARE [ROOT\]RegKey [ROOT\]RegKey [/ve] [Output] [/s]

Key:
   ROOT :
         HKLM = HKey_Local_machine (default)
         HKCU = HKey_current_user
         HKU  = HKey_users
         HKCR = HKey_classes_root

   ValueName : The value, under the selected RegKey, to edit.
               (default is all keys and values)

   /d Data   : The actual data to store as a "String", integer etc

   /f        : Force an update without prompting "Value exists, overwrite Y/N"

   \\Machine : Name of remote machine - omitting defaults to current machine.
                Only HKLM and HKU are available on remote machines.

   FileName  : The filename to save or restore a registry hive.

   KeyName   : A key name to load a hive file into. (Creating a new key)

   /S        : Query all subkeys and values.

   /S Separator : Character to use as the separator in REG_MULTI_SZ values
                  the default is "\0" 

   /t DataType  : REG_SZ (default) | REG_DWORD | REG_EXPAND_SZ | REG_MULTI_SZ

   Output    : /od (only differences) /os (only matches) /oa (all) /on (no output)

What is the purpose of "pip install --user ..."?

--user installs in site.USER_SITE.

For my case, it was /Users/.../Library/Python/2.7/bin. So I have added that to my PATH (in ~/.bash_profile file):

export PATH=$PATH:/Users/.../Library/Python/2.7/bin

VB.NET - If string contains "value1" or "value2"

Interestingly, this solution can break, but a workaround: Looking for my database called KeyWorks.accdb which must exist:

Run this:

Dim strDataPath As String = GetSetting("KeyWorks", "dataPath", "01", "") 'get from registry

If Not strDataPath.Contains("KeyWorks.accdb") Then....etc.

If my database is named KeyWorksBB.accdb, the If statement will find this acceptable and exit the If statement because it did indeed find KeyWorks and accdb.

If I surround the If statement qualifier with single quotes like 'KeyWorks.accdb', it now looks for all the consecutive characters in order and would enter the If block because it did not match.

How to limit the maximum files chosen when using multiple file input

Another possible solution with JS

function onSelect(e) {
    if (e.files.length > 5) {
        alert("Only 5 files accepted.");
        e.preventDefault();
    }
}

Python socket connection timeout

If you are using Python2.6 or newer, it's convenient to use socket.create_connection

sock = socket.create_connection(address, timeout=10)
sock.settimeout(None)
fileobj = sock.makefile('rb', 0)

How to include a quote in a raw Python string

Nevermind, the answer is raw triple-quoted strings:

r"""what"ever"""

Key existence check in HashMap

Do you mean that you've got code like

if(map.containsKey(key)) doSomethingWith(map.get(key))

all over the place ? Then you should simply check whether map.get(key) returned null and that's it. By the way, HashMap doesn't throw exceptions for missing keys, it returns null instead. The only case where containsKey is needed is when you're storing null values, to distinguish between a null value and a missing value, but this is usually considered bad practice.

How to Get Element By Class in JavaScript?

I think something like:

function ReplaceContentInContainer(klass,content) {
var elems = document.getElementsByTagName('*');
for (i in elems){
    if(elems[i].getAttribute('class') == klass || elems[i].getAttribute('className') == klass){
        elems[i].innerHTML = content;
    }
}
}

would work

JQuery Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

This happened for me when my ajax was replacing contents on the page and ending up with two elements the same class for the dialog which meant when my line to close the dialog executed based on the CSS class selector, it found two elements not one and the second one had never been initialised.

$(".dialogClass").dialog("close"); //This line was expecting to find one element but found two where the second had not been initialised.

For anyone on ASP.NET MVC this occured because my controller action was returning a full view including the shared layout page which had the element when it should have been returning a partial view since the javascript was replacing only the main content area.

Eclipse executable launcher error: Unable to locate companion shared library

I had the same message after a system restore with the eclipse folder (V. 3/2020) being located on a second drive (that was NOT restored at the same time, I use it for large files mainly).

Restoring the faulty installations C:\Users<user>.p2 folder to the new installation (referenced in eclipse.ini of the eclipse folder) worked.

Pandas: Setting no. of max rows

Personally, I like setting the options directly with an assignment statement as it is easy to find via tab completion thanks to iPython. I find it hard to remember what the exact option names are, so this method works for me.

For instance, all I have to remember is that it begins with pd.options

pd.options.<TAB>

enter image description here

Most of the options are available under display

pd.options.display.<TAB>

enter image description here

From here, I usually output what the current value is like this:

pd.options.display.max_rows
60

I then set it to what I want it to be:

pd.options.display.max_rows = 100

Also, you should be aware of the context manager for options, which temporarily sets the options inside of a block of code. Pass in the option name as a string followed by the value you want it to be. You may pass in any number of options in the same line:

with pd.option_context('display.max_rows', 100, 'display.max_columns', 10):
    some pandas stuff

You can also reset an option back to its default value like this:

pd.reset_option('display.max_rows')

And reset all of them back:

pd.reset_option('all')

It is still perfectly good to set options via pd.set_option. I just find using the attributes directly is easier and there is less need for get_option and set_option.

How to create a zip archive of a directory in Python?

To give more flexibility, e.g. select directory/file by name use:

import os
import zipfile

def zipall(ob, path, rel=""):
    basename = os.path.basename(path)
    if os.path.isdir(path):
        if rel == "":
            rel = basename
        ob.write(path, os.path.join(rel))
        for root, dirs, files in os.walk(path):
            for d in dirs:
                zipall(ob, os.path.join(root, d), os.path.join(rel, d))
            for f in files:
                ob.write(os.path.join(root, f), os.path.join(rel, f))
            break
    elif os.path.isfile(path):
        ob.write(path, os.path.join(rel, basename))
    else:
        pass

For a file tree:

.
+-- dir
¦   +-- dir2
¦   ¦   +-- file2.txt
¦   +-- dir3
¦   ¦   +-- file3.txt
¦   +-- file.txt
+-- dir4
¦   +-- dir5
¦   +-- file4.txt
+-- listdir.zip
+-- main.py
+-- root.txt
+-- selective.zip

You can e.g. select only dir4 and root.txt:

cwd = os.getcwd()
files = [os.path.join(cwd, f) for f in ['dir4', 'root.txt']]

with zipfile.ZipFile("selective.zip", "w" ) as myzip:
    for f in files:
        zipall(myzip, f)

Or just listdir in script invocation directory and add everything from there:

with zipfile.ZipFile("listdir.zip", "w" ) as myzip:
    for f in os.listdir():
        if f == "listdir.zip":
            # Creating a listdir.zip in the same directory
            # will include listdir.zip inside itself, beware of this
            continue
        zipall(myzip, f)

How to abort an interactive rebase if --abort doesn't work?

Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.

git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67

Then, abort the rebase again.

Create a <ul> and fill it based on a passed array

First of all, don't create HTML elements by string concatenation. Use DOM manipulation. It's faster, cleaner, and less error-prone. This alone solves one of your problems. Then, just let it accept any array as an argument:

var options = [
        set0 = ['Option 1','Option 2'],
        set1 = ['First Option','Second Option','Third Option']
    ];

function makeUL(array) {
    // Create the list element:
    var list = document.createElement('ul');

    for (var i = 0; i < array.length; i++) {
        // Create the list item:
        var item = document.createElement('li');

        // Set its contents:
        item.appendChild(document.createTextNode(array[i]));

        // Add it to the list:
        list.appendChild(item);
    }

    // Finally, return the constructed list:
    return list;
}

// Add the contents of options[0] to #foo:
document.getElementById('foo').appendChild(makeUL(options[0]));

Here's a demo. You might also want to note that set0 and set1 are leaking into the global scope; if you meant to create a sort of associative array, you should use an object:

var options = {
    set0: ['Option 1', 'Option 2'],
    set1: ['First Option', 'Second Option', 'Third Option']
};

And access them like so:

makeUL(options.set0);

How to reduce a huge excel file

I save files in .XLSB format to cut size. The XLSB also allows for VBA and macros to stay with the file. I've seen 50 meg files down to less than 10 with the Binary formatting.