Programs & Examples On #Umask

umask is a Unix command to specify default permissions for the new files, created by the current user. umask is inverted ( umask 0 = world readable, writeable and executable).

Setting default permissions for newly created files and sub-directories under a directory in Linux?

in your shell script (or .bashrc) you may use somthing like:

umask 022

umask is a command that determines the settings of a mask that controls how file permissions are set for newly created files.

Build a simple HTTP server in C

The HTTP spec and Firebug were very useful for me when I had to do it for my homework.

Good luck with yours. :)

Remove all git files from a directory?

How to remove all .git directories under a folder in Linux.

Run this find command, it will list all .git directories under the current folder:

find . -type d -name ".git" \
&& find . -name ".gitignore" \
&& find . -name ".gitmodules"

Prints:

./.git
./.gitmodules
./foobar/.git
./footbar2/.git
./footbar2/.gitignore

There should only be like 3 or 4 .git directories because git only has one .git folder for every project. You can rm -rf yourpath each of the above by hand.

If you feel like removing them all in one command and living dangerously:

//Retrieve all the files named ".git" and pump them into 'rm -rf'
//WARNING if you don't understand why/how this command works, DO NOT run it!

( find . -type d -name ".git" \
  && find . -name ".gitignore" \
  && find . -name ".gitmodules" ) | xargs rm -rf

//WARNING, if you accidentally pipe a `.` or `/` or other wildcard
//into xargs rm -rf, then the next question you will have is: "why is
//the bash ls command not found?  Requiring an OS reinstall.

What is the easiest way to encrypt a password when I save it to the registry?

If you need more than this, for example securing a connection string (for connection to a database), check this article, as it provides the best "option" for this.

Oli's answer is also good, as it shows how you can create a hash for a string.

Why don’t my SVG images scale using the CSS "width" property?

SVGs are different than bitmap images such as PNG etc. If an SVG has a viewBox - as yours appear to - then it will be scaled to fit it's defined viewport. It won't directly scale like a PNG would.

So increasing the width of the img won't make the icons any taller if the height is restricted. You'll just end up with the img horizontally centred in a wider box.

I believe your problem is that your SVGs have a fixed height defined in them. Open up the SVG files and make sure they either:

  1. have no width and height defined, or
  2. have width and height both set to "100%".

That should solve your problem. If it doesn't, post one of your SVGs into your question so we can see how it is defined.

How do I add a .click() event to an image?

First of all, this line

<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />.click()

You're mixing HTML and JavaScript. It doesn't work like that. Get rid of the .click() there.

If you read the JavaScript you've got there, document.getElementById('foo') it's looking for an HTML element with an ID of foo. You don't have one. Give your image that ID:

<img id="foo" src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />

Alternatively, you could throw the JS in a function and put an onclick in your HTML:

<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" onclick="myfunction()" />

I suggest you do some reading up on JavaScript and HTML though.


The others are right about needing to move the <img> above the JS click binding too.

3-dimensional array in numpy

As much as people like to say "order doesn't matter its just convention" this breaks down when entering cross domain interfaces, IE transfer from C ordering to Fortran ordering or some other ordering scheme. There, precisely how your data is layed out and how shape is represented in numpy is very important.

By default, numpy uses C ordering, which means contiguous elements in memory are the elements stored in rows. You can also do FORTRAN ordering ("F"), this instead orders elements based on columns, indexing contiguous elements.

Numpy's shape further has its own order in which it displays the shape. In numpy, shape is largest stride first, ie, in a 3d vector, it would be the least contiguous dimension, Z, or pages, 3rd dim etc... So when executing:

np.zeros((2,3,4)).shape

you will get

(2,3,4)

which is actually (frames, rows, columns). doing np.zeros((2,2,3,4)).shape instead would mean (metaframs, frames, rows, columns). This makes more sense when you think of creating multidimensional arrays in C like langauges. For C++, creating a non contiguously defined 4D array results in an array [ of arrays [ of arrays [ of elements ]]]. This forces you to de reference the first array that holds all the other arrays (4th dimension) then the same all the way down (3rd, 2nd, 1st) resulting in syntax like:

double element = array4d[w][z][y][x];

In fortran, this indexed ordering is reversed (x is instead first array4d[x][y][z][w]), most contiguous to least contiguous and in matlab, it gets all weird.

Matlab tried to preserve both mathematical default ordering (row, column) but also use column major internally for libraries, and not follow C convention of dimensional ordering. In matlab, you order this way:

double element = array4d[y][x][z][w];

which deifies all convention and creates weird situations where you are sometimes indexing as if row ordered and sometimes column ordered (such as with matrix creation).

In reality, Matlab is the unintuitive one, not Numpy.

What is the precise meaning of "ours" and "theirs" in git?

I know it doesn't explain the meaning but I've made myself a little image, as reference to remind which one to use:

enter image description here

Hope it helps!

PS - Give a check also to the link in Nitay's answer

Can I change the height of an image in CSS :before/:after pseudo-elements?

Since my other answer was obviously not well understood, here's a second attempt:

There's two approaches to answer the question.

Practical (just show me the goddamn picture!)

Forget about the :after pseudo-selector, and go for something like

.pdflink {
    min-height: 20px;
    padding-right: 10px;
    background-position: right bottom;
    background-size: 10px 20px;
    background-repeat: no-repeat;
}

Theoretical

The question is: Can you style generated content? The answer is: No, you can't. There's been a lengthy discussion on the W3C mailing list on this issue, but no solution so far.

Generated content is rendered into a generated box, and you can style that box, but not the content as such. Different browsers show very different behaviour

#foo         {content: url("bar.jpg"); width: 42px; height:42px;}  
#foo::before {content: url("bar.jpg"); width: 42px; height:42px;}

Chrome resizes the first one, but uses the intrinsic dimensions of the image for the second

firefox and ie don't support the first, and use intrinsic dimensions for the second

opera uses intrinsic dimensions for both cases

(from http://lists.w3.org/Archives/Public/www-style/2011Nov/0451.html )

Similarly, browsers show very different results on things like http://jsfiddle.net/Nwupm/1/ , where more than one element is generated. Keep in mind that CSS3 is still in early development stage, and this issue has yet to be solved.

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

Scan your workspace .metadata directory for files called *.launch. I forget which plugin directory exactly holds these records, but it might even be the most basic org.eclipse.plugins.core one.

What is the reason for the error message "System cannot find the path specified"?

There is not only 1 %SystemRoot%\System32 on Windows x64. There are 2 such directories.

The real %SystemRoot%\System32 directory is for 64-bit applications. This directory contains a 64-bit cmd.exe.

But there is also %SystemRoot%\SysWOW64 for 32-bit applications. This directory is used if a 32-bit application accesses %SystemRoot%\System32. It contains a 32-bit cmd.exe.

32-bit applications can access %SystemRoot%\System32 for 64-bit applications by using the alias %SystemRoot%\Sysnative in path.

For more details see the Microsoft documentation about File System Redirector.

So the subdirectory run was created either in %SystemRoot%\System32 for 64-bit applications and 32-bit cmd is run for which this directory does not exist because there is no subdirectory run in %SystemRoot%\SysWOW64 which is %SystemRoot%\System32 for 32-bit cmd.exe or the subdirectory run was created in %SystemRoot%\System32 for 32-bit applications and 64-bit cmd is run for which this directory does not exist because there is no subdirectory run in %SystemRoot%\System32 as this subdirectory exists only in %SystemRoot%\SysWOW64.

The following code could be used at top of the batch file in case of subdirectory run is in %SystemRoot%\System32 for 64-bit applications:

@echo off
set "SystemPath=%SystemRoot%\System32"
if not "%ProgramFiles(x86)%" == "" if exist %SystemRoot%\Sysnative\* set "SystemPath=%SystemRoot%\Sysnative"

Every console application in System32\run directory must be executed with %SystemPath% in the batch file, for example %SystemPath%\run\YourApp.exe.

How it works?

There is no environment variable ProgramFiles(x86) on Windows x86 and therefore there is really only one %SystemRoot%\System32 as defined at top.

But there is defined the environment variable ProgramFiles(x86) with a value on Windows x64. So it is additionally checked on Windows x64 if there are files in %SystemRoot%\Sysnative. In this case the batch file is processed currently by 32-bit cmd.exe and only in this case %SystemRoot%\Sysnative needs to be used at all. Otherwise %SystemRoot%\System32 can be used also on Windows x64 as when the batch file is processed by 64-bit cmd.exe, this is the directory containing the 64-bit console applications (and the subdirectory run).

Note: %SystemRoot%\Sysnative is not a directory! It is not possible to cd to %SystemRoot%\Sysnative or use if exist %SystemRoot%\Sysnative or if exist %SystemRoot%\Sysnative\. It is a special alias existing only for 32-bit executables and therefore it is necessary to check if one or more files exist on using this path by using if exist %SystemRoot%\Sysnative\cmd.exe or more general if exist %SystemRoot%\Sysnative\*.

How to remove an id attribute from a div using jQuery?

The capitalization is wrong, and you have an extra argument.

Do this instead:

$('img#thumb').removeAttr('id');

For future reference, there aren't any jQuery methods that begin with a capital letter. They all take the same form as this one, starting with a lower case, and the first letter of each joined "word" is upper case.

Laravel Controller Subfolder routing

Just found a way how to do it:

Just add the paths to the /app/start/global.php

ClassLoader::addDirectories(array(

    app_path().'/commands',
    app_path().'/controllers',
    app_path().'/controllers/product',
    app_path().'/models',
    app_path().'/database/seeds',

));

Fastest way to determine if record exists

For MySql you can use LIMIT like below (Example shows in PHP)

  $sql = "SELECT column_name FROM table_name WHERE column_name = 'your_value' LIMIT 1";
  $result = $conn->query($sql);
  if ($result -> num_rows > 0) {
      echo "Value exists" ;
  } else {
      echo "Value not found";
  }

No provider for TemplateRef! (NgIf ->TemplateRef)

You missed the * in front of NgIf (like we all have, dozens of times):

<div *ngIf="answer.accepted">&#10004;</div>

Without the *, Angular sees that the ngIf directive is being applied to the div element, but since there is no * or <template> tag, it is unable to locate a template, hence the error.


If you get this error with Angular v5:

Error: StaticInjectorError[TemplateRef]:
  StaticInjectorError[TemplateRef]:
    NullInjectorError: No provider for TemplateRef!

You may have <template>...</template> in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>.

Javascript: How to check if a string is empty?

But for a better check:

if(str === null || str === '')
{
    //enter code here
}

Python Threading String Arguments

You're trying to create a tuple, but you're just parenthesizing a string :)

Add an extra ',':

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=(dRecieved,))  # <- note extra ','
processThread.start()

Or use brackets to make a list:

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=[dRecieved])  # <- 1 element list
processThread.start()

If you notice, from the stack trace: self.__target(*self.__args, **self.__kwargs)

The *self.__args turns your string into a list of characters, passing them to the processLine function. If you pass it a one element list, it will pass that element as the first argument - in your case, the string.

Angular 2 Checkbox Two Way Data Binding

In Angular p-checkbox,

Use all attributes of p-checkbox

<p-checkbox name="checkbox" value="isAC" 
    label="All Colors" [(ngModel)]="selectedAllColors" 
    [ngModelOptions]="{standalone: true}" id="al" 
    binary="true">
</p-checkbox>

And more importantly, don't forget to include [ngModelOptions]="{standalone: true} as well as it SAVED MY DAY.

How to create a new column in a select query

select A, B, 'c' as C
from MyTable

Check if a string is a valid Windows directory (folder) path

    private bool IsValidPath(string path)
    {
        Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");
        if (!driveCheck.IsMatch(path.Substring(0, 3))) return false;
        string strTheseAreInvalidFileNameChars = new string(Path.GetInvalidPathChars());
        strTheseAreInvalidFileNameChars += @":/?*" + "\"";
        Regex containsABadCharacter = new Regex("[" + Regex.Escape(strTheseAreInvalidFileNameChars) + "]");
        if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3)))
            return false;

        DirectoryInfo dir = new DirectoryInfo(Path.GetFullPath(path));
        if (!dir.Exists)
            dir.Create();
        return true;
    }

How to check that Request.QueryString has a specific value or not in ASP.NET?

Check for the value of the parameter:

// .NET < 4.0
if (string.IsNullOrEmpty(Request.QueryString["aspxerrorpath"]))
{
 // not there!
}

// .NET >= 4.0
if (string.IsNullOrWhiteSpace(Request.QueryString["aspxerrorpath"]))
{
 // not there!
}

If it does not exist, the value will be null, if it does exist, but has no value set it will be an empty string.

I believe the above will suit your needs better than just a test for null, as an empty string is just as bad for your specific situation.

Git clone without .git directory

Alternatively, if you have Node.js installed, you can use the following command:

npx degit GIT_REPO

npx comes with Node, and it allows you to run binary node-based packages without installing them first (alternatively, you can first install degit globally using npm i -g degit).

Degit is a tool created by Rich Harris, the creator of Svelte and Rollup, which he uses to quickly create a new project by cloning a repository without keeping the git folder. But it can also be used to clone any repo once...

Merging arrays with the same keys

 $A = array('a' => 1, 'b' => 2, 'c' => 3);
 $B = array('c' => 4, 'd'=> 5);
 $C = array_merge_recursive($A, $B);
 $aWhere = array();
 foreach ($C as $k=>$v) {

    if (is_array($v)) {
        $aWhere[] = $k . ' in ('.implode(', ',$v).')';
    }
    else {
        $aWhere[] = $k . ' = ' . $v;
    }
 }
 $where = implode(' AND ', $aWhere);
 echo $where;

How can you have SharePoint Link Lists default to opening in a new window?

You can edit the page in SharePoint designer, convert the List View web part to an XSLT Data View. (by right click + "Convert to XSLT Data View").
Then you can edit the XSLT - find the A tag and add an attribute target="_blank"

Python: Append item to list N times

Use extend to add a list comprehension to the end.

l.extend([x for i in range(100)])

See the Python docs for more information.

Creating table variable in SQL server 2008 R2

@tableName Table variables are alive for duration of the script running only i.e. they are only session level objects.

To test this, open two query editor windows under sql server management studio, and create table variables with same name but different structures. You will get an idea. The @tableName object is thus temporary and used for our internal processing of data, and it doesn't contribute to the actual database structure.

There is another type of table object which can be created for temporary use. They are #tableName objects declared like similar create statement for physical tables:

Create table #test (Id int, Name varchar(50))

This table object is created and stored in temp database. Unlike the first one, this object is more useful, can store large data and takes part in transactions etc. These tables are alive till the connection is open. You have to drop the created object by following script before re-creating it.

IF OBJECT_ID('tempdb..#test') IS NOT NULL
  DROP TABLE #test 

Hope this makes sense !

How do I add a library (android-support-v7-appcompat) in IntelliJ IDEA

Using Maven

First of all you should install android libraries to your local maven repository using Maven Android SDK Deployer

Then you can add dependency to your pom like this:

    <dependency>
        <groupId>android.support</groupId>
        <artifactId>compatibility-v7-appcompat</artifactId>
        <version>${compatibility.version}</version>
        <type>apklib</type>
    </dependency>

    <dependency>
        <groupId>android.support</groupId>
        <artifactId>compatibility-v7-appcompat</artifactId>
        <version>${compatibility.version}</version>
        <type>jar</type>
    </dependency>

how to convert rgb color to int in java

You want to use intvalue = Color.parseColor("#" + colorobject);

Run Function After Delay

$(document).ready(function() {

  // place this within dom ready function
  function showpanel() {     
    $(".navigation").hide();
    $(".page").children(".panel").fadeIn(1000);
 }

 // use setTimeout() to execute
 setTimeout(showpanel, 1000)

});

For more see here

How can I add a Google search box to my website?

No need to embed! Just simply send the user to google and add the var in the search like this: (Remember, code might not work on this, so try in a browser if it doesn't.) Hope it works!

<textarea id="Blah"></textarea><button onclick="search()">Search</button>
<script>
function search() {
var Blah = document.getElementById("Blah").value;
location.replace("https://www.google.com/search?q=" + Blah + "");
}
</script>

_x000D_
_x000D_
    function search() {_x000D_
    var Blah = document.getElementById("Blah").value;_x000D_
    location.replace("https://www.google.com/search?q=" + Blah + "");_x000D_
    }
_x000D_
<textarea id="Blah"></textarea><button onclick="search()">Search</button>
_x000D_
_x000D_
_x000D_

Telnet is not recognized as internal or external command

If your Windows 7 machine is a member of an AD, or if you have UAC enabled, or if security policies are in effect, telnet more often than not must be run as an admin. The easiest way to do this is as follows

  1. Create a shortcut that calls cmd.exe

  2. Go to the shortcut's properties

  3. Click on the Advanced button

  4. Check the "Run as an administrator" checkbox

    After these steps you're all set and telnet should work now.

This action could not be completed. Try Again (-22421)

Just try exporting the iPA file and then upload that exported iPA file with application loader. It will solve your problem.

Split a string into an array of strings based on a delimiter

I always use something similar to this:

Uses
   StrUtils, Classes;

Var
  Str, Delimiter : String;
begin
  // Str is the input string, Delimiter is the delimiter
  With TStringList.Create Do
  try
    Text := ReplaceText(S,Delim,#13#10);

    // From here on and until "finally", your desired result strings are
    // in strings[0].. strings[Count-1)

  finally
    Free; //Clean everything up, and liberate your memory ;-)
  end;

end;

access key and value of object using *ngFor

Thought of adding an answer for Angular 8:

For looping you can do:

<ng-container *ngFor="let item of BATCH_FILE_HEADERS | keyvalue: keepOriginalOrder">
   <th nxHeaderCell>{{'upload.bulk.headings.'+item.key |translate}}</th>
</ng-container>

Also if you need the above array to keep the original order then declare this inside your class:

public keepOriginalOrder = (a, b) => a.key;

comparing two strings in ruby

Here are some:

"Ali".eql? "Ali"
=> true

The spaceship (<=>) method can be used to compare two strings in relation to their alphabetical ranking. The <=> method returns 0 if the strings are identical, -1 if the left hand string is less than the right hand string, and 1 if it is greater:

"Apples" <=> "Apples"
=> 0

"Apples" <=> "Pears"
=> -1

"Pears" <=> "Apples"
=> 1

A case insensitive comparison may be performed using the casecmp method which returns the same values as the <=> method described above:

"Apples".casecmp "apples"
=> 0

Java, return if trimmed String in List contains String

You may be able to use an approximate string matching library to do this, e.g. SecondString, but that is almost certainly overkill - just use one of the for-loop answers provided instead.

Disable elastic scrolling in Safari

There are a to of situations where the above CSS solutions do not work. For instance a transparent fixed header and a sticky footer on the same page. To prevent the top bounce in safari messing things and causing flashes on full screen sliders, you can use this.

    if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {

        $window.bind('mousewheel', function(e) {

            if (e.originalEvent.wheelDelta / 120 > 0) {

                if ($window.scrollTop() < 2) return false;
            } 
        });

    }

Using env variable in Spring Boot's application.properties

The easiest way to have different configurations for different environments is to use spring profiles. See externalised configuration.

This gives you a lot of flexibility. I am using it in my projects and it is extremely helpful. In your case you would have 3 profiles: 'local', 'jenkins', and 'openshift'

You then have 3 profile specific property files: application-local.properties, application-jenkins.properties, and application-openshift.properties

There you can set the properties for the regarding environment. When you run the app you have to specify the profile to activate like this: -Dspring.profiles.active=jenkins

Edit

According to the spring doc you can set the system environment variable SPRING_PROFILES_ACTIVE to activate profiles and don't need to pass it as a parameter.

is there any way to pass active profile option for web app at run time ?

No. Spring determines the active profiles as one of the first steps, when building the application context. The active profiles are then used to decide which property files are read and which beans are instantiated. Once the application is started this cannot be changed.

How to extract multiple JSON objects from one file?

So, as was mentioned in a couple comments containing the data in an array is simpler but the solution does not scale well in terms of efficiency as the data set size increases. You really should only use an iterator when you want to access a random object in the array, otherwise, generators are the way to go. Below I have prototyped a reader function which reads each json object individually and returns a generator.

The basic idea is to signal the reader to split on the carriage character "\n" (or "\r\n" for Windows). Python can do this with the file.readline() function.

import json
def json_reader(filename):
    with open(filename) as f:
        for line in f:
            yield json.loads(line)

However, this method only really works when the file is written as you have it -- with each object separated by a newline character. Below I wrote an example of a writer that separates an array of json objects and saves each one on a new line.

def json_writer(file, json_objects):
    with open(file, "w") as f:
        for jsonobj in json_objects:
            jsonstr = json.dumps(jsonobj)
            f.write(jsonstr + "\n")

You could also do the same operation with file.writelines() and a list comprehension:

...
    json_strs = [json.dumps(j) + "\n" for j in json_objects]
    f.writelines(json_strs)
...

And if you wanted to append the data instead of writing a new file just change open(file, "w") to open(file, "a").

In the end I find this helps a great deal not only with readability when I try and open json files in a text editor but also in terms of using memory more efficiently.

On that note if you change your mind at some point and you want a list out of the reader, Python allows you to put a generator function inside of a list and populate the list automatically. In other words, just write

lst = list(json_reader(file))

How do I apply a CSS class to Html.ActionLink in ASP.NET MVC?

In VB.NET

<%=Html.ActionLink("Contact Us", "ContactUs", "Home", Nothing, New With {.class = "link"})%>

This will assign css class "link" to the Contact Us.

This will generate following HTML :

<a class="link" href="www.domain.com/Home/ContactUs">Contact Us</a>

MySQL - select data from database between two dates

You need to use '2011-12-07' as the end point as a date without a time default to time 00:00:00.

So what you have actually written is interpreted as:

 SELECT users.* 
 FROM   users
 WHERE  created_at >= '2011-12-01 00:00:00' 
   AND  created_at <= '2011-12-06 00:00:00'

And your time stamp is: 2011-12-06 10:45:36 which is not between those points.
Change this too:

 SELECT users.* 
 FROM   users
 WHERE  created_at >= '2011-12-01'  -- Implied 00:00:00
   AND  created_at <  '2011-12-07'  -- Implied 00:00:00 and smaller than 
                                   --                  thus any time on 06

Remove a specific character using awk or sed

Using just awk you could do (I also shortened some of your piping):

strings -a libAddressDoctor5.so | awk '/EngineVersion/ { if(NR==2) { gsub("\"",""); print $2 } }'

I can't verify it for you because I don't know your exact input, but the following works:

echo "Blah EngineVersion=\"123\"" | awk '/EngineVersion/ { gsub("\"",""); print $2 }'

See also this question on removing single quotes.

How can I make one python file run another?

There are more than a few ways. I'll list them in order of inverted preference (i.e., best first, worst last):

  1. Treat it like a module: import file. This is good because it's secure, fast, and maintainable. Code gets reused as it's supposed to be done. Most Python libraries run using multiple methods stretched over lots of files. Highly recommended. Note that if your file is called file.py, your import should not include the .py extension at the end.
  2. The infamous (and unsafe) exec command: Insecure, hacky, usually the wrong answer. Avoid where possible.
    • execfile('file.py') in Python 2
    • exec(open('file.py').read()) in Python 3
  3. Spawn a shell process: os.system('python file.py'). Use when desperate.

How to make a submit out of a <a href...>...</a> link?

Something like this page ?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>BSO Communication</title>

<style type="text/css">
.submit {
    border : 0;
    background : url(ok.gif) left top no-repeat;
    height : 24px;
    width : 24px;
    cursor : pointer;
    text-indent : -9999px;
}
html:first-child .submit {
    padding-left : 1000px;
}
</style>
<!--[if IE]>
<style type="text/css">
.submit {
    text-indent : 0;
    color : expression(this.value = '');
}
</style>
<![endif]-->
</head>

<body>
    <h1>Display input submit as image with CSS</h1>

    <p>Take a look at <a href="/2007/07/26/afficher-un-input-submit-comme-une-image/">the related article</a> (in french).</p>
    <form action="" method="get">
        <fieldset>
            <legend>Some form</legend>
            <p class="field">
                <label for="input">Some value</label>

                <input type="text" id="input" name="value" />
                <input type="submit" class="submit" />
            </p>
        </fieldset>
    </form>

    <hr />
    <p>This page is part of the <a href="http://www.bsohq.fr">BSO Communication blog</a>.</p>

</body>
</html>

Syntax error on print with Python 3

In Python 3, print became a function. This means that you need to include parenthesis now like mentioned below:

print("Hello World")

java create date object using a value string

Here is the optimized solution to do it with SimpleDateFormat parse() method.

SimpleDateFormat formatter = new SimpleDateFormat(
        "EEEE, dd/MM/yyyy/hh:mm:ss");
String strDate = formatter.format(new Date());

try {
    Date pDate = formatter.parse(strDate);
} catch (ParseException e) { // note: parse method can throw ParseException
    e.printStackTrace();
}

Few things to notice

  • We don't need to create a Calendar instance to get the current date & time instead use new Date()
  • Also it doesn't require 2 instances of SimpleDateFormat as found in the most voted answer for this question. It's just a waste of memory
  • Furthermore, catching a generic exception like Exception is a bad practice when we know that the parse method only stands a chance to throw a ParseException. We need to be as specific as possible when dealing with Exceptions. You can refer, throws Exception bad practice?

Rounding SQL DateTime to midnight

SELECT getdate()

Result: 2012-12-14 16:03:33.360

SELECT convert(datetime,convert(bigint, getdate()))

Result 2012-12-15 00:00:00.000

android - how to convert int to string and place it in a EditText?

Use +, the string concatenation operator:

ed = (EditText) findViewById (R.id.box);
int x = 10;
ed.setText(""+x);

or use String.valueOf(int):

ed.setText(String.valueOf(x));

or use Integer.toString(int):

ed.setText(Integer.toString(x));

TypeError: ufunc 'add' did not contain a loop with signature matching types

You have a numpy array of strings, not floats. This is what is meant by dtype('<U9') -- a little endian encoded unicode string with up to 9 characters.

try:

return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))

However, you don't need numpy here at all. You can really just do:

return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)

Or if you're really set on using numpy.

return np.asarray(listOfEmb, dtype=float).mean()

How do I crop an image in Java?

This question has not enough information to answer. A general solution (depending on your GUI framework): add a mouse event handler that will catch clicks and mouse movements. This will give you your (x, y) coordinates. Next use these coordinates to crop your image.

Manually map column names with class properties

for all of you who use Dapper 1.12, Here's what you need to do to get this done:

  • Add a new column attribute class:

      [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property]
    
      public class ColumnAttribute : Attribute
      {
    
        public string Name { get; set; }
    
        public ColumnAttribute(string name)
        {
          this.Name = name;
        }
      }
    

  • Search for this line:

    map = new DefaultTypeMap(type);
    

    and comment it out.

  • Write this instead:

            map = new CustomPropertyTypeMap(type, (t, columnName) =>
            {
              PropertyInfo pi = t.GetProperties().FirstOrDefault(prop =>
                                prop.GetCustomAttributes(false)
                                    .OfType<ColumnAttribute>()
                                    .Any(attr => attr.Name == columnName));
    
              return pi != null ? pi : t.GetProperties().FirstOrDefault(prop => prop.Name == columnName);
            });
    

  • How to use python numpy.savetxt to write strings and float number to an ASCII file?

    You have to specify the format (fmt) of you data in savetxt, in this case as a string (%s):

    num.savetxt('test.txt', DAT, delimiter=" ", fmt="%s") 
    

    The default format is a float, that is the reason it was expecting a float instead of a string and explains the error message.

    Format bytes to kilobytes, megabytes, gigabytes

    I did this converting all input to byte and so converting to any output needed. Also, I used a auxiliar function to get base 1000 or 1024, but left it flex to decide use 1024 on popular type (without 'i', like MB instead of MiB).

        public function converte_binario($size=0,$format_in='B',$format_out='MB',$force_in_1024=false,$force_out_1024=false,$precisao=5,$return_format=true,$decimal=',',$centena=''){
        $out = false;
    
        if( (is_numeric($size)) && ($size>0)){
            $in_data = $this->converte_binario_aux($format_in,$force_in_1024);
            $out_data = $this->converte_binario_aux($format_out,$force_out_1024);
    
            // se formato de entrada e saída foram encontrados
            if( ((isset($in_data['sucesso'])) && ($in_data['sucesso']==true)) && ((isset($out_data['sucesso'])) && ($out_data['sucesso']==true))){
                // converte formato de entrada para bytes.
                $size_bytes_in = $size * (pow($in_data['base'], $in_data['pot']));
                $size_byte_out = (pow($out_data['base'], $out_data['pot']));
                // transforma bytes na unidade de destino
                $out = number_format($size_bytes_in / $size_byte_out,$precisao,$decimal,$centena);
                if($return_format){
                    $out .= $format_out;
                }
            }
        }
        return $out;
    }
    
    public function converte_binario_aux($format=false,$force_1024=false){
        $out = [];
        $out['sucesso'] = false;
        $out['base'] = 0;
        $out['pot'] = 0;
        if((is_string($format) && (strlen($format)>0))){
            $format = trim(strtolower($format));
            $units_1000 = ['b','kb' ,'mb' ,'gb' ,'tb' ,'pb' ,'eb' ,'zb' ,'yb' ];
            $units_1024 = ['b','kib','mib','gib','tib','pib','eib','zib','yib'];
            $pot = array_search($format,$units_1000);
            if( (is_numeric($pot)) && ($pot>=0)){
                $out['pot'] = $pot;
                $out['base'] = 1000;
                $out['sucesso'] = true;
            }
            else{
                $pot = array_search($format,$units_1024);
                if( (is_numeric($pot)) && ($pot>=0)){
                    $out['pot'] = $pot;
                    $out['base'] = 1024;
                    $out['sucesso'] = true;
                }
            }
            if($force_1024){
                $out['base'] = 1024;
            }
        }
        return $out;
    }
    

    Redirect within component Angular 2

    This worked for me Angular cli 6.x:

    import {Router} from '@angular/router';
    
    constructor(private artistService: ArtistService, private router: Router) { }
    
      selectRow(id: number): void{
           this.router.navigate([`./artist-detail/${id}`]);
    
      }
    

    Android: How to handle right to left swipe gestures

    @Edward Brey's method works great. If someone would also like to copy & paste the imports for the OnSwipeTouchListener, here they are:

     import android.content.Context;
     import android.view.GestureDetector;
     import android.view.GestureDetector.SimpleOnGestureListener;
     import android.view.MotionEvent;
     import android.view.View;
     import android.view.View.OnTouchListener;
    

    How do I find a list of Homebrew's installable packages?

    brew help will show you the list of commands that are available.

    brew list will show you the list of installed packages. You can also append formulae, for example brew list postgres will tell you of files installed by postgres (providing it is indeed installed).

    brew search <search term> will list the possible packages that you can install. brew search post will return multiple packages that are available to install that have post in their name.

    brew info <package name> will display some basic information about the package in question.

    You can also search http://searchbrew.com or https://brewformulas.org (both sites do basically the same thing)

    Why call git branch --unset-upstream to fixup?

    Actually torek told you already how to use the tools much better than I would be able to do. However, in this case I think it is important to point out something peculiar if you follow the guidelines at http://octopress.org/docs/deploying/github/. Namely, you will have multiple github repositories in your setup. First of all the one with all the source code for your website in say the directory $WEBSITE, and then the one with only the static generated files residing in $WEBSITE/_deploy. The funny thing of the setup is that there is a .gitignore file in the $WEBSITE directory so that this setup actually works.

    Enough introduction. In this case the error might also come from the repository in _deploy.

    cd _deploy
    
    git branch -a
    * master
    remotes/origin/master
    remotes/origin/source
    

    In .git/config you will normally need to find something like this:

    [core]
        repositoryformatversion = 0
        filemode = true
        bare = false
        logallrefupdates = true
    [remote "origin"]
        url = [email protected]:yourname/yourname.github.io.git
        fetch = +refs/heads/*:refs/remotes/origin/*
    [branch "master"]
        remote = origin
        merge = refs/heads/master
    

    But in your case the branch master does not have a remote.

    [core]
        repositoryformatversion = 0
        filemode = true
        bare = false
        logallrefupdates = true
    [remote "origin"]
        url = [email protected]:yourname/yourname.github.io.git
        fetch = +refs/heads/*:refs/remotes/origin/*
    

    Which you can solve by:

    cd _deploy
    git branch --set-upstream-to=origin/master
    

    So, everything is as torek told you, but it might be important to point out that this very well might concern the _deploy directory rather than the root of your website.

    PS: It might be worth to use a shell such as zsh with a git plugin to not be bitten by this thing in the future. It will immediately show that _deploy concerns a different repository.

    How to convert between bytes and strings in Python 3?

    The 'mangler' in the above code sample was doing the equivalent of this:

    bytesThing = stringThing.encode(encoding='UTF-8')
    

    There are other ways to write this (notably using bytes(stringThing, encoding='UTF-8'), but the above syntax makes it obvious what is going on, and also what to do to recover the string:

    newStringThing = bytesThing.decode(encoding='UTF-8')
    

    When we do this, the original string is recovered.

    Note, using str(bytesThing) just transcribes all the gobbledegook without converting it back into Unicode, unless you specifically request UTF-8, viz., str(bytesThing, encoding='UTF-8'). No error is reported if the encoding is not specified.

    File Upload to HTTP server in iphone programming

    I thought I would add some server side php code to this answer for any beginners that read this post and are struggling to figure out how to receive the file on the server side and save the file to the filesystem.

    I realize that this answer does not directly answer the OP's question, but since Brandon's answer is sufficient for the iOS device side of uploading and he mentions that some knowledge of php is necessary, I thought I would fill in the php gap with this answer.

    Here is a class I put together with some sample usage code. Note that the files are stored in directories based on which user is uploading them. This may or may not be applicable to your use, but I thought I'd leave it in place just in case.

    <?php
    
    
    class upload
    {
        protected $user;
    
        protected $isImage;
        protected $isMovie;
    
        protected $file;
        protected $uploadFilename;
        protected $uploadDirectory;
        protected $fileSize;
        protected $fileTmpName;
        protected $fileType;
        protected $fileExtension;
    
        protected $saveFilePath;
    
        protected $allowedExtensions;
    
    function __construct($file, $userPointer)
    {
        // set the file we're uploading
        $this->file = $file;
    
        // if this is tied to a user, link the user account here
        $this->user = $userPointer;
    
        // set default bool values to false since we don't know what file type is being uploaded yet
        $this->isImage   = FALSE;
        $this->isMovie   = FALSE;
    
        // setup file properties
        if (isset($this->file) && !empty($this->file))
        {   
            $this->uploadFilename   = $this->file['file']['name'];
            $this->fileSize         = $this->file['file']['size'];
            $this->fileTmpName      = $this->file['file']['tmp_name'];
            $this->fileType         = $this->file['file']['type'];
        }
        else
        {
            throw new Exception('Received empty data. No file found to upload.');
        }
    
        // get the file extension of the file we're trying to upload
        $tmp = explode('.', $this->uploadFilename);
        $this->fileExtension        = strtolower(end($tmp));
    
    }
    
    
    
    public function image($postParams)
    {
        // set default error alert (or whatever you want to return if error)
        $retVal = array('alert' => '115');
    
        // set our bool
        $this->isImage = TRUE;
    
        // set our type limits
        $this->allowedExtensions    = array("png");
    
        // setup destination directory path (without filename yet)
        $this->uploadDirectory      = DIR_IMG_UPLOADS.$this->user->uid."/photos/";
    
        // if user is not subscribed they are allowed only one image, clear their folder here
        if ($this->user->isSubscribed() == FALSE)
        {
            $this->clearFolder($this->uploadDirectory);
        }
    
        // try to upload the file
        $success = $this->startUpload();
    
        if ($success === TRUE)
        {
            // return the image name (NOTE: this wipes the error alert set above)
            $retVal = array(
                            'imageName' =>  $this->uploadFilename,
                            );
        }
    
        return $retVal;
    }
    
    
    
    public function movie($data)
    {
        // update php settings to handle larger uploads
        set_time_limit(300);
    
        // you may need to increase allowed filesize as well if your server is not set with a high enough limit
    
        // set default return value (error code for upload failed)
        $retVal = array('alert' => '92');
    
        // set our bool
        $this->isMovie = TRUE;
    
        // set our allowed movie types
        $this->allowedExtensions = array("mov", "mp4", "mpv", "3gp");
    
        // setup destination path
        $this->uploadDirectory = DIR_IMG_UPLOADS.$this->user->uid."/movies/";
    
        // only upload the movie if the user is a subscriber
        if ($this->user->isSubscribed())
        {
            // try to upload the file
            $success = $this->startUpload();
    
            if ($success === TRUE)
            {
                // file uploaded so set the new retval
                $retVal = array('movieName' => $this->uploadFilename);
            }
        }
        else
        {
            // return an error code so user knows this is a limited access feature
            $retVal = array('alert' => '13');
        }
    
        return $retVal;
    }
    
    
    
    
    //-------------------------------------------------------------------------------
    //                          Upload Process Methods
    //-------------------------------------------------------------------------------
    
    private function startUpload()
    {
        // see if there are any errors
        $this->checkForUploadErrors();
    
        // validate the type received is correct
        $this->checkFileExtension();
    
        // check the filesize
        $this->checkFileSize();
    
        // create the directory for the user if it does not exist
        $this->createUserDirectoryIfNotExists();
    
        // generate a local file name
        $this->createLocalFileName();
    
        // verify that the file is an uploaded file
        $this->verifyIsUploadedFile();
    
        // save the image to the appropriate folder
        $success = $this->saveFileToDisk();
    
        // return TRUE/FALSE
        return $success;
    }
    
    private function checkForUploadErrors()
    {
        if ($this->file['file']['error'] != 0)
        {
            throw new Exception($this->file['file']['error']);
        }
    }
    
    private function checkFileExtension()
    {
        if ($this->isImage)
        {
            // check if we are in fact uploading a png image, if not return error
            if (!(in_array($this->fileExtension, $this->allowedExtensions)) || $this->fileType != 'image/png' || exif_imagetype($this->fileTmpName) != IMAGETYPE_PNG)
            {
                throw new Exception('Unsupported image type. The image must be of type png.');
            }
        }
        else if ($this->isMovie)
        {
            // check if we are in fact uploading an accepted movie type
            if (!(in_array($this->fileExtension, $this->allowedExtensions)) || $this->fileType != 'video/mov')
            {
                throw new Exception('Unsupported movie type. Accepted movie types are .mov, .mp4, .mpv, or .3gp');
            }
        }   
    }
    
    private function checkFileSize()
    {
        if ($this->isImage)
        {
            if($this->fileSize > TenMB)
            {
                throw new Exception('The image filesize must be under 10MB.');
            }
        }
        else if ($this->isMovie)
        {
            if($this->fileSize > TwentyFiveMB) 
            {
                throw new Exception('The movie filesize must be under 25MB.');
            }
        }
    }
    
    private function createUserDirectoryIfNotExists()
    {
        if (!file_exists($this->uploadDirectory)) 
        {
            mkdir($this->uploadDirectory, 0755, true);
        }
        else
        {
            if ($this->isMovie)
            {
                // clear any prior uploads from the directory (only one movie file per user)
                $this->clearFolder($this->uploadDirectory);
            }
        }
    }
    
    private function createLocalFileName()
    {
        $now = time();
    
        // try to create a unique filename for this users file
        while(file_exists($this->uploadFilename = $now.'-'.$this->uid.'.'.$this->fileExtension))
        {
            $now++;
        }
    
        // create our full file save path
        $this->saveFilePath = $this->uploadDirectory.$this->uploadFilename;
    }
    
    private function clearFolder($path)
    {
        if(is_file($path))
        {
            // if there's already a file with this name clear it first
            return @unlink($path);
        }
        elseif(is_dir($path))
        {
            // if it's a directory, clear it's contents
            $scan = glob(rtrim($path,'/').'/*');
            foreach($scan as $index=>$npath)
            {
                $this->clearFolder($npath);
                @rmdir($npath);
            }
        }
    }
    
    private function verifyIsUploadedFile()
    {
        if (! is_uploaded_file($this->file['file']['tmp_name']))
        {
            throw new Exception('The file failed to upload.');
        }
    }
    
    
    private function saveFileToDisk()
    {
        if (move_uploaded_file($this->file['file']['tmp_name'], $this->saveFilePath))
        {
            return TRUE;     
        }
    
        throw new Exception('File failed to upload. Please retry.');
    }
    
    }
    
    
    ?>
    

    Here's some sample code demonstrating how you might use the upload class...

    // get a reference to your user object if applicable
    $myUser = $this->someMethodThatFetchesUserWithId($myUserId);
    
    // get reference to file to upload
    $myFile = isset($_FILES) ? $_FILES : NULL;
    
    // use try catch to return an error for any exceptions thrown in the upload script
    try 
    {
        // create and setup upload class
        $upload = new upload($myFile, $myUser);
    
        // trigger file upload
        $data   = $upload->image();     // if uploading an image
        $data  = $upload->movie();      // if uploading movie
    
        // return any status messages as json string
        echo json_encode($data);
    } 
    catch (Exception $exception) 
    {
        $retData = array(
                'status'    => 'FALSE',
                'payload'   => array(
                                'errorMsg' => $exception->getMessage()
                                ),
                    );
    
        echo json_encode($retData);
    }
    

    Disabling browser caching for all browsers from ASP.NET

    For what it's worth, I just had to handle this in my ASP.NET MVC 3 application. Here is the code block I used in the Global.asax file to handle this for all requests.

        protected void Application_BeginRequest()
        {
            //NOTE: Stopping IE from being a caching whore
            HttpContext.Current.Response.Cache.SetAllowResponseInBrowserHistory(false);
            HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            HttpContext.Current.Response.Cache.SetNoStore();
            Response.Cache.SetExpires(DateTime.Now);
            Response.Cache.SetValidUntilExpires(true);
        }
    

    Correct way to try/except using Python requests module?

    Have a look at the Requests exception docs. In short:

    In the event of a network problem (e.g. DNS failure, refused connection, etc), Requests will raise a ConnectionError exception.

    In the event of the rare invalid HTTP response, Requests will raise an HTTPError exception.

    If a request times out, a Timeout exception is raised.

    If a request exceeds the configured number of maximum redirections, a TooManyRedirects exception is raised.

    All exceptions that Requests explicitly raises inherit from requests.exceptions.RequestException.

    To answer your question, what you show will not cover all of your bases. You'll only catch connection-related errors, not ones that time out.

    What to do when you catch the exception is really up to the design of your script/program. Is it acceptable to exit? Can you go on and try again? If the error is catastrophic and you can't go on, then yes, you may abort your program by raising SystemExit (a nice way to both print an error and call sys.exit).

    You can either catch the base-class exception, which will handle all cases:

    try:
        r = requests.get(url, params={'s': thing})
    except requests.exceptions.RequestException as e:  # This is the correct syntax
        raise SystemExit(e)
    

    Or you can catch them separately and do different things.

    try:
        r = requests.get(url, params={'s': thing})
    except requests.exceptions.Timeout:
        # Maybe set up for a retry, or continue in a retry loop
    except requests.exceptions.TooManyRedirects:
        # Tell the user their URL was bad and try a different one
    except requests.exceptions.RequestException as e:
        # catastrophic error. bail.
        raise SystemExit(e)
    

    As Christian pointed out:

    If you want http errors (e.g. 401 Unauthorized) to raise exceptions, you can call Response.raise_for_status. That will raise an HTTPError, if the response was an http error.

    An example:

    try:
        r = requests.get('http://www.google.com/nothere')
        r.raise_for_status()
    except requests.exceptions.HTTPError as err:
        raise SystemExit(err)
    

    Will print:

    404 Client Error: Not Found for url: http://www.google.com/nothere
    

    How do I add multiple "NOT LIKE '%?%' in the WHERE clause of sqlite3?

    If you have any problems with the "not like" query, Consider that you may have a null in the database. In this case, Use:

    IFNULL(word, '') NOT LIKE '%something%'
    

    Creating and writing lines to a file

    You'll need to deal with File System Object. See this OpenTextFile method sample.

    How do I disable and re-enable a button in with javascript?

    you can try with

    document.getElementById('btn').disabled = !this.checked"

    _x000D_
    _x000D_
    <input type="submit" name="btn"  id="btn" value="submit" disabled/>_x000D_
    _x000D_
    <input type="checkbox"  onchange="document.getElementById('btn').disabled = !this.checked"/>
    _x000D_
    _x000D_
    _x000D_

    How to debug heap corruption errors?

    Application Verifier combined with Debugging Tools for Windows is an amazing setup. You can get both as a part of the Windows Driver Kit or the lighter Windows SDK. (Found out about Application Verifier when researching an earlier question about a heap corruption issue.) I've used BoundsChecker and Insure++ (mentioned in other answers) in the past too, although I was surprised how much functionality was in Application Verifier.

    Electric Fence (aka "efence"), dmalloc, valgrind, and so forth are all worth mentioning, but most of these are much easier to get running under *nix than Windows. Valgrind is ridiculously flexible: I've debugged large server software with many heap issues using it.

    When all else fails, you can provide your own global operator new/delete and malloc/calloc/realloc overloads -- how to do so will vary a bit depending on compiler and platform -- and this will be a bit of an investment -- but it may pay off over the long run. The desirable feature list should look familiar from dmalloc and electricfence, and the surprisingly excellent book Writing Solid Code:

    • sentry values: allow a little more space before and after each alloc, respecting maximum alignment requirement; fill with magic numbers (helps catch buffer overflows and underflows, and the occasional "wild" pointer)
    • alloc fill: fill new allocations with a magic non-0 value -- Visual C++ will already do this for you in Debug builds (helps catch use of uninitialized vars)
    • free fill: fill in freed memory with a magic non-0 value, designed to trigger a segfault if it's dereferenced in most cases (helps catch dangling pointers)
    • delayed free: don't return freed memory to the heap for a while, keep it free filled but not available (helps catch more dangling pointers, catches proximate double-frees)
    • tracking: being able to record where an allocation was made can sometimes be useful

    Note that in our local homebrew system (for an embedded target) we keep the tracking separate from most of the other stuff, because the run-time overhead is much higher.


    If you're interested in more reasons to overload these allocation functions/operators, take a look at my answer to "Any reason to overload global operator new and delete?"; shameless self-promotion aside, it lists other techniques that are helpful in tracking heap corruption errors, as well as other applicable tools.


    Because I keep finding my own answer here when searching for alloc/free/fence values MS uses, here's another answer that covers Microsoft dbgheap fill values.

    Check if a string matches a regex in Bash script

    I would use expr match instead of =~:

    expr match "$date" "[0-9]\{8\}" >/dev/null && echo yes
    

    This is better than the currently accepted answer of using =~ because =~ will also match empty strings, which IMHO it shouldn't. Suppose badvar is not defined, then [[ "1234" =~ "$badvar" ]]; echo $? gives (incorrectly) 0, while expr match "1234" "$badvar" >/dev/null ; echo $? gives correct result 1.

    We have to use >/dev/null to hide expr match's output value, which is the number of characters matched or 0 if no match found. Note its output value is different from its exit status. The exit status is 0 if there's a match found, or 1 otherwise.

    Generally, the syntax for expr is:

    expr match "$string" "$lead"
    

    Or:

    expr "$string" : "$lead"
    

    where $lead is a regular expression. Its exit status will be true (0) if lead matches the leading slice of string (Is there a name for this?). For example expr match "abcdefghi" "abc"exits true, but expr match "abcdefghi" "bcd" exits false. (Credit to @Carlo Wood for pointing out this.

    Python 3 sort a dict by its values

    You can sort by values in reverse order (largest to smallest) using a dictionary comprehension:

    {k: d[k] for k in sorted(d, key=d.get, reverse=True)}
    # {'b': 4, 'a': 3, 'c': 2, 'd': 1}
    

    If you want to sort by values in ascending order (smallest to largest)

    {k: d[k] for k in sorted(d, key=d.get)}
    # {'d': 1, 'c': 2, 'a': 3, 'b': 4}
    

    If you want to sort by the keys in ascending order

    {k: d[k] for k in sorted(d)}
    # {'a': 3, 'b': 4, 'c': 2, 'd': 1}
    

    This works on CPython 3.6+ and any implementation of Python 3.7+ because dictionaries keep insertion order.

    How to list all `env` properties within jenkins pipeline job?

    Show all variable in Windows system and Unix system is different, you can define a function to call it every time.

    def showSystemVariables(){    
       if(isUnix()){
         sh 'env'
       } else {
         bat 'set'
       }
    }
    

    I will call this function first to show all variables in all pipline script

    stage('1. Show all variables'){
         steps {
             script{            
                  showSystemVariables()
             }
         }
    } 
    

    Failed to find target with hash string 'android-25'

    You can open the SDK standalone by going to installation directory, just right click on the SDK Manager.exe and click on run as Administrator. i hope it will help.

    How to keep Docker container running after starting services?

    There are some cases during development when there is no service yet but you want to simulate it and keep the container alive.

    It is very easy to write a bash placeholder that simulates a running service:

    while true; do
      sleep 100
    done
    

    You replace this by something more serious as the development progress.

    On a CSS hover event, can I change another div's styling?

    The following example is based on jQuery but it can be achieved using any JS tool kit or even plain old JS

    $(document).ready(function(){
         $("#a").mouseover(function(){
             $("#b").css("background-color", "red");
         });
    });
    

    How to send FormData objects with Ajax-requests in jQuery?

    I believe you could do it like this :

    var fd = new FormData();    
    fd.append( 'file', input.files[0] );
    
    $.ajax({
      url: 'http://example.com/script.php',
      data: fd,
      processData: false,
      contentType: false,
      type: 'POST',
      success: function(data){
        alert(data);
      }
    });
    

    Notes:

    • Setting processData to false lets you prevent jQuery from automatically transforming the data into a query string. See the docs for more info.

    • Setting the contentType to false is imperative, since otherwise jQuery will set it incorrectly.

    Docker Compose wait for container X before starting Y

    Quite recently they've added the depends_on feature.

    Edit:

    As of compose version 2.1+ till version 3 you can use depends_on in conjunction with healthcheck to achieve this:

    From the docs:

    version: '2.1'
    services:
      web:
        build: .
        depends_on:
          db:
            condition: service_healthy
          redis:
            condition: service_started
      redis:
        image: redis
      db:
        image: redis
        healthcheck:
          test: "exit 0"
    

    Before version 2.1

    You can still use depends_on, but it only effects the order in which services are started - not if they are ready before the dependant service is started.

    It seems to require at least version 1.6.0.

    Usage would look something like this:

    version: '2'
    services:
      web:
        build: .
        depends_on:
          - db
          - redis
      redis:
        image: redis
      db:
        image: postgres 
    

    From the docs:

    Express dependency between services, which has two effects:

    • docker-compose up will start services in dependency order. In the following example, db and redis will be started before web.
    • docker-compose up SERVICE will automatically include SERVICE’s dependencies. In the following example, docker-compose up web will also create and start db and redis.

    Note: As I understand it, although this does set the order in which containers are loaded. It does not guarantee that the service inside the container has actually loaded.

    For example, you postgres container might be up. But the postgres service itself might still be initializing within the container.

    Easiest way to convert a List to a Set in Java

    There are various ways to get a Set as:

        List<Integer> sourceList = new ArrayList();
        sourceList.add(1);
        sourceList.add(2);
        sourceList.add(3);
        sourceList.add(4);
    
        // Using Core Java
        Set<Integer> set1 = new HashSet<>(sourceList);  //needs null-check if sourceList can be null.
    
        // Java 8
        Set<Integer> set2 = sourceList.stream().collect(Collectors.toSet());
        Set<Integer> set3 = sourceList.stream().collect(Collectors.toCollection(HashSet::new));
    
        //Guava
        Set<Integer> set4 = Sets.newHashSet(sourceList);
    
        // Apache commons
        Set<Integer> set5 = new HashSet<>(4);
        CollectionUtils.addAll(set5, sourceList);
    

    When we use Collectors.toSet() it returns a set and as per the doc:There are no guarantees on the type, mutability, serializability, or thread-safety of the Set returned. If we want to get a HashSet then we can use the other alternative to get a set (check set3).

    $_POST not working. "Notice: Undefined index: username..."

    first of all,

    be sure that there is a post

    if(isset($_POST['username'])) { 
        // check if the username has been set
    }
    

    second, and most importantly, sanitize the data, meaning that

    $query = "SELECT password FROM users WHERE username='".$_POST['username']."'";
    

    is deadly dangerous, instead use

    $query = "SELECT password FROM users WHERE username='".mysql_real_escape_string($_POST['username'])."'";
    

    and please research the subject sql injection

    How to change fonts in matplotlib (python)?

    Say you want Comic Sans for the title and Helvetica for the x label.

    csfont = {'fontname':'Comic Sans MS'}
    hfont = {'fontname':'Helvetica'}
    
    plt.title('title',**csfont)
    plt.xlabel('xlabel', **hfont)
    plt.show()
    

    How do you display code snippets in MS Word preserving format and syntax highlighting?

    Maybe this is overly simple, but have you tried pasting in your code and setting the font on it to Courier New?

    How to get date representing the first day of a month?

    Get First Day of Last Month

    Select ADDDATE(LAST_DAY(ADDDATE(now(), INTERVAL -2 MONTH)), INTERVAL 1 DAY);

    Get Last Day of Last Month

    Select LAST_DAY(ADDDATE(now(), INTERVAL -1 MONTH));

    xsl: how to split strings?

    If your XSLT processor supports EXSLT, you can use str:tokenize, otherwise, the link contains an implementation using functions like substring-before.

    Using "If cell contains #N/A" as a formula condition.

    Input the following formula in C1:

    =IF(ISNA(A1),B1,A1*B1)

    Screenshots:

    When #N/A:

    enter image description here

    When not #N/A:

    enter image description here

    Let us know if this helps.

    How do you concatenate Lists in C#?

    It also worth noting that Concat works in constant time and in constant memory. For example, the following code

            long boundary = 60000000;
            for (long i = 0; i < boundary; i++)
            {
                list1.Add(i);
                list2.Add(i);
            }
            var listConcat = list1.Concat(list2);
            var list = listConcat.ToList();
            list1.AddRange(list2);
    

    gives the following timing/memory metrics:

    After lists filled mem used: 1048730 KB
    concat two enumerables: 00:00:00.0023309 mem used: 1048730 KB
    convert concat to list: 00:00:03.7430633 mem used: 2097307 KB
    list1.AddRange(list2) : 00:00:00.8439870 mem used: 2621595 KB
    

    What is bootstrapping?

    An example of bootstrapping is in some web frameworks. You call index.php (the bootstrapper), and then it loads the frameworks helpers, models, configuration, and then loads the controller and passes off control to it.

    As you can see, it's a simple file that starts a large process.

    How do I sort strings alphabetically while accounting for value when a string is numeric?

    Even though this is an old question, I'd like to give a solution:

    string[] things= new string[] { "105", "101", "102", "103", "90" };
    
    foreach (var thing in things.OrderBy(x => Int32.Parse(x) )
    {
        Console.WriteLine(thing);
    }
    

    Woha quite simple right? :D

    Fit Image in ImageButton in Android

    Refer below link and try to find what you really want:

    ImageView.ScaleType CENTER Center the image in the view, but perform no scaling.

    ImageView.ScaleType CENTER_CROP Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding).

    ImageView.ScaleType CENTER_INSIDE Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or less than the corresponding dimension of the view (minus padding).

    ImageView.ScaleType FIT_CENTER Scale the image using CENTER.

    ImageView.ScaleType FIT_END Scale the image using END.

    ImageView.ScaleType FIT_START Scale the image using START.

    ImageView.ScaleType FIT_XY Scale the image using FILL.

    ImageView.ScaleType MATRIX Scale using the image matrix when drawing.

    https://developer.android.com/reference/android/widget/ImageView.ScaleType.html

    How to get the selected date value while using Bootstrap Datepicker?

    I was able to find the moment.js object for the selected date with the following:

    $('#datepicker').data('DateTimePicker').date()
    

    More info about moment.js and how to format the date using the moment.js object

    How to stick table header(thead) on top while scrolling down the table rows with fixed header(navbar) in bootstrap 3?

    Anyone looking for this functionality past 2018: it's much cleaner to do this with just CSS using position: sticky.

    position: sticky doesn't work with some table elements (thead/tr) in Chrome. You can move sticky to tds/ths of tr you need to be sticky. Like this:

    thead tr:nth-child(1) th {
      background: white;
      position: sticky;
      top: 0;
      z-index: 10;
    }
    

    size of NumPy array

    This is called the "shape" in NumPy, and can be requested via the .shape attribute:

    >>> a = zeros((2, 5))
    >>> a.shape
    (2, 5)
    

    If you prefer a function, you could also use numpy.shape(a).

    How to pass a datetime parameter?

    Since I have encoding ISO-8859-1 operating system the date format "dd.MM.yyyy HH:mm:sss" was not recognised what did work was to use InvariantCulture string.

    string url = "GetData?DagsPr=" + DagsProfs.ToString(CultureInfo.InvariantCulture)
    

    How do I run a simple bit of code in a new thread?

    I'd recommend looking at Jeff Richter's Power Threading Library and specifically the IAsyncEnumerator. Take a look at the video on Charlie Calvert's blog where Richter goes over it for a good overview.

    Don't be put off by the name because it makes asynchronous programming tasks easier to code.

    nodemon not working: -bash: nodemon: command not found

    npx nodemon filename.js

    This will work on macOS BigSur

    SQL Server Linked Server Example Query

    Usually direct queries should not be used in case of linked server because it heavily use temp database of SQL server. At first step data is retrieved into temp DB then filtering occur. There are many threads about this. It is better to use open OPENQUERY because it passes SQL to the source linked server and then it return filtered results e.g.

    SELECT *
    FROM OPENQUERY(Linked_Server_Name , 'select * from TableName where ID = 500')
    

    What is the proper way to comment functions in Python?

    The principles of good commenting are fairly subjective, but here are some guidelines:

    • Function comments should describe the intent of a function, not the implementation
    • Outline any assumptions that your function makes with regards to system state. If it uses any global variables (tsk, tsk), list those.
    • Watch out for excessive ASCII art. Having long strings of hashes may seem to make the comments easier to read, but they can be annoying to deal with when comments change
    • Take advantage of language features that provide 'auto documentation', i.e., docstrings in Python, POD in Perl, and Javadoc in Java

    @UniqueConstraint annotation in Java

    you can use @UniqueConstraint on class level, for combined primary key in a table. for example:

     @Entity
     @Table(name = "PRODUCT_ATTRIBUTE", uniqueConstraints = {
           @UniqueConstraint(columnNames = {"PRODUCT_ID"}) })
    

    public class ProductAttribute{}

    Calculating the difference between two Java date instances

    If you don't want to use JodaTime or similar, the best solution is probably this:

    final static long MILLIS_PER_DAY = 24 * 3600 * 1000;
    long msDiff= date1.getTime() - date2.getTime();
    long daysDiff = Math.round(msDiff / ((double)MILLIS_PER_DAY));
    

    The number of ms per day is not always the same (because of daylight saving time and leap seconds), but it's very close, and at least deviations due to daylight saving time cancel out over longer periods. Therefore dividing and then rounding will give a correct result (at least as long as the local calendar used does not contain weird time jumps other than DST and leap seconds).

    Note that this still assumes that date1 and date2 are set to the same time of day. For different times of day, you'd first have to define what "date difference" means, as pointed out by Jon Skeet.

    Write variable to a file in Ansible

    Unless you are writing very small files, you should probably use templates.

    Example:

    - name: copy upstart script
      template: 
        src: myCompany-service.conf.j2 
        dest: "/etc/init/myCompany-service.conf"
    

    Change size of axes title and labels in ggplot2

    To change the size of (almost) all text elements, in one place, and synchronously, rel() is quite efficient:
    g+theme(text = element_text(size=rel(3.5))

    You might want to tweak the number a bit, to get the optimum result. It sets both the horizontal and vertical axis labels and titles, and other text elements, on the same scale. One exception is faceted grids' titles which must be manually set to the same value, for example if both x and y facets are used in a graph:
    theme(text = element_text(size=rel(3.5)), strip.text.x = element_text(size=rel(3.5)), strip.text.y = element_text(size=rel(3.5)))

    Vue.js img src concatenate variable and text

    if you handel this from dataBase try :

    <img :src="baseUrl + 'path/path' + obj.key +'.png'">
    

    How can I find matching values in two arrays?

    Libraries like underscore and lodash have a utility method called intersection to find matches in arrays passed in. Take a look at: http://underscorejs.org/#intersection

    Selenium 2.53 not working on Firefox 47

    Firefox 47.0 stopped working with Webdriver.

    Easiest solution is to switch to Firefox 47.0.1 and Webdriver 2.53.1. This combination again works. In fact, restoring Webdriver compatibility was the main reason behind the 47.0.1 release, according to https://www.mozilla.org/en-US/firefox/47.0.1/releasenotes/.

    Gnuplot line types

    Until version 4.6

    The dash type of a linestyle is given by the linetype, which does also select the line color unless you explicitely set an other one with linecolor.

    However, the support for dashed lines depends on the selected terminal:

    1. Some terminals don't support dashed lines, like png (uses libgd)
    2. Other terminals, like pngcairo, support dashed lines, but it is disables by default. To enable it, use set termoption dashed, or set terminal pngcairo dashed ....
    3. The exact dash patterns differ between terminals. To see the defined linetype, use the test command:

    Running

    set terminal pngcairo dashed
    set output 'test.png'
    test
    set output
    

    gives:

    enter image description here

    whereas, the postscript terminal shows different dash patterns:

    set terminal postscript eps color colortext
    set output 'test.eps'
    test
    set output
    

    enter image description here

    Version 5.0

    Starting with version 5.0 the following changes related to linetypes, dash patterns and line colors are introduced:

    • A new dashtype parameter was introduced:

      To get the predefined dash patterns, use e.g.

      plot x dashtype 2
      

      You can also specify custom dash patterns like

      plot x dashtype (3,5,10,5),\
           2*x dashtype '.-_'
      
    • The terminal options dashed and solid are ignored. By default all lines are solid. To change them to dashed, use e.g.

      set for [i=1:8] linetype i dashtype i
      
    • The default set of line colors was changed. You can select between three different color sets with set colorsequence default|podo|classic:

    enter image description here

    Copying PostgreSQL database to another server

    If you are looking to migrate between versions (eg you updated postgres and have 9.1 running on localhost:5432 and 9.3 running on localhost:5434) you can run:

    pg_dumpall -p 5432 -U myuser91 | psql -U myuser94 -d postgres -p 5434
    

    Check out the migration docs.

    What is the difference between Python's list methods append and extend?

    To distinguish them intuitively

    l1 = ['a', 'b', 'c']
    l2 = ['d', 'e', 'f']
    l1.append(l2)
    l1
    ['a', 'b', 'c', ['d', 'e', 'f']]
    

    It's like l1 reproduce a body inside her body(nested).

    # Reset l1 = ['a', 'b', 'c']
    l1.extend(l2)
    l1
    ['a', 'b', 'c', 'd', 'e', 'f']
    

    It's like that two separated individuals get married and construct an united family.

    Besides I make an exhaustive cheatsheet of all list's methods for your reference.

    list_methods = {'Add': {'extend', 'append', 'insert'},
                    'Remove': {'pop', 'remove', 'clear'}
                    'Sort': {'reverse', 'sort'},
                    'Search': {'count', 'index'},
                    'Copy': {'copy'},
                    }
    

    "Repository does not have a release file" error

    Make sure your /etc/apt/sources.list has http://old-releases.ubuntu.com instead of in.archive

    Check if the number is integer

    In R, whether a number is numeric or integer can be determined by class function. Generally all numbers are stored as numeric and to explicitly define a number as integer we need to specify 'L' after the number.

    Example:

    x <- 1

    class(x)

    [1] "numeric"

    x <- 1L

    class(x)

    [1] "integer"

    I hope this is what was needed. Thanks :)

    Converting Chart.js canvas chart to image using .toDataUrl() results in blank image

    You should use the Chartjs API function toBase64Image() instead and call it after the animation is complete. Therefore:

    var pieChart, URI;
    
    var options = {
        animation : {
            onComplete : function(){    
                URI = pieChart.toBase64Image();
            }
        }
    };
    
    var content = {
        type: 'pie', //whatever, not relevant for this example
        data: {
            datasets: dataset //whatever, not relevant for this example
        },
        options: options        
    };    
    
    pieChart = new Chart(pieChart, content);
    

    Example

    You can check this example and run it

    _x000D_
    _x000D_
    var chart = new Chart(ctx, {_x000D_
       type: 'bar',_x000D_
       data: {_x000D_
          labels: ['Standing costs', 'Running costs'], // responsible for how many bars are gonna show on the chart_x000D_
          // create 12 datasets, since we have 12 items_x000D_
          // data[0] = labels[0] (data for first bar - 'Standing costs') | data[1] = labels[1] (data for second bar - 'Running costs')_x000D_
          // put 0, if there is no data for the particular bar_x000D_
          datasets: [{_x000D_
             label: 'Washing and cleaning',_x000D_
             data: [0, 8],_x000D_
             backgroundColor: '#22aa99'_x000D_
          }, {_x000D_
             label: 'Traffic tickets',_x000D_
             data: [0, 2],_x000D_
             backgroundColor: '#994499'_x000D_
          }, {_x000D_
             label: 'Tolls',_x000D_
             data: [0, 1],_x000D_
             backgroundColor: '#316395'_x000D_
          }, {_x000D_
             label: 'Parking',_x000D_
             data: [5, 2],_x000D_
             backgroundColor: '#b82e2e'_x000D_
          }, {_x000D_
             label: 'Car tax',_x000D_
             data: [0, 1],_x000D_
             backgroundColor: '#66aa00'_x000D_
          }, {_x000D_
             label: 'Repairs and improvements',_x000D_
             data: [0, 2],_x000D_
             backgroundColor: '#dd4477'_x000D_
          }, {_x000D_
             label: 'Maintenance',_x000D_
             data: [6, 1],_x000D_
             backgroundColor: '#0099c6'_x000D_
          }, {_x000D_
             label: 'Inspection',_x000D_
             data: [0, 2],_x000D_
             backgroundColor: '#990099'_x000D_
          }, {_x000D_
             label: 'Loan interest',_x000D_
             data: [0, 3],_x000D_
             backgroundColor: '#109618'_x000D_
          }, {_x000D_
             label: 'Depreciation of the vehicle',_x000D_
             data: [0, 2],_x000D_
             backgroundColor: '#109618'_x000D_
          }, {_x000D_
             label: 'Fuel',_x000D_
             data: [0, 1],_x000D_
             backgroundColor: '#dc3912'_x000D_
          }, {_x000D_
             label: 'Insurance and Breakdown cover',_x000D_
             data: [4, 0],_x000D_
             backgroundColor: '#3366cc'_x000D_
          }]_x000D_
       },_x000D_
       options: {_x000D_
          responsive: false,_x000D_
          legend: {_x000D_
             position: 'right' // place legend on the right side of chart_x000D_
          },_x000D_
          scales: {_x000D_
             xAxes: [{_x000D_
                stacked: true // this should be set to make the bars stacked_x000D_
             }],_x000D_
             yAxes: [{_x000D_
                stacked: true // this also.._x000D_
             }]_x000D_
          },_x000D_
          animation : {_x000D_
             onComplete : done_x000D_
          }      _x000D_
       }_x000D_
    });_x000D_
    _x000D_
    function done(){_x000D_
        alert(chart.toBase64Image());_x000D_
    }
    _x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>_x000D_
    <canvas id="ctx" width="700"></canvas>
    _x000D_
    _x000D_
    _x000D_

    MATLAB error: Undefined function or method X for input arguments of type 'double'

    You get this error when the function isn't on the MATLAB path or in pwd.

    First, make sure that you are able to find the function using:

    >> which divrat
    c:\work\divrat\divrat.m
    

    If it returns:

    >> which divrat
    'divrat' not found.
    

    It is not on the MATLAB path or in PWD.

    Second, make sure that the directory that contains divrat is on the MATLAB path using the PATH command. It may be that a directory that you thought was on the path isn't actually on the path.

    Finally, make sure you aren't using a "private" directory. If divrat is in a directory named private, it will be accessible by functions in the parent directory, but not from the MATLAB command line:

    >> foo
    
    ans =
    
         1
    
    >> divrat(1,1)
    ??? Undefined function or method 'divrat' for input arguments of type 'double'.
    
    >> which -all divrat
    c:\work\divrat\private\divrat.m  % Private to divrat
    

    Laravel view not found exception

    This happens when Laravel doesn't find a view file in your application. Make sure you have a file named: index.php or index.blade.php under your app/views directory.

    Note that Laravel will do the following when calling View::make:

    • For View::make('index') Laravel will look for the file: app/views/index.php.
    • For View::make('index.foo') Laravel will look for the file: app/views/index/foo.php.

    The file can have any of those two extensions: .php or .blade.php.

    What is the difference between --save and --save-dev?

    The difference between --save and --save-dev may not be immediately noticeable if you have tried them both on your own projects. So here are a few examples...

    Lets say you were building an app that used the moment package to parse and display dates. Your app is a scheduler so it really needs this package to run, as in: cannot run without it. In this case you would use

    npm install moment --save
    

    This would create a new value in your package.json

    "dependencies": {
       ...
       "moment": "^2.17.1"
    }
    

    When you are developing, it really helps to use tools such as test suites and may need jasmine-core and karma. In this case you would use

    npm install jasmine-core --save-dev
    npm install karma --save-dev
    

    This would also create a new value in your package.json

    "devDependencies": {
        ...
        "jasmine-core": "^2.5.2",
        "karma": "^1.4.1",
    }
    

    You do not need the test suite to run the app in its normal state, so it is a --save-dev type dependency, nothing more. You can see how if you do not understand what is really happening, it is a bit hard to imagine.

    Taken directly from NPM docs docs#dependencies

    Dependencies

    Dependencies are specified in a simple object that maps a package name to a version range. The version range is a string which has one or more space-separated descriptors. Dependencies can also be identified with a tarball or git URL.

    Please do not put test harnesses or transpilers in your dependencies object. See devDependencies, below.

    Even in the docs, it asks you to use --save-dev for modules such as test harnesses.

    I hope this helps and is clear.

    Check if URL has certain string with PHP

    You can try an .htaccess method similar to the concept of how wordpress works.

    Reference: http://monkeytooth.net/2010/12/htaccess-php-how-to-wordpress-slugs/

    But I'm not sure if thats what your looking for exactly per say..

    Laravel 5 - artisan seed [ReflectionException] Class SongsTableSeeder does not exist

    I had the same "reflection exception" error. The solution was to copy the class file to the server, from dev, for me. dumb mistake, but given how many files we deal with its easy to forget to copy them over to the server every time.

    Replace spaces with dashes and make all letters lower-case

    You can also use split and join:

    "Sonic Free Games".split(" ").join("-").toLowerCase(); //sonic-free-games
    

    Can't bind to 'ngIf' since it isn't a known property of 'div'

    If you are using RC5 then import this:

    import { CommonModule } from '@angular/common';  
    import { BrowserModule } from '@angular/platform-browser';
    

    and be sure to import CommonModule from the module that is providing your component.

     @NgModule({
        imports: [CommonModule],
        declarations: [MyComponent]
      ...
    })
    class MyComponentModule {}
    

    Can IntelliJ IDEA encapsulate all of the functionality of WebStorm and PHPStorm through plugins?

    Definitely a great question. I've noted this also as a sub question of the choice for versions within IDEa that this link may help to address...

    http://www.jetbrains.com/idea/features/editions_comparison_matrix.html

    it as well potentially possesses a ground work for looking at your other IDE choices and the options they provide.

    I'm thinking WebStorm is best for JavaScript and Git repo management, meaning the HTML5 CSS Cordova kinds of stacks, which is really where (I believe along with others) the future lies and energies should be focused now... but ya it depends on your needs, etc.

    Anyway this tells that story too... http://www.jetbrains.com/products.html

    Android SDK Setup under Windows 7 Pro 64 bit

    My problem was installing the Android SDK in Eclipse Helios on Windows 7 Enterprise 64bit, I was getting the following error:

    Missing requirement: Android Development Tools 0.9.7.v201005071157-36220 (com.android.ide.eclipse.adt.feature.group 0.9.7.v201005071157-36220) requires 'org.eclipse.jdt.junit 0.0.0' but it could not be found

    Having followed the advice above to ensure that the JDK was in my PATH variable (it wasn't), installation went smoothly. I guess the error was somewhat spurious (incidentally if you're looking for the JARs that correspond to that class, they were in my profile rather than the Eclipse installation directory)

    So, check that PATH variable!

    Angular checkbox and ng-click

    The order of execution of ng-click and ng-model is different with angular 1.2 vs 1.6

    You must test, with 1.2 and 1.6,

    for example, with angular 1.2, ng-click get execute before ng-model, with angular 1.6, ng-model maybe get excute before ng-click.

    so you get 'true checked' / 'false uncheck' value maybe not you expect

    Shortcut to open file in Vim

    There's also command-t which I find to be the best of the bunch (and I've tried them all). It's a minor hassle to install it but, once it's installed, it's a dream to use.

    https://wincent.com/products/command-t/

    How to sort an array of objects with jquery or javascript

    var array = [[1, "grape", 42], [2, "fruit", 9]];
    
    array.sort(function(a, b)
    {
        // a and b will here be two objects from the array
        // thus a[1] and b[1] will equal the names
    
        // if they are equal, return 0 (no sorting)
        if (a[1] == b[1]) { return 0; }
        if (a[1] > b[1])
        {
            // if a should come after b, return 1
            return 1;
        }
        else
        {
            // if b should come after a, return -1
            return -1;
        }
    });
    

    The sort function takes an additional argument, a function that takes two arguments. This function should return -1, 0 or 1 depending on which of the two arguments should come first in the sorting. More info.

    I also fixed a syntax error in your multidimensional array.

    ImageView in android XML layout with layout_height="wrap_content" has padding top & bottom

    I had a simular issue and resolved it using android:adjustViewBounds="true" on the ImageView.

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:contentDescription="@string/banner_alt"
        android:src="@drawable/banner_portrait" />
    

    Chrome doesn't delete session cookies

    If you set the domain for the php session cookie, browsers seem to hold on to it for 30 seconds or so. It doesn't seem to matter if you close the tab or browser window.

    So if you are managing sessions using something like the following it may be causing the cookie to hang in the browser for longer than expected.

    ini_set("session.cookie_domain", 'www.domain.com');
    

    The only way I've found to get rid of the hanging cookie is to remove the line of code that sets the session cookie's domain. Also watch out for session_set_cookie_params() function. Dot prefixing the domain seems to have no bearing on the issue either.

    This might be a php bug as php sends a session cookie (i.e. PHPSESSID=b855ed53d007a42a1d0d798d958e42c9) in the header after the session has been destroyed. Or it might be a server propagation issue but I don't thinks so since my test were on a private servers.

    SQL SERVER, SELECT statement with auto generate row id

    IDENTITY(int, 1, 1) should do it if you are doing a select into. In SQL 2000, I use to just put the results in a temp table and query that afterwords.

    Java: Calling a super method which calls an overridden method

    Since the only way to avoid a method to get overriden is to use the keyword super, I've thought to move up the method2() from SuperClass to another new Base class and then call it from SuperClass:

    class Base 
    {
        public void method2()
        {
            System.out.println("superclass method2");
        }
    }
    
    class SuperClass extends Base
    {
        public void method1()
        {
            System.out.println("superclass method1");
            super.method2();
        }
    }
    
    class SubClass extends SuperClass
    {
        @Override
        public void method1()
        {
            System.out.println("subclass method1");
            super.method1();
        }
    
        @Override
        public void method2()
        {
            System.out.println("subclass method2");
        }
    }
    
    public class Demo 
    {
        public static void main(String[] args) 
        {
            SubClass mSubClass = new SubClass();
            mSubClass.method1();
        }
    }
    

    Output:

    subclass method1
    superclass method1
    superclass method2
    

    Simple http post example in Objective-C?

    Thanks a lot it worked , please note I did a typo in php as it should be mysqli_query( $con2, $sql )

    How to delete all files from a specific folder?

    string[] filePaths = Directory.GetFiles(@"c:\MyDir\");
    foreach (string filePath in filePaths)
    File.Delete(filePath);
    

    Or in a single line:

    Array.ForEach(Directory.GetFiles(@"c:\MyDir\"), File.Delete);
    

    What is the difference between association, aggregation and composition?

    https://www.linkedin.com/pulse/types-relationships-object-oriented-programming-oop-sarah-el-dawody/

    Composition: is a "part-of" relationship.

    for example “engine is part of the car”, “heart is part of the body”.

    enter image description here

    Association: is a “has-a” type relationship

    For example, suppose we have two classes then these two classes are said to be “has-a” relationships if both of these entities share each other’s object for some work and at the same time they can exist without each other's dependency or both have their own lifetime.

    enter image description here

    The above example showing an association relationship because of both Employee and Manager class using the object of each other and both their own independent life cycle.

    Aggregation: is based is on "has-a" relationship and it's is \\a special form of association

    for example, “Student” and “address”. Each student must have an address so the relationship between Student class and Address class will be “Has-A” type relationship but vice versa is not true.

    enter image description here

    How to check if a std::string is set or not?

    Use empty():

    std::string s;
    
    if (s.empty())
        // nothing in s
    

    Have bash script answer interactive prompts

    A simple

    echo "Y Y N N Y N Y Y N" | ./your_script
    

    This allow you to pass any sequence of "Y" or "N" to your script.

    Check if Cookie Exists

    public static class CookieHelper
    {
        /// <summary>
        /// Checks whether a cookie exists.
        /// </summary>
        /// <param name="cookieCollection">A CookieCollection, such as Response.Cookies.</param>
        /// <param name="name">The cookie name to delete.</param>
        /// <returns>A bool indicating whether a cookie exists.</returns>
        public static bool Exists(this HttpCookieCollection cookieCollection, string name)
        {
            if (cookieCollection == null)
            {
                throw new ArgumentNullException("cookieCollection");
            }
    
            return cookieCollection[name] != null;
        }
    }
    

    Usage:

    Request.Cookies.Exists("MyCookie")
    

    How to copy folders to docker image from Dockerfile?

    Use ADD (docs)

    The ADD command can accept as a <src> parameter:

    1. A folder within the build folder (the same folder as your Dockerfile). You would then add a line in your Dockerfile like this:
    ADD folder /path/inside/your/container
    

    or

    1. A single-file archive anywhere in your host filesystem. To create an archive use the command:
    tar -cvzf newArchive.tar.gz /path/to/your/folder
    

    You would then add a line to your Dockerfile like this:

    ADD /path/to/archive/newArchive.tar.gz  /path/inside/your/container
    

    Notes:

    • ADD will automatically extract your archive.
    • presence/absence of trailing slashes is important, see the linked docs

    How do I find the width & height of a terminal window?

    There are some cases where your rows/LINES and columns do not match the actual size of the "terminal" being used. Perhaps you may not have a "tput" or "stty" available.

    Here is a bash function you can use to visually check the size. This will work up to 140 columns x 80 rows. You can adjust the maximums as needed.

    function term_size
    {
        local i=0 digits='' tens_fmt='' tens_args=()
        for i in {80..8}
        do
            echo $i $(( i - 2 ))
        done
        echo "If columns below wrap, LINES is first number in highest line above,"
        echo "If truncated, LINES is second number."
        for i in {1..14}
        do
            digits="${digits}1234567890"
            tens_fmt="${tens_fmt}%10d"
            tens_args=("${tens_args[@]}" $i)
        done
        printf "$tens_fmt\n" "${tens_args[@]}"
        echo "$digits"
    }
    

    SSH Private Key Permissions using Git GUI or ssh-keygen are too open

    FOR MAC USERS:

    Change the settings of your key pair file by typing this in the terminal:

    chmod og-r *filename.pem*
    

    (make sure you are in the correct directory, or path filename in the command correctly).

    Escape Character in SQL Server

    Escaping quotes in MSSQL is done by a double quote, so a '' or a "" will produce one escaped ' and ", respectively.

    Using sed to mass rename files

    First, I should say that the easiest way to do this is to use the prename or rename commands.

    On Ubuntu, OSX (Homebrew package rename, MacPorts package p5-file-rename), or other systems with perl rename (prename):

    rename s/0000/000/ F0000*
    

    or on systems with rename from util-linux-ng, such as RHEL:

    rename 0000 000 F0000*
    

    That's a lot more understandable than the equivalent sed command.

    But as for understanding the sed command, the sed manpage is helpful. If you run man sed and search for & (using the / command to search), you'll find it's a special character in s/foo/bar/ replacements.

      s/regexp/replacement/
             Attempt  to match regexp against the pattern space.  If success-
             ful,  replace  that  portion  matched  with  replacement.    The
             replacement may contain the special character & to refer to that
             portion of the pattern space  which  matched,  and  the  special
             escapes  \1  through  \9  to refer to the corresponding matching
             sub-expressions in the regexp.
    

    Therefore, \(.\) matches the first character, which can be referenced by \1. Then . matches the next character, which is always 0. Then \(.*\) matches the rest of the filename, which can be referenced by \2.

    The replacement string puts it all together using & (the original filename) and \1\2 which is every part of the filename except the 2nd character, which was a 0.

    This is a pretty cryptic way to do this, IMHO. If for some reason the rename command was not available and you wanted to use sed to do the rename (or perhaps you were doing something too complex for rename?), being more explicit in your regex would make it much more readable. Perhaps something like:

    ls F00001-0708-*|sed 's/F0000\(.*\)/mv & F000\1/' | sh
    

    Being able to see what's actually changing in the s/search/replacement/ makes it much more readable. Also it won't keep sucking characters out of your filename if you accidentally run it twice or something.

    What is the difference between Step Into and Step Over in a debugger

    Step Into The next expression on the currently-selected line to be executed is invoked, and execution suspends at the next executable line in the method that is invoked.

    Step Over The currently-selected line is executed and suspends on the next executable line.

    Adding values to Arraylist

    First simple rule: never use the String(String) constructor, it is absolutely useless (*).

    So arr.add("ss") is just fine.

    With 3 it's slightly different: 3 is an int literal, which is not an object. Only objects can be put into a List. So the int will need to be converted into an Integer object. In most cases that will be done automagically for you (that process is called autoboxing). It effectively does the same thing as Integer.valueOf(3) which can (and will) avoid creating a new Integer instance in some cases.

    So actually writing arr.add(3) is usually a better idea than using arr.add(new Integer(3)), because it can avoid creating a new Integer object and instead reuse and existing one.

    Disclaimer: I am focusing on the difference between the second and third code blocks here and pretty much ignoring the generics part. For more information on the generics, please check out the other answers.

    (*) there are some obscure corner cases where it is useful, but once you approach those you'll know never to take absolute statements as absolutes ;-)

    File upload from <input type="file">

    Try this small lib, works with Angular 5.0.0

    Quickstart example with ng2-file-upload 1.3.0:

    User clicks custom button, which triggers upload dialog from hidden input type="file" , uploading started automatically after selecting single file.

    app.module.ts:

    import {FileUploadModule} from "ng2-file-upload";
    

    your.component.html:

    ...
      <button mat-button onclick="document.getElementById('myFileInputField').click()" >
        Select and upload file
      </button>
      <input type="file" id="myFileInputField" ng2FileSelect [uploader]="uploader" style="display:none">
    ...
    

    your.component.ts:

    import {FileUploader} from 'ng2-file-upload';
    ...    
    uploader: FileUploader;
    ...
    constructor() {
       this.uploader = new FileUploader({url: "/your-api/some-endpoint"});
       this.uploader.onErrorItem = item => {
           console.error("Failed to upload");
           this.clearUploadField();
       };
       this.uploader.onCompleteItem = (item, response) => {
           console.info("Successfully uploaded");
           this.clearUploadField();
    
           // (Optional) Parsing of response
           let responseObject = JSON.parse(response) as MyCustomClass;
    
       };
    
       // Asks uploader to start upload file automatically after selecting file
      this.uploader.onAfterAddingFile = fileItem => this.uploader.uploadAll();
    }
    
    private clearUploadField(): void {
        (<HTMLInputElement>window.document.getElementById('myFileInputField'))
        .value = "";
    }
    

    Alternative lib, works in Angular 4.2.4, but requires some workarounds to adopt to Angular 5.0.0

    CSS smooth bounce animation

    Here is code not using the percentage in the keyframes. Because you used percentages the animation does nothing a long time.

    • 0% translate 0px
    • 20% translate 0px
    • etc.

    How does this example work:

    1. We set an animation. This is a short hand for animation properties.
    2. We immediately start the animation since we use from and to in the keyframes. from is = 0% and to is = 100%
    3. We can now control how fast it will bounce by setting the animation time: animation: bounce 1s infinite alternate; the 1s is how long the animation will last.

    _x000D_
    _x000D_
    .ball {_x000D_
      margin-top: 50px;_x000D_
      border-radius: 50%;_x000D_
      width: 50px;_x000D_
      height: 50px;_x000D_
      background-color: cornflowerblue;_x000D_
      border: 2px solid #999;_x000D_
      animation: bounce 1s infinite alternate;_x000D_
      -webkit-animation: bounce 1s infinite alternate;_x000D_
    }_x000D_
    @keyframes bounce {_x000D_
      from {_x000D_
        transform: translateY(0px);_x000D_
      }_x000D_
      to {_x000D_
        transform: translateY(-15px);_x000D_
      }_x000D_
    }_x000D_
    @-webkit-keyframes bounce {_x000D_
      from {_x000D_
        transform: translateY(0px);_x000D_
      }_x000D_
      to {_x000D_
        transform: translateY(-15px);_x000D_
      }_x000D_
    }
    _x000D_
    <div class="ball"></div>
    _x000D_
    _x000D_
    _x000D_

    Python exit commands - why so many and when should each be used?

    Different Means of Exiting

    os._exit():

    • Exit the process without calling the cleanup handlers.

    exit(0):

    • a clean exit without any errors / problems.

    exit(1):

    • There was some issue / error / problem and that is why the program is exiting.

    sys.exit():

    • When the system and python shuts down; it means less memory is being used after the program is run.

    quit():

    • Closes the python file.

    Summary

    Basically they all do the same thing, however, it also depends on what you are doing it for.

    I don't think you left anything out and I would recommend getting used to quit() or exit().

    You would use sys.exit() and os._exit() mainly if you are using big files or are using python to control terminal.

    Otherwise mainly use exit() or quit().

    MySQL - how to front pad zip code with "0"?

    You need to decide the length of the zip code (which I believe should be 5 characters long). Then you need to tell MySQL to zero-fill the numbers.

    Let's suppose your table is called mytable and the field in question is zipcode, type smallint. You need to issue the following query:

    ALTER TABLE mytable CHANGE `zipcode` `zipcode`
        MEDIUMINT( 5 ) UNSIGNED ZEROFILL NOT NULL;
    

    The advantage of this method is that it leaves your data intact, there's no need to use triggers during data insertion / updates, there's no need to use functions when you SELECT the data and that you can always remove the extra zeros or increase the field length should you change your mind.

    How to use comparison and ' if not' in python?

    There are two ways. In case of doubt, you can always just try it. If it does not work, you can add extra braces to make sure, like that:

    if not ((u0 <= u) and (u < u0+step)):
    

    How to write :hover condition for a:before and a:after?

    Try to use .card-listing:hover::after hover and after using :: it wil work

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

    For some looking for a solution to this problem, the root of the issue may be where you are setting your list views adapter. After you set the adapter on the listview, it resets the scroll position. Just something to consider. I moved setting the adapter into my onCreateView after we grab the reference to the listview, and it solved the problem for me. =)

    Pass a datetime from javascript to c# (Controller)

    There is a toJSON() method in javascript returns a string representation of the Date object. toJSON() is IE8+ and toISOString() is IE9+. Both results in YYYY-MM-DDTHH:mm:ss.sssZ format.

    var date = new Date();    
        $.ajax(
           {
               type: "POST",
               url: "/Group/Refresh",
               contentType: "application/json; charset=utf-8",
               data: "{ 'MyDate': " + date.toJSON() + " }",
               success: function (result) {
                   //do something
               },
               error: function (req, status, error) {
                   //error                        
               }
           });
    

    Referring to a Column Alias in a WHERE Clause

    HAVING works in MySQL according to documentation:

    The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions.

    Turn off iPhone/Safari input element rounding

    Please Try This one:

    Try Adding input Css like this:

     -webkit-appearance: none;
           border-radius: 0;
    

    How can I check out a GitHub pull request with git?

    There is an easy way for doing this using git-cli

    gh pr checkout {<number> | <url> | <branch>}
    

    Reference: https://cli.github.com/manual/gh_pr_checkout

    How can I play sound in Java?

    I wrote the following code that works fine. But I think it only works with .wav format.

    public static synchronized void playSound(final String url) {
      new Thread(new Runnable() {
      // The wrapper thread is unnecessary, unless it blocks on the
      // Clip finishing; see comments.
        public void run() {
          try {
            Clip clip = AudioSystem.getClip();
            AudioInputStream inputStream = AudioSystem.getAudioInputStream(
              Main.class.getResourceAsStream("/path/to/sounds/" + url));
            clip.open(inputStream);
            clip.start(); 
          } catch (Exception e) {
            System.err.println(e.getMessage());
          }
        }
      }).start();
    }
    

    JavaScript: filter() for Objects

    Plain ES6:

    var foo = {
        bar: "Yes"
    };
    
    const res = Object.keys(foo).filter(i => foo[i] === 'Yes')
    
    console.log(res)
    // ["bar"]
    

    How to call a MySQL stored procedure from within PHP code?

    You can call a stored procedure using the following syntax:

    $result = mysql_query('CALL getNodeChildren(2)');
    

    Delete default value of an input text on click

    Using jQuery, you can do:

    $("input:text").each(function ()
    {
        // store default value
        var v = this.value;
    
        $(this).blur(function ()
        {
            // if input is empty, reset value to default 
            if (this.value.length == 0) this.value = v;
        }).focus(function ()
        {
            // when input is focused, clear its contents
            this.value = "";
        }); 
    });
    

    And you could stuff all this into a custom plug-in, like so:

    jQuery.fn.hideObtrusiveText = function ()
    {
        return this.each(function ()
        {
            var v = this.value;
    
            $(this).blur(function ()
            {
                if (this.value.length == 0) this.value = v;
            }).focus(function ()
            {
                this.value = "";
            }); 
        });
    };
    

    Here's how you would use the plug-in:

    $("input:text").hideObtrusiveText();
    

    Advantages to using this code is:

    • Its unobtrusive and doesn't pollute the DOM
    • Code re-use: it works on multiple fields
    • It figures out the default value of inputs by itself



    Non-jQuery approach:

    function hideObtrusiveText(id)
    {
        var e = document.getElementById(id);
    
        var v = e.value;
    
        e.onfocus = function ()
        {
            e.value = "";
        };
    
        e.onblur = function ()
        {
            if (e.value.length == 0) e.value = v;
        };
    }
    

    What does the function then() mean in JavaScript?

    then() function is related to "Javascript promises" that are used in some libraries or frameworks like jQuery or AngularJS.

    A promise is a pattern for handling asynchronous operations. The promise allows you to call a method called "then" that lets you specify the function(s) to use as the callbacks.

    For more information see: http://wildermuth.com/2013/8/3/JavaScript_Promises

    And for Angular promises: http://liamkaufman.com/blog/2013/09/09/using-angularjs-promises/

    SQL Server : login success but "The database [dbName] is not accessible. (ObjectExplorer)"

    Please try this script.. What this script does is it looks at the active sessions of the database and kills them so you can bring the database back online.

     CREATE TABLE #temp_sp_who2
            (
              SPID INT,
              Status VARCHAR(1000) NULL,
              Login SYSNAME NULL,
              HostName SYSNAME NULL,
              BlkBy SYSNAME NULL,
              DBName SYSNAME NULL,
              Command VARCHAR(1000) NULL,
              CPUTime INT NULL,
              DiskIO INT NULL,
              LastBatch VARCHAR(1000) NULL,
              ProgramName VARCHAR(1000) NULL,
              SPID2 INT
              , rEQUESTID INT NULL --comment out for SQL 2000 databases
    
            )
    
    
        INSERT  INTO #temp_sp_who2
        EXEC sp_who2
    
    
        declare @kill nvarchar(max)= ''
        SELECT  @kill = @kill+ 'kill '+convert(varchar,spid) +';'
        FROM    #temp_sp_who2
        WHERE   DBName = 'databasename'
    
        exec sp_executesql @kill
    
    
      ALTER DATABASE DATABASENAME SET ONLINE WITH IMMEDIATE ROLLBACK
    

    How to filter a data frame

    Another method utilizing the dplyr package:

    library(dplyr)
    df <- mtcars %>%
            filter(mpg > 25)
    

    Without the chain (%>%) operator:

    library(dplyr)
    df <- filter(mtcars, mpg > 25)
    

    Detecting value change of input[type=text] in jQuery

    you can also use textbox events -

    <input id="txt1" type="text" onchange="SetDefault($(this).val());" onkeyup="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();">
    
    function SetDefault(Text){
      alert(Text);
    }
    

    Try This

    Write single CSV file using spark-csv

    import org.apache.hadoop.conf.Configuration
    import org.apache.hadoop.fs._
    import org.apache.spark.sql.{DataFrame,SaveMode,SparkSession}
    import org.apache.spark.sql.functions._
    

    I solved using below approach (hdfs rename file name):-

    Step 1:- (Crate Data Frame and write to HDFS)

    df.coalesce(1).write.format("csv").option("header", "false").mode(SaveMode.Overwrite).save("/hdfsfolder/blah/")
    

    Step 2:- (Create Hadoop Config)

    val hadoopConfig = new Configuration()
    val hdfs = FileSystem.get(hadoopConfig)
    

    Step3 :- (Get path in hdfs folder path)

    val pathFiles = new Path("/hdfsfolder/blah/")
    

    Step4:- (Get spark file names from hdfs folder)

    val fileNames = hdfs.listFiles(pathFiles, false)
    println(fileNames)
    

    setp5:- (create scala mutable list to save all the file names and add it to the list)

        var fileNamesList = scala.collection.mutable.MutableList[String]()
        while (fileNames.hasNext) {
          fileNamesList += fileNames.next().getPath.getName
        }
        println(fileNamesList)
    

    Step 6:- (filter _SUCESS file order from file names scala list)

        // get files name which are not _SUCCESS
        val partFileName = fileNamesList.filterNot(filenames => filenames == "_SUCCESS")
    

    step 7:- (convert scala list to string and add desired file name to hdfs folder string and then apply rename)

    val partFileSourcePath = new Path("/yourhdfsfolder/"+ partFileName.mkString(""))
        val desiredCsvTargetPath = new Path(/yourhdfsfolder/+ "op_"+ ".csv")
        hdfs.rename(partFileSourcePath , desiredCsvTargetPath)
    

    How to set iframe size dynamically

    The height is different depending on the browser's window size. It should be set dynamically depending on the size of the browser window

    <!DOCTYPE html>
        <html>
        <body>
        
        <center><h2>Heading</h2></center>
        <center><p>Paragraph</p></center>
        
        <iframe src="url" height="600" width="1350" title="Enter Here"></iframe>
        
        </body>
        </html>
    

    PHP - Session destroy after closing browser

    There are different ways to do this, but the server can't detect when de browser gets closed so destroying it then is hard.

    • timeout session.

    Either create a new session with the current time or add a time variable to the current session. and then check it when you start up or perform an action to see if the session has to be removed.

    session_start();
    $_SESSION["timeout"] = time();
    //if 100 seconds have passed since creating session delete it.
    if(time() - $_SESSION["timeout"] > 100){ 
        unset($_SESSION["timeout"];
    }
    
    • ajax

    Make javascript perform an ajax call that will delete the session, with onbeforeunload() a javascript function that calls a final action when the user leaves the page. For some reason this doesnt always work though.

    • delete it on startup.

    If you always want the user to see the login page on startup after the page has been closed you can just delete the session on startup.

    <? php
    session_start();
    unset($_SESSION["session"]);
    

    and there probably are some more.

    What in the world are Spring beans?

    Spring beans are classes. Instead of instantiating a class (using new), you get an instance as a bean cast to your class type from the application context, where the bean is what you configured in the application context configuration. This way, the whole application maintains singleton-scope instance throughout the application. All beans are initialized following their configuration order right after the application context is instantiated. Even if you don't get any beans in your application, all beans instances are already created the moment after you created the application context.

    Subtract days from a DateTime

    The dateTime.AddDays(-1) does not subtract that one day from the dateTime reference. It will return a new instance, with that one day subtracted from the original reference.

    DateTime dateTime = DateTime.Now;
    DateTime otherDateTime = dateTime.AddDays(-1);
    

    How can I run a directive after the dom has finished rendering?

    It depends on how your $('site-header') is constructed.

    You can try to use $timeout with 0 delay. Something like:

    return function(scope, element, attrs) {
        $timeout(function(){
            $('.main').height( $('.site-header').height() -  $('.site-footer').height() );
        });        
    }
    

    Explanations how it works: one, two.

    Don't forget to inject $timeout in your directive:

    .directive('sticky', function($timeout)
    

    SonarQube not picking up Unit Test Coverage

    I had the similar issue, 0.0% coverage & no unit tests count on Sonar dashboard with SonarQube 6.7.2: Maven : 3.5.2, Java : 1.8, Jacoco : Worked with 7.0/7.9/8.0, OS : Windows

    After a lot of struggle finding for correct solution on maven multi-module project,not like single module project here we need to say to pick jacoco reports from individual modules & merge to one report,So resolved issue with this configuration as my parent pom looks like:

     <properties>
                <!--Sonar -->
                <sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
                <sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>
            <sonar.jacoco.reportPath>${project.basedir}/../target/jacoco.exec</sonar.jacoco.reportPath>
                <sonar.language>java</sonar.language>
    
            </properties>
    
            <build>
                <pluginManagement>
                    <plugins>
                        <plugin>
                            <groupId>org.apache.maven.plugins</groupId>
                            <artifactId>maven-compiler-plugin</artifactId>
                            <configuration>
                                <source>1.5</source>
                                <target>1.5</target>
                            </configuration>
                        </plugin>
    
                        <plugin>
                            <groupId>org.sonarsource.scanner.maven</groupId>
                            <artifactId>sonar-maven-plugin</artifactId>
                            <version>3.4.0.905</version>
                        </plugin>
    
                        <plugin>
                            <groupId>org.jacoco</groupId>
                            <artifactId>jacoco-maven-plugin</artifactId>
                            <version>0.7.9</version>
                            <configuration>
                                <destFile>${sonar.jacoco.reportPath}</destFile>
                                <append>true</append>
                            </configuration>
                            <executions>
                                <execution>
                                    <id>agent</id>
                                    <goals>
                                        <goal>prepare-agent</goal>
                                    </goals>
                                </execution>
                            </executions>
                        </plugin>
    
                    </plugins>
                </pluginManagement>
            </build>
    

    I've tried few other options like jacoco-aggregate & even creating a sub-module by including that in parent pom but nothing really worked & this is simple. I see in logs <sonar.jacoco.reportPath> is deprecated,but still works as is and seems like auto replaced on execution or can be manually updated to <sonar.jacoco.reportPaths> or latest. Once after doing setup in cmd start with mvn clean install then mvn org.jacoco:jacoco-maven-plugin:prepare-agent install (Check on project's target folder whether jacoco.exec is created) & then do mvn sonar:sonar , this is what I've tried please let me know if some other best possible solution available.Hope this helps!! If not please post your question..

    MySQL: Cloning a MySQL database on the same MySql instance

    As the manual says in Copying Databases you can pipe the dump directly into the mysql client:

    mysqldump db_name | mysql new_db_name
    

    If you're using MyISAM you could copy the files, but I wouldn't recommend it. It's a bit dodgy.

    Integrated from various good other answers

    Both mysqldump and mysql commands accept options for setting connection details (and much more), like:

    mysqldump -u <user name> --password=<pwd> <original db> | mysql -u <user name> -p <new db>
    

    Also, if the new database is not existing yet, you have to create it beforehand (e.g. with echo "create database new_db_name" | mysql -u <dbuser> -p).

    Jquery Ajax Loading image

    Description

    You should do this using jQuery.ajaxStart and jQuery.ajaxStop.

    1. Create a div with your image
    2. Make it visible in jQuery.ajaxStart
    3. Hide it in jQuery.ajaxStop

    Sample

    <div id="loading" style="display:none">Your Image</div>
    
    <script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
    <script>
        $(function () {
            var loading = $("#loading");
            $(document).ajaxStart(function () {
                loading.show();
            });
    
            $(document).ajaxStop(function () {
                loading.hide();
            });
    
            $("#startAjaxRequest").click(function () {
                $.ajax({
                    url: "http://www.google.com",
                    // ... 
                });
            });
        });
    </script>
    
    <button id="startAjaxRequest">Start</button>
    

    More Information

    iloc giving 'IndexError: single positional indexer is out-of-bounds'

    This error is caused by:

    Y = Dataset.iloc[:,18].values
    

    Indexing is out of bounds here most probably because there are less than 19 columns in your Dataset, so column 18 does not exist. The following code you provided doesn't use Y at all, so you can just comment out this line for now.

    How can you create pop up messages in a batch script?

    Your best bet is to use NET SEND as documented on Rob van der Woude's site.

    Otherwise, you'll need to use an external scripting program. Batch files are really intended to send messages via ECHO.

    TypeError: got multiple values for argument

    My issue was similar to Q---ten's, but in my case it was that I had forgotten to provide the self argument to a class function:

    class A:
        def fn(a, b, c=True):
            pass
    

    Should become

    class A:
        def fn(self, a, b, c=True):
            pass
    

    This faulty implementation is hard to see when calling the class method as:

    a_obj = A()
    a.fn(a_val, b_val, c=False)
    

    Which will yield a TypeError: got multiple values for argument. Hopefully, the rest of the answers here are clear enough for anyone to be able to quickly understand and fix the error. If not, hope this answer helps you!

    Convert a List<T> into an ObservableCollection<T>

    ObervableCollection have constructor in which you can pass your list. Quoting MSDN:

     public ObservableCollection(
          List<T> list
     )
    

    Execute another jar in a Java program

    If you are java 1.6 then the following can also be done:

    import javax.tools.JavaCompiler; 
    import javax.tools.ToolProvider; 
    
    public class CompilerExample {
    
        public static void main(String[] args) {
            String fileToCompile = "/Users/rupas/VolatileExample.java";
    
            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    
            int compilationResult = compiler.run(null, null, null, fileToCompile);
    
            if (compilationResult == 0) {
                System.out.println("Compilation is successful");
            } else {
                System.out.println("Compilation Failed");
            }
        }
    }
    

    Jquery $(this) Child Selector

    http://jqapi.com/ Traversing--> Tree Traversal --> Children

    No newline at end of file

    The only reason is that Unix historically had a convention of all human-readable text files ending in a newline. At the time, this avoided extra processing when displaying or joining text files, and avoided treating text files differently to files containing other kinds of data (eg raw binary data which isn't human-readable).

    Because of this convention, many tools from that era expect the ending newline, including text editors, diffing tools, and other text processing tools. Mac OS X was built on BSD Unix, and Linux was developed to be Unix-compatible, so both operating systems have inherited the same convention, behaviour and tools.

    Windows wasn't developed to be Unix-compatible, so it doesn't have the same convention, and most Windows software will deal just fine with no trailing newline.

    But, since Git was developed for Linux first, and a lot of open-source software is built on Unix-compatible systems like Linux, Mac OS X, FreeBSD, etc, most open-source communities and their tools (including programming languages) continue to follow these conventions.

    There are technical reasons which made sense in 1971, but in this era it's mostly convention and maintaining compatibility with existing tools.

    Pass props to parent component in React.js

    Update (9/1/15): The OP has made this question a bit of a moving target. It’s been updated again. So, I feel responsible to update my reply.

    First, an answer to your provided example:

    Yes, this is possible.

    You can solve this by updating Child’s onClick to be this.props.onClick.bind(null, this):

    var Child = React.createClass({
      render: function () {
        return <a onClick={this.props.onClick.bind(null, this)}>Click me</a>;
      }
    });
    

    The event handler in your Parent can then access the component and event like so:

      onClick: function (component, event) {
        // console.log(component, event);
      },
    

    JSBin snapshot


    But the question itself is misleading

    Parent already knows Child’s props.

    This isn’t clear in the provided example because no props are actually being provided. This sample code might better support the question being asked:

    var Child = React.createClass({
      render: function () {
        return <a onClick={this.props.onClick}> {this.props.text} </a>;
      }
    });
    
    var Parent = React.createClass({
      getInitialState: function () {
        return { text: "Click here" };
      },
      onClick: function (event) {
        // event.component.props ?why is this not available? 
      },
      render: function() {
        return <Child onClick={this.onClick} text={this.state.text} />;
      }
    });
    

    It becomes much clearer in this example that you already know what the props of Child are.

    JSBin snapshot


    If it’s truly about using a Child’s props…

    If it’s truly about using a Child’s props, you can avoid any hookup with Child altogether.

    JSX has a spread attributes API I often use on components like Child. It takes all the props and applies them to a component. Child would look like this:

    var Child = React.createClass({
      render: function () {
        return <a {...this.props}> {this.props.text} </a>;
      }
    });
    

    Allowing you to use the values directly in the Parent:

    var Parent = React.createClass({
      getInitialState: function () {
        return { text: "Click here" };
      },
      onClick: function (text) {
        alert(text);
      },
      render: function() {
        return <Child onClick={this.onClick.bind(null, this.state.text)} text={this.state.text} />;
      }
    });
    

    JSBin snapshot


    And there's no additional configuration required as you hookup additional Child components

    var Parent = React.createClass({
      getInitialState: function () {
        return {
          text: "Click here",
          text2: "No, Click here",
        };
      },
      onClick: function (text) {
        alert(text);
      },
      render: function() {
        return <div>
          <Child onClick={this.onClick.bind(null, this.state.text)} text={this.state.text} />
          <Child onClick={this.onClick.bind(null, this.state.text2)} text={this.state.text2} />
        </div>;
      }
    });
    

    JSBin snapshot

    But I suspect that’s not your actual use case. So let’s dig further…


    A robust practical example

    The generic nature of the provided example is a hard to talk about. I’ve created a component that demonstrations a practical use for the question above, implemented in a very Reacty way:

    DTServiceCalculator working example
    DTServiceCalculator repo

    This component is a simple service calculator. You provide it with a list of services (with names and prices) and it will calculate a total the selected prices.

    Children are blissfully ignorant

    ServiceItem is the child-component in this example. It doesn’t have many opinions about the outside world. It requires a few props, one of which is a function to be called when clicked.

    <div onClick={this.props.handleClick.bind(this.props.index)} />

    It does nothing but to call the provided handleClick callback with the provided index[source].

    Parents are Children

    DTServicesCalculator is the parent-component is this example. It’s also a child. Let’s look.

    DTServiceCalculator creates a list of child-component (ServiceItems) and provides them with props [source]. It’s the parent-component of ServiceItem but it`s the child-component of the component passing it the list. It doesn't own the data. So it again delegates handling of the component to its parent-component source

    <ServiceItem chosen={chosen} index={i} key={id} price={price} name={name} onSelect={this.props.handleServiceItem} />

    handleServiceItem captures the index, passed from the child, and provides it to its parent [source]

    handleServiceClick (index) {
      this.props.onSelect(index);
    }
    

    Owners know everything

    The concept of “Ownership” is an important one in React. I recommend reading more about it here.

    In the example I’ve shown, I keep delegating handling of an event up the component tree until we get to the component that owns the state.

    When we finally get there, we handle the state selection/deselection like so [source]:

    handleSelect (index) {
      let services = […this.state.services];
      services[index].chosen = (services[index].chosen) ? false : true;
      this.setState({ services: services });
    }
    


    Conclusion

    Try keeping your outer-most components as opaque as possible. Strive to make sure that they have very few preferences about how a parent-component might choose to implement them.

    Keep aware of who owns the data you are manipulating. In most cases, you will need to delegate event handling up the tree to the component that owns that state.

    Aside: The Flux pattern is a good way to reduce this type of necessary hookup in apps.

    JPA Query selecting only specific columns without using Criteria Query?

    Excellent answer! I do have a small addition. Regarding this solution:

    TypedQuery<CustomObject> typedQuery = em.createQuery(query , String query = "SELECT NEW CustomObject(i.firstProperty, i.secondProperty) FROM ObjectName i WHERE i.id=100";
    TypedQuery<CustomObject> typedQuery = em.createQuery(query , CustomObject.class);
    List<CustomObject> results = typedQuery.getResultList();CustomObject.class);
    

    To prevent a class not found error simply insert the full package name. Assuming org.company.directory is the package name of CustomObject:

    String query = "SELECT NEW org.company.directory.CustomObject(i.firstProperty, i.secondProperty) FROM ObjectName i WHERE i.id=10";
    TypedQuery<CustomObject> typedQuery = em.createQuery(query , CustomObject.class);
    List<CustomObject> results = typedQuery.getResultList();
    

    What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

    This happened to me when I registered a new domain name, e.g., "new" for example.com (new.example.com). The name could not be resolved temporarily in my location for a couple of hours, while it could be resolved abroad. So I used a proxy to test the website where I saw net::ERR_HTTP2_PROTOCOL_ERROR in chrome console for some AJAX posts. Hours later, when the name could be resloved locally, those error just dissappeared.

    I think the reason for that error is those AJAX requests were not redirected by my proxy, it just visit a website which had not been resolved by my local DNS resolver.

    Restrict varchar() column to specific values?

    You want a check constraint.

    CHECK constraints determine the valid values from a logical expression that is not based on data in another column. For example, the range of values for a salary column can be limited by creating a CHECK constraint that allows for only data that ranges from $15,000 through $100,000. This prevents salaries from being entered beyond the regular salary range.

    You want something like:

    ALTER TABLE dbo.Table ADD CONSTRAINT CK_Table_Frequency
        CHECK (Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly'))
    

    You can also implement check constraints with scalar functions, as described in the link above, which is how I prefer to do it.

    Rails and PostgreSQL: Role postgres does not exist

    I ended up here after attempting to follow Ryan Bate's tutorial on deploying to AWS EC2 with rubber. Here is what happened for me: We created a new app using "

    rails new blog -d postgresql

    Obviosuly this creates a new app with pg as the database, but the database was not made yet. With sqlite, you just run rake db:migrate, however with pg you need to create the pg database first. Ryan did not do this step. The command is rake db:create:all, then we can run rake db:migrate

    The second part is changing the database.yml file. The default for the username when the file is generated is 'appname'. However, chances are your role for postgresql admin is something different (at least it was for me). I changed it to my name (see above advice about creating a role name) and I was good to go.

    Hope this helps.

    How to read a Parquet file into Pandas DataFrame?

    Aside from pandas, Apache pyarrow also provides way to transform parquet to dataframe

    The code is simple, just type:

    import pyarrow.parquet as pq
    
    df = pq.read_table(source=your_file_path).to_pandas()
    

    For more information, see the document from Apache pyarrow Reading and Writing Single Files

    Share link on Google+

    Yes, you can.

    https://plus.google.com/share?url=YOUR_URL_HERE

    Edit: It works only with eff.org.

    Edit: As of March 2012 it works on all sites.

    Documentation for this sharing method is available on the Google Developers site.

    Best algorithm for detecting cycles in a directed graph

    If you can't add a "visited" property to the nodes, use a set (or map) and just add all visited nodes to the set unless they are already in the set. Use a unique key or the address of the objects as the "key".

    This also gives you the information about the "root" node of the cyclic dependency which will come in handy when a user has to fix the problem.

    Another solution is to try to find the next dependency to execute. For this, you must have some stack where you can remember where you are now and what you need to do next. Check if a dependency is already on this stack before you execute it. If it is, you've found a cycle.

    While this might seem to have a complexity of O(N*M) you must remember that the stack has a very limited depth (so N is small) and that M becomes smaller with each dependency that you can check off as "executed" plus you can stop the search when you found a leaf (so you never have to check every node -> M will be small, too).

    In MetaMake, I created the graph as a list of lists and then deleted every node as I executed them which naturally cut down the search volume. I never actually had to run an independent check, it all happened automatically during normal execution.

    If you need a "test only" mode, just add a "dry-run" flag which disables the execution of the actual jobs.

    How to use a class from one C# project with another C# project

    1. In the 'Solution Explorer' tree, expand the P2 project and then right-click the project and select 'Add Reference' from the menu.
    2. On the 'Add Reference' dialog, select the 'Projects' tab and select your P1 project.
    3. If you are using namespaces then you will need to import the namespaces for your P1 types by adding 'using' statements to your files in P2.

    Note that the types in P1 that you wish to access directly must have a sufficient access level: typically this means they must be made public.

    Excel Create Collapsible Indented Row Hierarchies

    A much easier way is to go to Data and select Group or Subtotal. Instant collapsible rows without messing with pivot tables or VBA.

    spring PropertyPlaceholderConfigurer and context:property-placeholder

    First, you don't need to define both of those locations. Just use classpath:config/properties/database.properties. In a WAR, WEB-INF/classes is a classpath entry, so it will work just fine.

    After that, I think what you mean is you want to use Spring's schema-based configuration to create a configurer. That would go like this:

    <context:property-placeholder location="classpath:config/properties/database.properties"/>
    

    Note that you don't need to "ignoreResourceNotFound" anymore. If you need to define the properties separately using util:properties:

    <context:property-placeholder properties-ref="jdbcProperties" ignore-resource-not-found="true"/>
    

    There's usually not any reason to define them separately, though.

    Reset the database (purge all), then seed a database

    If you don't feel like dropping and recreating the whole shebang just to reload your data, you could use MyModel.destroy_all (or delete_all) in the seed.db file to clean out a table before your MyModel.create!(...) statements load the data. Then, you can redo the db:seed operation over and over. (Obviously, this only affects the tables you've loaded data into, not the rest of them.)

    There's a "dirty hack" at https://stackoverflow.com/a/14957893/4553442 to add a "de-seeding" operation similar to migrating up and down...

    How do you make websites with Java?

    Look into creating Applets if you want to make a website with Java. You most likely wont need to use anything but regular Java, unless you want something more specialized.

    Regular expression to match numbers with or without commas and decimals in text

    \d+(,\d+)*(\.\d+)?
    

    This assumes that there is always at least one digit before or after any comma or decimal and also assumes that there is at most one decimal and that all the commas precede the decimal.

    Selecting multiple classes with jQuery

    This should work:

    $('.myClass, .myOtherClass').removeClass('theclass');

    You must add the multiple selectors all in the first argument to $(), otherwise you are giving jQuery a context in which to search, which is not what you want.

    It's the same as you would do in CSS.

    Add image in pdf using jspdf

    You defined Base64? If you not defined, occurs this error:

    ReferenceError: Base64 is not defined

    div inside table

    While you can, as others have noted here, put a DIV inside a TD (not as a direct child of TABLE), I strongly advise against using a DIV as a child of a TD. Unless, of course, you're a fan of headaches.

    There is little to be gained and a whole lot to be lost, as there are many cross-browser discrepancies regarding how widths, margins, borders, etc., are handled when you combine the two. I can't tell you how many times I've had to clean up that kind of markup for clients because they were having trouble getting their HTML to display correctly in this or that browser.

    Then again, if you're not fussy about how things look, disregard this advice.

    How to remove a Gitlab project?

    To remove a project, you have to be the owner of this project, or the administrator of gitlab. Otherwise you can only see "rename project" but no "remove project".

    NOTE THAT: the creator project is NOT always the owner of the project. If the project is in a project-group, and the project-group is created by another one, then the owner is the creator of the project-group by default.

    You can find the owner's name of the project in the page Settings -> Members.

    How can Bash execute a command in a different directory context?

    (cd /path/to/your/special/place;/bin/your-special-command ARGS)
    

    How does a ArrayList's contains() method evaluate objects?

    I think that right implementations should be

    public class Thing
    {
        public int value;  
    
        public Thing (int x)
        {
            this.value = x;
        }
    
        @Override
        public boolean equals(Object object)
        {
            boolean sameSame = false;
    
            if (object != null && object instanceof Thing)
            {
                sameSame = this.value == ((Thing) object).value;
            }
    
            return sameSame;
        }
    }
    

    How are booleans formatted in Strings in Python?

    You may also use the Formatter class of string

    print "{0} {1}".format(True, False);
    print "{0:} {1:}".format(True, False);
    print "{0:d} {1:d}".format(True, False);
    print "{0:f} {1:f}".format(True, False);
    print "{0:e} {1:e}".format(True, False);
    

    These are the results

    True False
    True False
    1 0
    1.000000 0.000000
    1.000000e+00 0.000000e+00
    

    Some of the %-format type specifiers (%r, %i) are not available. For details see the Format Specification Mini-Language

    How to call any method asynchronously in c#

    public partial class MainForm : Form
    {
        Image img;
        private void button1_Click(object sender, EventArgs e)
        {
            LoadImageAsynchronously("http://media1.santabanta.com/full5/Indian%20%20Celebrities(F)/Jacqueline%20Fernandez/jacqueline-fernandez-18a.jpg");
        }
    
        private void LoadImageAsynchronously(string url)
        {
            /*
            This is a classic example of how make a synchronous code snippet work asynchronously.
            A class implements a method synchronously like the WebClient's DownloadData(…) function for example
                (1) First wrap the method call in an Anonymous delegate.
                (2) Use BeginInvoke(…) and send the wrapped anonymous delegate object as the last parameter along with a callback function name as the first parameter.
                (3) In the callback method retrieve the ar's AsyncState as a Type (typecast) of the anonymous delegate. Along with this object comes EndInvoke(…) as free Gift
                (4) Use EndInvoke(…) to retrieve the synchronous call’s return value in our case it will be the WebClient's DownloadData(…)’s return value.
            */
            try
            {
                Func<Image> load_image_Async = delegate()
                {
                    WebClient wc = new WebClient();
                    Bitmap bmpLocal = new Bitmap(new MemoryStream(wc.DownloadData(url)));
                    wc.Dispose();
                    return bmpLocal;
                };
    
                Action<IAsyncResult> load_Image_call_back = delegate(IAsyncResult ar)
                {
                    Func<Image> ss = (Func<Image>)ar.AsyncState;
                    Bitmap myBmp = (Bitmap)ss.EndInvoke(ar);
    
                    if (img != null) img.Dispose();
                    if (myBmp != null)
                        img = myBmp;
                    Invalidate();
                    //timer.Enabled = true;
                };
                //load_image_Async.BeginInvoke(callback_load_Image, load_image_Async);             
                load_image_Async.BeginInvoke(new AsyncCallback(load_Image_call_back), load_image_Async);             
            }
            catch (Exception ex)
            {
    
            }
        }
        protected override void OnPaint(PaintEventArgs e)
        {
            if (img != null)
            {
                Graphics grfx = e.Graphics;
                grfx.DrawImage(img,new Point(0,0));
            }
        }
    

    Insert NULL value into INT column

    If column is not NOT NULL (nullable).

    You just put NULL instead of value in INSERT statement.

    Which UUID version to use?

    Postgres documentation describes the differences between UUIDs. A couple of them:

    V3:

    uuid_generate_v3(namespace uuid, name text) - This function generates a version 3 UUID in the given namespace using the specified input name.

    V4:

    uuid_generate_v4 - This function generates a version 4 UUID, which is derived entirely from random numbers.

    adding 30 minutes to datetime php/mysql

    MySQL has a function called ADDTIME for adding two times together - so you can do the whole thing in MySQL (provided you're using >= MySQL 4.1.3).

    Something like (untested):

    SELECT * FROM my_table WHERE ADDTIME(endTime + '0:30:00') < CONVERT_TZ(NOW(), @@global.time_zone, 'GMT')
    

    What are the basic rules and idioms for operator overloading?

    The Decision between Member and Non-member

    The binary operators = (assignment), [] (array subscription), -> (member access), as well as the n-ary () (function call) operator, must always be implemented as member functions, because the syntax of the language requires them to.

    Other operators can be implemented either as members or as non-members. Some of them, however, usually have to be implemented as non-member functions, because their left operand cannot be modified by you. The most prominent of these are the input and output operators << and >>, whose left operands are stream classes from the standard library which you cannot change.

    For all operators where you have to choose to either implement them as a member function or a non-member function, use the following rules of thumb to decide:

    1. If it is a unary operator, implement it as a member function.
    2. If a binary operator treats both operands equally (it leaves them unchanged), implement this operator as a non-member function.
    3. If a binary operator does not treat both of its operands equally (usually it will change its left operand), it might be useful to make it a member function of its left operand’s type, if it has to access the operand's private parts.

    Of course, as with all rules of thumb, there are exceptions. If you have a type

    enum Month {Jan, Feb, ..., Nov, Dec}
    

    and you want to overload the increment and decrement operators for it, you cannot do this as a member functions, since in C++, enum types cannot have member functions. So you have to overload it as a free function. And operator<() for a class template nested within a class template is much easier to write and read when done as a member function inline in the class definition. But these are indeed rare exceptions.

    (However, if you make an exception, do not forget the issue of const-ness for the operand that, for member functions, becomes the implicit this argument. If the operator as a non-member function would take its left-most argument as a const reference, the same operator as a member function needs to have a const at the end to make *this a const reference.)


    Continue to Common operators to overload.