Programs & Examples On #Flexlm

CSS Circle with border

Here is a jsfiddle so you can see an example of this working.

HTML code:

<div class="circle"></div>

CSS code:

_x000D_
_x000D_
.circle {_x000D_
        /*This creates a 1px solid red border around your element(div) */_x000D_
        border:1px solid red;_x000D_
        background-color: #FFFFFF;_x000D_
        height: 100px;_x000D_
        /* border-radius 50% will make it fully rounded. */_x000D_
        border-radius: 50%;_x000D_
        -moz-border-radius:50%;_x000D_
        -webkit-border-radius: 50%;_x000D_
        width: 100px;_x000D_
    }
_x000D_
<div class='circle'></div>
_x000D_
_x000D_
_x000D_

How to make an image center (vertically & horizontally) inside a bigger div

In CSS do it as:

img
{

  display:table-cell;
  vertical-align:middle;
  margin:auto;
}

How do I determine height and scrolling position of window in jQuery?

Pure JS

window.innerHeight
window.scrollY

is more than 10x faster than jquery (and code has similar size):

enter image description here

Here you can perform test on your machine: https://jsperf.com/window-height-width

How to get the mobile number of current sim card in real device?

As many said:

String phoneNumber = TelephonyManager.getDefault().getLine1Number();

The availability depends strictly on the carrier and the way the number is encoded on the SIM card. If it is hardcoded by the company that makes the SIMs or by the mobile carrier itself. This returns the same as in Settings->about phone.

Google Maps API - how to get latitude and longitude from Autocomplete without showing the map?

As per late 2020 this as easy as follows.

For the geometry key to be presented on a place selected from the places dropdown, the field geometry should be set on Autocomplete object instance with setFields() method.

The code should look like this.

Load the API library:

<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initAutocomplete"

Init the autocomplete and process the selected place data generally same as all answers above. But use autocomplete.setFields(['geometry']) to get coordinates back;

const autocomplete;

// Init the autocomplete object
function initAutocomplete() {
    autocomplete = new window.google.maps.places.Autocomplete(
        document.getElementById('current_location'), { types: ["geocode"] }
    );

    // !!! This is where you set `geometry` field to be returned with the place.
    autocomplete.setFields(['address_component', 'geometry']); // <--

    autocomplete.addListener("place_changed", fillInAddress);
}

// Process the address selected by user
function fillInAddress() {
    const place = autocomplete.getPlace();

    // Here you can get your coordinates like this
    console.log(place.geometry.location.lat());
    console.log(place.geometry.location.lng());
}

See the Google API docs on Autocomplete.setFields and geometry option.

Angular 4/5/6 Global Variables

You can use the Window object and access it everwhere. example window.defaultTitle = "my title"; then you can access window.defaultTitle without importing anything.

Create ArrayList from array

If you use :

new ArrayList<T>(Arrays.asList(myArray));

you may create and fill two lists ! Filling twice a big list is exactly what you don't want to do because it will create another Object[] array each time the capacity needs to be extended.

Fortunately the JDK implementation is fast and Arrays.asList(a[]) is very well done. It create a kind of ArrayList named Arrays.ArrayList where the Object[] data points directly to the array.

// in Arrays
@SafeVarargs
public static <T> List<T> asList(T... a) {
    return new ArrayList<>(a);
}
//still in Arrays, creating a private unseen class
private static class ArrayList<E>

    private final E[] a;    
    ArrayList(E[] array) {
        a = array; // you point to the previous array
    }
    ....
}

The dangerous side is that if you change the initial array, you change the List ! Are you sure you want that ? Maybe yes, maybe not.

If not, the most understandable way is to do this :

ArrayList<Element> list = new ArrayList<Element>(myArray.length); // you know the initial capacity
for (Element element : myArray) {
    list.add(element);
}

Or as said @glglgl, you can create another independant ArrayList with :

new ArrayList<T>(Arrays.asList(myArray));

I love to use Collections, Arrays, or Guava. But if it don't fit, or you don't feel it, just write another inelegant line instead.

Could not find com.google.android.gms:play-services:3.1.59 3.2.25 4.0.30 4.1.32 4.2.40 4.2.42 4.3.23 4.4.52 5.0.77 5.0.89 5.2.08 6.1.11 6.1.71 6.5.87

I too had the same problem and resolved.

As per the above-mentioned solutions by others, I tried all the things and it does not solve my problem.

Even if you have two SDK locations, no need to worry about it and check whether your android home is set to Android studio SDK (If you have the Android repository and everything in that SDK location).

Solution:

  • Go to Your project structure
  • Select your modules
  • Click the dependance tap on the right side
  • Add library dependency
  • "com.google.android.gms:play-service:+"

I hope it will solve your problem.

Jquery Ajax Loading image

Try something like this:

<div id="LoadingImage" style="display: none">
  <img src="" />
</div>

<script>
  function ajaxCall(){
    $("#LoadingImage").show();
      $.ajax({ 
        type: "GET", 
        url: surl, 
        dataType: "jsonp", 
        cache : false, 
        jsonp : "onJSONPLoad", 
        jsonpCallback: "newarticlescallback", 
        crossDomain: "true", 
        success: function(response) { 
          $("#LoadingImage").hide();
          alert("Success"); 
        }, 
        error: function (xhr, status) {  
          $("#LoadingImage").hide();
          alert('Unknown error ' + status); 
        }    
      });  
    }
</script>

Emulate ggplot2 default color palette

It is just equally spaced hues around the color wheel, starting from 15:

gg_color_hue <- function(n) {
  hues = seq(15, 375, length = n + 1)
  hcl(h = hues, l = 65, c = 100)[1:n]
}

For example:

n = 4
cols = gg_color_hue(n)

dev.new(width = 4, height = 4)
plot(1:n, pch = 16, cex = 2, col = cols)

enter image description here

how to download file in react js

browsers are smart enough to detect the link and downloading it directly when clicking on an anchor tag without using the download attribute.

after getting your file link from the api, just use plain javascript by creating anchor tag and delete it after clicking on it dynamically immediately on the fly.

const link = document.createElement('a');
link.href = `your_link.pdf`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

commons httpclient - Adding query string parameters to GET/POST request

I am using httpclient 4.4.

For solr query I used the following way and it worked.

NameValuePair nv2 = new BasicNameValuePair("fq","(active:true) AND (category:Fruit OR category1:Vegetable)");
nvPairList.add(nv2);
NameValuePair nv3 = new BasicNameValuePair("wt","json");
nvPairList.add(nv3);
NameValuePair nv4 = new BasicNameValuePair("start","0");
nvPairList.add(nv4);
NameValuePair nv5 = new BasicNameValuePair("rows","10");
nvPairList.add(nv5);

HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
URI uri = new URIBuilder(request.getURI()).addParameters(nvPairList).build();
            request.setURI(uri);

HttpResponse response = client.execute(request);    
if (response.getStatusLine().getStatusCode() != 200) {

}

BufferedReader br = new BufferedReader(
                             new InputStreamReader((response.getEntity().getContent())));

String output;
System.out.println("Output  .... ");
String respStr = "";
while ((output = br.readLine()) != null) {
    respStr = respStr + output;
    System.out.println(output);
}

Using Tkinter in python to edit the title bar

Here it is nice and simple.

root = tkinter.Tk()
root.title('My Title')

root is the window you create and root.title() sets the title of that window.

Laravel - display a PDF file in storage without forcing download?

Retrieve File name first then in Blade file use anchor(a) tag like below shown. This would works for image view also.

<a href="{{ asset('storage/admission-document-uploads/' . $filename) }}" target="_black"> view Pdf </a>;

How can I cast int to enum?

var result = Enum.TryParse(yourString, out yourEnum) 

And make sure to check the result to determine if the conversion failed.

What does the "__block" keyword mean?

It tells the compiler that any variable marked by it must be treated in a special way when it is used inside a block. Normally, variables and their contents that are also used in blocks are copied, thus any modification done to these variables don't show outside the block. When they are marked with __block, the modifications done inside the block are also visible outside of it.

For an example and more info, see The __block Storage Type in Apple's Blocks Programming Topics.

The important example is this one:

extern NSInteger CounterGlobal;
static NSInteger CounterStatic;

{
    NSInteger localCounter = 42;
    __block char localCharacter;

    void (^aBlock)(void) = ^(void) {
        ++CounterGlobal;
        ++CounterStatic;
        CounterGlobal = localCounter; // localCounter fixed at block creation
        localCharacter = 'a'; // sets localCharacter in enclosing scope
    };

    ++localCounter; // unseen by the block
    localCharacter = 'b';

    aBlock(); // execute the block
    // localCharacter now 'a'
}

In this example, both localCounter and localCharacter are modified before the block is called. However, inside the block, only the modification to localCharacter would be visible, thanks to the __block keyword. Conversely, the block can modify localCharacter and this modification is visible outside of the block.

SQL query question: SELECT ... NOT IN

select * from table_name where id=5 and column_name not in ('sandy,'pandy');

angular.min.js.map not found, what is it exactly?

As eaon21 and monkey said, source map files basically turn minified code into its unminified version for debugging.

You can find the .map files here. Just add them into the same directory as the minified js files and it'll stop complaining. The reason they get fetched is the

/*
//@ sourceMappingURL=angular.min.js.map
*/

at the end of angular.min.js. If you don't want to add the .map files you can remove those lines and it'll stop the fetch attempt, but if you plan on debugging it's always good to keep the source maps linked.

Serializing class instance to JSON

Using jsonpickle

import jsonpickle

object = YourClass()
json_object = jsonpickle.encode(object)

Is it possible to use jQuery to read meta tags

Would this parser help you?

https://github.com/fiann/jquery.ogp

It parses meta OG data to JSON, so you can just use the data directly. If you prefer, you can read/write them directly using JQuery, of course. For example:

$("meta[property='og:title']").attr("content", document.title);
$("meta[property='og:url']").attr("content", location.toString());

Note the single-quotes around the attribute values; this prevents parse errors in jQuery.

Run class in Jar file

Use java -cp myjar.jar com.mypackage.myClass.

  1. If the class is not in a package then simply java -cp myjar.jar myClass.

  2. If you are not within the directory where myJar.jar is located, then you can do:

    1. On Unix or Linux platforms:

      java -cp /location_of_jar/myjar.jar com.mypackage.myClass

    2. On Windows:

      java -cp c:\location_of_jar\myjar.jar com.mypackage.myClass

How to revert uncommitted changes including files and folders?

One non-trivial way is to run these two commands:

  1. git stash This will move your changes to the stash, bringing you back to the state of HEAD
  2. git stash drop This will delete the latest stash created in the last command.

Interview Question: Merge two sorted singly linked lists without creating new nodes

Simple code in javascript to merge two linked list inplace.

function mergeLists(l1, l2) {
    let head = new ListNode(0); //dummy
    let curr = head;
    while(l1 && l2) {
        if(l2.val >= l1.val) {
            curr.next = l1;
            l1 = l1.next;
        } else {
            curr.next = l2;
            l2=l2.next
        }
        curr = curr.next;
    }
    if(!l1){
        curr.next=l2;
    }
    if(!l2){
        curr.next=l1;
    } 
    return head.next;
}

pull access denied repository does not exist or may require docker login

If you're downloading from somewhere else than your own registry or docker-hub, you might have to do a separate agreement of terms on their site, like the case with Oracle's docker registry. It allows you to do docker login fine, but pulling the container won't still work until you go to their site and agree on their terms.

LINUX: Link all files from one to another directory

The posted solutions will not link any hidden files. To include them, try this:

cd /usr/lib
find /mnt/usr/lib -maxdepth 1 -print "%P\n" | while read file; do ln -s "/mnt/usr/lib/$file" "$file"; done

If you should happen to want to recursively create the directories and only link files (so that if you create a file within a directory, it really is in /usr/lib not /mnt/usr/lib), you could do this:

cd /usr/lib
find /mnt/usr/lib -mindepth 1 -depth -type d -printf "%P\n" | while read dir; do mkdir -p "$dir"; done
find /mnt/usr/lib -type f -printf "%P\n" | while read file; do ln -s "/mnt/usr/lib/$file" "$file"; done

Why doesn't [01-12] range work as expected?

A character class in regular expressions, denoted by the [...] syntax, specifies the rules to match a single character in the input. As such, everything you write between the brackets specify how to match a single character.

Your pattern, [01-12] is thus broken down as follows:

  • 0 - match the single digit 0
  • or, 1-1, match a single digit in the range of 1 through 1
  • or, 2, match a single digit 2

So basically all you're matching is 0, 1 or 2.

In order to do the matching you want, matching two digits, ranging from 01-12 as numbers, you need to think about how they will look as text.

You have:

  • 01-09 (ie. first digit is 0, second digit is 1-9)
  • 10-12 (ie. first digit is 1, second digit is 0-2)

You will then have to write a regular expression for that, which can look like this:

  +-- a 0 followed by 1-9
  |
  |      +-- a 1 followed by 0-2
  |      |
<-+--> <-+-->
0[1-9]|1[0-2]
      ^
      |
      +-- vertical bar, this roughly means "OR" in this context

Note that trying to combine them in order to get a shorter expression will fail, by giving false positive matches for invalid input.

For instance, the pattern [0-1][0-9] would basically match the numbers 00-19, which is a bit more than what you want.

I tried finding a definite source for more information about character classes, but for now all I can give you is this Google Query for Regex Character Classes. Hopefully you'll be able to find some more information there to help you.

If REST applications are supposed to be stateless, how do you manage sessions?

Are they just saying don't use session/application level data store???

No. They aren't saying that in a trivial way.

They're saying do not define a "session". Don't login. Don't logout. Provide credentials with the request. Each request stands alone.

You still have data stores. You still have authentication and authorization. You just don't waste time establishing sessions and maintaining session state.

The point is that each request (a) stands completely alone and (b) can be trivially farmed out to a giant parallel server farm without any actual work. Apache or Squid can pass RESTful requests around blindly and successfully.

What if I had a queue of messages, and my user wanted to read the messages, but as he read them, wanted to block certain senders messages coming through for the duration of his session?

If the user wants a filter, then simply provide the filter on each request.

Wouldn't it make sense to ... have the server only send messages (or message ID's) that were not blocked by the user?

Yes. Provide the filter in the RESTful URI request.

Do I really have to send the entire list of message senders to block each time I request the new message list?

Yes. How big can this "list of message senders to block" be? A short list of PK's?

A GET request can be very large. If necessary, you can try a POST request even though it sounds like a kind of query.

Apache 2.4.3 (with XAMPP 1.8.1) not starting in windows 8

change 80 to 81 and 443 to 444 by clicking config button and editing httpd.conf and httpd-ssl.congf. Now you can Access XAMPP from 127.0.0.1:81

Linq Select Group By

    from p in PriceLog
    group p by p.LogDateTime.ToString("MMM") into g
    select new 
    { 
        LogDate = g.Key.ToString("MMM yyyy"),
        GoldPrice = (int)dateGroup.Average(p => p.GoldPrice), 
        SilverPrice = (int)dateGroup.Average(p => p.SilverPrice) 
    }

Best PHP IDE for Mac? (Preferably free!)

Here's the lowdown on Mac IDE's for PHP

NetBeans Free! Plus, the best functionality of all offerings. Includes inline database connections, code completion, syntax checking, color coding, split views etc. Downside: It's a memory hog on the Mac. Be prepared to allow half a gig of memory then you'll need to shut down and restart.

Komodo A step above a Text Editor. Does not support database connections or split views. Color coding and syntax checking are there to an extent. The project control on Komodo is very unwieldy and strange compared to the other IDEs.

Aptana The perfect solution. Eclipsed based and uses the Aptana PHP plug in. Real time syntax checking, word wrap, drag and drop split views, database connections and a slew of other excellent features. Downside: Not a supported product any more. Aptana Studio 2.0+ uses PDT which is a watered down, under-developed (at present) php plug in.

Zend Studio - Almost identical to Aptana, except no word wrap and you can't change alot of the php configuration on the MAC apparently due to bugs.

Coda Created by Panic, Coda has nice integration with source control and their popular FTP client, transmit. They also have a collaboration feature which is cool for pair-programming.

PhpEd with Parallels or Wine. The best IDE for Windows has all the feature you could need and is worth the effort to pass it through either Parallels or Wine.

Dreamweaver Good for Javascript/HTML/CSS, but only marginal for PHP. There is some color coding, but no syntax checking or code completion native to the package. Database connections are supported, and so are split views.

I'm using NetBeans, which is free, and feature rich. I can deal with the memory issues for a while, but it could be slow coming to the MAC.

Cheers! Korky Kathman Senior Partner Entropy Dynamics, LLC

Generating all permutations of a given string

public static void permutation(String str) { 
    permutation("", str); 
}

private static void permutation(String prefix, String str) {
    int n = str.length();
    if (n == 0) System.out.println(prefix);
    else {
        for (int i = 0; i < n; i++)
            permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
    }
}

(via Introduction to Programming in Java)

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 do I get the collection of Model State Errors in ASP.NET MVC?

This will give you one string with all the errors with comma separating

string validationErrors = string.Join(",",
                    ModelState.Values.Where(E => E.Errors.Count > 0)
                    .SelectMany(E => E.Errors)
                    .Select(E => E.ErrorMessage)
                    .ToArray());

Integrating MySQL with Python in Windows

If you are looking for Python 3.2 this seems the best solution I found so far

Source: http://wiki.python.org/moin/MySQL

Authorize attribute in ASP.NET MVC

Real power comes with understanding and implementation membership provider together with role provider. You can assign users into roles and according to that restriction you can apply different access roles for different user to controller actions or controller itself.

 [Authorize(Users = "Betty, Johnny")]
 public ActionResult SpecificUserOnly()
 {
     return View();
 }

or you can restrict according to group

[Authorize(Roles = "Admin, Super User")]
public ActionResult AdministratorsOnly()
{
    return View();
}

Loading DLLs at runtime in C#

foreach (var f in Directory.GetFiles(".", "*.dll"))
            Assembly.LoadFrom(f);

That loads all the DLLs present in your executable's folder.

In my case I was trying to use Reflection to find all subclasses of a class, even in other DLLs. This worked, but I'm not sure if it's the best way to do it.

EDIT: I timed it, and it only seems to load them the first time.

Stopwatch stopwatch = new Stopwatch();
for (int i = 0; i < 4; i++)
{
    stopwatch.Restart();
    foreach (var f in Directory.GetFiles(".", "*.dll"))
        Assembly.LoadFrom(f);
    stopwatch.Stop();
    Console.WriteLine(stopwatch.ElapsedMilliseconds);
}

Output: 34 0 0 0

So one could potentially run that code before any Reflection searches just in case.

Render partial from different folder (not shared)

In my case I was using MvcMailer (https://github.com/smsohan/MvcMailer) and wanted to access a partial view from another folder, that wasn't in "Shared." The above solutions didn't work, but using a relative path did.

@Html.Partial("../MyViewFolder/Partials/_PartialView", Model.MyObject)

Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

I had to change the Test Settings after changing the test projects CPU to x64. Then the tests where detected again.

Architecture

How to install PyQt5 on Windows?

If you are facing problem with pip3 install pyqt5 then try pip3 install pyqt5==5.12.0
This solved the problem for me

Countdown timer using Moment js

You're not using react native or react so forgive me this isn't a solution for you. - since this is a 7 year old post I'm pretty sure you figured it out by now ;)

But I was looking for something similar for react-native and it led me to this SO question. Incase anyone else winds up down the same road I thought I'd share my use-moment-countdown hook for react or react native: https://github.com/BrooklinJazz/use-moment-countdown.

For example you can make a 10 minute timer like so:

import React from 'react'

import  { useCountdown } from 'use-moment-countdown'

const App = () => {
  const {start, time} = useCountdown({m: 10})
  return (
    <div onClick={start}>
      {time.format("hh:mm:ss")}
    </div>
  )
}

export default App

Develop Android app using C#

You should try something running Mono (its compatible with .NET).

For game development, I recommend unity: http://unity3d.com/

for general aplications: http://xamarin.com/monoforandroid

How to get multiple counts with one SQL query?

I think this can also works for you select count(*) as anc,(select count(*) from Patient where sex='F')as patientF,(select count(*) from Patient where sex='M') as patientM from anc

and also you can select and count related tables like this select count(*) as anc,(select count(*) from Patient where Patient.Id=anc.PatientId)as patientF,(select count(*) from Patient where sex='M') as patientM from anc

How to restart a node.js server

I had the same problem and then wrote this shell script which kills all of the existing node processes:

#!/bin/bash
echo "The following node processes were found:"
ps aux | grep " node " | grep -v grep
nodepids=$(ps aux | grep " node " | grep -v grep | cut -c10-15)

echo "OK, so we will stop these process/es now..."

for nodepid in ${nodepids[@]}
do
echo "Stopping PID :"$nodepid
kill -9 $nodepid
done
echo "Done"

After this is saved as a shell script (xxx.sh) file you might want to add it to your PATH as described here.

(Please note that this will kill all of the processes with " node " in it's name except grep's own, so I guess in some cases it may also kill some other processes with a similar name)

MySQL load NULL values from CSV data

(variable1, @variable2, ..) SET variable2 = nullif(@variable2, '' or ' ') >> you can put any condition

Which HTTP methods match up to which CRUD methods?

The Symfony project tries to keep its HTTP methods joined up with CRUD methods, and their list associates them as follows:

  • GET Retrieve the resource from the server
  • POST Create a resource on the server
  • PUT Update the resource on the server
  • DELETE Delete the resource from the server

It's worth noting that, as they say on that page, "In reality, many modern browsers don't support the PUT and DELETE methods."

From what I remember, Symfony "fakes" PUT and DELETE for those browsers that don't support them when generating its forms, in order to try to be as close to using the theoretically-correct HTTP method even when a browser doesn't support it.

1 = false and 0 = true?

There's no good reason for 1 to be true and 0 to be false; that's just the way things have always been notated. So from a logical perspective, the function in your API isn't "wrong", per se.

That said, it's normally not advisable to work against the idioms of whatever language or framework you're using without a damn good reason to do so, so whoever wrote this function was probably pretty bone-headed, assuming it's not simply a bug.

What are .NumberFormat Options In Excel VBA?

In Excel, you can set a Range.NumberFormat to any string as you would find in the "Custom" format selection. Essentially, you have two choices:

  1. General for no particular format.
  2. A custom formatted string, like "$#,##0", to specify exactly what format you're using.

$(window).scrollTop() vs. $(document).scrollTop()

First, you need to understand the difference between window and document. The window object is a top level client side object. There is nothing above the window object. JavaScript is an object orientated language. You start with an object and apply methods to its properties or the properties of its object groups. For example, the document object is an object of the window object. To change the document's background color, you'd set the document's bgcolor property.

window.document.bgcolor = "red" 

To answer your question, There is no difference in the end result between window and document scrollTop. Both will give the same output.

Check working example at http://jsfiddle.net/7VRvj/6/

In general use document mainly to register events and use window to do things like scroll, scrollTop, and resize.

Nginx not running with no error message

For what it's worth: I just had the same problem, after editing the nginx.conf file. I tried and tried restarting it by commanding sudo nginx restart and various other commands. None of them produced any output. Commanding sudo nginx -t to check the configuration file gave the output sudo: nginx: command not found, which was puzzling. I was starting to think there were problems with the path.

Finally, I logged in as root (sudo su) and commanded sudo nginx restart. Now, the command displayed an error message concerning the configuration file. After fixing that, it restarted successfully.

How do I include a JavaScript file in another JavaScript file?

I have created a function that will allow you to use similar verbiage to C#/Java to include a JavaScript file. I've tested it a little bit even from inside of another JavaScript file and it seems to work. It does require jQuery though for a bit of "magic" at the end.

I put this code in a file at the root of my script directory (I named it global.js, but you can use whatever you want. Unless I'm mistaken this and jQuery should be the only required scripts on a given page. Keep in mind this is largely untested beyond some basic usage, so there may or may not be any issues with the way I've done it; use at your own risk yadda yadda I am not responsible if you screw anything up yadda yadda:

/**
* @fileoverview This file stores global functions that are required by other libraries.
*/

if (typeof(jQuery) === 'undefined') {
    throw 'jQuery is required.';
}

/** Defines the base script directory that all .js files are assumed to be organized under. */
var BASE_DIR = 'js/';

/**
* Loads the specified file, outputting it to the <head> HTMLElement.
*
* This method mimics the use of using in C# or import in Java, allowing
* JavaScript files to "load" other JavaScript files that they depend on
* using a familiar syntax.
*
* This method assumes all scripts are under a directory at the root and will
* append the .js file extension automatically.
*
* @param {string} file A file path to load using C#/Java "dot" syntax.
*
* Example Usage:
* imports('core.utils.extensions');
* This will output: <script type="text/javascript" src="/js/core/utils/extensions.js"></script>
*/
function imports(file) {
    var fileName = file.substr(file.lastIndexOf('.') + 1, file.length);

    // Convert PascalCase name to underscore_separated_name
    var regex = new RegExp(/([A-Z])/g);
    if (regex.test(fileName)) {
        var separated = fileName.replace(regex, ",$1").replace(',', '');
        fileName = separated.replace(/[,]/g, '_');
    }

    // Remove the original JavaScript file name to replace with underscore version
    file = file.substr(0, file.lastIndexOf('.'));

    // Convert the dot syntax to directory syntax to actually load the file
    if (file.indexOf('.') > 0) {
        file = file.replace(/[.]/g, '/');
    }

    var src = BASE_DIR + file + '/' + fileName.toLowerCase() + '.js';
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = src;

    $('head').find('script:last').append(script);
}

read complete file without using loop in java

If the file is small, you can read the whole data once:

File file = new File("a.txt");
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fis.read(data);
fis.close();

String str = new String(data, "UTF-8");

Python socket receive - incoming packets always have a different size

That's the nature of TCP: the protocol fills up packets (lower layer being IP packets) and sends them. You can have some degree of control over the MTU (Maximum Transfer Unit).

In other words: you must devise a protocol that rides on top of TCP where your "payload delineation" is defined. By "payload delineation" I mean the way you extract the unit of message your protocol supports. This can be as simple as "every NULL terminated strings".

excel vba getting the row,cell value from selection.address

Dim f as Range

Set f=ActiveSheet.Cells.Find(...)

If Not f Is Nothing then
    msgbox "Row=" & f.Row & vbcrlf & "Column=" & f.Column
Else
    msgbox "value not found!"
End If

Javascript: set label text

For a dynamic approach, if your labels are always in front of your text areas:

$(object).prev("label").text(charsleft);

Date Conversion from String to sql Date in Java giving different output?

mm stands for "minutes". Use MM instead:

SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy");

Getting request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

Basically, to make a cross domain AJAX requests, the requested server should allow the cross origin sharing of resources (CORS). You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/

In your scenario, you are setting the headers in the client which in fact needs to be set into http://localhost:8080/app server side code.

If you are using PHP Apache server, then you will need to add following in your .htaccess file:

Header set Access-Control-Allow-Origin "*"

How to install maven on redhat linux

Pretty much what others said, but using "~/.bash_profile" and step by step (for beginners):

  1. Move to home folder and create a new folder for maven artifacts:
    • cd ~ && mkdir installed-packages
  2. Go to https://maven.apache.org/download.cgi and wget the latest artifact:
    • If you don't have wget installed: sudo yum install -y wget
    • cd ~/installed-packages
    • wget http://www-eu.apache.org/dist/maven/maven-3/3.5.0/binaries/apache-maven-3.5.0-bin.tar.gz
  3. Uncompress the downloaded file:
    • tar -xvf apache-maven-3.5.0-bin.tar.gz
  4. Create a symbolic link of the uncompressed file:
    • ln -s ~/installed-packages/apache-maven-3.5.0 /usr/local/apache-maven
  5. Edit ~/.bash_profile (This is where environment variables are commonly stored):
    • vi ~/.bash_profile
    • Add the variable: MVN_HOME=/usr/local/apache-maven (do this before PATH variable is defined)
      • (For those who don't know vi tool: Press i key to enable insert mode)
    • Go to the end of the line where PATH variable is defined and append the following: :$MVN_HOME:$MVN_HOME/bin
    • Save changes
      • (For those who don't know vi tool: Press esc key to exit insert mode and :wq! to save and quit file)
  6. Reload environment variables:
    • source ~/.bash_profile
  7. Confirm that maven command now works properly:
    • mvn --help

How to install bcmath module?

For PHP 7+ version you can use only:

sudo apt install php-bcmath

Reading a json file in Android

Put that file in assets.

For project created in Android Studio project you need to create assets folder under the main folder.

Read that file as:

public String loadJSONFromAsset(Context context) {
        String json = null;
        try {
            InputStream is = context.getAssets().open("file_name.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }

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

JSONObject obj = new JSONObject(json_return_by_the_function);

For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html

Hope you will get what you want.

Can git undo a checkout of unstaged files

Check local history in your IDE.

JPA and Hibernate - Criteria vs. JPQL or HQL

I mostly prefer Criteria Queries for dynamic queries. For example it is much easier to add some ordering dynamically or leave some parts (e.g. restrictions) out depending on some parameter.

On the other hand I'm using HQL for static and complex queries, because it's much easier to understand/read HQL. Also, HQL is a bit more powerful, I think, e.g. for different join types.

What is the best way to auto-generate INSERT statements for a SQL Server table?

You can use SSMS Tools Pack (available for SQL Server 2005 and 2008). It comes with a feature for generating insert statements.

http://www.ssmstoolspack.com/

AngularJS - add HTML element to dom in directive without jQuery

Why not to try simple (but powerful) html() method:

iElement.html('<svg width="600" height="100" class="svg"></svg>');

Or append as an alternative:

iElement.append('<svg width="600" height="100" class="svg"></svg>');

And , of course , more cleaner way:

 var svg = angular.element('<svg width="600" height="100" class="svg"></svg>');
 iElement.append(svg);

Fiddle: http://jsfiddle.net/cherniv/AgGwK/

How to replace space with comma using sed?

If you want the output on terminal then,

$sed 's/ /,/g' filename.txt

But if you want to edit the file itself i.e. if you want to replace space with the comma in the file then,

$sed -i 's/ /,/g' filename.txt

How to run a PowerShell script from a batch file

You need the -ExecutionPolicy parameter:

Powershell.exe -executionpolicy remotesigned -File  C:\Users\SE\Desktop\ps.ps1

Otherwise PowerShell considers the arguments a line to execute and while Set-ExecutionPolicy is a cmdlet, it has no -File parameter.

Join two data frames, select all columns from one and some columns from the other

Here is the code snippet that does the inner join and select the columns from both dataframe and alias the same column to different column name.

emp_df  = spark.read.csv('Employees.csv', header =True);
dept_df = spark.read.csv('dept.csv', header =True)


emp_dept_df = emp_df.join(dept_df,'DeptID').select(emp_df['*'], dept_df['Name'].alias('DName'))
emp_df.show()
dept_df.show()
emp_dept_df.show()
Output  for 'emp_df.show()':

+---+---------+------+------+
| ID|     Name|Salary|DeptID|
+---+---------+------+------+
|  1|     John| 20000|     1|
|  2|    Rohit| 15000|     2|
|  3|    Parth| 14600|     3|
|  4|  Rishabh| 20500|     1|
|  5|    Daisy| 34000|     2|
|  6|    Annie| 23000|     1|
|  7| Sushmita| 50000|     3|
|  8| Kaivalya| 20000|     1|
|  9|    Varun| 70000|     3|
| 10|Shambhavi| 21500|     2|
| 11|  Johnson| 25500|     3|
| 12|     Riya| 17000|     2|
| 13|    Krish| 17000|     1|
| 14| Akanksha| 20000|     2|
| 15|   Rutuja| 21000|     3|
+---+---------+------+------+

Output  for 'dept_df.show()':
+------+----------+
|DeptID|      Name|
+------+----------+
|     1|     Sales|
|     2|Accounting|
|     3| Marketing|
+------+----------+

Join Output:
+---+---------+------+------+----------+
| ID|     Name|Salary|DeptID|     DName|
+---+---------+------+------+----------+
|  1|     John| 20000|     1|     Sales|
|  2|    Rohit| 15000|     2|Accounting|
|  3|    Parth| 14600|     3| Marketing|
|  4|  Rishabh| 20500|     1|     Sales|
|  5|    Daisy| 34000|     2|Accounting|
|  6|    Annie| 23000|     1|     Sales|
|  7| Sushmita| 50000|     3| Marketing|
|  8| Kaivalya| 20000|     1|     Sales|
|  9|    Varun| 70000|     3| Marketing|
| 10|Shambhavi| 21500|     2|Accounting|
| 11|  Johnson| 25500|     3| Marketing|
| 12|     Riya| 17000|     2|Accounting|
| 13|    Krish| 17000|     1|     Sales|
| 14| Akanksha| 20000|     2|Accounting|
| 15|   Rutuja| 21000|     3| Marketing|
+---+---------+------+------+----------+

Git Commit Messages: 50/72 Formatting

Regarding “thought leaders”: Linus emphatically advocates line wrapping for the full commit message:

[…] we use 72-character columns for word-wrapping, except for quoted material that has a specific line format.

The exceptions refers mainly to “non-prose” text, that is, text that was not typed by a human for the commit — for example, compiler error messages.

CSS Image size, how to fill, but not stretch?

Another solution is to put the image in a container with the desired width and height. Using this method you would not have to set the image as a background image of an element.

Then you can do this with an img tag and just set a max-width and max-height on the element.

CSS:

.imgContainer {
    display: block;
    width: 150px; 
    height: 100px;
}

.imgContainer img {
    max-width: 100%;
    max-height: 100%;
}

HTML:

<div class='imgContainer'>
    <img src='imagesrc.jpg' />
</div>

Now when you change the size of the container the image will automatically grow as large as it can without going outside the bounds or distorting.

If you want to center the image vertically and horizontally you can change the container css to:

.imgContainer {
    display: table-cell;
    width: 150px; 
    height: 100px;
    text-align: center;
    vertical-align: middle;
}

Here is a JS Fiddle http://jsfiddle.net/9kUYC/2/

Java array reflection: isArray vs. instanceof

There is no difference in behavior that I can find between the two (other than the obvious null-case). As for which version to prefer, I would go with the second. It is the standard way of doing this in Java.

If it confuses readers of your code (because String[] instanceof Object[] is true), you may want to use the first to be more explicit if code reviewers keep asking about it.

Splitting comma separated string in a PL/SQL stored proc

create or replace procedure pro_ss(v_str varchar2) as
v_str1 varchar2(100); 
v_comma_pos number := 0;    
v_start_pos number := 1;
begin             
    loop        
    v_comma_pos := instr(v_str,',',v_start_pos);   
    if  v_comma_pos = 0 then     
      v_str1 := substr(v_str,v_start_pos);  
      dbms_output.put_line(v_str1);    
      exit;
      end if;    
    v_str1 := substr(v_str,v_start_pos,(v_comma_pos - v_start_pos)); 
    dbms_output.put_line(v_str1);       
    v_start_pos := v_comma_pos + 1;    
    end loop; 
end;
/

call pro_ss('aa,bb,cc,dd,ee,ff,gg,hh,ii,jj');

outout: aa bb cc dd ee ff gg hh ii jj

select unique rows based on single distinct column

If you are using MySql 5.7 or later, according to these links (MySql Official, SO QA), we can select one record per group by with out the need of any aggregate functions.

So the query can be simplified to this.

select * from comments_table group by commentname;

Try out the query in action here

Cannot construct instance of - Jackson

In your concrete example the problem is that you don't use this construct correctly:

@JsonSubTypes({ @JsonSubTypes.Type(value = MyAbstractClass.class, name = "MyAbstractClass") })

@JsonSubTypes.Type should contain the actual non-abstract subtypes of your abstract class.

Therefore if you have:

abstract class Parent and the concrete subclasses

Ch1 extends Parent and Ch2 extends Parent

Then your annotation should look like:

@JsonSubTypes({ 
          @JsonSubTypes.Type(value = Ch1.class, name = "ch1"),
          @JsonSubTypes.Type(value = Ch2.class, name = "ch2")
})

Here name should match the value of your 'discriminator':

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, 
include = JsonTypeInfo.As.WRAPPER_OBJECT, 
property = "type")

in the property field, here it is equal to type. So type will be the key and the value you set in name will be the value.

Therefore, when the json string comes if it has this form:

{
 "type": "ch1",
 "other":"fields"
}

Jackson will automatically convert this to a Ch1 class.

If you send this:

{
 "type": "ch2",
 "other":"fields"
}

You would get a Ch2 instance.

Difference between binary tree and binary search tree

As everybody above has explained about the difference between binary tree and binary search tree, i am just adding how to test whether the given binary tree is binary search tree.

boolean b = new Sample().isBinarySearchTree(n1, Integer.MIN_VALUE, Integer.MAX_VALUE);
.......
.......
.......
public boolean isBinarySearchTree(TreeNode node, int min, int max)
{

    if(node == null)
    {
        return true;
    }

    boolean left = isBinarySearchTree(node.getLeft(), min, node.getValue());
    boolean right = isBinarySearchTree(node.getRight(), node.getValue(), max);

    return left && right && (node.getValue()<max) && (node.getValue()>=min);

}

Hope it will help you. Sorry if i am diverting from the topic as i felt it's worth mentioning this here.

How to add an object to an array

obejct is clearly a typo. But both object and array need capital letters.

You can use short hands for new Array and new Object these are [] and {}

You can push data into the array using .push. This adds it to the end of the array. or you can set an index to contain the data.

function saveToArray() {
    var o = {};
    o.foo = 42;
    var arr = [];
    arr.push(o);
    return arr;
}

function other() {
    var arr = saveToArray();
    alert(arr[0]);
}

other();

How can I make a div stick to the top of the screen once it's been scrolled to?

In javascript you can do:

var element = document.getElementById("myid");
element.style.position = "fixed";
element.style.top = "0%";

How to get date in BAT file

Locale-independent one liner to get any date format you like. I use it to generate archive names. Back quote option is needed because PowerShell command line is using single quotes.

:: Get date in yyyyMMdd_HHmm format to use with file name.
FOR /f "usebackq" %%i IN (`PowerShell ^(Get-Date^).ToString^('yyyy-MM-dd'^)`) DO SET DTime=%%i

:: Get formatted yesterday date.
FOR /f "usebackq" %%i IN (`PowerShell ^(Get-Date^).AddDays^(-1^).ToString^('yyyy-MM-dd'^)`) DO SET DTime=%%i

:: Show file name with the date.
echo Archive.%DTime%.zip

Export P7b file with all the certificate chain into CER file

-print_certs is the option you want to use to list all of the certificates in the p7b file, you may need to specify the format of the p7b file you are reading.

You can then redirect the output to a new file to build the concatenated list of certificates.

Open the file in a text editor, you will either see Base64 (PEM) or binary data (DER).

openssl pkcs7 -inform DER -outform PEM -in certificate.p7b -print_certs > certificate_bundle.cer

http://www.openssl.org/docs/apps/pkcs7.html

In Java, how do I call a base class's method from the overriding method in a derived class?

// Using super keyword access parent class variable
class test {
    int is,xs;

    test(int i,int x) {
        is=i;
        xs=x;
        System.out.println("super class:");
    }
}

class demo extends test {
    int z;

    demo(int i,int x,int y) {
        super(i,x);
        z=y;
        System.out.println("re:"+is);
        System.out.println("re:"+xs);
        System.out.println("re:"+z);
    }
}

class free{
    public static void main(String ar[]){
        demo d=new demo(4,5,6);
    }
}

Checkbox for nullable boolean

This is an old question, and the existing answers describe most of the alternatives. But there's one simple option, if you have bool? in your viewmodel, and you don't care about null in your UI:

@Html.CheckBoxFor(m => m.boolValue ?? false);

Excel formula to display ONLY month and year?

Try the formula

=TEXT(TODAY(),"MMYYYY")

Calling a function within a Class method?

  class sampleClass
    { 
        public function f1()
        {
           return "f1 run";
        }

        public function f2()
        {
           echo ("f2 run" );
           $result =  $this->f1();
           echo ($result);
        }   

    f2();  

    }

output :

f2 run f1 run

repository element was not specified in the POM inside distributionManagement element or in -DaltDep loymentRepository=id::layout::url parameter

You should include the repository where you want to deploy in the distribution management section of the pom.xml.

Example:

<project xmlns="http://maven.apache.org/POM/4.0.0"   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                      http://maven.apache.org/xsd/maven-4.0.0.xsd">
...   
<distributionManagement>
    <repository>
      <uniqueVersion>false</uniqueVersion>
      <id>corp1</id>
      <name>Corporate Repository</name>
      <url>scp://repo/maven2</url>
      <layout>default</layout>
    </repository>
    ...
</distributionManagement>
...
</project>

See Distribution Management

Should I use pt or px?

A pt is 1/72th of an inch and is a useless measure for anything that is rendered on a device which doesn't calculate the DPI correctly. This makes it a reasonable choice for printing and a dreadful choice for use on screen.

A px is a pixel, which will map on to a screen pixel in most cases.

CSS provides a bunch of other units, and which one you should choose depends on what you are setting the size of.

A pixel is great if you need to size something to match an image, or if you want a thin border.

Percentages are great for font sizes as, if you use them consistently, you get font sizes proportional to the user's preference.

Ems are great when you want an element to size itself based on the font size (so a paragraph might get wider if the font size is larger)

… and so on.

Give column name when read csv file pandas

user1  = pd.read_csv('dataset/1.csv',  names=['Time',  'X',  'Y',  'Z']) 

names parameter in read_csv function is used to define column names. If you pass extra name in this list, it will add another new column with that name with NaN values.

header=None is used to trim column names is already exists in CSV file.

How to increase space between dotted border dots

Short answer: You can't.

You will have to use border-image property and a few images.

Why use static_cast<int>(x) instead of (int)x?

The question is bigger than just using wither static_cast or C style casting because there are different things that happen when using C style casts. The C++ casting operators are intended to make these operations more explicit.

On the surface static_cast and C style casts appear to the same thing, for example when casting one value to another:

int i;
double d = (double)i;                  //C-style cast
double d2 = static_cast<double>( i );  //C++ cast

Both of these cast the integer value to a double. However when working with pointers things get more complicated. some examples:

class A {};
class B : public A {};

A* a = new B;
B* b = (B*)a;                                  //(1) what is this supposed to do?

char* c = (char*)new int( 5 );                 //(2) that weird?
char* c1 = static_cast<char*>( new int( 5 ) ); //(3) compile time error

In this example (1) maybe OK because the object pointed to by A is really an instance of B. But what if you don't know at that point in code what a actually points to? (2) maybe perfectly legal(you only want to look at one byte of the integer), but it could also be a mistake in which case an error would be nice, like (3). The C++ casting operators are intended to expose these issues in the code by providing compile-time or run-time errors when possible.

So, for strict "value casting" you can use static_cast. If you want run-time polymorphic casting of pointers use dynamic_cast. If you really want to forget about types, you can use reintrepret_cast. And to just throw const out the window there is const_cast.

They just make the code more explicit so that it looks like you know what you were doing.

nginx - nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)

In my case, one of the services either Apache, Apache2 or Nginx was already running and due to that I was not able to start the other service.

Non-conformable arrays error in code

The problem is that omega in your case is matrix of dimensions 1 * 1. You should convert it to a vector if you wish to multiply t(X) %*% X by a scalar (that is omega)

In particular, you'll have to replace this line:

omega   = rgamma(1,a0,1) / L0

with:

omega   = as.vector(rgamma(1,a0,1) / L0)

everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.) or c(t(.)). Both are equivalent.

Here's the modified code that should work:

gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1, 
                     a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
    m0      = c(m01, m02) 
    C0      = matrix(nrow = 2, ncol = 2) 
    C0[1,1] = 1 / k01 
    C0[1,2] = 0 
    C0[2,1] = 0 
    C0[2,2] = 1 / k02 
    beta    = mvrnorm(1,m0,C0) 
    omega   = as.vector(rgamma(1,a0,1) / L0)
    draws   = matrix(ncol = 3,nrow = ndraw) 
    it      = -nburn 

    while (it < ndraw) {
        it    = it + 1 
        C1    = solve(solve(C0) + omega * t(X) %*% X) 
        m1    = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
        beta  = mvrnorm(1, m1, C1) 
        a1    = a0 + n / 2 
        L1    = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2 
        omega = as.vector(rgamma(1, a1, 1) / L1)
        if (it > 0) { 
            draws[it,1] = beta[1]
            draws[it,2] = beta[2]
            draws[it,3] = omega
        }
    }
    return(draws)
}

what are the .map files used for in Bootstrap 3.x?

These are source maps. Provide these alongside compressed source files; developer tools such as those in Firefox and Chrome will use them to allow debugging as if the code was not compressed.

Change Name of Import in Java, or import two classes with the same name

It's probably worth noting that Groovy has this feature:

import java.util.Calendar
import com.example.Calendar as MyCalendar

MyCalendar myCalendar = new MyCalendar()

CSS - Expand float child DIV height to parent's height

For the parent:

display: flex;

For children:

align-items: stretch;

You should add some prefixes, check caniuse.

How do I get the command-line for an Eclipse run configuration?

I found a solution on Stack Overflow for Java program run configurations which also works for JUnit run configurations.

You can get the full command executed by your configuration on the Debug tab, or more specifically the Debug view.

  1. Run your application
  2. Go to your Debug perspective
  3. There should be an entry in there (in the Debug View) for the app you've just executed
  4. Right-click the node which references java.exe or javaw.exe and select Properties In the dialog that pops up you'll see the Command Line which includes all jars, parameters, etc

Loop through childNodes

I'm very late to the party, but since element.lastChild.nextSibling === null, the following seems like the most straightforward option to me:

for(var child=element.firstChild; child!==null; child=child.nextSibling) {
    console.log(child);
}

JQuery: 'Uncaught TypeError: Illegal invocation' at ajax request - several elements

Please follow the procedure to get rid of this problem:

$.ajax({
   url: 'https://your-api-endpoint',
   type: 'post',
   data: new formData(this),
   processData: false,
   contentType: false,
   success: function(response) {
      console.log(response)
   }
})

You have to use processData: false and contentType: false, these two lines. Your problem will be solved.

Is there a way to view past mysql queries with phpmyadmin?

you can run your past mysql with run /PATH_PAST_MYSQL/bin/mysqld.exe

it run your last mysql and you can see it in phpmyadmin and other section of your system.

notice: stop your current mysql version.

S F My English.

JS jQuery - check if value is in array

As to your bonus question, try if (jQuery.inArray(jQuery("input:first").val(), ar) < 0)

Can anyone explain IEnumerable and IEnumerator to me?

Explanation via Analogy + Code Walkthrough

First an explanation without code, then I'll add it in later.

Let's say you are running an airline company. And in each plane you want to know information about the passengers flying in the plane. Basically you want to be able to "traverse" the plane. In other words, you want to be able to start at the front seat, and to then work your way towards the back of the plane, asking passengers some information: who they are, where they are from etc. An aeroplane can only do this, if it is:

  1. countable, and
  2. if it has a counter.

Why these requirements? Because that's what the interface requires.

If this is information overload, all you need to know is that you want to be able to ask each passenger in the plane some questions, starting from the first and making your way to the last.

What does countable mean?

If an airline is "countable", this means that there MUST be a flight attendant present on the plane, whose sole job is to count - and this flight attendant MUST count in a very specific manner:

  1. The counter/flight attendant MUST start before the first passenger (at the front of everyone where they demo safety, how to put the life jacket on etc).
  2. He/she (i.e. the flight attendant) MUST "move next" up the aisle to the first seat.
  3. He/she is to then record: (i) who the person is in the seat, and (ii) their current location in the aisle.

Counting Procedures

The captain of the airline wants a report on every passenger as and when they are investigated or counted. So after speaking to the person in the first seat, the flight-attendant/counter then reports to the captain, and when the report is given, the counter remembers his/her exact position in the aisle and continues counting right where he/she left off.

In this manner the captain is always able to have information on the current person being investigated. That way, if he finds out that this individual likes Manchester City, then he can give that passenger preferential treatment etc.

  • The counter keeps going till he reaches the end of the plane.

Let's tie this with the IEnumerables

  • An enumerable is just a collection of passengers on a plane. The Civil Aviation Law - these are basically the rules which all IEnumerables must follow. Everytime the airline attendant goes to the captain with the passeger information, we are basically 'yielding' the passenger to the captain. The captain can basically do whatever he wants with the passenger - except rearranging the passengers on the plane. In this case, they are given preferential treatment if they follow Manchester City (ugh!)

     foreach (Passenger passenger in Plane)
     // the airline hostess is now at the front of the plane
     // and slowly making her way towards the back
     // when she get to a particular passenger she gets some information
     // about the passenger and then immediately heads to the cabin
     // to let the captain decide what to do with it
     { // <---------- Note the curly bracket that is here.
         // we are now cockpit of the plane with the captain.
         // the captain wants to give the passenger free 
         // champaign if they support manchester city
         if (passenger.supports_mancestercity())
         {
             passenger.getFreeChampaign();
         } else
         {
             // you get nothing! GOOD DAY SIR!
         }
     } //  <---- Note the curly bracket that is here!
           the hostess has delivered the information 
           to the captain and goes to the next person
           on the plane (if she has not reached the 
           end of the plane)
    

Summary

In other words, something is countable if it has a counter. And counter must (basically): (i) remember its place (state), (ii) be able to move next, (iii) and know about the current person he is dealing with.

Enumerable is just a fancy word for "countable". In other words, an enumerable allows you to 'enumerate' (i.e. count).

Transaction isolation levels relation with locks on table

The locks are always taken at DB level:-

Oracle official Document:- To avoid conflicts during a transaction, a DBMS uses locks, mechanisms for blocking access by others to the data that is being accessed by the transaction. (Note that in auto-commit mode, where each statement is a transaction, locks are held for only one statement.) After a lock is set, it remains in force until the transaction is committed or rolled back. For example, a DBMS could lock a row of a table until updates to it have been committed. The effect of this lock would be to prevent a user from getting a dirty read, that is, reading a value before it is made permanent. (Accessing an updated value that has not been committed is considered a dirty read because it is possible for that value to be rolled back to its previous value. If you read a value that is later rolled back, you will have read an invalid value.)

How locks are set is determined by what is called a transaction isolation level, which can range from not supporting transactions at all to supporting transactions that enforce very strict access rules.

One example of a transaction isolation level is TRANSACTION_READ_COMMITTED, which will not allow a value to be accessed until after it has been committed. In other words, if the transaction isolation level is set to TRANSACTION_READ_COMMITTED, the DBMS does not allow dirty reads to occur. The interface Connection includes five values that represent the transaction isolation levels you can use in JDBC.

How to log PostgreSQL queries?

Edit your /etc/postgresql/9.3/main/postgresql.conf, and change the lines as follows.

Note: If you didn't find the postgresql.conf file, then just type $locate postgresql.conf in a terminal

  1. #log_directory = 'pg_log' to log_directory = 'pg_log'

  2. #log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log' to log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'

  3. #log_statement = 'none' to log_statement = 'all'

  4. #logging_collector = off to logging_collector = on

  5. Optional: SELECT set_config('log_statement', 'all', true);

  6. sudo /etc/init.d/postgresql restart or sudo service postgresql restart

  7. Fire query in postgresql select 2+2

  8. Find current log in /var/lib/pgsql/9.2/data/pg_log/

The log files tend to grow a lot over a time, and might kill your machine. For your safety, write a bash script that'll delete logs and restart postgresql server.

Thanks @paul , @Jarret Hardie , @Zoltán , @Rix Beck , @Latif Premani

Appending pandas dataframes generated in a for loop

you can try this.

data_you_need=pd.DataFrame()
for infile in glob.glob("*.xlsx"):
    data = pandas.read_excel(infile)
    data_you_need=data_you_need.append(data,ignore_index=True)

I hope it can help.

DirectX SDK (June 2010) Installation Problems: Error Code S1023

I have encounter this issue too. And I'm running in XP SP3.

The following website http://www.docin.com/p-60410380.html# pointing out the solution. But it's simplified Chinese.

I translated its main idea into English here.

run regedit; open HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\DirectX Then you must change the following two items: Item 1: Name: Version, Type:REG_SZ, The value should be a rather little number to make the installation success.

Item 2: Name: SDKVersion. But in your machine, the name can be different, for example, it can be ManagedDirectXVersion. But the type should be REG_SZ. Type:REG_SZ, The value should be a rather little number to make the installation success.

In fact, you can refer to the DirectX.lgo file to find the exact version number.

It works for me.

How to convert a String to a Date using SimpleDateFormat?

String newstr = "08/16/2011";
SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat format = new SimpleDateFormat("EE MMM dd hh:mm:ss z yyyy");
Calendar c = Calendar.getInstance();
c.setTime(format1.parse(newstr));
System.out.println(format.format(c.getTime()));

How to spawn a process and capture its STDOUT in .NET?

It looks like two of your lines are out of order. You start the process before setting up an event handler to capture the output. It's possible the process is just finishing before the event handler is added.

Switch the lines like so.

p.OutputDataReceived += ...
p.Start();        

Split string by single spaces

If you are not averse to boost, boost.tokenizer is flexible enough to solve this

#include <string>
#include <iostream>
#include <boost/tokenizer.hpp>

void split_and_show(const std::string s)
{
    boost::char_separator<char> sep(" ", "", boost::keep_empty_tokens);
    boost::tokenizer<boost::char_separator<char> > tok(s, sep);
    for(auto i = tok.begin(); i!=tok.end(); ++i)
            std::cout << '"' << *i << "\"\n";
}
int main()
{
    split_and_show("This is a string");
    split_and_show("This  is a string");

}

test: https://ideone.com/mN2sR

How to connect SQLite with Java?

You have to download and add the SQLite JDBC driver to your classpath.
You can download from here https://bitbucket.org/xerial/sqlite-jdbc/downloads

If you use Gradle, you will only have to add the SQLite dependency:

dependencies {
    compile 'org.xerial:sqlite-jdbc:3.8.11.2'
} 

Next thing you have to do is to initialize the driver:

try {
    Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException eString) {
    System.err.println("Could not init JDBC driver - driver not found");
}

ReactJS - How to use comments?

Here is another approach that allows you to use // to include comments:

return (
  <div>
    <div>
      {
        // Your comment goes in here.
      }
    </div>
    {
      // Note that comments using this style must be wrapped in curly braces!
    }
  </div>
);

The catch here is you cannot include a one-line comment using this approach. For example, this does not work:

{// your comment cannot be like this}

because the closing bracket } is considered to be part of the comment and is thus ignored, which throws an error.

Convert String to int array in java

In tight loops or on mobile devices it's not a good idea to generate lots of garbage through short-lived String objects, especially when parsing long arrays.

The method in my answer parses data without generating garbage, but it does not deal with invalid data gracefully and cannot parse negative numbers. If your data comes from untrusted source, you should be doing some additional validation or use one of the alternatives provided in other answers.

public static void readToArray(String line, int[] resultArray) {
    int index = 0;
    int number = 0;

    for (int i = 0, n = line.length(); i < n; i++) {
        char c = line.charAt(i);
        if (c == ',') {
            resultArray[index] = number;
            index++;
            number = 0;
        }
        else if (Character.isDigit(c)) {
            int digit = Character.getNumericValue(c);
            number = number * 10 + digit;
        }
    }

    if (index < resultArray.length) {
        resultArray[index] = number;
    }
}

public static int[] toArray(String line) {
    int[] result = new int[countOccurrences(line, ',') + 1];
    readToArray(line, result);
    return result;
}

public static int countOccurrences(String haystack, char needle) {
    int count = 0;
    for (int i=0; i < haystack.length(); i++) {
        if (haystack.charAt(i) == needle) {
            count++;
        }
    }
    return count;
}

countOccurrences implementation was shamelessly stolen from John Skeet

Pandas count(distinct) equivalent

Distinct of column along with aggregations on other columns

To get the distinct number of values for any column (CLIENTCODE in your case), we can use nunique. We can pass the input as a dictionary in agg function, along with aggregations on other columns:

grp_df = df.groupby('YEARMONTH').agg({'CLIENTCODE': ['nunique'],
                                      'other_col_1': ['sum', 'count']})

# to flatten the multi-level columns
grp_df.columns = ["_".join(col).strip() for col in grp_df.columns.values]

# if you wish to reset the index
grp_df.reset_index(inplace=True)

Javascript Date - set just the date, ignoring time?

If you don't mind creating an extra date object, you could try:

var tempDate = new Date(parseInt(item.timestamp, 10));
var visitDate = new Date (tempDate.getUTCFullYear(), tempDate.getUTCMonth(), tempDate.getUTCDate());

I do something very similar to get a date of the current month without the time.

Floating point exception( core dump

You are getting Floating point exception because Number % i, when i is 0:

int Is_Prime( int Number ){

  int i ;

  for( i = 0 ; i < Number / 2 ; i++ ){

    if( Number % i != 0 ) return -1 ;

  }

  return Number ;

}

Just start the loop at i = 2. Since i = 1 in Number % i it always be equal to zero, since Number is a int.

Bootstrap modal opening on page load

Use a document.ready() event around your call.

$(document).ready(function () {

    $('#memberModal').modal('show');

});

jsFiddle updated - http://jsfiddle.net/uvnggL8w/1/

How do you do dynamic / dependent drop downs in Google Sheets?

Continuing the evolution of this solution I've upped the ante by adding support for multiple root selections and deeper nested selections. This is a further development of JavierCane's solution (which in turn built on tarheel's).

_x000D_
_x000D_
/**_x000D_
 * "on edit" event handler_x000D_
 *_x000D_
 * Based on JavierCane's answer in _x000D_
 * _x000D_
 *   http://stackoverflow.com/questions/21744547/how-do-you-do-dynamic-dependent-drop-downs-in-google-sheets_x000D_
 *_x000D_
 * Each set of options has it own sheet named after the option. The _x000D_
 * values in this sheet are used to populate the drop-down._x000D_
 *_x000D_
 * The top row is assumed to be a header._x000D_
 *_x000D_
 * The sub-category column is assumed to be the next column to the right._x000D_
 *_x000D_
 * If there are no sub-categories the next column along is cleared in _x000D_
 * case the previous selection did have options._x000D_
 */_x000D_
_x000D_
function onEdit() {_x000D_
_x000D_
  var NESTED_SELECTS_SHEET_NAME = "Sitemap"_x000D_
  var NESTED_SELECTS_ROOT_COLUMN = 1_x000D_
  var SUB_CATEGORY_COLUMN = NESTED_SELECTS_ROOT_COLUMN + 1_x000D_
  var NUMBER_OF_ROOT_OPTION_CELLS = 3_x000D_
  var OPTION_POSSIBLE_VALUES_SHEET_SUFFIX = ""_x000D_
  _x000D_
  var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()_x000D_
  var activeSheet = SpreadsheetApp.getActiveSheet()_x000D_
  _x000D_
  if (activeSheet.getName() !== NESTED_SELECTS_SHEET_NAME) {_x000D_
  _x000D_
    // Not in the sheet with nested selects, exit!_x000D_
    return_x000D_
  }_x000D_
  _x000D_
  var activeCell = SpreadsheetApp.getActiveRange()_x000D_
  _x000D_
  // Top row is the header_x000D_
  if (activeCell.getColumn() > SUB_CATEGORY_COLUMN || _x000D_
      activeCell.getRow() === 1 ||_x000D_
      activeCell.getRow() > NUMBER_OF_ROOT_OPTION_CELLS + 1) {_x000D_
_x000D_
    // Out of selection range, exit!_x000D_
    return_x000D_
  }_x000D_
  _x000D_
  var sheetWithActiveOptionPossibleValues = activeSpreadsheet_x000D_
    .getSheetByName(activeCell.getValue() + OPTION_POSSIBLE_VALUES_SHEET_SUFFIX)_x000D_
  _x000D_
  if (sheetWithActiveOptionPossibleValues === null) {_x000D_
  _x000D_
    // There are no further options for this value, so clear out any old_x000D_
    // values_x000D_
    activeSheet_x000D_
      .getRange(activeCell.getRow(), activeCell.getColumn() + 1)_x000D_
      .clearDataValidations()_x000D_
      .clearContent()_x000D_
      _x000D_
    return_x000D_
  }_x000D_
  _x000D_
  // Get all possible values_x000D_
  var activeOptionPossibleValues = sheetWithActiveOptionPossibleValues_x000D_
    .getSheetValues(1, 1, -1, 1)_x000D_
  _x000D_
  var possibleValuesValidation = SpreadsheetApp.newDataValidation()_x000D_
  possibleValuesValidation.setAllowInvalid(false)_x000D_
  possibleValuesValidation.requireValueInList(activeOptionPossibleValues, true)_x000D_
  _x000D_
  activeSheet_x000D_
    .getRange(activeCell.getRow(), activeCell.getColumn() + 1)_x000D_
    .setDataValidation(possibleValuesValidation.build())_x000D_
    _x000D_
} // onEdit()
_x000D_
_x000D_
_x000D_

As Javier says:

  • Create the sheet where you'll have the nested selectors
  • Go to the "Tools" > "Script Editor…" and select the "Blank project" option
  • Paste the code attached to this answer
  • Modify the constants at the top of the script setting up your values and save it
  • Create one sheet within this same document for each possible value of the "root selector". They must be named as the value + the specified suffix.

And if you wanted to see it in action I've created a demo sheet and you can see the code if you take a copy.

exceeds the list view threshold 5000 items in Sharepoint 2010

You can increase the List View Threshold beyond the 5,000 default, but it is highly recommended that you don't, as it has performance implications. The recommended fix is to add an index to the field or fields used in the query (usually the ID field for a list or the Title field for a library).

When there is an index, that is used to retrieve the item(s); when there is no index the whole list is opened for a scan (and therefore hits the threshold). You create the index on the List (or Library) settings page.

This article is a good overview: http://office.microsoft.com/en-us/sharepoint-foundation-help/manage-lists-and-libraries-with-many-items-HA010377496.aspx

Colorized grep -- viewing the entire file with highlighted matches

another dirty way:

grep -A80 -B80 --color FIND_THIS IN_FILE

I did an

alias grepa='grep -A80 -B80 --color'

in bashrc.

How do I concatenate strings in Swift?

You can now use stringByAppendingString in Swift.

var string = "Swift"
var resultString = string.stringByAppendingString(" is new Programming Language")

Using setTimeout to delay timing of jQuery actions

This is how I solved the problem The menu closes a few seconds after mouse out (that if hover didn't fire),

//Set timer switch
$setM_swith=0;

$(function(){
    $(".navbar-nav li a").click(function(event) {
        if (!$(this).parent().hasClass('dropdown'))
            $(".navbar-collapse").collapse('hide');
    });
    $(".navbar-collapse").mouseleave(function(){
        $setM_swith=1;
        setTimeout(function(){ 
           if($setM_swith==1) {
             $(".navbar-collapse").collapse('hide');
             $setM_swith=0;} 
        }, 3000);
    });
    $(".navbar-collapse").mouseover(function() {
        $setM_swith=0;
    });
 });

Document directory path of Xcode Device Simulator

Despite the fact that here are many answers, none of them provides an understanding of how the folder structure of the iOS 8.3 simulators have changed and are not providing a quick way to find the App's Data (Documents folder).

Since iOS 8 the Data storage folder(s) of an App are separate from the App's executable files while the iOS 7 and below are having the same folder structure, the only difference being the fact that all the simulators (different types and versions) are now in one, big folder.

So, the path to an iOS 8,7,6 simulator is the following:

~/Library/Developer/CoreSimulator/Devices

Every simulator is now contained in a folder named with an unique identifier which changes at every reset of a simulator.

You can find the Identifier for each of your devices & simulators by going to Xcode > Window > Devices (the first 3 or 4 characters of the identifier are more than enough to remember).

To find the one on which you have installed your app(s) on, take a look at your Run scheme > devices (screen 2).

screen 1

screen 2

Now, after you identify your simulator, depending on its version the folder structure is very different:

On iOS 8 the executable and the data folder of an app are in different folders:

Executable: ~/Library/Developer/CoreSimulator/Devices/[simID]/data/Containers/Bundle/Application/[appID]

Data Folder: ~/Library/Developer/CoreSimulator/Devices/[simID]/data/Containers/Data/Application/[appID]/

Documents Folder: ~/Library/Developer/CoreSimulator/Devices/[simID]/data/Containers/Data/Application/[appID]/Documents

On iOS 7 and below the folder structure is the same as before only remember that now every simulator is in the same folder (see above).

how to display toolbox on the left side of window of Visual Studio Express for windows phone 7 development?

Sometimes you can just do 'Window -> Reset Window Layout', and that'll work :)

Using context in a fragment

Previously I'm using onAttach (Activity activity) to get context in Fragment

Problem

The onAttach (Activity activity) method was deprecated in API level 23.

Solution

Now to get context in Fragment we can use onAttach (Context context)

onAttach (Context context)

  • Called when a fragment is first attached to its context. onCreate(Bundle) will be called after this.

Documentation

/**
 * Called when a fragment is first attached to its context.
 * {@link #onCreate(Bundle)} will be called after this.
 */
@CallSuper
public void onAttach(Context context) {
    mCalled = true;
    final Activity hostActivity = mHost == null ? null : mHost.getActivity();
    if (hostActivity != null) {
        mCalled = false;
        onAttach(hostActivity);
    }
}

SAMPLE CODE

public class FirstFragment extends Fragment {


    private Context mContext;
    public FirstFragment() {
        // Required empty public constructor
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext=context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rooView=inflater.inflate(R.layout.fragment_first, container, false);

        Toast.makeText(mContext, "THIS IS SAMPLE TOAST", Toast.LENGTH_SHORT).show();
        // Inflate the layout for this fragment
        return rooView;
    }

}

NOTE

We can also use getActivity() to get context in Fragments but getActivity() can return null if the your fragment is not currently attached to a parent activity,

PHP regular expressions: No ending delimiter '^' found in

PHP regex strings need delimiters. Try:

$numpattern="/^([0-9]+)$/";

Also, note that you have a lower case o, not a zero. In addition, if you're just validating, you don't need the capturing group, and can simplify the regex to /^\d+$/.

Example: http://ideone.com/Ec3zh

See also: PHP - Delimiters

how to fix EXE4J_JAVA_HOME, No JVM could be found on your system error?

There are few steps to overcome this problem:

  1. Uninstall Java related softwares
  2. Uninstall NodeJS if installed
  3. Download java 8 update161
  4. Install it

The problem solved: The problem raised to me at the uninstallation on openfire server.

How to stop the task scheduled in java.util.Timer class

Terminate the Timer once after awake at a specific time in milliseconds.

Timer t = new Timer();
t.schedule(new TimerTask() {
            @Override
             public void run() {
             System.out.println(" Run spcific task at given time.");
             t.cancel();
             }
 }, 10000);

Copying files into the application folder at compile time

You can also put the files or links into the root of the solution explorer and then set the files properties:

Build action = Content

and

Copy to Output Directory = Copy if newer (for example)

For a link drag the file from the windows explorer into the solution explorer holding down the shift and control keys.

enter image description here

Proper indentation for Python multiline strings

Some more options. In Ipython with pylab enabled, dedent is already in the namespace. I checked and it is from matplotlib. Or it can be imported with:

from matplotlib.cbook import dedent

In documentation it states that it is faster than the textwrap equivalent one and in my tests in ipython it is indeed 3 times faster on average with my quick tests. It also has the benefit that it discards any leading blank lines this allows you to be flexible in how you construct the string:

"""
line 1 of string
line 2 of string
"""

"""\
line 1 of string
line 2 of string
"""

"""line 1 of string
line 2 of string
"""

Using the matplotlib dedent on these three examples will give the same sensible result. The textwrap dedent function will have a leading blank line with 1st example.

Obvious disadvantage is that textwrap is in standard library while matplotlib is external module.

Some tradeoffs here... the dedent functions make your code more readable where the strings get defined, but require processing later to get the string in usable format. In docstrings it is obvious that you should use correct indentation as most uses of the docstring will do the required processing.

When I need a non long string in my code I find the following admittedly ugly code where I let the long string drop out of the enclosing indentation. Definitely fails on "Beautiful is better than ugly.", but one could argue that it is simpler and more explicit than the dedent alternative.

def example():
    long_string = '''\
Lorem ipsum dolor sit amet, consectetur adipisicing
elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip.\
'''
    return long_string

print example()

ArrayIndexOutOfBoundsException when using the ArrayList's iterator

You could also do a for loop as you would for an array but instead of array[i] you would use list.get(i)

for (int i = 0; i < list.size(); i++) {
    System.out.println(list.get(i));
}

Passing ArrayList from servlet to JSP

<html>
    <%

        ArrayList<Actor> list = new ArrayList<Actor>();
        list = (ArrayList<Actor>) request.getAttribute("actors");
    %>
<head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Actor</title>
</head>

<body>

    <h2>This is Actor Class</h2>
    <table>
        <thead>
            <tr>
                <th>Id</th>
                <th>First Name</th>
                <th>Last Name</th>
            </tr>
        </thead>
        <tbody>
            <% for(int i = 0; i < list.size(); i++) {
                Actor actor = new Actor();
                actor = list.get(i);
                //out.println(actor.getId());
                //out.println(actor.getFirstname());
                //out.println(actor.getLastname());
            %>


            <tr>
                <td><%=actor.getId()%></td>
                <td><%=actor.getFirstname()%></td>
                <td><%=actor.getLastname()%></td>
               </tr>
            <%
            };
            %>
        </tbody>
    </table>

</body>

Minimum rights required to run a windows service as a domain account

I do know that the account needs to have "Log on as a Service" privileges. Other than that, I'm not sure. A quick reference to Log on as a Service can be found here, and there is a lot of information of specific privileges here.

Using a BOOL property

There's no benefit to using properties with primitive types. @property is used with heap allocated NSObjects like NSString*, NSNumber*, UIButton*, and etc, because memory managed accessors are created for free. When you create a BOOL, the value is always allocated on the stack and does not require any special accessors to prevent memory leakage. isWorking is simply the popular way of expressing the state of a boolean value.

In another OO language you would make a variable private bool working; and two accessors: SetWorking for the setter and IsWorking for the accessor.

Can we execute a java program without a main() method?

Yes You can compile and execute without main method By using static block. But after static block executed (printed) you will get an error saying no main method found.

And Latest INFO --> YOU cant Do this with JAVA 7 version. IT will not execute.

{
    static
    {
        System.out.println("Hello World!");
        System.exit(0); // prevents “main method not found” error
    }
}

But this will not execute with JAVA 7 version.

Getting JavaScript object key list

If you only want the keys which are specific to that particular object and not any derived prototype properties:

function getKeys(obj) {
    var r = []
    for (var k in obj) {
        if (!obj.hasOwnProperty(k)) 
            continue
        r.push(k)
    }
    return r
}

e.g:

var keys = getKeys({'eggs': null, 'spam': true})
var length = keys.length // access the `length` property as usual for arrays

How to call VS Code Editor from terminal / command line

I use the following command to load a project quickly (in linux)

  1. cd into the project cd /project
  2. run command code pwd

similar steps can be used in other Os too.

Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)

This might be because the browser cannot access a file. I stumbled with this type of error when creating application with node.js. You can try to directly request the script file (copying and pasting url) and see if you can retrieve it. You can see then what the real problem is. It can be because of permission of folder in which the file is located, or browser just cannot find it due to incorrect path to it. In node.js, after specifying route to file, all works.

Debugging "Element is not clickable at point" error

If you're using the line below in your conf.js file, please comment it out and try again

browser.ignoreSynchronization = true;

How to automatically generate N "distinct" colors?

You can use the HSL color model to create your colors.

If all you want is differing hues (likely), and slight variations on lightness or saturation, you can distribute the hues like so:

// assumes hue [0, 360), saturation [0, 100), lightness [0, 100)

for(i = 0; i < 360; i += 360 / num_colors) {
    HSLColor c;
    c.hue = i;
    c.saturation = 90 + randf() * 10;
    c.lightness = 50 + randf() * 10;

    addColor(c);
}

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 102

You didn't bind all your bindings here

$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate     FROM comments WHERE articleid = :art 
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";

$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );

You've declared a binding called :numRows but you never actually bind anything to it.

UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion

Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.

In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)

How can I compare strings in C using a `switch` statement?

Assuming little endianness and sizeof(char) == 1, you could do that (something like this was suggested by MikeBrom).

char* txt = "B1";
int tst = *(int*)txt;
if ((tst & 0x00FFFFFF) == '1B')
    printf("B1!\n");

It could be generalized for BE case.

Regular expression that matches valid IPv6 addresses

This regular expression will match valid IPv6 and IPv4 addresses in accordance with GNU C++ implementation of regex with REGULAR EXTENDED mode used:

"^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:)))(%.+)?\s*$"

Howto: Clean a mysql InnoDB storage engine?

The InnoDB engine does not store deleted data. As you insert and delete rows, unused space is left allocated within the InnoDB storage files. Over time, the overall space will not decrease, but over time the 'deleted and freed' space will be automatically reused by the DB server.

You can further tune and manage the space used by the engine through an manual re-org of the tables. To do this, dump the data in the affected tables using mysqldump, drop the tables, restart the mysql service, and then recreate the tables from the dump files.

Enable/disable buttons with Angular

Set a property for the current lesson: currentLesson. It will hold, obviously, the 'number' of the choosen lesson. On each button click, set the currentLesson value to 'number'/ order of the button, i.e. for the first button, it will be '1', for the second '2' and so on. Each button now can be disabled with [disabled] attribute, if it the currentLesson is not the same as it's order.

HTML

  <button  (click)="currentLesson = '1'"
         [disabled]="currentLesson !== '1'" class="primair">
           Start lesson</button>
  <button (click)="currentLesson = '2'"
         [disabled]="currentLesson !== '2'" class="primair">
           Start lesson</button>
 .....//so on

Typescript

currentLesson:string;

  classes = [
{
  name: 'string',
  level: 'string',
  code: 'number',
  currentLesson: '1'
}]

constructor(){
  this.currentLesson=this.classes[0].currentLesson
}

DEMO

Putting everything in a loop:

HTML

<div *ngFor="let class of classes; let i = index">
   <button [disabled]="currentLesson !== i + 1" class="primair">
           Start lesson {{i +  1}}</button>
</div>

Typescript

currentLesson:string;

classes = [
{
  name: 'Lesson1',
  level: 1,
  code: 1,
},{
  name: 'Lesson2',
  level: 1,
  code: 2,
},
{
  name: 'Lesson3',
  level: 2,
  code: 3,
}]

DEMO

Position a CSS background image x pixels from the right?

Works for all real browsers (and for IE9+):

background-position: right 10px top 10px;

I use it to RTL WordPress themes. See example: temporary website or the real website will be up soon. Look at the icons at the big DIVs right corners.

Using LINQ to group by multiple properties and sum

Linus is spot on in the approach, but a few properties are off. It looks like 'AgencyContractId' is your Primary Key, which is unrelated to the output you want to give the user. I think this is what you want (assuming you change your ViewModel to match the data you say you want in your view).

var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
                   {
                       ac.AgencyID,
                       ac.VendorID,
                       ac.RegionID
                   })
    .Select(ac => new AgencyContractViewModel
                   {
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Total = ac.Sum(acs => acs.Amount) + ac.Sum(acs => acs.Fee)
                   });

BASH Syntax error near unexpected token 'done'

Open new file named foobar

nano -w foobar

Input script

 #!/bin/bash
 while [ 0 = 0 ]; do
   echo "Press [CTRL+C] to stop.."
   sleep 1
 done;

Exit and save

CTRL+X then Y and Enter

Set script executable and run

chmod +x foobar
./foobar

Why is SQL Server 2008 Management Studio Intellisense not working?

I tried all the fixes - taking databases offline and then bringing them online, installed Cumulative update 10, repaired SQL Server Installation, refreshed local cache, made changes to the required settings on SQL Server Management Studio but everything was in vain. Finally installing the correct service pack (SP1) did the trick for me !

Follow the link below, and download SQLServer2008R2SP1-KB2528583-x86-ENU.exe (or the x64 file for a x64 bit instance of SQL Server)

http://www.microsoft.com/download/en/details.aspx?id=26727

Finally i have Intellisense enabled !

drag drop files into standard html file input

For anyone who's looking to do this in 2018, I've got a much better and simpler solution then all the old stuff posted here. You can make a nice looking drag & drop box with just vanilla HTML, JavaScript and CSS.

(Only works in Chrome so far)

Let's start with the HTML.

<div>
<input type="file" name="file" id="file" class="file">
<span id="value"></span>
</div>

Then we'll get to the styling.

    .file {
        width: 400px;
        height: 50px;
        background: #171717;
        padding: 4px;
        border: 1px dashed #333;
        position: relative;
        cursor: pointer;
    }

    .file::before {
        content: '';
        position: absolute;
        background: #171717;
        font-size: 20px;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 100%;
        height: 100%;
    }

    .file::after {
        content: 'Drag & Drop';
        position: absolute;
        color: #808080;
        font-size: 20px;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }

After you've done this it already looks fine. But I imagine you'd like to see what file you actaully uploaded, so we're going to do some JavaScript. Remember that pfp-value span? That's where we'll print out the file name.

let file = document.getElementById('file');
file.addEventListener('change', function() {
    if(file && file.value) {
        let val = file.files[0].name;
        document.getElementById('value').innerHTML = "Selected" + val;
    }
});

And that's it.

How to remove empty cells in UITableView?

override func viewWillAppear(animated: Bool) {
    self.tableView.tableFooterView = UIView(frame: CGRect.zeroRect)

/// OR 

    self.tableView.tableFooterView = UIView()
}

How to Use Multiple Columns in Partition By And Ensure No Duplicate Row is Returned

Try this, It worked for me

SELECT * FROM (
            SELECT
                [Code],
                [Name],
                [CategoryCode],
                [CreatedDate],
                [ModifiedDate],
                [CreatedBy],
                [ModifiedBy],
                [IsActive],
                ROW_NUMBER() OVER(PARTITION BY [Code],[Name],[CategoryCode] ORDER BY ID DESC) rownumber
            FROM MasterTable
          ) a
        WHERE rownumber = 1 

Appending output of a Batch file To log file

This is not an answer to your original question: "Appending output of a Batch file To log file?"

For reference, it's an answer to your followup question: "What lines should i add to my batch file which will make it execute after every 30mins?"

(But I would take Jon Skeet's advice: "You probably shouldn't do that in your batch file - instead, use Task Scheduler.")

Timeout:

Example (1 second):

TIMEOUT /T 1000 /NOBREAK

Sleep:

Example (1 second):

sleep -m 1000

Alternative methods:

Here's an answer to your 2nd followup question: "Along with the Timestamp?"

Create a date and time stamp in your batch files

Example:

echo *** Date: %DATE:/=-% and Time:%TIME::=-% *** >> output.log

Java Timer vs ExecutorService?

According to Java Concurrency in Practice:

  • Timer can be sensitive to changes in the system clock, ScheduledThreadPoolExecutor isn't.
  • Timer has only one execution thread, so long-running task can delay other tasks. ScheduledThreadPoolExecutor can be configured with any number of threads. Furthermore, you have full control over created threads, if you want (by providing ThreadFactory).
  • Runtime exceptions thrown in TimerTask kill that one thread, thus making Timer dead :-( ... i.e. scheduled tasks will not run anymore. ScheduledThreadExecutor not only catches runtime exceptions, but it lets you handle them if you want (by overriding afterExecute method from ThreadPoolExecutor). Task which threw exception will be canceled, but other tasks will continue to run.

If you can use ScheduledThreadExecutor instead of Timer, do so.

One more thing... while ScheduledThreadExecutor isn't available in Java 1.4 library, there is a Backport of JSR 166 (java.util.concurrent) to Java 1.2, 1.3, 1.4, which has the ScheduledThreadExecutor class.

Error message "Linter pylint is not installed"

The following fix works for me. In a Ubuntu 16.04 (Xenial Xerus) terminal, type:

$ pip3 install pylint
$ sudo apt install python3-pip

If your Python 3 is installed in the /usr/bin/python3.6 folder, run the following command, and it should work fine. Last, make sure your Visual Studio Code is running the Python 3 interpreter, not Python 2.7 which is default in Ubuntu.

$ /usr/bin/python3.6 -m pip install -U pylint

Format string to a 3 digit number

This is how it's done using string interpolation C# 7

$"{myString:000}"

Regex to replace everything except numbers and a decimal point

Check the link Regular Expression Demo

use the below reg exp

[a-z] + [^0-9\s.]+|.(?!\d)

PHP: Get the key from an array in a foreach loop

you need nested foreach loops

foreach($samplearr as $key => $item){
   echo $key;
    foreach($item as $detail){
       echo $detail['value1'] . " " . $detail['value2']
     }
 }

what is the difference between const_iterator and iterator?

Performance wise there is no difference. The only purpose of having const_iterator over iterator is to manage the accessesibility of the container on which the respective iterator runs. You can understand it more clearly with an example:

std::vector<int> integers{ 3, 4, 56, 6, 778 };

If we were to read & write the members of a container we will use iterator:

for( std::vector<int>::iterator it = integers.begin() ; it != integers.end() ; ++it )
       {*it = 4;  std::cout << *it << std::endl; }

If we were to only read the members of the container integers you might wanna use const_iterator which doesn't allow to write or modify members of container.

for( std::vector<int>::const_iterator it = integers.begin() ; it != integers.end() ; ++it )
       { cout << *it << endl; }

NOTE: if you try to modify the content using *it in second case you will get an error because its read-only.

Sending the bearer token with axios

If you want to some data after passing token in header so that try this code

const api = 'your api'; 
const token = JSON.parse(sessionStorage.getItem('data'));
const token = user.data.id; /*take only token and save in token variable*/
axios.get(api , { headers: {"Authorization" : `Bearer ${token}`} })
.then(res => {
console.log(res.data);
.catch((error) => {
  console.log(error)
});

Making button go full-width?

Bootstrap / CSS

Use col-12, btn-block, w-100, form-control or width:100%

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>

         <button class="btn btn-success col-12">
             class="col-12"
         </button>
    
         <button class="btn btn-primary w-100">
             class="w-100"
         </button>

         <button class="btn btn-secondary btn-block">
             class="btn-block"
         </button>
         
         <button class="btn btn-success form-control">
             class="form-control"
         </button>
         
         <button class="btn btn-danger" style="width:100%">
             style="width:100%"
         </button>
_x000D_
_x000D_
_x000D_

How do I correctly use "Not Equal" in MS Access?

Like this

SELECT DISTINCT Table1.Column1
FROM Table1
WHERE NOT EXISTS( SELECT * FROM Table2
    WHERE Table1.Column1 = Table2.Column1  )

You want NOT EXISTS, not "Not Equal"


By the way, you rarely want to write a FROM clause like this:

FROM Table1, Table2

as this means "FROM all combinations of every row in Table1 with every row in Table2..." Usually that's a lot more result rows than you ever want to see. And in the rare case that you really do want to do that, the more accepted syntax is:

FROM Table1 CROSS JOIN Table2

how to display data values on Chart.js

This animation option works for 2.1.3 on a bar chart.

Slightly modified @Ross answer

animation: {
duration: 0,
onComplete: function () {
    // render the value of the chart above the bar
    var ctx = this.chart.ctx;
    ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, 'normal', Chart.defaults.global.defaultFontFamily);
    ctx.fillStyle = this.chart.config.options.defaultFontColor;
    ctx.textAlign = 'center';
    ctx.textBaseline = 'bottom';
    this.data.datasets.forEach(function (dataset) {
        for (var i = 0; i < dataset.data.length; i++) {
            var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
            ctx.fillText(dataset.data[i], model.x, model.y - 5);
        }
    });
}}

How to trim a string after a specific character in java

you can use StringTokenizer:

StringTokenizer st = new StringTokenizer("34.1 -118.33\n<!--ABCDEFG-->", "\n");
System.out.println(st.nextToken());

output:

34.1 -118.33

Count number of rows per group and add result to original data frame

You can use ave:

df$count <- ave(df$num, df[,c("name","type")], FUN=length)

Setting environment variable in react-native?

[Source] From what I've found, it looks like by default, it's only possible to do production and development configs (no staging or other environments) – is that right?

Right now, I've been using a environment.js file that can be used to detect expo release channels and change the variables returned based on that, but for building, I need to update the non- DEV variable returned to be either staging or prod:

import { Constants } from 'expo';
import { Platform } from 'react-native';
const localhost = Platform.OS === 'ios' ? 'http://localhost:4000/' : 'http://10.0.2.2:4000/';
const ENV = {
  dev: {
    apiUrl: localhost,
  },
  staging: {
    apiUrl: 'https://your-staging-api-url-here.com/'
  },
  prod: {
    apiUrl: 'https://your-prod-api-url-here.com/'
  },
}
const getEnvVars = (env = Constants.manifest.releaseChannel) => {
  // What is __DEV__ ?
  // This variable is set to true when react-native is running in Dev mode.
  // __DEV__ is true when run locally, but false when published.
  if (__DEV__) {
    return ENV.dev;
  } else {
    // When publishing to production, change this to `ENV.prod` before running an `expo build`
    return ENV.staging;
  }
}
export default getEnvVars;

Alternatives

does anyone have experience using react-native-dotenv for projects built with expo? I'd love to hear your thoughts

https://github.com/goatandsheep/react-native-dotenv

RegExp in TypeScript

In typescript, the declaration is something like this:

const regex : RegExp = /.+\*.+/;

using RegExp constructor:

const regex = new RegExp('.+\\*.+');

Evaluate expression given as a string

The eval() function evaluates an expression, but "5+5" is a string, not an expression. Use parse() with text=<string> to change the string into an expression:

> eval(parse(text="5+5"))
[1] 10
> class("5+5")
[1] "character"
> class(parse(text="5+5"))
[1] "expression"

Calling eval() invokes many behaviours, some are not immediately obvious:

> class(eval(parse(text="5+5")))
[1] "numeric"
> class(eval(parse(text="gray")))
[1] "function"
> class(eval(parse(text="blue")))
Error in eval(expr, envir, enclos) : object 'blue' not found

See also tryCatch.

How to directly execute SQL query in C#?

To execute your command directly from within C#, you would use the SqlCommand class.

Quick sample code using paramaterized SQL (to avoid injection attacks) might look like this:

string queryString = "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday  FROM  [dbo].[TPatientRaw] WHERE tPatSName = @tPatSName";
string connectionString = "Server=.\PDATA_SQLEXPRESS;Database=;User Id=sa;Password=2BeChanged!;";

using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand(queryString, connection);
    command.Parameters.AddWithValue("@tPatSName", "Your-Parm-Value");
    connection.Open();
    SqlDataReader reader = command.ExecuteReader();
    try
    {
        while (reader.Read())
        {
            Console.WriteLine(String.Format("{0}, {1}",
            reader["tPatCulIntPatIDPk"], reader["tPatSFirstname"]));// etc
        }
    }
    finally
    {
        // Always call Close when done reading.
        reader.Close();
    }
}

How to set timer in android?

for whom wants to do this in kotlin:

val timer = fixedRateTimer(period = 1000L) {
            val currentTime: Date = Calendar.getInstance().time
            runOnUiThread {
                tvFOO.text = currentTime.toString()
            }
        }

for stopping the timer you can use this:

timer.cancel()

this function has many other options, give it a try

Check If array is null or not in php

I understand what you want. You want to check every data of the array if all of it is empty or at least 1 is not empty

Empty array

Array ( [Tags] => SimpleXMLElement Object ( [0] => ) )

Not an Empty array

Array ( [Tags] => SimpleXMLElement Object ( [0] =>,[1] => "s" ) )


I hope I am right. You can use this function to check every data of an array if at least 1 of them has a value.

/*
 return true if the array is not empty
 return false if it is empty
*/
function is_array_empty($arr){
  if(is_array($arr)){     
      foreach($arr $key => $value){
          if(!empty($value) || $value != NULL || $value != ""){
              return true;
              break;//stop the process we have seen that at least 1 of the array has value so its not empty
          }
      }
      return false;
  }
}

if(is_array_empty($result['Tags'])){
    //array is not empty
}else{
    //array is empty
}

Hope that helps.

How do you implement a class in C?

I had to do it once too for a homework. I followed this approach:

  1. Define your data members in a struct.
  2. Define your function members that take a pointer to your struct as first argument.
  3. Do these in one header & one c. Header for struct definition & function declarations, c for implementations.

A simple example would be this:

/// Queue.h
struct Queue
{
    /// members
}
typedef struct Queue Queue;

void push(Queue* q, int element);
void pop(Queue* q);
// etc.
/// 

How to trigger a file download when clicking an HTML button or JavaScript

I think this is the solution you were looking for

<button type="submit" onclick="window.location.href='file.doc'">Download!</button>

I hade a case where my Javascript generated a CSV file. Since there is no remote URL to download it I use the following implementation.

downloadCSV: function(data){
    var MIME_TYPE = "text/csv";

    var blob = new Blob([data], {type: MIME_TYPE});
    window.location.href = window.URL.createObjectURL(blob);
}

Regular Expression: Any character that is NOT a letter or number

To match anything other than letter or number you could try this:

[^a-zA-Z0-9]

And to replace:

var str = 'dfj,dsf7lfsd .sdklfj';
str = str.replace(/[^A-Za-z0-9]/g, ' ');

How can I use UIColorFromRGB in Swift?

This is a nice extension for UIColor. You can use enum values(hex, string) and direct string values when you creating UIColor objects.

The extension we deserve https://github.com/ioramashvili/UsefulExtensions/blob/master/Extensions.playground/Pages/UIColor.xcplaygroundpage/Contents.swift

Add error bars to show standard deviation on a plot in R

In addition to @csgillespie's answer, segments is also vectorised to help with this sort of thing:

plot (x, y, ylim=c(0,6))
segments(x,y-sd,x,y+sd)
epsilon <- 0.02
segments(x-epsilon,y-sd,x+epsilon,y-sd)
segments(x-epsilon,y+sd,x+epsilon,y+sd)

enter image description here

How to get HttpContext.Current in ASP.NET Core?

There is a solution to this if you really need a static access to the current context. In Startup.Configure(….)

app.Use(async (httpContext, next) =>
{
    CallContext.LogicalSetData("CurrentContextKey", httpContext);
    try
    {
        await next();
    }
    finally
    {
        CallContext.FreeNamedDataSlot("CurrentContextKey");
    }
});

And when you need it you can get it with :

HttpContext context = CallContext.LogicalGetData("CurrentContextKey") as HttpContext;

I hope that helps. Keep in mind this workaround is when you don’t have a choice. The best practice is to use de dependency injection.

Validation for 10 digit mobile number and focus input field on invalid

_x000D_
_x000D_
var message = document.getElementById('contact-error');_x000D_
$('#contact').focusout(function(){_x000D_
 if(!$(this).val().match('[0-9]{10}'))  {_x000D_
  $('#contact-error').addClass('contact-message');_x000D_
        message.innerHTML = "required 10 digits, match requested format!";_x000D_
    }else {_x000D_
     $('#contact-error').removeClass('contact-message');_x000D_
     message.innerHTML = "";_x000D_
    }_x000D_
})
_x000D_
.contact-message {_x000D_
    display: block;_x000D_
    margin-bottom: 20px;_x000D_
    color: #cc0033;_x000D_
}
_x000D_
<input type="text" id="contact" required>_x000D_
<span id="contact-error"></span>
_x000D_
_x000D_
_x000D_

Open a Web Page in a Windows Batch FIle

You can use the start command to do much the same thing as ShellExecute. For example

 start "" http://www.stackoverflow.com

This will launch whatever browser is the default browser, so won't necessarily launch Internet Explorer.

Truncate Two decimal places without rounding

Would ((long)(3.4679 * 100)) / 100.0 give what you want?

jQuery issue in Internet Explorer 8

The solution in my case was to take any special characters out of the URL you're trying to access. I had a tilde (~) and a percentage symbol in there, and the $.get() call failed silently.

Use string.Contains() with switch()

switch(message)
{
  case "test":
    Console.WriteLine("yes");
    break;                
  default:
    if (Contains("test2")) {
      Console.WriteLine("yes for test2");
    }
    break;
}

Pass parameters in setInterval function

now with ES5, bind method Function prototype :

setInterval(funca.bind(null,10,3),500);

Reference here

BasicHttpBinding vs WsHttpBinding vs WebHttpBinding

You're comparing apples to oranges here:

  • webHttpBinding is the REST-style binding, where you basically just hit a URL and get back a truckload of XML or JSON from the web service

  • basicHttpBinding and wsHttpBinding are two SOAP-based bindings which is quite different from REST. SOAP has the advantage of having WSDL and XSD to describe the service, its methods, and the data being passed around in great detail (REST doesn't have anything like that - yet). On the other hand, you can't just browse to a wsHttpBinding endpoint with your browser and look at XML - you have to use a SOAP client, e.g. the WcfTestClient or your own app.

So your first decision must be: REST vs. SOAP (or you can expose both types of endpoints from your service - that's possible, too).

Then, between basicHttpBinding and wsHttpBinding, there differences are as follows:

  • basicHttpBinding is the very basic binding - SOAP 1.1, not much in terms of security, not much else in terms of features - but compatible to just about any SOAP client out there --> great for interoperability, weak on features and security

  • wsHttpBinding is the full-blown binding, which supports a ton of WS-* features and standards - it has lots more security features, you can use sessionful connections, you can use reliable messaging, you can use transactional control - just a lot more stuff, but wsHttpBinding is also a lot *heavier" and adds a lot of overhead to your messages as they travel across the network

For an in-depth comparison (including a table and code examples) between the two check out this codeproject article: Differences between BasicHttpBinding and WsHttpBinding

Wireshark vs Firebug vs Fiddler - pros and cons?

I use both Charles Proxy and Fiddler for my HTTP/HTTPS level debugging.

Pros of Charles Proxy:

  1. Handles HTTPS better (you get a Charles Certificate which you'd put in 'Trusted Authorities' list)
  2. Has more features like Load/Save Session (esp. useful when debugging multiple pages), Mirror a website (useful in caching assets and hence faster debugging), etc.
  3. As mentioned by jburgess, handles AMF.
  4. Displays JSON, XML and other kind of responses in a tree structure, making it easier to read. Displays images in image responses instead of binary data.

Cons of Charles Proxy:

  1. Cost :-)

What does [object Object] mean?

You have a javascript object

$1 and $2 are jquery objects, maybe use alert($1.text()); to get text or alert($1.attr('id'); etc...

you have to treat $1 and $2 like jQuery objects.

Apple Mach-O Linker Error when compiling for device

In my own case, I had duplicate declarations of some keys. I declared some NSString Constants using the extern keyword and did exactly the same thing in two different class files. When I removed one of them, the error disappeared.

extern NSString *const CFDataStatusKey;
extern NSString *const CFDataErrorKey;
extern NSString *const CFDataReasonKey;
extern NSString *const CFDataChannelsKey;

These where declared and initialized respectively in .h and .m files of the two classes. Removing a duplicate solved the issue. Hopes this helps

Is there a way to pass jvm args via command line to maven?

I think MAVEN_OPTS would be most appropriate for you. See here: http://maven.apache.org/configure.html

In Unix:

Add the MAVEN_OPTS environment variable to specify JVM properties, e.g. export MAVEN_OPTS="-Xms256m -Xmx512m". This environment variable can be used to supply extra options to Maven.

In Win, you need to set environment variable via the dialogue box

Add ... environment variable by opening up the system properties (WinKey + Pause),... In the same dialog, add the MAVEN_OPTS environment variable in the user variables to specify JVM properties, e.g. the value -Xms256m -Xmx512m. This environment variable can be used to supply extra options to Maven.

What is SELF JOIN and when would you use it?

SQL self-join simply is a normal join which is used to join a table to itself.

Example:

Select *
FROM Table t1, Table t2
WHERE t1.Id = t2.ID

Understanding MongoDB BSON Document size limit

I have not yet seen a problem with the limit that did not involve large files stored within the document itself. There are already a variety of databases which are very efficient at storing/retrieving large files; they are called operating systems. The database exists as a layer over the operating system. If you are using a NoSQL solution for performance reasons, why would you want to add additional processing overhead to the access of your data by putting the DB layer between your application and your data?

JSON is a text format. So, if you are accessing your data through JSON, this is especially true if you have binary files because they have to be encoded in uuencode, hexadecimal, or Base 64. The conversion path might look like

binary file <> JSON (encoded) <> BSON (encoded)

It would be more efficient to put the path (URL) to the data file in your document and keep the data itself in binary.

If you really want to keep these files of unknown length in your DB, then you would probably be better off putting these in GridFS and not risking killing your concurrency when the large files are accessed.

Postgresql - change the size of a varchar column to lower length

Here's the cache of the page described by Greg Smith. In case that dies as well, the alter statement looks like this:

UPDATE pg_attribute SET atttypmod = 35+4
WHERE attrelid = 'TABLE1'::regclass
AND attname = 'COL1';

Where your table is TABLE1, the column is COL1 and you want to set it to 35 characters (the +4 is needed for legacy purposes according to the link, possibly the overhead referred to by A.H. in the comments).

How to set 00:00:00 using moment.js

Moment.js stores dates it utc and can apply different timezones to it. By default it applies your local timezone. If you want to set time on utc date time you need to specify utc timezone.

Try the following code:

var m = moment().utcOffset(0);
m.set({hour:0,minute:0,second:0,millisecond:0})
m.toISOString()
m.format()

How to change font size in Eclipse for Java text editors?

Enter image description here

Menu Window ? Preferences. General ? Appearance ? Colors and Fonts ? Basic ? Text Font

Redirect HTTP to HTTPS on default virtual host without ServerName

I have use mkcert to create infinites *.dev.net subdomains & localhost with valid HTTPS/SSL certs (Windows 10 XAMPP & Linux Debian 10 Apache2)

I create the certs on Windows with mkcert v1.4.0 (execute CMD as Administrator):

mkcert -install
mkcert localhost "*.dev.net"

This create in Windows 10 this files (I will install it first in Windows 10 XAMPP)

localhost+1.pem
localhost+1-key.pem

Overwrite the XAMPP default certs:

copy "localhost+1.pem" C:\xampp\apache\conf\ssl.crt\server.crt
copy "localhost+1-key.pem"  C:\xampp\apache\conf\ssl.key\server.key

Now, in Apache2 for Debian 10, activate SSL & vhost_alias

a2enmod vhosts_alias
a2enmod ssl
a2ensite default-ssl
systemctl restart apache2

For vhost_alias add this Apache2 config:

nano /etc/apache2/sites-available/999-vhosts_alias.conf

With this content:

<VirtualHost *:80>
   UseCanonicalName Off
   ServerAlias *.dev.net
   VirtualDocumentRoot "/var/www/html/%0/"
</VirtualHost>

Add the site:

a2ensite 999-vhosts_alias

Copy the certs to /root/mkcert by SSH and let overwrite the Debian ones:

systemctl stop apache2

mv /etc/ssl/certs/ssl-cert-snakeoil.pem /etc/ssl/certs/ssl-cert-snakeoil.pem.bak
mv /etc/ssl/private/ssl-cert-snakeoil.key /etc/ssl/private/ssl-cert-snakeoil.key.bak

cp "localhost+1.pem" /etc/ssl/certs/ssl-cert-snakeoil.pem
cp "localhost+1-key.pem" /etc/ssl/private/ssl-cert-snakeoil.key

chown root:ssl-cert /etc/ssl/private/ssl-cert-snakeoil.key
chmod 640 /etc/ssl/private/ssl-cert-snakeoil.key

systemctl start apache2

Edit the SSL config

nano /etc/apache2/sites-enabled/default-ssl.conf

At the start edit the file with this content:

<IfModule mod_ssl.c>
    <VirtualHost *:443>

            UseCanonicalName Off
            ServerAlias *.dev.net
            ServerAdmin webmaster@localhost

            # DocumentRoot /var/www/html/
            VirtualDocumentRoot /var/www/html/%0/

...

Last restart:

systemctl restart apache2

NOTE: don´t forget to create the folders for your subdomains in /var/www/html/

/var/www/html/subdomain1.dev.net
/var/www/html/subdomain2.dev.net
/var/www/html/subdomain3.dev.net

Maximum on http header values?

HTTP does not place a predefined limit on the length of each header field or on the length of the header section as a whole, as described in Section 2.5. Various ad hoc limitations on individual header field length are found in practice, often depending on the specific field semantics.

HTTP Header values are restricted by server implementations. Http specification doesn't restrict header size.

A server that receives a request header field, or set of fields, larger than it wishes to process MUST respond with an appropriate 4xx (Client Error) status code. Ignoring such header fields would increase the server's vulnerability to request smuggling attacks (Section 9.5).

Most servers will return 413 Entity Too Large or appropriate 4xx error when this happens.

A client MAY discard or truncate received header fields that are larger than the client wishes to process if the field semantics are such that the dropped value(s) can be safely ignored without changing the message framing or response semantics.

Uncapped HTTP header size keeps the server exposed to attacks and can bring down its capacity to serve organic traffic.

Source

Delaying function in swift

 NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(3), target: self, selector: "functionHere", userInfo: nil, repeats: false)

This would call the function functionHere() with a 3 seconds delay

How to use andWhere and orWhere in Doctrine?

Why not just

$q->where("a = 1");
$q->andWhere("b = 1 OR b = 2");
$q->andWhere("c = 1 OR d = 2");

EDIT: You can also use the Expr class (Doctrine2).

how to call url of any other website in php

As other's have mentioned, PHP's cURL functions will allow you to perform advanced HTTP requests. You can also use file_get_contents to access REST APIs:

$payload = file_get_contents('http://api.someservice.com/SomeMethod?param=value');

Starting with PHP 5 you can also create a stream context which will allow you to change headers or post data to the service.

SELECT max(x) is returning null; how can I make it return 0?

Like this (for MySQL):

SELECT IFNULL(MAX(X), 0) AS MaxX
FROM tbl
WHERE XID = 1

For MSSQL replace IFNULL with ISNULL or for Oracle use NVL

Find out a Git branch creator

A branch is nothing but a commit pointer. As such, it doesn't track metadata like "who created me." See for yourself. Try cat .git/refs/heads/<branch> in your repository.

That written, if you're really into tracking this information in your repository, check out branch descriptions. They allow you to attach arbitrary metadata to branches, locally at least.

Also DarVar's answer below is a very clever way to get at this information.

Excluding Maven dependencies

Global exclusions look like they're being worked on, but until then...

From the Sonatype maven reference (bottom of the page):

Dependency management in a top-level POM is different from just defining a dependency on a widely shared parent POM. For starters, all dependencies are inherited. If mysql-connector-java were listed as a dependency of the top-level parent project, every single project in the hierarchy would have a reference to this dependency. Instead of adding in unnecessary dependencies, using dependencyManagement allows you to consolidate and centralize the management of dependency versions without adding dependencies which are inherited by all children. In other words, the dependencyManagement element is equivalent to an environment variable which allows you to declare a dependency anywhere below a project without specifying a version number.

As an example:

  <dependencies>
    <dependency>
      <groupId>commons-httpclient</groupId>
      <artifactId>commons-httpclient</artifactId>
      <version>3.1</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>3.0.5.RELEASE</version>
    </dependency>
  </dependencies>
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <exclusions>
          <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
          </exclusion>
        </exclusions>
      </dependency>
      <dependency>
        <groupId>commons-httpclient</groupId>
        <artifactId>commons-httpclient</artifactId>
        <exclusions>
          <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
          </exclusion>
        </exclusions>
      </dependency>
    </dependencies>
  </dependencyManagement>

It doesn't make the code less verbose overall, but it does make it less verbose where it counts. If you still want it less verbose you can follow these tips also from the Sonatype reference.

Can't access 127.0.0.1

In windows first check under services if world wide web publishing services is running. If not start it.

If you cannot find it switch on IIS features of windows: In 7,8,10 it is under control panel , "turn windows features on or off". Internet Information Services World Wide web services and Internet information Services Hostable Core are required. Not sure if there is another way to get it going on windows, but this worked for me for all browsers. You might need to add localhost or http:/127.0.0.1 to the trusted websites also under IE settings.

How to get folder path for ClickOnce application

ApplicationDeployment.CurrentDeployment.ActivationUri might work

"A zero-length string if the TrustUrlParameters property in the deployment manifest is false, or if the user has supplied a UNC to open the deployment or has opened it locally. Otherwise, the return value is the full URL used to launch the application, including any parameters."


BUT what I think you really want is ApplicationDeployment.CurrentDeployment.DataDirectory which gives you a folder you can write data to. When you update the application anyways you'll lose what was in the original .exe folder, but you can migrate the data directory over to a new version of the app. Your app can write to this folder with whatever log files it has - and I'm pretty sure its guaranteed to be writable.

Creating CSS Global Variables : Stylesheet theme management

I do it this way:

The html:

<head>
    <style type="text/css"> <? require_once('xCss.php'); ?> </style>
</head>

The xCss.php:

<? // place here your vars
$fntBtn = 'bold 14px  Arial'
$colBorder  = '#556677' ;
$colBG0     = '#dddddd' ;
$colBG1     = '#44dddd' ;
$colBtn     = '#aadddd' ;

// here goes your css after the php-close tag: 
?>
button { border: solid 1px <?= $colBorder; ?>; border-radius:4px; font: <?= $fntBtn; ?>; background-color:<?= $colBtn; ?>; }