Programs & Examples On #Cognos

Cognos is an IBM subsidiary which provides a range of business intelligence and performance management products.

Get filename from file pointer

You can get the path via fp.name. Example:

>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'

You might need os.path.basename if you want only the file name:

>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'

File object docs (for Python 2) here.

Git push existing repo to a new and different remote repo server?

There is a deleted answer on this question that had a useful link: https://help.github.com/articles/duplicating-a-repository

The gist is

0. create the new empty repository (say, on github)
1. make a bare clone of the repository in some temporary location
2. change to the temporary location
3. perform a mirror-push to the new repository
4. change to another location and delete the temporary location

OP's example:

On your local machine

$ cd $HOME
$ git clone --bare https://git.fedorahosted.org/the/path/to/my_repo.git
$ cd my_repo.git
$ git push --mirror https://github.com/my_username/my_repo.git
$ cd ..
$ rm -rf my_repo.git

Adding delay between execution of two following lines

If you're targeting iOS 4.0+, you can do the following:

[executing first operation];
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    [executing second operation];
});

Maven error "Failure to transfer..."

I had a similar issue with only a few projects in my workspace. Other projects with nearly identical POMs didn't have an error at all. None of the other answers listed fixed my problem. I finally stumbled upon removing/re-applying the Maven nature for each project and the errors disappeared:

For each project that has a pom with the "resolution will not be reattempted..." error:

  1. Right-click on the project in Eclipse and select Maven->Disable Maven Nature
  2. Right-click on the project in Eclipse and select Configure->Convert to Maven Project

Importing a csv into mysql via command line

Most answers missing an important point like if you have created csv file exported from Microsoft Excel on windows and importing the same in linux environment, you will get unexpected result.

the correct syntax would be

load data local infile 'file.csv' into table table fields terminated by ',' enclosed by '"' lines terminated by '\r\n'

here the difference is '\r\n' as against simply '\n

Visual Studio Community 2015 expiration date

There is and there isn't an expiration date. If you register Visual Studio 2015 Community Edition by successfully signing into Visual Studio then the product is fully unlocked with no set expiry date. If you don't sign in (or haven't entered a purchased licence key), you only have 30 day evaluation license.

You can check whether your copy of Visual Studio has is registered or not by selecting Help -> About Microsoft Studio and clicking on the "License Status" link in the upper right of the About dialog. If your product isn't registered you'll see something like this:

Visual Studio 2015 License Status Window

IIS7 Settings File Locations

It sounds like you're looking for applicationHost.config, which is located in C:\Windows\System32\inetsrv\config.

Yes, it's an XML file, and yes, editing the file by hand will affect the IIS config after a restart. You can think of IIS Manager as a GUI front-end for editing applicationHost.config and web.config.

Ping site and return result in PHP

function urlExists($url=NULL)  
{  
    if($url == NULL) return false;  
    $ch = curl_init($url);  
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);  
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
    $data = curl_exec($ch);  
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
    curl_close($ch);  
    if($httpcode>=200 && $httpcode<300){  
        return true;  
    } else {  
        return false;  
    }  
}  

This was grabbed from this post on how to check if a URL exists. Because Twitter should provide an error message above 300 when it is in maintenance, or a 404, this should work perfectly.

How to run a makefile in Windows?

If you install Cygwin. Make sure to select make in the installer. You can then run the following command provided you have a Makefile.

make -f Makefile

https://cygwin.com/install.html

CMake unable to determine linker language with C++

By default the JNI Native folder is named as jni . Renaming it to cpp fixed the issue

Detect if range is empty

Another possible solution. Count empty cells and subtract that value from the total number of cells

Sub Emptys()

Dim r As range
Dim totalCells As Integer

'My range To check'
Set r = ActiveSheet.range("A1:B5")

'Check for filled cells'
totalCells = r.Count- WorksheetFunction.CountBlank(r)


If totalCells = 0 Then
    MsgBox "Range is empty"
Else
    MsgBox "Range is not empty"
End If

End Sub

How to change color of Android ListView separator line?

Use android:divider="#FF0000" and android:dividerHeight="2px" for ListView.

<ListView 
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="#0099FF"
android:dividerHeight="2px"/>

'do...while' vs. 'while'

I use do-while loops all the time when reading in files. I work with a lot of text files that include comments in the header:

# some comments
# some more comments
column1 column2
  1.234   5.678
  9.012   3.456
    ...     ...

i'll use a do-while loop to read up to the "column1 column2" line so that I can look for the column of interest. Here's the pseudocode:

do {
    line = read_line();
} while ( line[0] == '#');
/* parse line */

Then I'll do a while loop to read through the rest of the file.

Git submodule update

This GitPro page does summarize the consequence of a git submodule update nicely

When you run git submodule update, it checks out the specific version of the project, but not within a branch. This is called having a detached head — it means the HEAD file points directly to a commit, not to a symbolic reference.
The issue is that you generally don’t want to work in a detached head environment, because it’s easy to lose changes.
If you do an initial submodule update, commit in that submodule directory without creating a branch to work in, and then run git submodule update again from the superproject without committing in the meantime, Git will overwrite your changes without telling you. Technically you won’t lose the work, but you won’t have a branch pointing to it, so it will be somewhat difficult to retrieve.


Note March 2013:

As mentioned in "git submodule tracking latest", a submodule now (git1.8.2) can track a branch.

# add submodule to track master branch
git submodule add -b master [URL to Git repo];

# update your submodule
git submodule update --remote 
# or (with rebase)
git submodule update --rebase --remote

See "git submodule update --remote vs git pull".

MindTooth's answer illustrate a manual update (without local configuration):

git submodule -q foreach git pull -q origin master

In both cases, that will change the submodules references (the gitlink, a special entry in the parent repo index), and you will need to add, commit and push said references from the main repo.
Next time you will clone that parent repo, it will populate the submodules to reflect those new SHA1 references.

The rest of this answer details the classic submodule feature (reference to a fixed commit, which is the all point behind the notion of a submodule).


To avoid this issue, create a branch when you work in a submodule directory with git checkout -b work or something equivalent. When you do the submodule update a second time, it will still revert your work, but at least you have a pointer to get back to.

Switching branches with submodules in them can also be tricky. If you create a new branch, add a submodule there, and then switch back to a branch without that submodule, you still have the submodule directory as an untracked directory:


So, to answer your questions:

can I create branches/modifications and use push/pull just like I would in regular repos, or are there things to be cautious about?

You can create a branch and push modifications.

WARNING (from Git Submodule Tutorial): Always publish (push) the submodule change before publishing (push) the change to the superproject that references it. If you forget to publish the submodule change, others won't be able to clone the repository.

how would I advance the submodule referenced commit from say (tagged) 1.0 to 1.1 (even though the head of the original repo is already at 2.0)

The page "Understanding Submodules" can help

Git submodules are implemented using two moving parts:

  • the .gitmodules file and
  • a special kind of tree object.

These together triangulate a specific revision of a specific repository which is checked out into a specific location in your project.


From the git submodule page

you cannot modify the contents of the submodule from within the main project

100% correct: you cannot modify a submodule, only refer to one of its commits.

This is why, when you do modify a submodule from within the main project, you:

  • need to commit and push within the submodule (to the upstream module), and
  • then go up in your main project, and re-commit (in order for that main project to refer to the new submodule commit you just created and pushed)

A submodule enables you to have a component-based approach development, where the main project only refers to specific commits of other components (here "other Git repositories declared as sub-modules").

A submodule is a marker (commit) to another Git repository which is not bound by the main project development cycle: it (the "other" Git repo) can evolves independently.
It is up to the main project to pick from that other repo whatever commit it needs.

However, should you want to, out of convenience, modify one of those submodules directly from your main project, Git allows you to do that, provided you first publish those submodule modifications to its original Git repo, and then commit your main project refering to a new version of said submodule.

But the main idea remains: referencing specific components which:

  • have their own lifecycle
  • have their own set of tags
  • have their own development

The list of specific commits you are refering to in your main project defines your configuration (this is what Configuration Management is all about, englobing mere Version Control System)

If a component could really be developed at the same time as your main project (because any modification on the main project would involve modifying the sub-directory, and vice-versa), then it would be a "submodule" no more, but a subtree merge (also presented in the question Transferring legacy code base from cvs to distributed repository), linking the history of the two Git repo together.

Does that help understanding the true nature of Git Submodules?

Does Index of Array Exist

What exactly do you mean by "is a valid element"? You could just do:

if (array.Length >= 26)

which would tell you whether 25 is a valid index into the array or not (assuming a 0 lower bound).

If you need to know whether it's non-null or not, just use:

if (array[25] != null)

(or a combination of the two).

If these don't help, please give a more precise meaning of "valid" for your problem.

How to use pip with Python 3.x alongside Python 2.x

Thought this is old question, I think I have better solution

  1. To use pip for a python 2.x environment, use this command -

    py -2 -m pip install -r requirements.txt

  2. To use pip for python 3.x environment, use this command -

    py -3 -m pip install -r requirements.txt

How to change the map center in Leaflet.js

Use map.panTo(); does not do anything if the point is in the current view. Use map.setView() instead.

I had a polyline and I had to center map to a new point in polyline at every second. Check the code : GOOD: https://jsfiddle.net/nstudor/xcmdwfjk/

mymap.setView(point, 11, { animation: true });        

BAD: https://jsfiddle.net/nstudor/Lgahv905/

mymap.panTo(point);
mymap.setZoom(11);

Python: Importing urllib.quote

This is how I handle this, without using exceptions.

import sys
if sys.version_info.major > 2:  # Python 3 or later
    from urllib.parse import quote
else:  # Python 2
    from urllib import quote

Best practice when adding whitespace in JSX

Because &nbsp causes you to have non-breaking spaces, you should only use it where necessary. In most cases, this will have unintended side effects.

Older versions of React, I believe all those before v14, would automatically insert <span> </span> when you had a newline inside of a tag.

While they no longer do this, that's a safe way to handle this in your own code. Unless you have styling that specifically targets span (bad practice in general), then this is the safest route.

Per your example, you can put them on a single line together as it's pretty short. In longer-line scenarios, this is how you should probably do it:

  <div className="top-element-formatting">
    Hello <span className="second-word-formatting">World!</span>
    <span> </span>
    So much more text in this box that it really needs to be on another line.
  </div>

This method is also safe against auto-trimming text editors.

The other method is using {' '} which doesn't insert random HTML tags. This could be more useful when styling, highlighting elements, and removes clutter from the DOM. If you don't need backwards compatibility with React v14 or earlier, this should be your preferred method.

  <div className="top-element-formatting">
    Hello <span className="second-word-formatting">World!</span>
    {' '}
    So much more text in this box that it really needs to be on another line.
  </div>

Recyclerview and handling different type of row inflation

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

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

The Adapter exposes two methods which you should override:

getItemViewType(int position)

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

createViewHolder(ViewGroup parent, int viewType)

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

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

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

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

Here's a code sample:

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

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

public class MyAdapter extends Adapter<ViewHolder> {

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

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


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

        final int itemType = getItemViewType(position);

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

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

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

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

public MyHeaderViewHolder extends ViewHolder {

    private TextView headerLabel;    

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

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

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


public MyNormalViewHolder extends ViewHolder {

    private TextView titleLabel;
    private TextView descriptionLabel;    

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

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

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

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

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

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

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

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

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

    myData = data.toArray();
}

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

How to get video duration, dimension and size in PHP?

If you have FFMPEG installed on your server (http://www.mysql-apache-php.com/ffmpeg-install.htm), it is possible to get the attributes of your video using the command "-vstats" and parsing the result with some regex - as shown in the example below. Then, you need the PHP funtion filesize() to get the size.

$ffmpeg_path = 'ffmpeg'; //or: /usr/bin/ffmpeg , or /usr/local/bin/ffmpeg - depends on your installation (type which ffmpeg into a console to find the install path)
$vid = 'PATH/TO/VIDEO'; //Replace here!

 if (file_exists($vid)) {

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime_type = finfo_file($finfo, $vid); // check mime type
    finfo_close($finfo);

    if (preg_match('/video\/*/', $mime_type)) {

        $video_attributes = _get_video_attributes($vid, $ffmpeg_path);

        print_r('Codec: ' . $video_attributes['codec'] . '<br/>');

        print_r('Dimension: ' . $video_attributes['width'] . ' x ' . $video_attributes['height'] . ' <br/>');

        print_r('Duration: ' . $video_attributes['hours'] . ':' . $video_attributes['mins'] . ':'
                . $video_attributes['secs'] . '.' . $video_attributes['ms'] . '<br/>');

        print_r('Size:  ' . _human_filesize(filesize($vid)));

    } else {
        print_r('File is not a video.');
    }
} else {
    print_r('File does not exist.');
}

function _get_video_attributes($video, $ffmpeg) {

    $command = $ffmpeg . ' -i ' . $video . ' -vstats 2>&1';
    $output = shell_exec($command);

    $regex_sizes = "/Video: ([^,]*), ([^,]*), ([0-9]{1,4})x([0-9]{1,4})/"; // or : $regex_sizes = "/Video: ([^\r\n]*), ([^,]*), ([0-9]{1,4})x([0-9]{1,4})/"; (code from @1owk3y)
    if (preg_match($regex_sizes, $output, $regs)) {
        $codec = $regs [1] ? $regs [1] : null;
        $width = $regs [3] ? $regs [3] : null;
        $height = $regs [4] ? $regs [4] : null;
    }

    $regex_duration = "/Duration: ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}).([0-9]{1,2})/";
    if (preg_match($regex_duration, $output, $regs)) {
        $hours = $regs [1] ? $regs [1] : null;
        $mins = $regs [2] ? $regs [2] : null;
        $secs = $regs [3] ? $regs [3] : null;
        $ms = $regs [4] ? $regs [4] : null;
    }

    return array('codec' => $codec,
        'width' => $width,
        'height' => $height,
        'hours' => $hours,
        'mins' => $mins,
        'secs' => $secs,
        'ms' => $ms
    );
}

function _human_filesize($bytes, $decimals = 2) {
    $sz = 'BKMGTP';
    $factor = floor((strlen($bytes) - 1) / 3);
    return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}

How to create EditText with rounded corners?

Just to add to the other answers, I found that the simplest solution to achieve the rounded corners was to set the following as a background to your Edittext.

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

    <solid android:color="@android:color/white"/>
    <corners android:radius="8dp"/>

</shape>

Rails update_attributes without save?

You can use the 'attributes' method:

@car.attributes = {:model => 'Sierra', :years => '1990', :looks => 'Sexy'}

Source: http://api.rubyonrails.org/classes/ActiveRecord/Base.html

attributes=(new_attributes, guard_protected_attributes = true) Allows you to set all the attributes at once by passing in a hash with keys matching the attribute names (which again matches the column names).

If guard_protected_attributes is true (the default), then sensitive attributes can be protected from this form of mass-assignment by using the attr_protected macro. Or you can alternatively specify which attributes can be accessed with the attr_accessible macro. Then all the attributes not included in that won’t be allowed to be mass-assigned.

class User < ActiveRecord::Base
  attr_protected :is_admin
end

user = User.new
user.attributes = { :username => 'Phusion', :is_admin => true }
user.username   # => "Phusion"
user.is_admin?  # => false

user.send(:attributes=, { :username => 'Phusion', :is_admin => true }, false)
user.is_admin?  # => true

Escape text for HTML

You can use actual html tags <xmp> and </xmp> to output the string as is to show all of the tags in between the xmp tags.

Or you can also use on the server Server.UrlEncode or HttpUtility.HtmlEncode.

How to stop event propagation with inline onclick attribute?

For ASP.NET web pages (not MVC), you can use Sys.UI.DomEvent object as wrapper of native event.

<div onclick="event.stopPropagation();" ...

or, pass event as a parameter to inner function:

<div onclick="someFunction(event);" ...

and in someFunction:

function someFunction(event){
    event.stopPropagation(); // here Sys.UI.DomEvent.stopPropagation() method is used
    // other onclick logic
}

jQuery selectors on custom data attributes using HTML5

jsFiddle Demo

jQuery provides several selectors (full list) in order to make the queries you are looking for work. To address your question "In other cases is it possible to use other selectors like "contains, less than, greater than, etc..."." you can also use contains, starts with, and ends with to look at these html5 data attributes. See the full list above in order to see all of your options.

The basic querying has been covered above, and using John Hartsock's answer is going to be the best bet to either get every data-company element, or to get every one except Microsoft (or any other version of :not).

In order to expand this to the other points you are looking for, we can use several meta selectors. First, if you are going to do multiple queries, it is nice to cache the parent selection.

var group = $('ul[data-group="Companies"]');

Next, we can look for companies in this set who start with G

var google = $('[data-company^="G"]',group);//google

Or perhaps companies which contain the word soft

var microsoft = $('[data-company*="soft"]',group);//microsoft

It is also possible to get elements whose data attribute's ending matches

var facebook = $('[data-company$="book"]',group);//facebook

_x000D_
_x000D_
//stored selector_x000D_
var group = $('ul[data-group="Companies"]');_x000D_
_x000D_
//data-company starts with G_x000D_
var google = $('[data-company^="G"]',group).css('color','green');_x000D_
_x000D_
//data-company contains soft_x000D_
var microsoft = $('[data-company*="soft"]',group).css('color','blue');_x000D_
_x000D_
//data-company ends with book_x000D_
var facebook = $('[data-company$="book"]',group).css('color','pink');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<ul data-group="Companies">_x000D_
  <li data-company="Microsoft">Microsoft</li>_x000D_
  <li data-company="Google">Google</li>_x000D_
  <li data-company ="Facebook">Facebook</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Java: Static vs inner class

Discussing nested classes...

The difference is that a nested class declaration that is also static can be instantiated outside of the enclosing class.

When you have a nested class declaration that is not static, Java won't let you instantiate it except via the enclosing class. The object created out of the inner class is linked to the object created from the outer class, so the inner class can reference the fields of the outer.

But if it's static, then the link does not exist, the outer fields cannot be accessed (except via an ordinary reference like any other object) and you can therefore instantiate the nested class by itself.

How to hide a <option> in a <select> menu with CSS?

Simple answer: You can't. Form elements have very limited styling capabilities.

The best alternative would be to set disabled=true on the option (and maybe a gray colour, since only IE does that automatically), and this will make the option unclickable.

Alternatively, if you can, completely remove the option element.

generate a random number between 1 and 10 in c

srand(time(NULL));

int nRandonNumber = rand()%((nMax+1)-nMin) + nMin;
printf("%d\n",nRandonNumber);

Javascript seconds to minutes and seconds

The Following function will help you to get Days , Hours , Minutes , seconds

toDDHHMMSS(inputSeconds){
        const Days = Math.floor( inputSeconds / (60 * 60 * 24) );
        const Hour = Math.floor((inputSeconds % (60 * 60 * 24)) / (60 * 60));
        const Minutes = Math.floor(((inputSeconds % (60 * 60 * 24)) % (60 * 60)) / 60 );
        const Seconds = Math.floor(((inputSeconds % (60 * 60 * 24)) % (60 * 60)) % 60 );
        let ddhhmmss  = '';
        if (Days > 0){
            ddhhmmss += Days + ' Day ';
        }
        if (Hour > 0){
            ddhhmmss += Hour + ' Hour ';
        }

        if (Minutes > 0){
            ddhhmmss += Minutes + ' Minutes ';
        }

        if (Seconds > 0){
            ddhhmmss += Seconds + ' Seconds ';
        }
        return ddhhmmss;
    }
alert( toDDHHMMSS(2000));

Android Fragment handle back button press

in fragment class put this code for back event:

 rootView.setFocusableInTouchMode(true);
        rootView.requestFocus();
        rootView.setOnKeyListener( new OnKeyListener()
        {
            @Override
            public boolean onKey( View v, int keyCode, KeyEvent event )
            {
                if( keyCode == KeyEvent.KEYCODE_BACK )
                {
                    FragmentManager fragmentManager = getFragmentManager();
                    fragmentManager.beginTransaction()
                            .replace(R.id.frame_container, new Book_service_provider()).commit();

                    return true;
                }
                return false;
            }
        } );

How to detect simple geometric shapes using OpenCV

If you have only these regular shapes, there is a simple procedure as follows :

  1. Find Contours in the image ( image should be binary as given in your question)
  2. Approximate each contour using approxPolyDP function.
  3. First, check number of elements in the approximated contours of all the shapes. It is to recognize the shape. For eg, square will have 4, pentagon will have 5. Circles will have more, i don't know, so we find it. ( I got 16 for circle and 9 for half-circle.)
  4. Now assign the color, run the code for your test image, check its number, fill it with corresponding colors.

Below is my example in Python:

import numpy as np
import cv2

img = cv2.imread('shapes.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret,thresh = cv2.threshold(gray,127,255,1)

contours,h = cv2.findContours(thresh,1,2)

for cnt in contours:
    approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
    print len(approx)
    if len(approx)==5:
        print "pentagon"
        cv2.drawContours(img,[cnt],0,255,-1)
    elif len(approx)==3:
        print "triangle"
        cv2.drawContours(img,[cnt],0,(0,255,0),-1)
    elif len(approx)==4:
        print "square"
        cv2.drawContours(img,[cnt],0,(0,0,255),-1)
    elif len(approx) == 9:
        print "half-circle"
        cv2.drawContours(img,[cnt],0,(255,255,0),-1)
    elif len(approx) > 15:
        print "circle"
        cv2.drawContours(img,[cnt],0,(0,255,255),-1)

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Below is the output:

enter image description here

Remember, it works only for regular shapes.

Alternatively to find circles, you can use houghcircles. You can find a tutorial here.

Regarding iOS, OpenCV devs are developing some iOS samples this summer, So visit their site : www.code.opencv.org and contact them.

You can find slides of their tutorial here : http://code.opencv.org/svn/gsoc2012/ios/trunk/doc/CVPR2012_OpenCV4IOS_Tutorial.pdf

Text-align class for inside a table

In this three class Bootstrap invalid class

 .text-right {
     text-align: right; }

 .text-center {
     text-align: center; }

 .text-left {
    text-align: left; }

Paste text on Android Emulator

In a terminal, type adb shell input text 'my string here. With some characters escaped like \$ that'

Note that an alternative method for including spaces in the text is to substitute %s for each space character.

Remote debugging a Java application

I'd like to emphasize that order of arguments is important.

For me java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000 -jar app.jar command opens debugger port,

but java -jar app.jar -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000 command doesn't.

How to recognize vehicle license / number plate (ANPR) from an image?

The blurring is not a problem but is there a library or component (open source preferred) that will help with finding a licence within a photo?

Ans: The CARMEN FreeFlow ANPR Software engine (Commerical)

docker: Error response from daemon: Get https://registry-1.docker.io/v2/: Service Unavailable. IN DOCKER , MAC

I had the following entries in my /etc/hosts file:

34.228.211.243  registry-1.docker.io
34.205.88.205   auth.docker.io
104.18.121.25   production.cloudflare.docker.com

Just by commenting them out, I fixed the problem.

Numbering rows within groups in a data frame

I would like to add a data.table variant using the rank() function which provides the additional possibility to change the ordering and thus makes it a bit more flexible than the seq_len() solution and is pretty similar to row_number functions in RDBMS.

# Variant with ascending ordering
library(data.table)
dt <- data.table(df)
dt[, .( val
   , num = rank(val))
    , by = list(cat)][order(cat, num),]

    cat        val num
 1: aaa 0.05638315   1
 2: aaa 0.25767250   2
 3: aaa 0.30776611   3
 4: aaa 0.46854928   4
 5: aaa 0.55232243   5
 6: bbb 0.17026205   1
 7: bbb 0.37032054   2
 8: bbb 0.48377074   3
 9: bbb 0.54655860   4
10: bbb 0.81240262   5
11: ccc 0.28035384   1
12: ccc 0.39848790   2
13: ccc 0.62499648   3
14: ccc 0.76255108   4

# Variant with descending ordering
dt[, .( val
   , num = rank(-val))
    , by = list(cat)][order(cat, num),]

Run function from the command line

Interestingly enough, if the goal was to print to the command line console or perform some other minute python operation, you can pipe input into the python interpreter like so:

echo print("hi:)") | python

as well as pipe files..

python < foo.py

*Note that the extension does not have to be .py for the second to work. **Also note that for bash you may need to escape the characters

echo print\(\"hi:\)\"\) | python

Keep the order of the JSON keys during JSON conversion to CSV

Apache Wink has OrderedJSONObject. It keeps the order while parsing the String.

Echoing the last command run in Bash?

After reading the answer from Gilles, I decided to see if the $BASH_COMMAND var was also available (and the desired value) in an EXIT trap - and it is!

So, the following bash script works as expected:

#!/bin/bash

exit_trap () {
  local lc="$BASH_COMMAND" rc=$?
  echo "Command [$lc] exited with code [$rc]"
}

trap exit_trap EXIT
set -e

echo "foo"
false 12345
echo "bar"

The output is

foo
Command [false 12345] exited with code [1]

bar is never printed because set -e causes bash to exit the script when a command fails and the false command always fails (by definition). The 12345 passed to false is just there to show that the arguments to the failed command are captured as well (the false command ignores any arguments passed to it)

Is it possible to hide/encode/encrypt php source code and let others have the system?

There are many ways for doing that (you might want to obfuscate the source code, you can compress it, ...). Some of these methods need additional code to transform your program in an executable form (compression, for example).

But the thing all methods cannot do, is keeping the source code secret. The other party gets your binary code, which can always be transformed (reverse-engineered) into a human-readable form again, because the binary code contains all functionality information that is provided in your source code.

How to unload a package without restarting R

Note also that you can only use unload() once. If you use it a second time without rerunning library(), y'll get the not very informative error message invalid 'name' argument:

library(vegan)
#> Loading required package: permute
#> Loading required package: lattice
#> This is vegan 2.5-6
detach("package:vegan",  unload=TRUE)
detach("package:vegan",  unload=TRUE)
#> Error in detach("package:vegan", unload = TRUE): invalid 'name' argument

Created on 2020-05-09 by the reprex package (v0.3.0)

Hide div by default and show it on click with bootstrap

I realize this question is a bit dated and since it shows up on Google search for similar issue I thought I will expand a little bit more on top of @CowWarrior's answer. I was looking for somewhat similar solution, and after scouring through countless SO question/answers and Bootstrap documentations the solution was pretty simple. Again, this would be using inbuilt Bootstrap collapse class to show/hide divs and Bootstrap's "Collapse Event".

What I realized is that it is easy to do it using a Bootstrap Accordion, but most of the time even though the functionality required is "somewhat" similar to an Accordion, it's different in a way that one would want to show hide <div> based on, lets say, menu buttons on a navbar. Below is a simple solution to this. The anchor tags (<a>) could be navbar items and based on a collapse event the corresponding div will replace the existing div. It looks slightly sloppy in CodeSnippet, but it is pretty close to achieving the functionality-

All that the JavaScript does is makes all the other <div> hide using

$(".main-container.collapse").not($(this)).collapse('hide');

when the loaded <div> is displayed by checking the Collapse event shown.bs.collapse. Here's the Bootstrap documentation on Collapse Event.

Note: main-container is just a custom class.

Here it goes-

_x000D_
_x000D_
$(".main-container.collapse").on('shown.bs.collapse', function () {    _x000D_
//when a collapsed div is shown hide all other collapsible divs that are visible_x000D_
       $(".main-container.collapse").not($(this)).collapse('hide');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<a href="#Foo" class="btn btn-default" data-toggle="collapse">Toggle Foo</a>_x000D_
<a href="#Bar" class="btn btn-default" data-toggle="collapse">Toggle Bar</a>_x000D_
_x000D_
<div id="Bar" class="main-container collapse in">_x000D_
    This div (#Bar) is shown by default and can toggle_x000D_
</div>_x000D_
<div id="Foo" class="main-container collapse">_x000D_
    This div (#Foo) is hidden by default_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to run mysql command on bash?

I have written a shell script which will read data from properties file and then run mysql script on shell script. sharing this may help to others.

#!/bin/bash
    PROPERTY_FILE=filename.properties

    function getProperty {
       PROP_KEY=$1
       PROP_VALUE=`cat $PROPERTY_FILE | grep "$PROP_KEY" | cut -d'=' -f2`
       echo $PROP_VALUE
    }

    echo "# Reading property from $PROPERTY_FILE"
    DB_USER=$(getProperty "db.username")
    DB_PASS=$(getProperty "db.password")
    ROOT_LOC=$(getProperty "root.location")
    echo $DB_USER
    echo $DB_PASS
    echo $ROOT_LOC
    echo "Writing on DB ... "
    mysql -u$DB_USER -p$DB_PASS dbname<<EOFMYSQL

    update tablename set tablename.value_ = "$ROOT_LOC" where tablename.name_="Root directory location";
    EOFMYSQL
    echo "Writing root location($ROOT_LOC) is done ... "
    counter=`mysql -u${DB_USER} -p${DB_PASS} dbname -e "select count(*) from tablename where tablename.name_='Root directory location' and tablename.value_ = '$ROOT_LOC';" | grep -v "count"`;

    if [ "$counter" = "1" ]
    then
    echo "ROOT location updated"
    fi

How do I get the browser scroll position in jQuery?

It's better to use $(window).scroll() rather than $('#Eframe').on("mousewheel")

$('#Eframe').on("mousewheel") will not trigger if people manually scroll using up and down arrows on the scroll bar or grabbing and dragging the scroll bar itself.

$(window).scroll(function(){
    var scrollPos = $(document).scrollTop();
    console.log(scrollPos);
});

If #Eframe is an element with overflow:scroll on it and you want it's scroll position. I think this should work (I haven't tested it though).

$('#Eframe').scroll(function(){
    var scrollPos = $('#Eframe').scrollTop();
    console.log(scrollPos);
});

WPF: Grid with column/row margin/padding?

As was stated before create a GridWithMargins class. Here is my working code example

public class GridWithMargins : Grid
{
    public Thickness RowMargin { get; set; } = new Thickness(10, 10, 10, 10);
    protected override Size ArrangeOverride(Size arrangeSize)
    {
        var basesize = base.ArrangeOverride(arrangeSize);

        foreach (UIElement child in InternalChildren)
        {
            var pos = GetPosition(child);
            pos.X += RowMargin.Left;
            pos.Y += RowMargin.Top;

            var actual = child.RenderSize;
            actual.Width -= (RowMargin.Left + RowMargin.Right);
            actual.Height -= (RowMargin.Top + RowMargin.Bottom);
            var rec = new Rect(pos, actual);
            child.Arrange(rec);
        }
        return arrangeSize;
    }

    private Point GetPosition(Visual element)
    {
        var posTransForm = element.TransformToAncestor(this);
        var areaTransForm = posTransForm.Transform(new Point(0, 0));
        return areaTransForm;
    }
}

Usage:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApplication1"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <local:GridWithMargins ShowGridLines="True">
            <Grid.RowDefinitions>
                <RowDefinition />
                <RowDefinition />
                <RowDefinition />
                <RowDefinition />
                <RowDefinition />
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition />
                <ColumnDefinition />
                <ColumnDefinition />
            </Grid.ColumnDefinitions>
            <Rectangle Fill="Red" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
            <Rectangle Fill="Green" Grid.Row="1" Grid.Column="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
            <Rectangle Fill="Blue" Grid.Row="1" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
        </local:GridWithMargins>
    </Grid>
</Window>

Java logical operator short-circuiting

if(demon!=0&& num/demon>10)

Since the short-circuit form of AND(&&) is used, there is no risk of causing a run-time exception when demon is zero.

Ref. Java 2 Fifth Edition by Herbert Schildt

"fatal: Not a git repository (or any of the parent directories)" from git status

In my case, the original repository was a bare one.

So, I had to type (in windows):

mkdir   dest
cd dest
git init
git remote add origin a\valid\yet\bare\repository
git pull origin master

To check if a repository is a bare one:

git rev-parse --is-bare-repository 

Want to show/hide div based on dropdown box selection

The core problem is the js errors:

$('#purpose').on('change', function () {
    // if (this.value == '1'); { No semicolon and I used === instead of ==
    if (this.value === '1'){
        $("#business").show();
    } else {
        $("#business").hide();
    }
});
// }); remove

http://jsfiddle.net/Bushwazi/2kGzZ/3/

I had to clean up the html & js...I couldn't help myself.

HTML:

<select id='purpose'>
    <option value="0">Personal use</option>
    <option value="1">Business use</option>
    <option value="2">Passing on to a client</option>
</select>
<form id="business">
    <label for="business">Business Name</label>
    <input type='text' class='text' name='business' value size='20' />
</form>

CSS:

#business {
  display:none;
}

JS:

$('#purpose').on('change', function () {
    if(this.value === "1"){
        $("#business").show();
    } else {
        $("#business").hide();
    }
});

C++ display stack trace on exception

Poppy can gather not only the stack trace, but also parameter values, local variables, etc. - everything leading to the crash.

Calling a phone number in swift

Okay I got help and figured it out. Also I put in a nice little alert system just in case the phone number is not valid. My issue was I was calling it right but the number had spaces and unwanted characters such as ("123 456-7890"). UIApplication only works or accepts if your number is ("1234567890"). So you basically remove the space and invalid characters by making a new variable to pull only the numbers. Then calls those numbers with the UIApplication.

func callSellerPressed (sender: UIButton!){
        var newPhone = ""

        for (var i = 0; i < countElements(busPhone); i++){

            var current:Int = i
            switch (busPhone[i]){
                case "0","1","2","3","4","5","6","7","8","9" : newPhone = newPhone + String(busPhone[i])
                default : println("Removed invalid character.")
            }
        }

        if  (busPhone.utf16Count > 1){

        UIApplication.sharedApplication().openURL(NSURL(string: "tel://" + newPhone)!)
        }
        else{
            let alert = UIAlertView()
            alert.title = "Sorry!"
            alert.message = "Phone number is not available for this business"
            alert.addButtonWithTitle("Ok")
                alert.show()
        }
        }

How to add many functions in ONE ng-click?

Try this:

  • Make a collection of functions
  • Make a function that loops through and executes all the functions in the collection.
  • Add the function to the html
array = [
    function() {},
    function() {},
    function() {}
]

function loop() {
    array.forEach(item) {
        item()
    }
}

ng - click = "loop()"

Return array from function

At a minimum, change this:

function BlockID() {
    var IDs = new Array();
        images['s'] = "Images/Block_01.png";
        images['g'] = "Images/Block_02.png";
        images['C'] = "Images/Block_03.png";
        images['d'] = "Images/Block_04.png";
    return IDs;
}

To this:

function BlockID() {
    var IDs = new Object();
        IDs['s'] = "Images/Block_01.png";
        IDs['g'] = "Images/Block_02.png";
        IDs['C'] = "Images/Block_03.png";
        IDs['d'] = "Images/Block_04.png";
    return IDs;
}

There are a couple fixes to point out. First, images is not defined in your original function, so assigning property values to it will throw an error. We correct that by changing images to IDs. Second, you want to return an Object, not an Array. An object can be assigned property values akin to an associative array or hash -- an array cannot. So we change the declaration of var IDs = new Array(); to var IDs = new Object();.

After those changes your code will run fine, but it can be simplified further. You can use shorthand notation (i.e., object literal property value shorthand) to create the object and return it immediately:

function BlockID() {
    return {
            "s":"Images/Block_01.png"
            ,"g":"Images/Block_02.png"
            ,"C":"Images/Block_03.png"
            ,"d":"Images/Block_04.png"
    };
}

Developing C# on Linux

I would suggest using MonoDevelop.

It is pretty much explicitly designed for use with Mono, and all set up to develop in C#.

The simplest way to install it on Ubuntu would be to install the monodevelop package in Ubuntu. (link on Mono on ubuntu.com) (However, if you want to install a more recent version, I am not sure which PPA would be appropriate)

However, I would not recommend developing with the WinForms toolkit - I do not expect it to have the same behavior in Windows and Mono (the implementations are pretty different). For an overview of the UI toolkits that work with Mono, you can go to the information page on Mono-project.

Best way to disable button in Twitter's Bootstrap

Building off jeroenk's answer, here's the rundown:

$('button').addClass('disabled'); // Disables visually
$('button').prop('disabled', true); // Disables visually + functionally

$('input[type=button]').addClass('disabled'); // Disables visually
$('input[type=button]').prop('disabled', true); // Disables visually + functionally

$('a').addClass('disabled'); // Disables visually
$('a').prop('disabled', true); // Does nothing
$('a').attr('disabled', 'disabled'); // Disables visually

See fiddle

Where can I download english dictionary database in a text format?

The Gutenberg Project hosts Webster's Unabridged English Dictionary plus many other public domain literary works. Actually it looks like they've got several versions of the dictionary hosted with copyright from different years. The one I linked has a 2009 copyright. You may want to poke around the site and investigate the different versions of Webster's dictionary.

What is difference between INNER join and OUTER join

INNER JOIN: Returns all rows when there is at least one match in BOTH tables

LEFT JOIN: Return all rows from the left table, and the matched rows from the right table

RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table

FULL JOIN: Return all rows when there is a match in ONE of the tables

How to compare two colors for similarity/difference

A simple method that only uses RGB is

cR=R1-R2 
cG=G1-G2 
cB=B1-B2 
uR=R1+R2 
distance=cR*cR*(2+uR/256) + cG*cG*4 + cB*cB*(2+(255-uR)/256)

I've used this one for a while now, and it works well enough for most purposes.

What is the difference between statically typed and dynamically typed languages?

Sweet and simple definitions, but fitting the need: Statically typed languages binds the type to a variable for its entire scope (Seg: SCALA) Dynamically typed languages bind the type to the actual value referenced by a variable.

Docker official registry (Docker Hub) URL

It's just docker pull busybox, are you using an up to date version of the docker client. I think they stopped supporting clients lower than 1.5.

Incidentally that curl works for me:

$ curl -k https://registry.hub.docker.com/v1/repositories/busybox/tags
[{"layer": "fc0db02f", "name": "latest"}, {"layer": "fc0db02f", "name": "1"}, {"layer": "a6dbc8d6", "name": "1-ubuntu"}, {"layer": "a6dbc8d6", "name": "1.21-ubuntu"}, {"layer": "a6dbc8d6", "name": "1.21.0-ubuntu"}, {"layer": "d7057cb0", "name": "1.23"}, {"layer": "d7057cb0", "name": "1.23.2"}, {"layer": "fc0db02f", "name": "1.24"}, {"layer": "3d5bcd78", "name": "1.24.0"}, {"layer": "fc0db02f", "name": "1.24.1"}, {"layer": "1c677c87", "name": "buildroot-2013.08.1"}, {"layer": "0f864637", "name": "buildroot-2014.02"}, {"layer": "a6dbc8d6", "name": "ubuntu"}, {"layer": "ff8f955d", "name": "ubuntu-12.04"}, {"layer": "633fcd11", "name": "ubuntu-14.04"}]

Interesting enough if you sniff the headers you get a HTTP 405 (Method not allowed). I think this might be to do with the fact that Docker have deprecated their Registry API.

Easy way to use variables of enum types as string in C?

Check out the ideas at Mu Dynamics Research Labs - Blog Archive. I found this earlier this year - I forget the exact context where I came across it - and have adapted it into this code. We can debate the merits of adding an E at the front; it is applicable to the specific problem addressed, but not part of a general solution. I stashed this away in my 'vignettes' folder - where I keep interesting scraps of code in case I want them later. I'm embarrassed to say that I didn't keep a note of where this idea came from at the time.

Header: paste1.h

/*
@(#)File:           $RCSfile: paste1.h,v $
@(#)Version:        $Revision: 1.1 $
@(#)Last changed:   $Date: 2008/05/17 21:38:05 $
@(#)Purpose:        Automated Token Pasting
*/

#ifndef JLSS_ID_PASTE_H
#define JLSS_ID_PASTE_H

/*
 * Common case when someone just includes this file.  In this case,
 * they just get the various E* tokens as good old enums.
 */
#if !defined(ETYPE)
#define ETYPE(val, desc) E##val,
#define ETYPE_ENUM
enum {
#endif /* ETYPE */

   ETYPE(PERM,  "Operation not permitted")
   ETYPE(NOENT, "No such file or directory")
   ETYPE(SRCH,  "No such process")
   ETYPE(INTR,  "Interrupted system call")
   ETYPE(IO,    "I/O error")
   ETYPE(NXIO,  "No such device or address")
   ETYPE(2BIG,  "Arg list too long")

/*
 * Close up the enum block in the common case of someone including
 * this file.
 */
#if defined(ETYPE_ENUM)
#undef ETYPE_ENUM
#undef ETYPE
ETYPE_MAX
};
#endif /* ETYPE_ENUM */

#endif /* JLSS_ID_PASTE_H */

Example source:

/*
@(#)File:           $RCSfile: paste1.c,v $
@(#)Version:        $Revision: 1.2 $
@(#)Last changed:   $Date: 2008/06/24 01:03:38 $
@(#)Purpose:        Automated Token Pasting
*/

#include "paste1.h"

static const char *sys_errlist_internal[] = {
#undef JLSS_ID_PASTE_H
#define ETYPE(val, desc) desc,
#include "paste1.h"
    0
#undef ETYPE
};

static const char *xerror(int err)
{
    if (err >= ETYPE_MAX || err <= 0)
        return "Unknown error";
    return sys_errlist_internal[err];
}

static const char*errlist_mnemonics[] = {
#undef JLSS_ID_PASTE_H
#define ETYPE(val, desc) [E ## val] = "E" #val,
#include "paste1.h"
#undef ETYPE
};

#include <stdio.h>

int main(void)
{
    int i;

    for (i = 0; i < ETYPE_MAX; i++)
    {
        printf("%d: %-6s: %s\n", i, errlist_mnemonics[i], xerror(i));
    }
    return(0);
}

Not necessarily the world's cleanest use of the C pre-processor - but it does prevent writing the material out multiple times.

How to delete history of last 10 commands in shell?

to delete last 10 entries (based on your example) :

history -d 511 520

What does string::npos mean in this code?

An answer for these days of C++17, when we have std::optional:

If you squint a bit and pretend std::string::find() returns an std::optional<std::string::size_type> (which it sort of should...) - then the condition becomes:

auto position = str.find(str2);

if ( position.has_value() ) {
    std::cout << "first 'needle' found at: " << found.value() << std::endl;
}

"The remote certificate is invalid according to the validation procedure." using Gmail SMTP server

The link here solved my problem.

http://brainof-dave.blogspot.com.au/2008/08/remote-certificate-is-invalid-according.html

I went to url of the web service (on the server that had the issue), clicked on the little security icon in IE, which brought up the certificate. I then clicked on the Details tab, clicked the Copy To File button, which allowed me to export the certifcate as a .cer file. Once I had the certificate locally, I was able to import it into the certificate store on the server using the below instructions.

Start a new MMC. File --> Add/Remove Snap-In... Click Add... Choose Certificates and click Add. Check the "Computer Account" radio button. Click Next.

Choose the client computer in the next screen. Click Finish. Click Close. Click OK. NOW install the certificate into the Trusted Root Certification Authorities certificate store. This will allow all users to trust the certificate.

Content Type application/soap+xml; charset=utf-8 was not supported by service

check the client config file that identified to the web.config on the binding section

How to change the JDK for a Jenkins job?

Using latest Jenkins version 2.7.4 which is also having a bug for existing jobs.

  1. Add new JDKs through Manage Jenkins -> Global Tool Configuration -> JDK ** If you edit current job then JDK dropdown is not showing (bug)

  2. Hit http://your_jenkin_server:8080/restart and restart the server

  3. Re-configure job

Now, you should see JDK dropdown in "job name" -> Configure in Jenkins web ui. It will list all JDKs available in Jenkins configuration.

wp-admin shows blank page, how to fix it?

Had this same issue after changing the PHP version from 5.6 to 7.3 (eaphp73). So what I did was I simply changed the version to alt-php74.

So what's the problem? Probably a plugin that relied on a certain PHP extension that wasn't available on eaphp73.

Before you touch any wordpress files, just try changing your site's PHP version. You can do this in the cPanel.

And if that doesn't work, go back into the cPanel and activate every PHP extension there is. And if your site starts working at this stage, then it's probably an extension it couldn't function without. Now slowly work backwards deactivating (one at a time) ONLY the extensions you just activated.

You should be able to figure out which extension was the required feature.

Can it be a plugin that's causing the issue? Certainly. Maybe the rogue plugin just wanted that extra extension.

If changing the PHP version, and juggling with the PHP extensions didn't work, then try renaming (which automatically deactivates) one plugin folder at a time.

What is the difference between static_cast<> and C style casting?

struct A {};
struct B : A {};
struct C {}; 

int main()
{
    A* a = new A;    

    int i = 10;

    a = (A*) (&i); // NO ERROR! FAIL!

    //a = static_cast<A*>(&i); ERROR! SMART!

    A* b = new B;

    B* b2 = static_cast<B*>(b); // NO ERROR! SMART!

    C* c = (C*)(b); // NO ERROR! FAIL!

    //C* c = static_cast<C*>(b); ERROR! SMART!
}

What does [STAThread] do?

It tells the compiler that you're in a Single Thread Apartment model. This is an evil COM thing, it's usually used for Windows Forms (GUI's) as that uses Win32 for its drawing, which is implemented as STA. If you are using something that's STA model from multiple threads then you get corrupted objects.

This is why you have to invoke onto the Gui from another thread (if you've done any forms coding).

Basically don't worry about it, just accept that Windows GUI threads must be marked as STA otherwise weird stuff happens.

how to get data from selected row from datagridview

I was having the same issue and this works excellently.

Private Sub DataGridView17_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView17.CellFormatting  
  'Display complete contents in tooltip even though column display cuts off part of it.   
  DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).ToolTipText = DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).Value 
End Sub

Java Date vs Calendar

A little bit late at party, but Java has a new Date Time API in JDK 8. You may want to upgrade your JDK version and embrace the standard. No more messy date/calendar, no more 3rd party jars.

phantomjs not waiting for "full" page load

I found this solution useful in a NodeJS app. I use it just in desperate cases because it launches a timeout in order to wait for the full page load.

The second argument is the callback function which is going to be called once the response is ready.

phantom = require('phantom');

var fullLoad = function(anUrl, callbackDone) {
    phantom.create(function (ph) {
        ph.createPage(function (page) {
            page.open(anUrl, function (status) {
                if (status !== 'success') {
                    console.error("pahtom: error opening " + anUrl, status);
                    ph.exit();
                } else {
                    // timeOut
                    global.setTimeout(function () {
                        page.evaluate(function () {
                            return document.documentElement.innerHTML;
                        }, function (result) {
                            ph.exit(); // EXTREMLY IMPORTANT
                            callbackDone(result); // callback
                        });
                    }, 5000);
                }
            });
        });
    });
}

var callback = function(htmlBody) {
    // do smth with the htmlBody
}

fullLoad('your/url/', callback);

What is causing the error `string.split is not a function`?

Change this...

var string = document.location;

to this...

var string = document.location + '';

This is because document.location is a Location object. The default .toString() returns the location in string form, so the concatenation will trigger that.


You could also use document.URL to get a string.

Why should I prefer to use member initialization lists?

Apart from the performance reasons mentioned above, if your class stores references to objects passed as constructor parameters or your class has const variables then you don't have any choice except using initializer lists.

What is let-* in Angular 2 templates?

update Angular 5

ngOutletContext was renamed to ngTemplateOutletContext

See also https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29

original

Templates (<template>, or <ng-template> since 4.x) are added as embedded views and get passed a context.

With let-col the context property $implicit is made available as col within the template for bindings. With let-foo="bar" the context property bar is made available as foo.

For example if you add a template

<ng-template #myTemplate let-col let-foo="bar">
  <div>{{col}}</div>
  <div>{{foo}}</div>
</ng-template>

<!-- render above template with a custom context -->
<ng-template [ngTemplateOutlet]="myTemplate"
             [ngTemplateOutletContext]="{
                                           $implicit: 'some col value',
                                           bar: 'some bar value'
                                        }"
></ng-template>

See also this answer and ViewContainerRef#createEmbeddedView.

*ngFor also works this way. The canonical syntax makes this more obvious

<ng-template ngFor let-item [ngForOf]="items" let-i="index" let-odd="odd">
  <div>{{item}}</div>
</ng-template>

where NgFor adds the template as embedded view to the DOM for each item of items and adds a few values (item, index, odd) to the context.

See also Using $implict to pass multiple parameters

Fatal error: Call to a member function prepare() on null

@delato468 comment must be listed as a solution as it worked for me.

In addition to defining the parameter, the user must pass it too at the time of calling the function

fetch_data(PDO $pdo, $cat_id)

How to create a JQuery Clock / Timer

var timeInterval = 5;
    var blinkTime = 1;
    var open_signal = 'top_left';

    $(document).ready(function () {
        $('#div_top_left .timer').html(timeInterval);
        $('#div_top_right .timer').html(timeInterval);
        $('#div_bottom_right .timer').html(timeInterval * 2);
        $('#div_bottom_left .timer').html(timeInterval * 3);

        $('#div_top_left .green').css('background-color', 'green');
        $('#div_top_right .red').css('background-color', 'red');
        $('#div_bottom_right .red').css('background-color', 'red');
        $('#div_bottom_left .red').css('background-color', 'red');

        setInterval(function () {
            manageSignals();
        }, 1000);
    });

    function manageSignals() {
        var top_left_time = parseInt($('#div_top_left .timer').html()) - 1;
        var top_right_time = parseInt($('#div_top_right .timer').html()) - 1;
        var bottom_left_time = parseInt($('#div_bottom_left .timer').html()) - 1;
        var bottom_right_time = parseInt($('#div_bottom_right .timer').html()) - 1;

        if (top_left_time == -1 && open_signal == 'top_left') open_signal = 'top_right';
        else if (top_right_time == -1 && open_signal == 'top_right') open_signal = 'bottom_right';
        else if (bottom_right_time == -1 && open_signal == 'bottom_right') open_signal = 'bottom_left';
        else if (bottom_left_time == -1 && open_signal == 'bottom_left') open_signal = 'top_left';

        if (top_left_time == -1) {
            if (open_signal == 'top_right') {
                top_left_time = (timeInterval * 3) - 1;
                $('#div_top_left .red').css('background-color', 'red');
                $('#div_top_left .yellow').css('background-color', 'white');
                $('#div_top_left .green').css('background-color', 'white');
            }
            else if (open_signal == 'top_left') {
                top_left_time = timeInterval - 1;
                $('#div_top_left .red').css('background-color', 'white');
                $('#div_top_left .yellow').css('background-color', 'white');
                $('#div_top_left .green').css('background-color', 'green');
            }
        }

        if (top_right_time == -1) {
            if (open_signal == 'bottom_right') {
                top_right_time = (timeInterval * 3) - 1;
                $('#div_top_right .red').css('background-color', 'red');
                $('#div_top_right .yellow').css('background-color', 'white');
                $('#div_top_right .green').css('background-color', 'white');
            }
            else if (open_signal == 'top_right') {
                top_right_time = timeInterval - 1;
                $('#div_top_right .red').css('background-color', 'white');
                $('#div_top_right .yellow').css('background-color', 'white');
                $('#div_top_right .green').css('background-color', 'green');
            }
        }

        if (bottom_right_time == -1) {
            if (open_signal == 'bottom_left') {
                bottom_right_time = (timeInterval * 3) - 1;
                $('#div_bottom_right .red').css('background-color', 'red');
                $('#div_bottom_right .yellow').css('background-color', 'white');
                $('#div_bottom_right .green').css('background-color', 'white');
            }
            else if (open_signal == 'bottom_right') {
                bottom_right_time = timeInterval - 1;
                $('#div_bottom_right .red').css('background-color', 'white');
                $('#div_bottom_right .yellow').css('background-color', 'white');
                $('#div_bottom_right .green').css('background-color', 'green');
            }
        }

        if (bottom_left_time == -1) {
            if (open_signal == 'top_left') {
                bottom_left_time = (timeInterval * 3) - 1;
                $('#div_bottom_left .red').css('background-color', 'red');
                $('#div_bottom_left .yellow').css('background-color', 'white');
                $('#div_bottom_left .green').css('background-color', 'white');
            }
            else if (open_signal == 'bottom_left') {
                bottom_left_time = timeInterval - 1;
                $('#div_bottom_left .red').css('background-color', 'white');
                $('#div_bottom_left .yellow').css('background-color', 'white');
                $('#div_bottom_left .green').css('background-color', 'green');
            }
        }

        if (top_left_time == blinkTime && open_signal == 'top_left') {
            $('#div_top_left .yellow').css('background-color', 'yellow');
            $('#div_top_left .green').css('background-color', 'white');
        }
        if (top_right_time == blinkTime && open_signal == 'top_right') {
            $('#div_top_right .yellow').css('background-color', 'yellow');
            $('#div_top_right .green').css('background-color', 'white');
        }
        if (bottom_left_time == blinkTime && open_signal == 'bottom_left') {
            $('#div_bottom_left .yellow').css('background-color', 'yellow');
            $('#div_bottom_left .green').css('background-color', 'white');
        }
        if (bottom_right_time == blinkTime && open_signal == 'bottom_right') {
            $('#div_bottom_right .yellow').css('background-color', 'yellow');
            $('#div_bottom_right .green').css('background-color', 'white');
        }

        $('#div_top_left .timer').html(top_left_time);
        $('#div_top_right .timer').html(top_right_time);
        $('#div_bottom_left .timer').html(bottom_left_time);
        $('#div_bottom_right .timer').html(bottom_right_time);
    }

Display date in dd/mm/yyyy format in vb.net

Dim formattedDate As String = Date.Today.ToString("dd/MM/yyyy")

Check link below

Remove Item from ArrayList

In this specific case, you should remove the elements in descending order. First index 5, then 3, then 1. This will remove the elements from the list without undesirable side effects.

for (int j = i.length-1; j >= 0; j--) {
    list.remove(i[j]);
}

Is it correct to use alt tag for an anchor link?

Such things are best answered by looking at the official specification:

  1. go to the specification: https://www.w3.org/TR/html5/

  2. search for "a element": https://www.w3.org/TR/html5/text-level-semantics.html#the-a-element

  3. check "Content attributes", which lists all allowed attributes for the a element:

    • Global attributes
    • href
    • target
    • download
    • rel
    • hreflang
    • type
  4. check the linked "Global attributes": https://www.w3.org/TR/html5/dom.html#global-attributes

As you will see, the alt attribute is not allowed on the a element.
Also you’d notice that the src attribute isn’t allowed either.

By validating your HTML, errors like these are reported to you.


Note that the above is for HTML5, which is W3C’s HTML standard from 2014. In 2016, HTML 5.1 became the next HTML standard. Finding the allowed attributes works in the same way. You’ll see that the a element can have another attribute in HTML 5.1: rev.

You can find all HTML specifications (including the latest standard) on W3C’s HTML Current Status.

How to launch an application from a browser?

You can use SilverLight to launch an application from the browser (this will work only on IE and Firefox, newer versions of chrome don't support this)

Example code here

Add new item in existing array in c#.net

That could be a solution;

Array.Resize(ref array, newsize);
array[newsize - 1] = "newvalue"

But for dynamic sized array I would prefer list too.

Best way to remove from NSMutableArray while iterating?

For iOS 4+ or OS X 10.6+, Apple added passingTest series of APIs in NSMutableArray, like – indexesOfObjectsPassingTest:. A solution with such API would be:

NSIndexSet *indexesToBeRemoved = [someList indexesOfObjectsPassingTest:
    ^BOOL(id obj, NSUInteger idx, BOOL *stop) {
    return [self shouldRemove:obj];
}];
[someList removeObjectsAtIndexes:indexesToBeRemoved];

$http get parameters does not work

The 2nd parameter in the get call is a config object. You want something like this:

$http
    .get('accept.php', {
        params: {
            source: link,
            category_id: category
        }
     })
     .success(function (data,status) {
          $scope.info_show = data
     });

See the Arguments section of http://docs.angularjs.org/api/ng.$http for more detail

jQuery: get parent, parent id?

$(this).parent().parent().attr('id');

Is how you would get the id of the parent's parent.

EDIT:

$(this).closest('ul').attr('id');

Is a more foolproof solution for your case.

Python - List of unique dictionaries

In python 3.6+ (what I've tested), just use:

import json

#Toy example, but will also work for your case 
myListOfDicts = [{'a':1,'b':2},{'a':1,'b':2},{'a':1,'b':3}]
#Start by sorting each dictionary by keys
myListOfDictsSorted = [sorted(d.items()) for d in myListOfDicts]

#Using json methods with set() to get unique dict
myListOfUniqueDicts = list(map(json.loads,set(map(json.dumps, myListOfDictsSorted))))

print(myListOfUniqueDicts)

Explanation: we're mapping the json.dumps to encode the dictionaries as json objects, which are immutable. set can then be used to produce an iterable of unique immutables. Finally, we convert back to our dictionary representation using json.loads. Note that initially, one must sort by keys to arrange the dictionaries in a unique form. This is valid for Python 3.6+ since dictionaries are ordered by default.

How to get my Android device Internal Download Folder path

if a device has an SD card, you use:

Environment.getExternalStorageState() 

if you don't have an SD card, you use:

Environment.getDataDirectory()

if there is no SD card, you can create your own directory on the device locally.

    //if there is no SD card, create new directory objects to make directory on device
        if (Environment.getExternalStorageState() == null) {
                        //create new file directory object
            directory = new File(Environment.getDataDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(Environment.getDataDirectory()
                    + "/Robotium-Screenshots/");
            /*
             * this checks to see if there are any previous test photo files
             * if there are any photos, they are deleted for the sake of
             * memory
             */
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length != 0) {
                    for (int ii = 0; ii <= dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                }
            }
            // if no directory exists, create new directory
            if (!directory.exists()) {
                directory.mkdir();
            }

            // if phone DOES have sd card
        } else if (Environment.getExternalStorageState() != null) {
            // search for directory on SD card
            directory = new File(Environment.getExternalStorageDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(
                    Environment.getExternalStorageDirectory()
                            + "/Robotium-Screenshots/");
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length > 0) {
                    for (int ii = 0; ii < dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                    dirFiles = null;
                }
            }
            // if no directory exists, create new directory to store test
            // results
            if (!directory.exists()) {
                directory.mkdir();
            }
        }// end of SD card checking

add permissions on your manifest.xml

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

Happy coding..

How do I count the number of occurrences of a char in a String?

use a lambda function which removes all characters to count
the count is the difference of the before-length and after-length

String s = "a.b.c.d";
int count = s.length() - deleteChars.apply( s, "." ).length();  // 3

find deleteChars here


if you have to count the occurrences of more than one character it can be done in one swoop:
eg. for b c and .:

int count = s.length() - deleteChars.apply( s, "bc." ).length();  // 5

Change bullets color of an HTML list without using span

For me the best option is to use CSS pseudo elements, so for disc bullet styling it would look like that:

_x000D_
_x000D_
ul {_x000D_
  list-style-type: none;_x000D_
}_x000D_
_x000D_
li {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
li:before {_x000D_
  content: '';_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  width: 5px; /* adjust to suit your needs */_x000D_
  height: 5px; /* adjust to suit your needs */_x000D_
  border-radius: 50%;_x000D_
  left: -15px; /* adjust to suit your needs */_x000D_
  top: 0.5em;_x000D_
  background: #f00; /* adjust to suit your needs */_x000D_
}
_x000D_
<ul>_x000D_
  <li>first</li>_x000D_
  <li>second</li>_x000D_
  <li>third</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Notes:

  • width and height should have equal values to keep pointers rounded
  • you may set border-radius to zero if you want to have square list bullets

For more bullets styles you may use other css shapes https://css-tricks.com/examples/ShapesOfCSS/ (choose this which doesn't require pseudo elements to work, so for example triangles)

Why use the INCLUDE clause when creating an index?

An additional consideraion that I have not seen in the answers already given, is that included columns can be of data types that are not allowed as index key columns, such as varchar(max).

This allows you to include such columns in a covering index. I recently had to do this to provide a nHibernate generated query, which had a lot of columns in the SELECT, with a useful index.

Remove the last three characters from a string

read last 3 characters from string [Initially asked question]

You can use string.Substring and give it the starting index and it will get the substring starting from given index till end.

myString.Substring(myString.Length-3)

Retrieves a substring from this instance. The substring starts at a specified character position. MSDN

Edit, for updated post

Remove last 3 characters from string [Updated question]

To remove the last three characters from the string you can use string.Substring(Int32, Int32) and give it the starting index 0 and end index three less than the string length. It will get the substring before last three characters.

myString = myString.Substring(0, myString.Length-3);

String.Substring Method (Int32, Int32)

Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length.

You can also using String.Remove(Int32) method to remove the last three characters by passing start index as length - 3, it will remove from this point to end of string.

myString = myString.Remove(myString.Length-3)

String.Remove Method (Int32)

Returns a new string in which all the characters in the current instance, beginning at a specified position and continuing through the last position, have been deleted

Select Last Row in the Table

Another fancy way to do it in Laravel 6.x (Unsure but must work for 5.x aswell) :

DB::table('your_table')->get()->last();

You can access fields too :

DB::table('your_table')->get()->last()->id;

Get specific line from text file using just shell script

Best performance method

sed '5q;d' file

Because sed stops reading any lines after the 5th one

Update experiment from Mr. Roger Dueck

I installed wcanadian-insane (6.6MB) and compared sed -n 1p /usr/share/dict/words and sed '1q;d' /usr/share/dict/words using the time command; the first took 0.043s, the second only 0.002s, so using 'q' is definitely a performance improvement!

MongoDB inserts float when trying to insert integer

db.data.update({'name': 'zero'}, {'$set': {'value': NumberInt(0)}})

You can also use NumberLong.

No process is on the other end of the pipe (SQL Server 2012)

To solve this, connect to SQL Management Studio using Windows Authentication, then right-click on server node Properties->Security and enable SQL Server and Windows Authentication mode. If you're using 'sa' make sure the account is enabled. To do this open 'sa' under Logins and view Status.

enable sa admin

If this didn't work, you may need to reinstall SQL Server

How to modify list entries during for loop?

It's considered poor form. Use a list comprehension instead, with slice assignment if you need to retain existing references to the list.

a = [1, 3, 5]
b = a
a[:] = [x + 2 for x in a]
print(b)

List all files from a directory recursively with Java

public class GetFilesRecursive {
    public static List <String> getFilesRecursively(File dir){
        List <String> ls = new ArrayList<String>();
        for (File fObj : dir.listFiles()) {
            if(fObj.isDirectory()) {
                ls.add(String.valueOf(fObj));
                ls.addAll(getFilesRecursively(fObj));               
            } else {
                ls.add(String.valueOf(fObj));       
            }
        }

        return ls;
    }
    public static List <String> getListOfFiles(String fullPathDir) {
        List <String> ls = new ArrayList<String> ();
        File f = new File(fullPathDir);
        if (f.exists()) {
            if(f.isDirectory()) {
                ls.add(String.valueOf(f));
                ls.addAll(getFilesRecursively(f));
            }
        } else {
            ls.add(fullPathDir);
        }
        return ls;
    }

    public static void main(String[] args) {
        List <String> ls = getListOfFiles("/Users/srinivasab/Documents");
        for (String file:ls) {
            System.out.println(file);
        }
        System.out.println(ls.size());
    }
}

Capturing TAB key in text box

The previous answer is fine, but I'm one of those guys that's firmly against mixing behavior with presentation (putting JavaScript in my HTML) so I prefer to put my event handling logic in my JavaScript files. Additionally, not all browsers implement event (or e) the same way. You may want to do a check prior to running any logic:

document.onkeydown = TabExample;

function TabExample(evt) {
  var evt = (evt) ? evt : ((event) ? event : null);
  var tabKey = 9;
  if(evt.keyCode == tabKey) {
    // do work
  }
}

Global javascript variable inside document.ready

You can define the variable inside the document ready function without var to make it a global variable. In javascript any variable declared without var automatically becomes a global variable

$(document).ready(function() {
    intro =  "something";
});

although you cant use the variable immediately, but it would be accessible to other functions

Oracle date difference to get number of years

I'd use months_between, possibly combined with floor:

select floor(months_between(date '2012-10-10', date '2011-10-10') /12) from dual;

select floor(months_between(date '2012-10-9' , date '2011-10-10') /12) from dual;

floor makes sure you get down-rounded years. If you want the fractional parts, you obviously want to not use floor.

How to percent-encode URL parameters in Python?

It is better to use urlencode here. Not much difference for single parameter but IMHO makes the code clearer. (It looks confusing to see a function quote_plus! especially those coming from other languates)

In [21]: query='lskdfj/sdfkjdf/ksdfj skfj'

In [22]: val=34

In [23]: from urllib.parse import urlencode

In [24]: encoded = urlencode(dict(p=query,val=val))

In [25]: print(f"http://example.com?{encoded}")
http://example.com?p=lskdfj%2Fsdfkjdf%2Fksdfj+skfj&val=34

Docs

urlencode: https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlencode

quote_plus: https://docs.python.org/3/library/urllib.parse.html#urllib.parse.quote_plus

"Use the new keyword if hiding was intended" warning

In the code below, Class A implements the interface IShow and implements its method ShowData. Class B inherits Class A. In order to use ShowData method in Class B, we have to use keyword new in the ShowData method in order to hide the base class Class A method and use override keyword in order to extend the method.

interface IShow
{
    protected void ShowData();
}

class A : IShow
{
    protected void ShowData()
    {
        Console.WriteLine("This is Class A");
    }
}

class B : A
{
    protected new void ShowData()
    {
        Console.WriteLine("This is Class B");
    }
}

Removing elements by class name?

Brett - are you aware that getElementyByClassName support from IE 5.5 to 8 is not there according to quirksmode?. You would be better off following this pattern if you care about cross-browser compatibility:

  • Get container element by ID.
  • Get needed child elements by tag name.
  • Iterate over children, test for matching className property.
  • elements[i].parentNode.removeChild(elements[i]) like the other guys said.

Quick example:

var cells = document.getElementById("myTable").getElementsByTagName("td");
var len = cells.length;
for(var i = 0; i < len; i++) {
    if(cells[i].className.toLowerCase() == "column") {
        cells[i].parentNode.removeChild(cells[i]);
    }
}

Here's a quick demo.

EDIT: Here is the fixed version, specific to your markup:

var col_wrapper = document.getElementById("columns").getElementsByTagName("div");

var elementsToRemove = [];
for (var i = 0; i < col_wrapper.length; i++) {
    if (col_wrapper[i].className.toLowerCase() == "column") {
        elementsToRemove.push(col_wrapper[i]);
    }
}
for(var i = 0; i < elementsToRemove.length; i++) {
    elementsToRemove[i].parentNode.removeChild(elementsToRemove[i]);
}

The problem was my fault; when you remove an element from the resulting array of elements, the length changes, so one element gets skipped at each iteration. The solution is to store a reference to each element in a temporary array, then subsequently loop over those, removing each one from the DOM.

Try it here.

Run a mySQL query as a cron job?

It depends on what runs cron on your system, but all you have to do to run a php script from cron is to do call the location of the php installation followed by the script location. An example with crontab running every hour:

# crontab -e
00 * * * * /usr/local/bin/php /home/path/script.php

On my system, I don't even have to put the path to the php installation:

00 * * * * php /home/path/script.php

On another note, you should not be using mysql extension because it is deprecated, unless you are using an older installation of php. Read here for a comparison.

Parse HTML table to Python list?

If the HTML is not XML you can't do it with etree. But even then, you don't have to use an external library for parsing a HTML table. In python 3 you can reach your goal with HTMLParser from html.parser. I've the code of the simple derived HTMLParser class here in a github repo.

You can use that class (here named HTMLTableParser) the following way:

import urllib.request
from html_table_parser import HTMLTableParser

target = 'http://www.twitter.com'

# get website content
req = urllib.request.Request(url=target)
f = urllib.request.urlopen(req)
xhtml = f.read().decode('utf-8')

# instantiate the parser and feed it
p = HTMLTableParser()
p.feed(xhtml)
print(p.tables)

The output of this is a list of 2D-lists representing tables. It looks maybe like this:

[[['   ', ' Anmelden ']],
 [['Land', 'Code', 'Für Kunden von'],
  ['Vereinigte Staaten', '40404', '(beliebig)'],
  ['Kanada', '21212', '(beliebig)'],
  ...
  ['3424486444', 'Vodafone'],
  ['  Zeige SMS-Kurzwahlen für andere Länder ']]]

JFrame background image

This is a simple example for adding the background image in a JFrame:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class BackgroundImageJFrame extends JFrame
{
    JButton b1;
    JLabel l1;

    public BackgroundImageJFrame()
    {
        setTitle("Background Color for JFrame");
        setSize(400,400);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);

        /*
        One way
        -----------------
        setLayout(new BorderLayout());
        JLabel background=new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful design.png"));
        add(background);
        background.setLayout(new FlowLayout());
        l1=new JLabel("Here is a button");
        b1=new JButton("I am a button");
        background.add(l1);
        background.add(b1);
        */

        // Another way
        setLayout(new BorderLayout());
        setContentPane(new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful design.png")));
        setLayout(new FlowLayout());
        l1=new JLabel("Here is a button");
        b1=new JButton("I am a button");
        add(l1);
        add(b1);
        // Just for refresh :) Not optional!
        setSize(399,399);
        setSize(400,400);
    }

    public static void main(String args[])
    {
        new BackgroundImageJFrame();
    }
} 
  • Click here for more info

Best Way to do Columns in HTML/CSS

Bootstrap. Check out their awesome grid system here.

Using Bootstrap, you could make three columns like this:

<div class="container">
  <div class="row">
    <div class="col-md-4">.col-md-4</div>
    <div class="col-md-4">.col-md-4</div>
    <div class="col-md-4">.col-md-4</div>
  </div>
</div>

Adobe Acrobat Pro make all pages the same dimension

You have to use the Print to a New PDF option using the PDF printer. Once in the dialog box, set the page scaling to 100% and set your page size. Once you do that, your new PDF will be uniform in page sizes.

Redirect using AngularJS

With an example of the not-working code, it will be easy to answer this question, but with this information the best that I can think is that you are calling the $location.path outside of the AngularJS digest.

Try doing this on the directive scope.$apply(function() { $location.path("/route"); });

Enable CORS in fetch api

Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors at your server side.

You can fetch request using mode: 'cors'. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.

So in both condition you need to configure cors in your server or you need to use custom proxy server.

Difference between Width:100% and width:100vw?

Havengard's answer doesn't seem to be strictly true. I've found that vw fills the viewport width, but doesn't account for the scrollbars. So, if your content is taller than the viewport (so that your site has a vertical scrollbar), then using vw results in a small horizontal scrollbar. I had to switch out width: 100vw for width: 100% to get rid of the horizontal scrollbar.

R plot: size and resolution

If you'd like to use base graphics, you may have a look at this. An extract:

You can correct this with the res= argument to png, which specifies the number of pixels per inch. The smaller this number, the larger the plot area in inches, and the smaller the text relative to the graph itself.

File Upload to HTTP server in iphone programming

This is a great wrapper, but when posting to a asp.net web page, two additional post values need to be set:

    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    //ADD THESE, BECAUSE ASP.NET is Expecting them for validation
    //Even if they are empty you will be able to post the file
    [request setPostValue:@"" forKey:@"__VIEWSTATE"];
    [request setPostValue:@"" forKey:@"__EVENTVALIDATION"]; 
    ///

    [request setFile:FIleName forKey:@"fileupload_control_Name"];
    [request startSynchronous];

datetime dtypes in pandas read_csv

Why it does not work

There is no datetime dtype to be set for read_csv as csv files can only contain strings, integers and floats.

Setting a dtype to datetime will make pandas interpret the datetime as an object, meaning you will end up with a string.

Pandas way of solving this

The pandas.read_csv() function has a keyword argument called parse_dates

Using this you can on the fly convert strings, floats or integers into datetimes using the default date_parser (dateutil.parser.parser)

headers = ['col1', 'col2', 'col3', 'col4']
dtypes = {'col1': 'str', 'col2': 'str', 'col3': 'str', 'col4': 'float'}
parse_dates = ['col1', 'col2']
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes, parse_dates=parse_dates)

This will cause pandas to read col1 and col2 as strings, which they most likely are ("2016-05-05" etc.) and after having read the string, the date_parser for each column will act upon that string and give back whatever that function returns.

Defining your own date parsing function:

The pandas.read_csv() function also has a keyword argument called date_parser

Setting this to a lambda function will make that particular function be used for the parsing of the dates.

GOTCHA WARNING

You have to give it the function, not the execution of the function, thus this is Correct

date_parser = pd.datetools.to_datetime

This is incorrect:

date_parser = pd.datetools.to_datetime()

Pandas 0.22 Update

pd.datetools.to_datetime has been relocated to date_parser = pd.to_datetime

Thanks @stackoverYC

Add string in a certain position in Python

Python 3.6+ using f-string:

mys = '1362511338314'
f"{mys[:10]}_{mys[10:]}"

gives

'1362511338_314'

Converting java.util.Properties to HashMap<String,String>

When I see Spring framework source code,I find this way

Properties props = getPropertiesFromSomeWhere();
 // change properties to map
Map<String,String> map = new HashMap(props)

Use CSS to automatically add 'required field' asterisk to form inputs

It is 2019 and previous answers to this problem are not using

  1. CSS grid
  2. CSS variables
  3. HTML5 form elements
  4. SVG in CSS

CSS grid is the way to do forms in 2019 as you can have your labels preceding your inputs without having extra divs, spans, spans with asterisks in and other relics.

Here is where we are going with minimal CSS:

Example screenshot

The HTML for the above:

<form action="https://www.example.com/register/" method="post" id="form-validate" enctype="multipart/form-data">
    <p class="form-instructions">Please enter the following information to create your account.</p>
    <label for="firstname">First name</label>
    <input type="text" id="firstname" name="firstname" value="" title="First name" maxlength="255" required="">
    <label for="lastname">Last name</label>
    <input type="text" id="lastname" name="lastname" value="" title="Last name" maxlength="255" required="">
    <label for="email_address">Email address</label>
    <input type="email" autocapitalize="off" autocorrect="off" spellcheck="false" name="email" id="email_address" value="" title="Email address" size="30" required="">
    <label for="password">Password</label>
    <input type="password" name="password" id="password" title="Password" required="">
    <label for="confirmation">Confirm password</label>
    <input type="password" name="confirmation" title="Confirm password" id="confirmation" required="">
    <input type="checkbox" name="is_subscribed" title="Subscribe to our newsletter" value="1" id="is_subscribed" class="checkbox">
    <label for="is_subscribed">Subscribe to the newsletter</label>
    <input type="checkbox" name="persistent_remember_me" id="remember_meGCJiRe0GbJ" checked="checked" title="Remember me">
    <label for="remember_meGCJiRe0GbJ">Remember me</label>
    <p class="required">* Required</p>
    <button type="submit" title="Register">Register</button>
</form>

Placeholder text can be added too and is highly recommended. (I am just answering this mid-form).

Now for the CSS variables:

--icon-required: url('data:image/svg+xml,\
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="-10 -6 16 16"> \
  <line id="line" y1="-3" y2="3" stroke="%23df0000" stroke-linecap="butt" transform="rotate(15)"></line> \
  <line id="line" y1="-3" y2="3" stroke="%23df0000" stroke-linecap="butt" transform="rotate(75)"></line> \
  <line id="line" y1="-3" y2="3" stroke="%23df0000" stroke-linecap="butt" transform="rotate(-45)"></line> \
</svg>');

--icon-tick: url('data:image/svg+xml,\
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100" viewBox="-2 -2 16 16"> \
            <path fill="green" stroke-linejoin="round" d="M2 6L1 7l3 4 7-10h-1L4 8z"/> \
</svg>');

The CSS for the form elements:

input[type=text][required],
input[type=email][required],
input[type=password][required],
input[type=tel][required] {
    background-image: var(--icon-required);
    background-position-x: right;
    background-repeat: no-repeat;
    background-size: contain;
}

input:valid {
    --icon-required: var(--icon-tick);
}

The form itself should be in CSS grid:

form {
    align-items: center;
    display: grid;
    grid-gap: var(--form-grid-gap);
    grid-template-columns: var(--form-grid-template-columns);
    margin: auto;
}

The values for the columns can be set to 1fr auto or 1fr with anything such as <p> tags in the form set to span 1/-1. You change the variables in your media queries so that you have the input boxes going full width on mobile and as per above on desktop. You can also change your grid gap on mobile if you wish by using the CSS variables approach.

When the boxes are valid then you should get a green tick instead of the asterisk.

The SVG in CSS is a way of saving the browser from having to do a round trip to the server to get an image of the asterisk. In this way you can fine tune the asterisks, the examples here are at an unusual angle, you can edit this out as the SVG icon above is entirely readable. The viewbox can also be amended to place the asterisk above or below the centre.

The zip() function in Python 3

The zip() function in Python 3 returns an iterator. That is the reason why when you print test1 you get - <zip object at 0x1007a06c8>. From documentation -

Make an iterator that aggregates elements from each of the iterables.

But once you do - list(test1) - you have exhausted the iterator. So after that anytime you do list(test1) would only result in empty list.

In case of test2, you have already created the list once, test2 is a list, and hence it will always be that list.

Run command on the Ansible host

I'd like to share that Ansible can be run on localhost via shell:

ansible all -i "localhost," -c local -m shell -a 'echo hello world'

This could be helpful for simple tasks or for some hands-on learning of Ansible.

The example of code is taken from this good article:

Running ansible playbook in localhost

How to pass variable from jade template file to a script file?

See this question: JADE + EXPRESS: Iterating over object in inline JS code (client-side)?

I'm having the same problem. Jade does not pass local variables in (or do any templating at all) to javascript scripts, it simply passes the entire block in as literal text. If you use the local variables 'address' and 'port' in your Jade file above the script tag they should show up.

Possible solutions are listed in the question I linked to above, but you can either: - pass every line in as unescaped text (!= at the beginning of every line), and simply put "-" before every line of javascript that uses a local variable, or: - Pass variables in through a dom element and access through JQuery (ugly)

Is there no better way? It seems the creators of Jade do not want multiline javascript support, as shown by this thread in GitHub: https://github.com/visionmedia/jade/pull/405

How to fit a smooth curve to my data in R?

I didn't see this method shown, so if someone else is looking to do this I found that ggplot documentation suggested a technique for using the gam method that produced similar results to loess when working with small data sets.

library(ggplot2)
x <- 1:10
y <- c(2,4,6,8,7,8,14,16,18,20)

df <- data.frame(x,y)
r <- ggplot(df, aes(x = x, y = y)) + geom_smooth(method = "gam", formula = y ~ s(x, bs = "cs"))+geom_point()
r

First with the loess method and auto formula Second with the gam method with suggested formula

Add to python path mac os x

Mathew's answer works for the terminal python shell, but it didn't work for IDLE shell in my case because many versions of python existed before I replaced them all with Python2.7.7. How I solved the problem with IDLE.

  1. In terminal, cd /Applications/Python\ 2.7/IDLE.app/Contents/Resources/
  2. then sudo nano idlemain.py, enter password if required.
  3. after os.chdir(os.path.expanduser('~/Documents')) this line, I added sys.path.append("/Users/admin/Downloads....") NOTE: replace contents of the quotes with the directory where python module to be added
  4. to save the change, ctrl+x and enter Now open idle and try to import the python module, no error for me!!!

Split function equivalent in T-SQL?

DECLARE
    @InputString NVARCHAR(MAX) = 'token1,token2,token3,token4,token5'
    , @delimiter varchar(10) = ','

DECLARE @xml AS XML = CAST(('<X>'+REPLACE(@InputString,@delimiter ,'</X><X>')+'</X>') AS XML)
SELECT C.value('.', 'varchar(10)') AS value
FROM @xml.nodes('X') as X(C)

Source of this response: http://sqlhint.com/sqlserver/how-to/best-split-function-tsql-delimited

CSS Border Not Working

The height is a 100% unsure, try putting display: block; or display: inline-block;

Failed linking file resources

This might be useful for someone who is looking for a different answer. Go to the Gradle Panel and select your module -> Task -> Verification -> Check. This will check the project for errors and will print the log where the error occurs. Most of the time this Kind of error must be a typo present in your XML file of your project

How to generate a core dump in Linux on a segmentation fault?

In order to activate the core dump do the following:

  1. In /etc/profile comment the line:

    # ulimit -S -c 0 > /dev/null 2>&1
    
  2. In /etc/security/limits.conf comment out the line:

    *               soft    core            0
    
  3. execute the cmd limit coredumpsize unlimited and check it with cmd limit:

    # limit coredumpsize unlimited
    # limit
    cputime      unlimited
    filesize     unlimited
    datasize     unlimited
    stacksize    10240 kbytes
    coredumpsize unlimited
    memoryuse    unlimited
    vmemoryuse   unlimited
    descriptors  1024
    memorylocked 32 kbytes
    maxproc      528383
    #
    
  4. to check if the corefile gets written you can kill the relating process with cmd kill -s SEGV <PID> (should not be needed, just in case no core file gets written this can be used as a check):

    # kill -s SEGV <PID>
    

Once the corefile has been written make sure to deactivate the coredump settings again in the relating files (1./2./3.) !

java.net.SocketException: Connection reset by peer: socket write error When serving a file

This problem is usually caused by writing to a connection that had already been closed by the peer. In this case it could indicate that the user cancelled the download for example.

Sum values in foreach loop php

$total=0;
foreach($group as $key=>$value)
{
   echo $key. " = " .$value. "<br>"; 
   $total+= $value;
}
echo $total;

How to set DOM element as the first child?

You can implement it directly i all your window html elements.
Like this :

HTMLElement.prototype.appendFirst = function(childNode) {
    if (this.firstChild) {
        this.insertBefore(childNode, this.firstChild);
    }
    else {
        this.appendChild(childNode);
    }
};

Way to *ngFor loop defined number of times instead of repeating over array?

Within your component, you can define an array of number (ES6) as described below:

export class SampleComponent {
  constructor() {
    this.numbers = Array(5).fill(0).map((x,i)=>i);
  }
}

See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.

You can then iterate over this array with ngFor:

@View({
  template: `
    <ul>
      <li *ngFor="let number of numbers">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Or shortly:

@View({
  template: `
    <ul>
      <li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Hope it helps you, Thierry

Edit: Fixed the fill statement and template syntax.

GCC -fPIC option

The link to a function in a dynamic library is resolved when the library is loaded or at run time. Therefore, both the executable file and dynamic library are loaded into memory when the program is run. The memory address at which a dynamic library is loaded cannot be determined in advance, because a fixed address might clash with another dynamic library requiring the same address.


There are two commonly used methods for dealing with this problem:

1.Relocation. All pointers and addresses in the code are modified, if necessary, to fit the actual load address. Relocation is done by the linker and the loader.

2.Position-independent code. All addresses in the code are relative to the current position. Shared objects in Unix-like systems use position-independent code by default. This is less efficient than relocation if program run for a long time, especially in 32-bit mode.


The name "position-independent code" actually implies following:

  • The code section contains no absolute addresses that need relocation, but only self relative addresses. Therefore, the code section can be loaded at an arbitrary memory address and shared between multiple processes.

  • The data section is not shared between multiple processes because it often contains writeable data. Therefore, the data section may contain pointers or addresses that need relocation.

  • All public functions and public data can be overridden in Linux. If a function in the main executable has the same name as a function in a shared object, then the version in main will take precedence, not only when called from main, but also when called from the shared object. Likewise, when a global variable in main has the same name as a global variable in the shared object, then the instance in main will be used, even when accessed from the shared object.


This so-called symbol interposition is intended to mimic the behavior of static libraries.

A shared object has a table of pointers to its functions, called procedure linkage table (PLT) and a table of pointers to its variables called global offset table (GOT) in order to implement this "override" feature. All accesses to functions and public variables go through this tables.

p.s. Where dynamic linking cannot be avoided, there are various ways to avoid the timeconsuming features of the position-independent code.

You can read more from this article: http://www.agner.org/optimize/optimizing_cpp.pdf

CSS align one item right with flexbox

For a terse, pure flexbox option, group the left-aligned items and the right-aligned items:

<div class="wrap">
  <div>
    <span>One</span>
    <span>Two</span>
  </div>
  <div>Three</div>
</div>

and use space-between:

.wrap {
  display: flex;
  background: #ccc;
  justify-content: space-between;
}

This way you can group multiple items to the right(or just one).

https://jsfiddle.net/c9mkewwv/3/

How do I select the "last child" with a specific class name in CSS?

This can be done using an attribute selector.

[class~='list']:last-of-type  {
    background: #000;
}

The class~ selects a specific whole word. This allows your list item to have multiple classes if need be, in various order. It'll still find the exact class "list" and apply the style to the last one.

See a working example here: http://codepen.io/chasebank/pen/ZYyeab

Read more on attribute selectors:

http://css-tricks.com/attribute-selectors/ http://www.w3schools.com/css/css_attribute_selectors.asp

What datatype should be used for storing phone numbers in SQL Server 2005?

It is always better to have separate tables for multi valued attributes like phone number.

As you have no control on source data so, you can parse the data from XML file and convert it into the proper format so that there will not be any issue with formats of a particular country and store it in a separate table so that indexing and retrieval both will be efficient.

Thank you.

What does "static" mean in C?

If you declare a variable in a function static, its value will not be stored on the function call stack and will still be available when you call the function again.

If you declare a global variable static, its scope will be restricted to within the file in which you declared it. This is slightly safer than a regular global which can be read and modified throughout your entire program.

Reverse / invert a dictionary mapping

Here is another way to do it.

my_map = {'a': 1, 'b': 2}

inv_map= {}
for key in my_map.keys() :
    val = my_map[key]
    inv_map[val] = key

Example using Hyperlink in WPF

IMHO the simplest way is to use new control inherited from Hyperlink:

/// <summary>
/// Opens <see cref="Hyperlink.NavigateUri"/> in a default system browser
/// </summary>
public class ExternalBrowserHyperlink : Hyperlink
{
    public ExternalBrowserHyperlink()
    {
        RequestNavigate += OnRequestNavigate;
    }

    private void OnRequestNavigate(object sender, RequestNavigateEventArgs e)
    {
        Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
        e.Handled = true;
    }
}

How to check the presence of php and apache on ubuntu server through ssh

Try this.

dpkg -s apache2 | grep Status 

dpkg -s php5 | grep Status

Stored procedure - return identity as output parameter or scalar

SELECT IDENT_CURRENT('databasename.dbo.tablename') AS your identity column;

Can you do a partial checkout with Subversion?

If you already have the full local copy, you can remove unwanted sub folders by using --set-depth command.

svn update --set-depth=exclude www

See: http://blogs.collab.net/subversion/sparse-directories-now-with-exclusion

The set-depth command support multipile paths.

Updating the root local copy will not change the depth of the modified folder.

To restore the folder to being recusively checkingout, you could use --set-depth again with infinity param.

svn update --set-depth=infinity www

AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource

This is a server side issue. You don't need to add any headers in angular for cors. You need to add header on the server side:

Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Origin: *

First two answers here: How to enable CORS in AngularJs

instanceof Vs getClass( )

I know it has been a while since this was asked, but I learned an alternative yesterday

We all know you can do:

if(o instanceof String) {   // etc

but what if you dont know exactly what type of class it needs to be? you cannot generically do:

if(o instanceof <Class variable>.getClass()) {   

as it gives a compile error.
Instead, here is an alternative - isAssignableFrom()

For example:

public static boolean isASubClass(Class classTypeWeWant, Object objectWeHave) {

    return classTypeWeWant.isAssignableFrom(objectWeHave.getClass())
}

Add a column to a table, if it does not already exist

IF NOT EXISTS (SELECT 1  FROM SYS.COLUMNS WHERE  
OBJECT_ID = OBJECT_ID(N'[dbo].[Person]') AND name = 'DateOfBirth')
BEGIN
ALTER TABLE [dbo].[Person] ADD DateOfBirth DATETIME
END

Iterating over every property of an object in javascript using Prototype?

You should iterate over the keys and get the values using square brackets.

See: How do I enumerate the properties of a javascript object?

EDIT: Obviously, this makes the question a duplicate.

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

In my case i was missing dll in bin folder which was referenced in web.config file. So check whether you were using any setting in web.config but actually don't have dll.

Thanks

Link to all Visual Studio $ variables

Nikita's answer is nice for the macros that Visual Studio sets up in its environment, but this is far from comprehensive. (Environment variables become MSBuild macros, but not vis-a-versa.)

Slight tweak to ojdo's answer: Go to the "Pre-build event command line" in "Build Events" of the IDE for any project (where you find this in the IDE may depend on the language, i.e. C#, c++, etc. See other answers for location.) Post the code below into the "Pre-build event command line", then build that project. After the build starts, you will have a "macros.txt" file in your TEMP directory with a nice list of all the macros and their values. I based the list entirely on the list contained within ojdo's answer. I have no idea if it is comprehensive, but it's a good start!

echo AllowLocalNetworkLoopback=$(AllowLocalNetworkLoopback) >>$(TEMP)\macros.txt
echo ALLUSERSPROFILE=$(ALLUSERSPROFILE) >>$(TEMP)\macros.txt
echo AndroidTargetsPath=$(AndroidTargetsPath) >>$(TEMP)\macros.txt
echo APPDATA=$(APPDATA) >>$(TEMP)\macros.txt
echo AppxManifestMetadataClHostArchDir=$(AppxManifestMetadataClHostArchDir) >>$(TEMP)\macros.txt
echo AppxManifestMetadataCITargetArchDir=$(AppxManifestMetadataCITargetArchDir) >>$(TEMP)\macros.txt
echo Attach=$(Attach) >>$(TEMP)\macros.txt
echo BaseIntermediateOutputPath=$(BaseIntermediateOutputPath) >>$(TEMP)\macros.txt
echo BuildingInsideVisualStudio=$(BuildingInsideVisualStudio) >>$(TEMP)\macros.txt
echo CharacterSet=$(CharacterSet) >>$(TEMP)\macros.txt
echo CLRSupport=$(CLRSupport) >>$(TEMP)\macros.txt
echo CommonProgramFiles=$(CommonProgramFiles) >>$(TEMP)\macros.txt
echo CommonProgramW6432=$(CommonProgramW6432) >>$(TEMP)\macros.txt
echo COMPUTERNAME=$(COMPUTERNAME) >>$(TEMP)\macros.txt
echo ComSpec=$(ComSpec) >>$(TEMP)\macros.txt
echo Configuration=$(Configuration) >>$(TEMP)\macros.txt
echo ConfigurationType=$(ConfigurationType) >>$(TEMP)\macros.txt
echo CppWinRT_IncludePath=$(CppWinRT_IncludePath) >>$(TEMP)\macros.txt
echo CrtSDKReferencelnclude=$(CrtSDKReferencelnclude) >>$(TEMP)\macros.txt
echo CrtSDKReferenceVersion=$(CrtSDKReferenceVersion) >>$(TEMP)\macros.txt
echo CustomAfterMicrosoftCommonProps=$(CustomAfterMicrosoftCommonProps) >>$(TEMP)\macros.txt
echo CustomBeforeMicrosoftCommonProps=$(CustomBeforeMicrosoftCommonProps) >>$(TEMP)\macros.txt
echo DebugCppRuntimeFilesPath=$(DebugCppRuntimeFilesPath) >>$(TEMP)\macros.txt
echo DebuggerFlavor=$(DebuggerFlavor) >>$(TEMP)\macros.txt
echo DebuggerLaunchApplication=$(DebuggerLaunchApplication) >>$(TEMP)\macros.txt
echo DebuggerRequireAuthentication=$(DebuggerRequireAuthentication) >>$(TEMP)\macros.txt
echo DebuggerType=$(DebuggerType) >>$(TEMP)\macros.txt
echo DefaultLanguageSourceExtension=$(DefaultLanguageSourceExtension) >>$(TEMP)\macros.txt
echo DefaultPlatformToolset=$(DefaultPlatformToolset) >>$(TEMP)\macros.txt
echo DefaultWindowsSDKVersion=$(DefaultWindowsSDKVersion) >>$(TEMP)\macros.txt
echo DefineExplicitDefaults=$(DefineExplicitDefaults) >>$(TEMP)\macros.txt
echo DelayImplib=$(DelayImplib) >>$(TEMP)\macros.txt
echo DesignTimeBuild=$(DesignTimeBuild) >>$(TEMP)\macros.txt
echo DevEnvDir=$(DevEnvDir) >>$(TEMP)\macros.txt
echo DocumentLibraryDependencies=$(DocumentLibraryDependencies) >>$(TEMP)\macros.txt
echo DotNetSdk_IncludePath=$(DotNetSdk_IncludePath) >>$(TEMP)\macros.txt
echo DotNetSdk_LibraryPath=$(DotNetSdk_LibraryPath) >>$(TEMP)\macros.txt
echo DotNetSdk_LibraryPath_arm=$(DotNetSdk_LibraryPath_arm) >>$(TEMP)\macros.txt
echo DotNetSdk_LibraryPath_arm64=$(DotNetSdk_LibraryPath_arm64) >>$(TEMP)\macros.txt
echo DotNetSdk_LibraryPath_x64=$(DotNetSdk_LibraryPath_x64) >>$(TEMP)\macros.txt
echo DotNetSdk_LibraryPath_x86=$(DotNetSdk_LibraryPath_x86) >>$(TEMP)\macros.txt
echo DotNetSdkRoot=$(DotNetSdkRoot) >>$(TEMP)\macros.txt
echo DriverData=$(DriverData) >>$(TEMP)\macros.txt
echo EmbedManifest=$(EmbedManifest) >>$(TEMP)\macros.txt
echo EnableManagedIncrementalBuild=$(EnableManagedIncrementalBuild) >>$(TEMP)\macros.txt
echo EspXtensions=$(EspXtensions) >>$(TEMP)\macros.txt
echo ExcludePath=$(ExcludePath) >>$(TEMP)\macros.txt
echo ExecutablePath=$(ExecutablePath) >>$(TEMP)\macros.txt
echo ExtensionsToDeleteOnClean=$(ExtensionsToDeleteOnClean) >>$(TEMP)\macros.txt
echo FPS_BROWSER_APP_PROFILE_STRING=$(FPS_BROWSER_APP_PROFILE_STRING) >>$(TEMP)\macros.txt
echo FPS_BROWSER_USER_PROFILE_STRING=$(FPS_BROWSER_USER_PROFILE_STRING) >>$(TEMP)\macros.txt
echo FrameworkDir=$(FrameworkDir) >>$(TEMP)\macros.txt
echo FrameworkDir_110=$(FrameworkDir_110) >>$(TEMP)\macros.txt
echo FrameworkSdkDir=$(FrameworkSdkDir) >>$(TEMP)\macros.txt
echo FrameworkSDKRoot=$(FrameworkSDKRoot) >>$(TEMP)\macros.txt
echo FrameworkVersion=$(FrameworkVersion) >>$(TEMP)\macros.txt
echo GenerateManifest=$(GenerateManifest) >>$(TEMP)\macros.txt
echo GPURefDebuggerBreakOnAllThreads=$(GPURefDebuggerBreakOnAllThreads) >>$(TEMP)\macros.txt
echo HOMEDRIVE=$(HOMEDRIVE) >>$(TEMP)\macros.txt
echo HOMEPATH=$(HOMEPATH) >>$(TEMP)\macros.txt
echo IgnorelmportLibrary=$(IgnorelmportLibrary) >>$(TEMP)\macros.txt
echo ImportByWildcardAfterMicrosoftCommonProps=$(ImportByWildcardAfterMicrosoftCommonProps) >>$(TEMP)\macros.txt
echo ImportByWildcardBeforeMicrosoftCommonProps=$(ImportByWildcardBeforeMicrosoftCommonProps) >>$(TEMP)\macros.txt
echo ImportDirectoryBuildProps=$(ImportDirectoryBuildProps) >>$(TEMP)\macros.txt
echo ImportProjectExtensionProps=$(ImportProjectExtensionProps) >>$(TEMP)\macros.txt
echo ImportUserLocationsByWildcardAfterMicrosoftCommonProps=$(ImportUserLocationsByWildcardAfterMicrosoftCommonProps) >>$(TEMP)\macros.txt
echo ImportUserLocationsByWildcardBeforeMicrosoftCommonProps=$(ImportUserLocationsByWildcardBeforeMicrosoftCommonProps) >>$(TEMP)\macros.txt
echo IncludePath=$(IncludePath) >>$(TEMP)\macros.txt
echo IncludeVersionInInteropName=$(IncludeVersionInInteropName) >>$(TEMP)\macros.txt
echo IntDir=$(IntDir) >>$(TEMP)\macros.txt
echo InteropOutputPath=$(InteropOutputPath) >>$(TEMP)\macros.txt
echo iOSTargetsPath=$(iOSTargetsPath) >>$(TEMP)\macros.txt
echo Keyword=$(Keyword) >>$(TEMP)\macros.txt
echo KIT_SHARED_IncludePath=$(KIT_SHARED_IncludePath) >>$(TEMP)\macros.txt
echo LangID=$(LangID) >>$(TEMP)\macros.txt
echo LangName=$(LangName) >>$(TEMP)\macros.txt
echo Language=$(Language) >>$(TEMP)\macros.txt
echo LIBJABRA_TRACE_LEVEL=$(LIBJABRA_TRACE_LEVEL) >>$(TEMP)\macros.txt
echo LibraryPath=$(LibraryPath) >>$(TEMP)\macros.txt
echo LibraryWPath=$(LibraryWPath) >>$(TEMP)\macros.txt
echo LinkCompiled=$(LinkCompiled) >>$(TEMP)\macros.txt
echo LinkIncremental=$(LinkIncremental) >>$(TEMP)\macros.txt
echo LOCALAPPDATA=$(LOCALAPPDATA) >>$(TEMP)\macros.txt
echo LocalDebuggerAttach=$(LocalDebuggerAttach) >>$(TEMP)\macros.txt
echo LocalDebuggerDebuggerlType=$(LocalDebuggerDebuggerlType) >>$(TEMP)\macros.txt
echo LocalDebuggerMergeEnvironment=$(LocalDebuggerMergeEnvironment) >>$(TEMP)\macros.txt
echo LocalDebuggerSQLDebugging=$(LocalDebuggerSQLDebugging) >>$(TEMP)\macros.txt
echo LocalDebuggerWorkingDirectory=$(LocalDebuggerWorkingDirectory) >>$(TEMP)\macros.txt
echo LocalGPUDebuggerTargetType=$(LocalGPUDebuggerTargetType) >>$(TEMP)\macros.txt
echo LOGONSERVER=$(LOGONSERVER) >>$(TEMP)\macros.txt
echo MicrosoftCommonPropsHasBeenImported=$(MicrosoftCommonPropsHasBeenImported) >>$(TEMP)\macros.txt
echo MpiDebuggerCleanupDeployment=$(MpiDebuggerCleanupDeployment) >>$(TEMP)\macros.txt
echo MpiDebuggerDebuggerType=$(MpiDebuggerDebuggerType) >>$(TEMP)\macros.txt
echo MpiDebuggerDeployCommonRuntime=$(MpiDebuggerDeployCommonRuntime) >>$(TEMP)\macros.txt
echo MpiDebuggerNetworkSecurityMode=$(MpiDebuggerNetworkSecurityMode) >>$(TEMP)\macros.txt
echo MpiDebuggerSchedulerNode=$(MpiDebuggerSchedulerNode) >>$(TEMP)\macros.txt
echo MpiDebuggerSchedulerTimeout=$(MpiDebuggerSchedulerTimeout) >>$(TEMP)\macros.txt
echo MSBuild_ExecutablePath=$(MSBuild_ExecutablePath) >>$(TEMP)\macros.txt
echo MSBuildAllProjects=$(MSBuildAllProjects) >>$(TEMP)\macros.txt
echo MSBuildAssemblyVersion=$(MSBuildAssemblyVersion) >>$(TEMP)\macros.txt
echo MSBuildBinPath=$(MSBuildBinPath) >>$(TEMP)\macros.txt
echo MSBuildExtensionsPath=$(MSBuildExtensionsPath) >>$(TEMP)\macros.txt
echo MSBuildExtensionsPath32=$(MSBuildExtensionsPath32) >>$(TEMP)\macros.txt
echo MSBuildExtensionsPath64=$(MSBuildExtensionsPath64) >>$(TEMP)\macros.txt
echo MSBuildFrameworkToolsPath=$(MSBuildFrameworkToolsPath) >>$(TEMP)\macros.txt
echo MSBuildFrameworkToolsPath32=$(MSBuildFrameworkToolsPath32) >>$(TEMP)\macros.txt
echo MSBuildFrameworkToolsPath64=$(MSBuildFrameworkToolsPath64) >>$(TEMP)\macros.txt
echo MSBuildFrameworkToolsRoot=$(MSBuildFrameworkToolsRoot) >>$(TEMP)\macros.txt
echo MSBuildLoadMicrosoftTargetsReadOnly=$(MSBuildLoadMicrosoftTargetsReadOnly) >>$(TEMP)\macros.txt
echo MSBuildNodeCount=$(MSBuildNodeCount) >>$(TEMP)\macros.txt
echo MSBuildProgramFiles32=$(MSBuildProgramFiles32) >>$(TEMP)\macros.txt
echo MSBuildProjectDefaultTargets=$(MSBuildProjectDefaultTargets) >>$(TEMP)\macros.txt
echo MSBuildProjectDirectory=$(MSBuildProjectDirectory) >>$(TEMP)\macros.txt
echo MSBuildProjectDirectoryNoRoot=$(MSBuildProjectDirectoryNoRoot) >>$(TEMP)\macros.txt
echo MSBuildProjectExtension=$(MSBuildProjectExtension) >>$(TEMP)\macros.txt
echo MSBuildProjectExtensionsPath=$(MSBuildProjectExtensionsPath) >>$(TEMP)\macros.txt
echo MSBuildProjectFile=$(MSBuildProjectFile) >>$(TEMP)\macros.txt
echo MSBuildProjectFullPath=$(MSBuildProjectFullPath) >>$(TEMP)\macros.txt
echo MSBuildProjectName=$(MSBuildProjectName) >>$(TEMP)\macros.txt
echo MSBuildRuntimeType=$(MSBuildRuntimeType) >>$(TEMP)\macros.txt
echo MSBuildRuntimeVersion=$(MSBuildRuntimeVersion) >>$(TEMP)\macros.txt
echo MSBuildSDKsPath=$(MSBuildSDKsPath) >>$(TEMP)\macros.txt
echo MSBuildStartupDirectory=$(MSBuildStartupDirectory) >>$(TEMP)\macros.txt
echo MSBuildToolsPath=$(MSBuildToolsPath) >>$(TEMP)\macros.txt
echo MSBuildToolsPath32=$(MSBuildToolsPath32) >>$(TEMP)\macros.txt
echo MSBuildToolsPath64=$(MSBuildToolsPath64) >>$(TEMP)\macros.txt
echo MSBuildToolsRoot=$(MSBuildToolsRoot) >>$(TEMP)\macros.txt
echo MSBuildToolsVersion=$(MSBuildToolsVersion) >>$(TEMP)\macros.txt
echo MSBuildUserExtensionsPath=$(MSBuildUserExtensionsPath) >>$(TEMP)\macros.txt
echo MSBuildVersion=$(MSBuildVersion) >>$(TEMP)\macros.txt
echo MultiToolTask=$(MultiToolTask) >>$(TEMP)\macros.txt
echo NETFXKitsDir=$(NETFXKitsDir) >>$(TEMP)\macros.txt
echo NETFXSDKDir=$(NETFXSDKDir) >>$(TEMP)\macros.txt
echo NuGetProps=$(NuGetProps) >>$(TEMP)\macros.txt
echo NUMBER_OF_PROCESSORS=$(NUMBER_OF_PROCESSORS) >>$(TEMP)\macros.txt
echo OCTAVE_EXECUTABLE=$(OCTAVE_EXECUTABLE) >>$(TEMP)\macros.txt
echo OneDrive=$(OneDrive) >>$(TEMP)\macros.txt
echo OneDriveCommercial=$(OneDriveCommercial) >>$(TEMP)\macros.txt
echo OS=$(OS) >>$(TEMP)\macros.txt
echo OutDir=$(OutDir) >>$(TEMP)\macros.txt
echo OutDirWasSpecified=$(OutDirWasSpecified) >>$(TEMP)\macros.txt
echo OutputType=$(OutputType) >>$(TEMP)\macros.txt
echo Path=$(Path) >>$(TEMP)\macros.txt
echo PATHEXT=$(PATHEXT) >>$(TEMP)\macros.txt
echo PkgDefApplicationConfigFile=$(PkgDefApplicationConfigFile) >>$(TEMP)\macros.txt
echo Platform=$(Platform) >>$(TEMP)\macros.txt
echo Platform_Actual=$(Platform_Actual) >>$(TEMP)\macros.txt
echo PlatformArchitecture=$(PlatformArchitecture) >>$(TEMP)\macros.txt
echo PlatformName=$(PlatformName) >>$(TEMP)\macros.txt
echo PlatformPropsFound=$(PlatformPropsFound) >>$(TEMP)\macros.txt
echo PlatformShortName=$(PlatformShortName) >>$(TEMP)\macros.txt
echo PlatformTarget=$(PlatformTarget) >>$(TEMP)\macros.txt
echo PlatformTargetsFound=$(PlatformTargetsFound) >>$(TEMP)\macros.txt
echo PlatformToolset=$(PlatformToolset) >>$(TEMP)\macros.txt
echo PlatformToolsetVersion=$(PlatformToolsetVersion) >>$(TEMP)\macros.txt
echo PostBuildEventUseInBuild=$(PostBuildEventUseInBuild) >>$(TEMP)\macros.txt
echo PreBuildEventUseInBuild=$(PreBuildEventUseInBuild) >>$(TEMP)\macros.txt
echo PreferredToolArchitecture=$(PreferredToolArchitecture) >>$(TEMP)\macros.txt
echo PreLinkEventUselnBuild=$(PreLinkEventUselnBuild) >>$(TEMP)\macros.txt
echo PROCESSOR_ARCHITECTURE=$(PROCESSOR_ARCHITECTURE) >>$(TEMP)\macros.txt
echo PROCESSOR_ARCHITEW6432=$(PROCESSOR_ARCHITEW6432) >>$(TEMP)\macros.txt
echo PROCESSOR_IDENTIFIER=$(PROCESSOR_IDENTIFIER) >>$(TEMP)\macros.txt
echo PROCESSOR_LEVEL=$(PROCESSOR_LEVEL) >>$(TEMP)\macros.txt
echo PROCESSOR_REVISION=$(PROCESSOR_REVISION) >>$(TEMP)\macros.txt
echo ProgramData=$(ProgramData) >>$(TEMP)\macros.txt
echo ProgramFiles=$(ProgramFiles) >>$(TEMP)\macros.txt
echo ProgramW6432=$(ProgramW6432) >>$(TEMP)\macros.txt
echo ProjectDir=$(ProjectDir) >>$(TEMP)\macros.txt
echo ProjectExt=$(ProjectExt) >>$(TEMP)\macros.txt
echo ProjectFileName=$(ProjectFileName) >>$(TEMP)\macros.txt
echo ProjectGuid=$(ProjectGuid) >>$(TEMP)\macros.txt
echo ProjectName=$(ProjectName) >>$(TEMP)\macros.txt
echo ProjectPath=$(ProjectPath) >>$(TEMP)\macros.txt
echo PSExecutionPolicyPreference=$(PSExecutionPolicyPreference) >>$(TEMP)\macros.txt
echo PSModulePath=$(PSModulePath) >>$(TEMP)\macros.txt
echo PUBLIC=$(PUBLIC) >>$(TEMP)\macros.txt
echo ReferencePath=$(ReferencePath) >>$(TEMP)\macros.txt
echo RemoteDebuggerAttach=$(RemoteDebuggerAttach) >>$(TEMP)\macros.txt
echo RemoteDebuggerConnection=$(RemoteDebuggerConnection) >>$(TEMP)\macros.txt
echo RemoteDebuggerDebuggerlype=$(RemoteDebuggerDebuggerlype) >>$(TEMP)\macros.txt
echo RemoteDebuggerDeployDebugCppRuntime=$(RemoteDebuggerDeployDebugCppRuntime) >>$(TEMP)\macros.txt
echo RemoteDebuggerServerName=$(RemoteDebuggerServerName) >>$(TEMP)\macros.txt
echo RemoteDebuggerSQLDebugging=$(RemoteDebuggerSQLDebugging) >>$(TEMP)\macros.txt
echo RemoteDebuggerWorkingDirectory=$(RemoteDebuggerWorkingDirectory) >>$(TEMP)\macros.txt
echo RemoteGPUDebuggerTargetType=$(RemoteGPUDebuggerTargetType) >>$(TEMP)\macros.txt
echo RetargetAlwaysSupported=$(RetargetAlwaysSupported) >>$(TEMP)\macros.txt
echo RootNamespace=$(RootNamespace) >>$(TEMP)\macros.txt
echo RoslynTargetsPath=$(RoslynTargetsPath) >>$(TEMP)\macros.txt
echo SDK35ToolsPath=$(SDK35ToolsPath) >>$(TEMP)\macros.txt
echo SDK40ToolsPath=$(SDK40ToolsPath) >>$(TEMP)\macros.txt
echo SDKDisplayName=$(SDKDisplayName) >>$(TEMP)\macros.txt
echo SDKIdentifier=$(SDKIdentifier) >>$(TEMP)\macros.txt
echo SDKVersion=$(SDKVersion) >>$(TEMP)\macros.txt
echo SESSIONNAME=$(SESSIONNAME) >>$(TEMP)\macros.txt
echo SolutionDir=$(SolutionDir) >>$(TEMP)\macros.txt
echo SolutionExt=$(SolutionExt) >>$(TEMP)\macros.txt
echo SolutionFileName=$(SolutionFileName) >>$(TEMP)\macros.txt
echo SolutionName=$(SolutionName) >>$(TEMP)\macros.txt
echo SolutionPath=$(SolutionPath) >>$(TEMP)\macros.txt
echo SourcePath=$(SourcePath) >>$(TEMP)\macros.txt
echo SpectreMitigation=$(SpectreMitigation) >>$(TEMP)\macros.txt
echo SQLDebugging=$(SQLDebugging) >>$(TEMP)\macros.txt
echo SystemDrive=$(SystemDrive) >>$(TEMP)\macros.txt
echo SystemRoot=$(SystemRoot) >>$(TEMP)\macros.txt
echo TargetExt=$(TargetExt) >>$(TEMP)\macros.txt
echo TargetFrameworkVersion=$(TargetFrameworkVersion) >>$(TEMP)\macros.txt
echo TargetName=$(TargetName) >>$(TEMP)\macros.txt
echo TargetPlatformMinVersion=$(TargetPlatformMinVersion) >>$(TEMP)\macros.txt
echo TargetPlatformVersion=$(TargetPlatformVersion) >>$(TEMP)\macros.txt
echo TargetPlatformWinMDLocation=$(TargetPlatformWinMDLocation) >>$(TEMP)\macros.txt
echo TargetUniversalCRTVersion=$(TargetUniversalCRTVersion) >>$(TEMP)\macros.txt
echo TEMP=$(TEMP) >>$(TEMP)\macros.txt
echo TMP=$(TMP) >>$(TEMP)\macros.txt
echo ToolsetPropsFound=$(ToolsetPropsFound) >>$(TEMP)\macros.txt
echo ToolsetTargetsFound=$(ToolsetTargetsFound) >>$(TEMP)\macros.txt
echo UCRTContentRoot=$(UCRTContentRoot) >>$(TEMP)\macros.txt
echo UM_IncludePath=$(UM_IncludePath) >>$(TEMP)\macros.txt
echo UniversalCRT_IncludePath=$(UniversalCRT_IncludePath) >>$(TEMP)\macros.txt
echo UniversalCRT_LibraryPath_arm=$(UniversalCRT_LibraryPath_arm) >>$(TEMP)\macros.txt
echo UniversalCRT_LibraryPath_arm64=$(UniversalCRT_LibraryPath_arm64) >>$(TEMP)\macros.txt
echo UniversalCRT_LibraryPath_x64=$(UniversalCRT_LibraryPath_x64) >>$(TEMP)\macros.txt
echo UniversalCRT_LibraryPath_x86=$(UniversalCRT_LibraryPath_x86) >>$(TEMP)\macros.txt
echo UniversalCRT_PropsPath=$(UniversalCRT_PropsPath) >>$(TEMP)\macros.txt
echo UniversalCRT_SourcePath=$(UniversalCRT_SourcePath) >>$(TEMP)\macros.txt
echo UniversalCRTSdkDir=$(UniversalCRTSdkDir) >>$(TEMP)\macros.txt
echo UniversalCRTSdkDir_10=$(UniversalCRTSdkDir_10) >>$(TEMP)\macros.txt
echo UseDebugLibraries=$(UseDebugLibraries) >>$(TEMP)\macros.txt
echo UseLegacyManagedDebugger=$(UseLegacyManagedDebugger) >>$(TEMP)\macros.txt
echo UseOfATL=$(UseOfATL) >>$(TEMP)\macros.txt
echo UseOfMfc=$(UseOfMfc) >>$(TEMP)\macros.txt
echo USERDOMAIN=$(USERDOMAIN) >>$(TEMP)\macros.txt
echo USERDOMAIN_ROAMINGPROFILE=$(USERDOMAIN_ROAMINGPROFILE) >>$(TEMP)\macros.txt
echo USERNAME=$(USERNAME) >>$(TEMP)\macros.txt
echo USERPROFILE=$(USERPROFILE) >>$(TEMP)\macros.txt
echo UserRootDir=$(UserRootDir) >>$(TEMP)\macros.txt
echo VBOX_MSI_INSTALL_PATH=$(VBOX_MSI_INSTALL_PATH) >>$(TEMP)\macros.txt
echo VC_ATLMFC_IncludePath=$(VC_ATLMFC_IncludePath) >>$(TEMP)\macros.txt
echo VC_ATLMFC_SourcePath=$(VC_ATLMFC_SourcePath) >>$(TEMP)\macros.txt
echo VC_CRT_SourcePath=$(VC_CRT_SourcePath) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_ARM=$(VC_ExecutablePath_ARM) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_ARM64=$(VC_ExecutablePath_ARM64) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x64=$(VC_ExecutablePath_x64) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x64_ARM=$(VC_ExecutablePath_x64_ARM) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x64_ARM64=$(VC_ExecutablePath_x64_ARM64) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x64_x64=$(VC_ExecutablePath_x64_x64) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x64_x86=$(VC_ExecutablePath_x64_x86) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x86=$(VC_ExecutablePath_x86) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x86_ARM=$(VC_ExecutablePath_x86_ARM) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x86_ARM64=$(VC_ExecutablePath_x86_ARM64) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x86_x64=$(VC_ExecutablePath_x86_x64) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x86_x86=$(VC_ExecutablePath_x86_x86) >>$(TEMP)\macros.txt
echo VC_IFCPath=$(VC_IFCPath) >>$(TEMP)\macros.txt
echo VC_IncludePath=$(VC_IncludePath) >>$(TEMP)\macros.txt
echo VC_LibraryPath_ARM=$(VC_LibraryPath_ARM) >>$(TEMP)\macros.txt
echo VC_LibraryPath_ARM64=$(VC_LibraryPath_ARM64) >>$(TEMP)\macros.txt
echo VC_LibraryPath_ATL_ARM=$(VC_LibraryPath_ATL_ARM) >>$(TEMP)\macros.txt
echo VC_LibraryPath_ATL_ARM64=$(VC_LibraryPath_ATL_ARM64) >>$(TEMP)\macros.txt
echo VC_LibraryPath_ATL_x64=$(VC_LibraryPath_ATL_x64) >>$(TEMP)\macros.txt
echo VC_LibraryPath_ATL_x86=$(VC_LibraryPath_ATL_x86) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_ARM=$(VC_LibraryPath_VC_ARM) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_ARM_Desktop=$(VC_LibraryPath_VC_ARM_Desktop) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_ARM_OneCore=$(VC_LibraryPath_VC_ARM_OneCore) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_ARM_Store=$(VC_LibraryPath_VC_ARM_Store) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_ARM64=$(VC_LibraryPath_VC_ARM64) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_ARM64_Desktop=$(VC_LibraryPath_VC_ARM64_Desktop) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_ARM64_OneCore=$(VC_LibraryPath_VC_ARM64_OneCore) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_ARM64_Store=$(VC_LibraryPath_VC_ARM64_Store) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_x64=$(VC_LibraryPath_VC_x64) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_x64_Desktop=$(VC_LibraryPath_VC_x64_Desktop) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_x64_OneCore=$(VC_LibraryPath_VC_x64_OneCore) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_x64_Store=$(VC_LibraryPath_VC_x64_Store) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_x86=$(VC_LibraryPath_VC_x86) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_x86_Desktop=$(VC_LibraryPath_VC_x86_Desktop) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_x86_OneCore=$(VC_LibraryPath_VC_x86_OneCore) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_x86_Store=$(VC_LibraryPath_VC_x86_Store) >>$(TEMP)\macros.txt
echo VC_LibraryPath_x64=$(VC_LibraryPath_x64) >>$(TEMP)\macros.txt
echo VC_LibraryPath_x86=$(VC_LibraryPath_x86) >>$(TEMP)\macros.txt
echo VC_PGO_RunTime_Dir=$(VC_PGO_RunTime_Dir) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_ARM=$(VC_ReferencesPath_ARM) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_ARM64=$(VC_ReferencesPath_ARM64) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_ATL_ARM=$(VC_ReferencesPath_ATL_ARM) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_ATL_ARM64=$(VC_ReferencesPath_ATL_ARM64) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_ATL_x64=$(VC_ReferencesPath_ATL_x64) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_ATL_x86=$(VC_ReferencesPath_ATL_x86) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_VC_ARM=$(VC_ReferencesPath_VC_ARM) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_VC_ARM64=$(VC_ReferencesPath_VC_ARM64) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_VC_x64=$(VC_ReferencesPath_VC_x64) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_VC_x86=$(VC_ReferencesPath_VC_x86) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_x64=$(VC_ReferencesPath_x64) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_x86=$(VC_ReferencesPath_x86) >>$(TEMP)\macros.txt
echo VC_SourcePath=$(VC_SourcePath) >>$(TEMP)\macros.txt
echo VC_VC_IncludePath=$(VC_VC_IncludePath) >>$(TEMP)\macros.txt
echo VC_VS_IncludePath=$(VC_VS_IncludePath) >>$(TEMP)\macros.txt
echo VC_VS_LibraryPath_VC_VS_ARM=$(VC_VS_LibraryPath_VC_VS_ARM) >>$(TEMP)\macros.txt
echo VC_VS_LibraryPath_VC_VS_x64=$(VC_VS_LibraryPath_VC_VS_x64) >>$(TEMP)\macros.txt
echo VC_VS_LibraryPath_VC_VS_x86=$(VC_VS_LibraryPath_VC_VS_x86) >>$(TEMP)\macros.txt
echo VC_VS_SourcePath=$(VC_VS_SourcePath) >>$(TEMP)\macros.txt
echo VCIDEInstallDir=$(VCIDEInstallDir) >>$(TEMP)\macros.txt
echo VCIDEInstallDir_150=$(VCIDEInstallDir_150) >>$(TEMP)\macros.txt
echo VCInstallDir=$(VCInstallDir) >>$(TEMP)\macros.txt
echo VCInstallDir_150=$(VCInstallDir_150) >>$(TEMP)\macros.txt
echo VCLibPackagePath=$(VCLibPackagePath) >>$(TEMP)\macros.txt
echo VCProjectVersion=$(VCProjectVersion) >>$(TEMP)\macros.txt
echo VCTargetsPath=$(VCTargetsPath) >>$(TEMP)\macros.txt
echo VCTargetsPath10=$(VCTargetsPath10) >>$(TEMP)\macros.txt
echo VCTargetsPath11=$(VCTargetsPath11) >>$(TEMP)\macros.txt
echo VCTargetsPath12=$(VCTargetsPath12) >>$(TEMP)\macros.txt
echo VCTargetsPath14=$(VCTargetsPath14) >>$(TEMP)\macros.txt
echo VCTargetsPath15=$(VCTargetsPath15) >>$(TEMP)\macros.txt
echo VCTargetsPathActual=$(VCTargetsPathActual) >>$(TEMP)\macros.txt
echo VCTargetsPathEffective=$(VCTargetsPathEffective) >>$(TEMP)\macros.txt
echo VCToolArchitecture=$(VCToolArchitecture) >>$(TEMP)\macros.txt
echo VCToolsInstallDir=$(VCToolsInstallDir) >>$(TEMP)\macros.txt
echo VCToolsInstallDir_150=$(VCToolsInstallDir_150) >>$(TEMP)\macros.txt
echo VCToolsVersion=$(VCToolsVersion) >>$(TEMP)\macros.txt
echo VisualStudioDir=$(VisualStudioDir) >>$(TEMP)\macros.txt
echo VisualStudioEdition=$(VisualStudioEdition) >>$(TEMP)\macros.txt
echo VisualStudioVersion=$(VisualStudioVersion) >>$(TEMP)\macros.txt
echo VS_ExecutablePath=$(VS_ExecutablePath) >>$(TEMP)\macros.txt
echo VS140COMNTOOLS=$(VS140COMNTOOLS) >>$(TEMP)\macros.txt
echo VSAPPIDDIR=$(VSAPPIDDIR) >>$(TEMP)\macros.txt
echo VSAPPIDNAME=$(VSAPPIDNAME) >>$(TEMP)\macros.txt
echo VSInstallDir=$(VSInstallDir) >>$(TEMP)\macros.txt
echo VSInstallDir_150=$(VSInstallDir_150) >>$(TEMP)\macros.txt
echo VsInstallRoot=$(VsInstallRoot) >>$(TEMP)\macros.txt
echo VSLANG=$(VSLANG) >>$(TEMP)\macros.txt
echo VSSKUEDITION=$(VSSKUEDITION) >>$(TEMP)\macros.txt
echo VSVersion=$(VSVersion) >>$(TEMP)\macros.txt
echo WDKBinRoot=$(WDKBinRoot) >>$(TEMP)\macros.txt
echo WebBrowserDebuggerDebuggerlype=$(WebBrowserDebuggerDebuggerlype) >>$(TEMP)\macros.txt
echo WebServiceDebuggerDebuggerlype=$(WebServiceDebuggerDebuggerlype) >>$(TEMP)\macros.txt
echo WebServiceDebuggerSQLDebugging=$(WebServiceDebuggerSQLDebugging) >>$(TEMP)\macros.txt
echo WholeProgramOptimization=$(WholeProgramOptimization) >>$(TEMP)\macros.txt
echo WholeProgramOptimizationAvailabilityInstrument=$(WholeProgramOptimizationAvailabilityInstrument) >>$(TEMP)\macros.txt
echo WholeProgramOptimizationAvailabilityOptimize=$(WholeProgramOptimizationAvailabilityOptimize) >>$(TEMP)\macros.txt
echo WholeProgramOptimizationAvailabilityTrue=$(WholeProgramOptimizationAvailabilityTrue) >>$(TEMP)\macros.txt
echo WholeProgramOptimizationAvailabilityUpdate=$(WholeProgramOptimizationAvailabilityUpdate) >>$(TEMP)\macros.txt
echo windir=$(windir) >>$(TEMP)\macros.txt
echo Windows81SdkInstalled=$(Windows81SdkInstalled) >>$(TEMP)\macros.txt
echo WindowsAppContainer=$(WindowsAppContainer) >>$(TEMP)\macros.txt
echo WindowsSDK_ExecutablePath=$(WindowsSDK_ExecutablePath) >>$(TEMP)\macros.txt
echo WindowsSDK_ExecutablePath_arm=$(WindowsSDK_ExecutablePath_arm) >>$(TEMP)\macros.txt
echo WindowsSDK_ExecutablePath_arm64=$(WindowsSDK_ExecutablePath_arm64) >>$(TEMP)\macros.txt
echo WindowsSDK_ExecutablePath_x64=$(WindowsSDK_ExecutablePath_x64) >>$(TEMP)\macros.txt
echo WindowsSDK_LibraryPath_x86=$(WindowsSDK_LibraryPath_x86) >>$(TEMP)\macros.txt
echo WindowsSDK_MetadataFoundationPath=$(WindowsSDK_MetadataFoundationPath) >>$(TEMP)\macros.txt
echo WindowsSDK_MetadataPath=$(WindowsSDK_MetadataPath) >>$(TEMP)\macros.txt
echo WindowsSDK_MetadataPathVersioned=$(WindowsSDK_MetadataPathVersioned) >>$(TEMP)\macros.txt
echo WindowsSDK_PlatformPath=$(WindowsSDK_PlatformPath) >>$(TEMP)\macros.txt
echo WindowsSDK_SupportedAPIs_arm=$(WindowsSDK_SupportedAPIs_arm) >>$(TEMP)\macros.txt
echo WindowsSDK_SupportedAPIs_x64=$(WindowsSDK_SupportedAPIs_x64) >>$(TEMP)\macros.txt
echo WindowsSDK_SupportedAPIs_x86=$(WindowsSDK_SupportedAPIs_x86) >>$(TEMP)\macros.txt
echo WindowsSDK_UnionMetadataPath=$(WindowsSDK_UnionMetadataPath) >>$(TEMP)\macros.txt
echo WindowsSDK80Path=$(WindowsSDK80Path) >>$(TEMP)\macros.txt
echo WindowsSdkDir=$(WindowsSdkDir) >>$(TEMP)\macros.txt
echo WindowsSdkDir_10=$(WindowsSdkDir_10) >>$(TEMP)\macros.txt
echo WindowsSdkDir_81=$(WindowsSdkDir_81) >>$(TEMP)\macros.txt
echo WindowsSdkDir_81A=$(WindowsSdkDir_81A) >>$(TEMP)\macros.txt
echo WindowsSDKToolArchitecture=$(WindowsSDKToolArchitecture) >>$(TEMP)\macros.txt
echo WindowsTargetPlatformVersion=$(WindowsTargetPlatformVersion) >>$(TEMP)\macros.txt
echo WinRT_IncludePath=$(WinRT_IncludePath) >>$(TEMP)\macros.txt
echo WMSISProject=$(WMSISProject) >>$(TEMP)\macros.txt
echo WMSISProjectDirectory=$(WMSISProjectDirectory) >>$(TEMP)\macros.txt

How can I get the count of milliseconds since midnight for the current?

I did the test using java 8 It wont matter the order the builder always takes 0 milliseconds and the concat between 26 and 33 milliseconds under and iteration of a 1000 concatenation

Hope it helps try it with your ide

public void count() {

        String result = "";

        StringBuilder builder = new StringBuilder();

        long millis1 = System.currentTimeMillis(),
            millis2;

        for (int i = 0; i < 1000; i++) {
            builder.append("hello world this is the concat vs builder test enjoy");
        }

        millis2 = System.currentTimeMillis();

        System.out.println("Diff: " + (millis2 - millis1));

        millis1 = System.currentTimeMillis();

        for (int i = 0; i < 1000; i++) {
            result += "hello world this is the concat vs builder test enjoy";
        }

        millis2 = System.currentTimeMillis();

        System.out.println("Diff: " + (millis2 - millis1));
    }

How can I control the width of a label tag?

Inline elements (like SPAN, LABEL, etc.) are displayed so that their height and width are calculated by the browser based on their content. If you want to control height and width you have to change those elements' blocks.

display: block; makes the element displayed as a solid block (like DIV tags) which means that there is a line break after the element (it's not inline). Although you can use display: inline-block to fix the issue of line break, this solution does not work in IE6 because IE6 doesn't recognize inline-block. If you want it to be cross-browser compatible then look at this article: http://webjazz.blogspot.com/2008/01/getting-inline-block-working-across.html

Finding Key associated with max Value in a Java Map

Basically you'd need to iterate over the map's entry set, remembering both the "currently known maximum" and the key associated with it. (Or just the entry containing both, of course.)

For example:

Map.Entry<Foo, Bar> maxEntry = null;

for (Map.Entry<Foo, Bar> entry : map.entrySet())
{
    if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0)
    {
        maxEntry = entry;
    }
}

How to install "ifconfig" command in my ubuntu docker image?

In case you want to use the Docker image as a "regular" Ubuntu installation, you can also run unminimize. This will install a lot more than ifconfig, so this might not be what you want.

How can I convert String to Int?

This may help you ;D

{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        float Stukprijs;
        float Aantal;
        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            MessageBox.Show("In de eersre textbox staat een geldbedrag." + Environment.NewLine + "In de tweede textbox staat een aantal." + Environment.NewLine + "Bereken wat er moetworden betaald." + Environment.NewLine + "Je krijgt 15% korting over het bedrag BOVEN de 100." + Environment.NewLine + "Als de korting meer dan 10 euri is," + Environment.NewLine + "wordt de korting textbox lichtgroen");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            errorProvider1.Clear();
            errorProvider2.Clear();
            if (float.TryParse(textBox1.Text, out Stukprijs))
            {
                if (float.TryParse(textBox2.Text, out Aantal))
                {
                    float Totaal = Stukprijs * Aantal;
                    string Output = Totaal.ToString();
                    textBox3.Text = Output;
                    if (Totaal >= 100)
                    {
                        float korting = Totaal - 100;
                        float korting2 = korting / 100 * 15;
                        string Output2 = korting2.ToString();
                        textBox4.Text = Output2;
                        if (korting2 >= 10)
                        {
                            textBox4.BackColor = Color.LightGreen;
                        }
                        else
                        {
                            textBox4.BackColor = SystemColors.Control;
                        }
                    }
                    else
                    {
                        textBox4.Text = "0";
                        textBox4.BackColor = SystemColors.Control;
                    }
                }
                else
                {
                    errorProvider2.SetError(textBox2, "Aantal plz!");
                }

            }
            else
            {
                errorProvider1.SetError(textBox1, "Bedrag plz!");
                if (float.TryParse(textBox2.Text, out Aantal))
                {

                }
                else
                {
                    errorProvider2.SetError(textBox2, "Aantal plz!");
                }
            }

        }

        private void BTNwissel_Click(object sender, EventArgs e)
        {
            //LL, LU, LR, LD.
            Color c = LL.BackColor;
            LL.BackColor = LU.BackColor;
            LU.BackColor = LR.BackColor;
            LR.BackColor = LD.BackColor;
            LD.BackColor = c;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            MessageBox.Show("zorg dat de kleuren linksom wisselen als je op de knop drukt.");
        }
    }
}

Merge 2 arrays of objects

Try this:

var a = [{"a":20, "b":10,"c":"c","d":"asd","f":"any"}]
var b = [{"a":20, "b":10,"c":"c", "e":"nan","g":10200}]

var p = []
_.map(a, function(da){
var chk = _.filter(b, function(ds){
return da.a ===ds.a
})[0]
p.push(_.extend(da, chk))


})

console.log(p)

OutPut will be :

  [{
    "a": 20,
    "b": 10,
    "c": "c",
    "d": "asd",
    "f": "any",
    "e": "nan",
    "g": 10200
  }]

python NameError: name 'file' is not defined

file is not defined in Python3, which you are using apparently. The package you're instaling is not suitable for Python 3, instead, you should install Python 2.7 and try again.

See: http://docs.python.org/release/3.0/whatsnew/3.0.html#builtins

Format number as percent in MS SQL Server

And for all SQL Server versions

SELECT CAST(0.973684210526315789 * 100 AS DECIMAL(18, 2))

Query to search all packages for table and/or column

You can do this:

select *
from user_source
where upper(text) like upper('%SOMETEXT%');

Alternatively, SQL Developer has a built-in report to do this under:

View > Reports > Data Dictionary Reports > PLSQL > Search Source Code

The 11G docs for USER_SOURCE are here

How to get jQuery dropdown value onchange event

If you have simple dropdown like:

<select name="status" id="status">
    <option value="1">Active</option>
    <option value="0">Inactive</option>
</select>

Then you can use this code for getting value:

$(function(){

 $("#status").change(function(){
     var status = this.value;
     alert(status);
   if(status=="1")
     $("#icon_class, #background_class").hide();// hide multiple sections
  });

});

How to fix "The ConnectionString property has not been initialized"

Simply in Code Behind Page use:-

SqlConnection con = new SqlConnection("Data Source = DellPC; Initial Catalog = Account; user = sa; password = admin");

It Should Work Just Fine

Remove part of a string

Use regular expressions. In this case, you can use gsub:

gsub("^.*?_","_","ATGAS_1121")
[1] "_1121"

This regular expression matches the beginning of the string (^), any character (.) repeated zero or more times (*), and underscore (_). The ? makes the match "lazy" so that it only matches are far as the first underscore. That match is replaced with just an underscore. See ?regex for more details and references

What's a good (free) visual merge tool for Git? (on windows)

I don't know a good free tool but winmerge is ok(ish). I've been using the beyond compare tools since 1999 and can't rate it enough - it costs about 50 USD and this investment has paid for it self in time savings more than I can possible imagine.

Sometimes tools should be paid for if they are very very good.

Convert string to datetime

https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

var unixTimeZero = Date.parse('01 Jan 1970 00:00:00 GMT');
var javaScriptRelease = Date.parse('04 Dec 1995 00:12:00 GMT');

console.log(unixTimeZero);
// expected output: 0

console.log(javaScriptRelease);
// expected output: 818035920000

How do I clear a C++ array?

Hey i think The fastest way to handle that kind of operation is to memset() the memory.

Example-

memset(&myPage.pageArray[0][0], 0, sizeof(myPage.pageArray));

A similar C++ way would be to use std::fill

char *begin = myPage.pageArray[0][0];
char *end = begin + sizeof(myPage.pageArray);
std::fill(begin, end, 0);

How to force reloading a page when using browser back button?

It's been a while since this was posted but I found a more elegant solution if you are not needing to support old browsers.

You can do a check with

performance.navigation.type

Documentation including browser support is here: https://developer.mozilla.org/en-US/docs/Web/API/Performance/navigation

So to see if the page was loaded from history using back you can do

if(performance.navigation.type == 2){
   location.reload(true);
}

The 2 indicates the page was accessed by navigating into the history. Other possibilities are-

0:The page was accessed by following a link, a bookmark, a form submission, or a script, or by typing the URL in the address bar.

1:The page was accessed by clicking the Reload button or via the Location.reload() method.

255: Any other way

These are detailed here: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigation


Note Performance.navigation.type is now deprecated in favour of PerformanceNavigationTiming.type which returns 'navigate' / 'reload' / 'back_forward' / 'prerender': https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming/type

how to set background image in submit button?

Typically one would use one (or more) image tags, maybe in combination with setting div background images in css to act as the submit button. The actual submit would be done in javascript on the click event.

A tutorial on the subject.

How to uncommit my last commit in Git

If you commit to the wrong branch

While on the wrong branch:

  1. git log -2 gives you hashes of 2 last commits, let's say $prev and $last
  2. git checkout $prev checkout correct commit
  3. git checkout -b new-feature-branch creates a new branch for the feature
  4. git cherry-pick $last patches a branch with your changes

Then you can follow one of the methods suggested above to remove your commit from the first branch.

How do I bind to list of checkbox values with AngularJS?

Check out this directive that manages effectively lists of checkboxes. I hope it works for you. CheckList Model

json.dump throwing "TypeError: {...} is not JSON serializable" on seemingly valid object?

In my case, boolean values in my Python dict were the problem. JSON boolean values are in lowercase ("true", "false") whereas in Python they are in Uppercase ("True", "False"). Couldn't find this solution anywhere online but hope it helps.

What is the Java equivalent for LINQ?

An anonymous user mentioned another one, Diting:

Diting is a class library provides query capabilities on collections through chainable methods and anonymous interface like Linq in .NET. Unlike most of other collection library those are using static methods need iterate whole collection, Diting provides a core Enumerable class whitch contains deffered chainable methods to implement query on collection or array.

Supported Methods: any, cast, contact, contains, count, distinct, elementAt, except, first, firstOrDefault, groupBy, interset, join, last, lastOrDefault, ofType, orderBy, orderByDescending, reverse, select, selectMany, single, singleOrDefault, skip, skipWhile, take, takeWhile, toArray, toArrayList, union, where

Comparison of C++ unit test frameworks

CPUnit (http://cpunit.sourceforge.net) is a framework that is similar to Google Test, but which relies on less macos (asserts are functions), and where the macros are prefixed to avoid the usual macro pitfall. Tests look like:

#include <cpunit>

namespace MyAssetTest {
    using namespace cpunit;

    CPUNIT_FUNC(MyAssetTest, test_stuff) {
        int some_value = 42;
        assert_equals("Wrong value!", 666, some_value);
    }

    // Fixtures go as follows:
    CPUNIT_SET_UP(MyAssetTest) {
        // Setting up suite here...
        // And the same goes for tear-down.
    }

}

They auto-register, so you need not more than this. Then it is just compile and run. I find using this framework very much like using JUnit, for those who have had to spend some time programming Java. Very nice!

Get month name from number

I'll offer this in case (like me) you have a column of month numbers in a dataframe:

df['monthName'] = df['monthNumer'].apply(lambda x: calendar.month_name[x])

Applying an ellipsis to multiline text

My solution that works for me for multiline ellipsis:

.crd-para {
    color: $txt-clr-main;
    line-height: 2rem;
    font-weight: 600;
    margin-bottom: 1rem !important;
    overflow: hidden;

    span::after {
        content: "...";
        padding-left: 0.125rem;
    }
}

Save file/open file dialog box, using Swing & Netbeans GUI editor

saving in any format is very much possible. Check following- http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html

2ndly , What exactly you are expecting the save dialog to work , it works like that, Opening a doc file is very much possible- http://srikanthtechnologies.com/blog/openworddoc.html

Getting RAW Soap Data from a Web Reference Client running in ASP.net

Not sure why all the fuss with web.config or a serializer class. The below code worked for me:

XmlSerializer xmlSerializer = new XmlSerializer(myEnvelope.GetType());

using (StringWriter textWriter = new StringWriter())
{
    xmlSerializer.Serialize(textWriter, myEnvelope);
    return textWriter.ToString();
}

What is the difference between tinyint, smallint, mediumint, bigint and int in MySQL?

The difference is the amount of memory allocated to each integer, and how large a number they each can store.

Extract filename and extension in Bash

You can use basename.

Example:

$ basename foo-bar.tar.gz .tar.gz
foo-bar

You do need to provide basename with the extension that shall be removed, however if you are always executing tar with -z then you know the extension will be .tar.gz.

This should do what you want:

tar -zxvf $1
cd $(basename $1 .tar.gz)

How to change Toolbar home icon color

This answer maybe too late, but here is how I do it. Styling the toolbar will do the trick. Create toolbar.xml with following code.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:layout_alignParentTop="true"
android:layout_gravity="bottom"
local:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
local:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

and in the styles.xml

<style name="AppBaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!--
    -->
</style>

<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
    <item name="windowNoTitle">true</item>
    <item name="windowActionBar">false</item>
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
</style>

Finally, include the toolbar inside layout

<include
        android:id="@+id/toolbar"
        layout="@layout/toolbar" />

Angular 2: How to access an HTTP response body?

I had the same issue too and this worked for me try:

this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
  subscribe((res) => {
    let resSTR = JSON.stringify(res);
    let resJSON = JSON.parse(resStr);
    console.log(resJSON._body);
  })

JavaScript: how to change form action attribute value based on selection?

$("#selectsearch").change(function() {
  var action = $(this).val() == "people" ? "user" : "content";
  $("#search-form").attr("action", "/search/" + action);
});

Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint

this is easy,
if you use .htaccess , check http: for https: ,
if you use codeigniter, check config : url_base -> you url http change for https.....
I solved my problem.

Turning off eslint rule for a specific line

Or for multiple ignores on the next line, string the rules using commas

// eslint-disable-next-line class-methods-use-this, no-unused-vars

Ignoring a class property in Entity Framework 4.1 Code First

As of EF 5.0, you need to include the System.ComponentModel.DataAnnotations.Schema namespace.

how to hide the content of the div in css

Without changing the markup or using JavaScript, you'd pretty much have to alter the text color as knut mentions, or set text-indent: -1000em;

IE6 will not read the :hover selector on anything other than an anchor element, so you will have to use something like Dean Edwards' IE7.

Really though, you're better off putting the text in some kind of element (like p or span or a) and setting that to display: none; on hover.

Determine version of Entity Framework I am using?

If you go to references, click on the Entity Framework, view properties It will tell you the version number.

How to call any method asynchronously in c#

Starting with .Net 4.5 you can use Task.Run to simply start an action:

void Foo(string args){}
...
Task.Run(() => Foo("bar"));

Task.Run vs Task.Factory.StartNew

pandas dataframe convert column type to string or categorical

Prior answers focused on nominal data (e.g. unordered). If there is a reason to impose order for an ordinal variable, then one would use:

# Transform to category
df['zipcode_category'] = df['zipcode_category'].astype('category')

# Add ordered category
df['zipcode_ordered'] = df['zipcode_category']

# Setup the ordering
df.zipcode_ordered.cat.set_categories(
    new_categories = [90211, 90210], ordered = True, inplace = True
)

# Output IDs
df['zipcode_ordered_id'] = df.zipcode_ordered.cat.codes
print(df)
#  zipcode_category zipcode_ordered  zipcode_ordered_id
#            90210           90210                   1
#            90211           90211                   0

More details on setting ordered categories can be found at the pandas website:

https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html#sorting-and-order

Access props inside quotes in React JSX

you can use

<img className="image" src=`images/${this.props.image}`>

or

<img className="image" src={'images/'+this.props.image}>

or

  render() {
         let imageUrl = this.props.image ? "images/"+this.props.image : 'some placeholder url image';
    return (
       <div>
          <img className="image" src={imageUrl} />
       </div>
    )
  }

Detect IE version (prior to v9) in JavaScript

It helped me

function IsIE8Browser() {
  var rv = -1;
  var ua = navigator.userAgent;
  var re = new RegExp("Trident\/([0-9]{1,}[\.0-9]{0,})");
  if (re.exec(ua) != null) {
    rv = parseFloat(RegExp.$1);
  }
  return (rv == 4);
}

Select count(*) from multiple tables

As I can't see any other answer bring this up.

If you don't like sub-queries and have primary keys in each table you can do this:

select count(distinct tab1.id) as count_t1,
       count(distinct tab2.id) as count_t2
    from tab1, tab2

But performance wise I believe that Quassnoi's solution is better, and the one I would use.

Combine multiple JavaScript files into one JS file

You can use a script that I made. You need JRuby to run this though. https://bitbucket.org/ardee_aram/jscombiner (JSCombiner).

What sets this apart is that it watches file changes in the javascript, and combines it automatically to the script of your choice. So there is no need to manually "build" your javascript each time you test it. Hope it helps you out, I am currently using this.

Insert php variable in a href

Try using printf function or the concatination operator

http://php.net/manual/en/function.printf.php

How to install and run phpize

Install from linux terminal

sudo apt-get install <php_version>-dev

Example :

sudo apt-get install php5-dev     #For `php` version 5
sudo apt-get install php7.0-dev   #For `php` version 7.0

In Powershell what is the idiomatic way of converting a string to an int?

A quick true/false test of whether it will cast to [int]

[bool]($var -as [int] -is [int])

PHP filesize MB/KB conversion

I think this is a better approach. Simple and straight forward.

public function sizeFilter( $bytes )
{
    $label = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB' );
    for( $i = 0; $bytes >= 1024 && $i < ( count( $label ) -1 ); $bytes /= 1024, $i++ );
    return( round( $bytes, 2 ) . " " . $label[$i] );
}

Setting the height of a SELECT in IE

you could do similar to what facebook does, just add padding around. It is not as good as one could wish but looks reasonably well.

How can I require at least one checkbox be checked before a form can be submitted?

Using this you can check at least one checkbox is selected or not in different checkbox groups or multiple checkboxes.

Reference : Link

<label class="control-label col-sm-4">Check Box 1</label>
    <input type="checkbox" name="checkbox1" id="checkbox1" value=Male /> Male<br />
    <input type="checkbox" name="checkbox1" id="checkbox1" value=Female /> Female<br />

<label class="control-label col-sm-4">Check Box 2</label>
    <input type="checkbox" name="checkbox2" id="checkbox2" value=ck1 /> ck1<br />
    <input type="checkbox" name="checkbox2" id="checkbox2" value=ck2 /> ck2<br />

<label class="control-label col-sm-4">Check Box 3</label>
    <input type="checkbox" name="checkbox3" id="checkbox3" value=ck3 /> ck3<br />
    <input type="checkbox" name="checkbox3" id="checkbox3" value=ck4 /> ck4<br />

<script>
function checkFormData() {
    if (!$('input[name=checkbox1]:checked').length > 0) {
        document.getElementById("errMessage").innerHTML = "Check Box 1 can not be null";
        return false;
    }
    if (!$('input[name=checkbox2]:checked').length > 0) {
        document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
        return false;
    }
    if (!$('input[name=checkbox3]:checked').length > 0) {
        document.getElementById("errMessage").innerHTML = "Check Box 3 can not be null";
        return false;
    }
    alert("Success");
    return true;
}
</script>

Launch programs whose path contains spaces

find an .exe file for the application you want to run example iexplore.exe and firefox.exe and remove .exe and use it in objShell.Run("firefox")

I hope this helps.

Parse string to DateTime in C#

Try the following code

Month = Date = DateTime.Now.Month.ToString();   
Year = DateTime.Now.Year.ToString(); 
ViewBag.Today = System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(Int32.Parse(Month)) + Year;