Programs & Examples On #Code metrics

Software metrics are quantitative data pertaining to source code, e.g. number of lines of code (LOC) for a file.

How to use IntelliJ IDEA to find all unused code?

In latest IntelliJ versions, you should run it from Analyze->Run Inspection By Name:

enter image description here

Than, pick Unused declaration:

enter image description here

And finally, uncheck the Include test sources:

enter image description here

How do you count the lines of code in a Visual Studio solution?

I used Ctrl+Shift+F. Next, put a \n in the search box and enable regular expressions box. Then in the find results, in the end of the screen are the number of files searched and lines of code found.

You can use [^\n\s]\r\n to skip blank and space-only lines (credits to Zach in the comments).

What is a reasonable code coverage % for unit tests (and why)?

85% would be a good starting place for checkin criteria.

I'd probably chose a variety of higher bars for shipping criteria - depending on the criticality of the subsystems/components being tested.

Convert DataSet to List

Here's extension method to convert DataTable to object list:

    public static class Extensions
    {
        public static List<T> ToList<T>(this DataTable table) where T : new()
        {
            IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
            List<T> result = new List<T>();

            foreach (var row in table.Rows)
            {
                var item = CreateItemFromRow<T>((DataRow)row, properties);
                result.Add(item);
            }

            return result;
        }

        private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
        {
            T item = new T();
            foreach (var property in properties)
            {
                if (property.PropertyType == typeof(System.DayOfWeek))
                {
                    DayOfWeek day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), row[property.Name].ToString());
                    property.SetValue(item,day,null);
                }
                else
                {
                    if(row[property.Name] == DBNull.Value)
                        property.SetValue(item, null, null);
                    else 
                        property.SetValue(item, row[property.Name], null); 
                }
            }
            return item;
        }
    }

usage:

List<Employee> lst = ds.Tables[0].ToList<Employee>();

@itay.b CODE EXPLAINED: We first read all the property names from the class T using reflection
then we iterate through all the rows in datatable and create new object of T,
then we set the properties of the newly created object using reflection.

The property values are picked from the row's matching column cell.

PS: class property name and table column names must be same

Spring mvc @PathVariable

suppose you want to write a url to fetch some order, you can say

www.mydomain.com/order/123

where 123 is orderId.

So now the url you will use in spring mvc controller would look like

/order/{orderId}

Now order id can be declared a path variable

@RequestMapping(value = " /order/{orderId}", method=RequestMethod.GET)
public String getOrder(@PathVariable String orderId){
//fetch order
}

if you use url www.mydomain.com/order/123, then orderId variable will be populated by value 123 by spring

Also note that PathVariable differs from requestParam as pathVariable is part of URL. The same url using request param would look like www.mydomain.com/order?orderId=123

API DOC
Spring Official Reference

How to copy in bash all directory and files recursive?

code for a simple copy.

cp -r ./SourceFolder ./DestFolder

code for a copy with success result

cp -rv ./SourceFolder ./DestFolder

code for Forcefully if source contains any readonly file it will also copy

cp -rf ./SourceFolder ./DestFolder

for details help

cp --help

Apache: The requested URL / was not found on this server. Apache

In httpd.conf file you need to remove #

#LoadModule rewrite_module modules/mod_rewrite.so

after removing # line will look like this:

LoadModule rewrite_module modules/mod_rewrite.so

And Apache restart

What is a good game engine that uses Lua?

World of Warcraft's engine seems all right, and it uses Lua. :)

Convert a python 'type' object to a string

print type(someObject).__name__

If that doesn't suit you, use this:

print some_instance.__class__.__name__

Example:

class A:
    pass
print type(A())
# prints <type 'instance'>
print A().__class__.__name__
# prints A

Also, it seems there are differences with type() when using new-style classes vs old-style (that is, inheritance from object). For a new-style class, type(someObject).__name__ returns the name, and for old-style classes it returns instance.

Django - limiting query results

Actually I think the LIMIT 10 would be issued to the database so slicing would not occur in Python but in the database.

See limiting-querysets for more information.

How / can I display a console window in Intellij IDEA?

  1. Press the left corner button
  2. Choose debug
  3. Click console

enter image description here

enter image description here

Angular 2 optional route parameter

The suggested answers here, including the accepted answer from rerezz which suggest adding multiple route entries work fine.

However the component will be recreated when changing between the route entries, i.e. between the route entry with the parameter and the entry without the parameter.

If you want to avoid this, you can create your own route matcher which will match both routes:

export function userPageMatcher(segments: UrlSegment[]): UrlMatchResult {
    if (segments.length > 0 && segments[0].path === 'user') {
        if (segments.length === 1) {
            return {
                consumed: segments,
                posParams: {},
            };
        }
        if (segments.length === 2) {
            return {
                consumed: segments,
                posParams: { id: segments[1] },
            };
        }
        return <UrlMatchResult>(null as any);
    }
    return <UrlMatchResult>(null as any);
 }

Then use the matcher in your route config:

const routes: Routes = [
    {
        matcher: userPageMatcher,
        component: User,
    }
];

ZIP file content type for HTTP request

.zip    application/zip, application/octet-stream

Stop setInterval call in JavaScript

Use setTimeOut to stop the interval after some time.

var interVal = setInterval(function(){console.log("Running")  }, 1000);
 setTimeout(function (argument) {
    clearInterval(interVal);
 },10000);

How to return a html page from a restful controller in spring boot?

I did three things:

  • Put the HTML page in {project.basedir}/resources/static/myPage.html;
  • Switch @RestController to @Controller;
  • This is my controller:
@RequestMapping(method = RequestMethod.GET, value = "/")
public String aName() {
    return "myPage.html";
}

No particular dependency is needed.

How to extract one column of a csv file

You could use GNU Awk, see this article of the user guide. As an improvement to the solution presented in the article (in June 2015), the following gawk command allows double quotes inside double quoted fields; a double quote is marked by two consecutive double quotes ("") there. Furthermore, this allows empty fields, but even this can not handle multiline fields. The following example prints the 3rd column (via c=3) of textfile.csv:

#!/bin/bash
gawk -- '
BEGIN{
    FPAT="([^,\"]*)|(\"((\"\")*[^\"]*)*\")"
}
{
    if (substr($c, 1, 1) == "\"") {
        $c = substr($c, 2, length($c) - 2) # Get the text within the two quotes
        gsub("\"\"", "\"", $c)  # Normalize double quotes
    }
    print $c
}
' c=3 < <(dos2unix <textfile.csv)

Note the use of dos2unix to convert possible DOS style line breaks (CRLF i.e. "\r\n") and UTF-16 encoding (with byte order mark) to "\n" and UTF-8 (without byte order mark), respectively. Standard CSV files use CRLF as line break, see Wikipedia.

If the input may contain multiline fields, you can use the following script. Note the use of special string for separating records in output (since the default separator newline could occur within a record). Again, the following example prints the 3rd column (via c=3) of textfile.csv:

#!/bin/bash
gawk -- '
BEGIN{
    RS="\0" # Read the whole input file as one record;
    # assume there is no null character in input.
    FS="" # Suppose this setting eases internal splitting work.
    ORS="\n####\n" # Use a special output separator to show borders of a record.
}
{
    nof=patsplit($0, a, /([^,"\n]*)|("(("")*[^"]*)*")/, seps)
    field=0;
    for (i=1; i<=nof; i++){
        field++
        if (field==c) {
            if (substr(a[i], 1, 1) == "\"") {
                a[i] = substr(a[i], 2, length(a[i]) - 2) # Get the text within 
                # the two quotes.
                gsub(/""/, "\"", a[i])  # Normalize double quotes.
            }
            print a[i]
        }
        if (seps[i]!=",") field=0
    }
}
' c=3 < <(dos2unix <textfile.csv)

There is another approach to the problem. csvquote can output contents of a CSV file modified so that special characters within field are transformed so that usual Unix text processing tools can be used to select certain column. For example the following code outputs the third column:

csvquote textfile.csv | cut -d ',' -f 3 | csvquote -u

csvquote can be used to process arbitrary large files.

How to check list A contains any value from list B?

I write a faster method for it can make the small one to set. But I test it in some data that some time it's faster that Intersect but some time Intersect fast that my code.

    public static bool Contain<T>(List<T> a, List<T> b)
    {
        if (a.Count <= 10 && b.Count <= 10)
        {
            return a.Any(b.Contains);
        }

        if (a.Count > b.Count)
        {
            return Contain((IEnumerable<T>) b, (IEnumerable<T>) a);
        }
        return Contain((IEnumerable<T>) a, (IEnumerable<T>) b);
    }

    public static bool Contain<T>(IEnumerable<T> a, IEnumerable<T> b)
    {
        HashSet<T> j = new HashSet<T>(a);
        return b.Any(j.Contains);
    }

The Intersect calls Set that have not check the second size and this is the Intersect's code.

        Set<TSource> set = new Set<TSource>(comparer);
        foreach (TSource element in second) set.Add(element);
        foreach (TSource element in first)
            if (set.Remove(element)) yield return element;

The difference in two methods is my method use HashSet and check the count and Intersect use set that is faster than HashSet. We dont warry its performance.

The test :

   static void Main(string[] args)
    {
        var a = Enumerable.Range(0, 100000);
        var b = Enumerable.Range(10000000, 1000);
        var t = new Stopwatch();
        t.Start();
        Repeat(()=> { Contain(a, b); });
        t.Stop();
        Console.WriteLine(t.ElapsedMilliseconds);//490ms

        var a1 = Enumerable.Range(0, 100000).ToList();
        var a2 = b.ToList();
        t.Restart();
        Repeat(()=> { Contain(a1, a2); });
        t.Stop();

        Console.WriteLine(t.ElapsedMilliseconds);//203ms

        t.Restart();
        Repeat(()=>{ a.Intersect(b).Any(); });
        t.Stop();
        Console.WriteLine(t.ElapsedMilliseconds);//190ms

        t.Restart();
        Repeat(()=>{ b.Intersect(a).Any(); });
        t.Stop();
        Console.WriteLine(t.ElapsedMilliseconds);//497ms

        t.Restart();
        a.Any(b.Contains);
        t.Stop();
        Console.WriteLine(t.ElapsedMilliseconds);//600ms

    }

    private static void Repeat(Action a)
    {
        for (int i = 0; i < 100; i++)
        {
            a();
        }
    }

Slide div left/right using jQuery

You can easy get that effect without using jQueryUI, for example:

$(document).ready(function(){
    $('#slide').click(function(){
    var hidden = $('.hidden');
    if (hidden.hasClass('visible')){
        hidden.animate({"left":"-1000px"}, "slow").removeClass('visible');
    } else {
        hidden.animate({"left":"0px"}, "slow").addClass('visible');
    }
    });
});

Try this working Fiddle:

http://jsfiddle.net/ZQTFq/

Uncaught TypeError: undefined is not a function on loading jquery-min.js

I just had the same message with the following code (in IcedCoffeeScript):

f = (err,cb) ->
  cb null, true

await f defer err, res
console.log err if err  

This seemed to me like regular ICS code. I unfolded the await-defer construct to regular CoffeeScript:

f (err,res) ->
  console.log err if err

What really happend was that I tried to pass 1 callback function( with 2 parameters ) to function f expecting two parameters, effectively not setting cb inside f, which the compiler correctly reported as undefined is not a function.

The mistake happened because I blindly pasted callback-style boilerplate code. f doesn't need an err parameter passed into it, thus should simply be:

f = (cb) ->
  cb null, true
f (err,res) ->
  console.log err if err

In the general case, I'd recommend to double-check function signatures and invocations for matching arities. The call-stack in the error message should be able to provide helpful hints.

In your special case, I recommend looking for function definitions appearing twice in the merged file, with different signatures, or assignments to global variables holding functions.

How to print the current Stack Trace in .NET without any exception?

An alternative to System.Diagnostics.StackTrace is to use System.Environment.StackTrace which returns a string-representation of the stacktrace.

Another useful option is to use the $CALLER and $CALLSTACK debugging variables in Visual Studio since this can be enabled run-time without rebuilding the application.

Second line in li starts under the bullet after CSS-reset

I second Dipaks' answer, but often just the text-indent is enough as you may/maynot be positioning the ul for better layout control.

ul li{
text-indent: -1em;
}

addClass and removeClass in jQuery - not removing class

I actually just resolved an issue I was having by swapping around the order that I was altering the properties in. For example I was changing the attribute first but I actually had to remove the class and add the new class before modifying the attributes. I'm not sure why it worked but it did. So something to try would be to change from $("XXXX").attr('something').removeClass( "class" ).addClass( "newClass" ) to $("XXXX").removeClass( "class" ).addClass( "newClass" ).attr('something').

Why Is Subtracting These Two Times (in 1927) Giving A Strange Result?

I'm sorry to say, but the time discontinuity has moved a bit in

JDK 6 two years ago, and in JDK 7 just recently in update 25.

Lesson to learn: avoid non-UTC times at all costs, except maybe for display.

How to access parent Iframe from JavaScript

Try this, in your parent frame set up you IFRAMEs like this:

<iframe id="frame1" src="inner.html#frame1"></iframe>
<iframe id="frame2" src="inner.html#frame2"></iframe>
<iframe id="frame3" src="inner.html#frame3"></iframe>

Note that the id of each frame is passed as an anchor in the src.

then in your inner html you can access the id of the frame it is loaded in via location.hash:

<button onclick="alert('I am frame: ' + location.hash.substr(1))">Who Am I?</button>

then you can access parent.document.getElementById() to access the iframe tag from inside the iframe

Difference between chr(13) and chr(10)

Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


Historically, Line Feed would move down a line but not return to column 1:

This  
    is  
        a  
            test.

Similarly Carriage Return would return to column 1 but not move down a line:

This  
is  
a  
test.

Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

What are some uses of template template parameters?

Here is a simple example taken from 'Modern C++ Design - Generic Programming and Design Patterns Applied' by Andrei Alexandrescu:

He uses a classes with template template parameters in order to implement the policy pattern:

// Library code
template <template <class> class CreationPolicy>
class WidgetManager : public CreationPolicy<Widget>
{
   ...
};

He explains: Typically, the host class already knows, or can easily deduce, the template argument of the policy class. In the example above, WidgetManager always manages objects of type Widget, so requiring the user to specify Widget again in the instantiation of CreationPolicy is redundant and potentially dangerous.In this case, library code can use template template parameters for specifying policies.

The effect is that the client code can use 'WidgetManager' in a more elegant way:

typedef WidgetManager<MyCreationPolicy> MyWidgetMgr;

Instead of the more cumbersome, and error prone way that a definition lacking template template arguments would have required:

typedef WidgetManager< MyCreationPolicy<Widget> > MyWidgetMgr;

Exception: Can't bind to 'ngFor' since it isn't a known native property

I forgot to annotate my component with "@Input" (Doh!)

book-list.component.html (Offending code):

<app-book-item
  *ngFor="let book of book$ | async"
  [book]="book">  <-- Can't bind to 'book' since it isn't a known property of 'app-book-item'
</app-book-item>

Corrected version of book-item.component.ts:

import { Component, OnInit, Input } from '@angular/core';

import { Book } from '../model/book';
import { BookService } from '../services/book.service';

@Component({
  selector: 'app-book-item',
  templateUrl: './book-item.component.html',
  styleUrls: ['./book-item.component.css']
})
export class BookItemComponent implements OnInit {

  @Input()
  public book: Book;

  constructor(private bookService: BookService)  { }

  ngOnInit() {}

}

Slack clean all messages (~8K) in a channel

I quickly found out there's someone already made a helper: slack-cleaner for this.

And for me it's just:

slack-cleaner --token=<TOKEN> --message --channel jenkins --user "*" --perform

npm notice created a lockfile as package-lock.json. You should commit this file

Yes it is wise to use a version control system for your project. Anyway, focusing on your installation warning issue you can try to launch npm install command starting from your root project folder instead of outside of it, so the installation steps will only update the existing package-lock.json file instead of creating a new one. Hope this helps.

MVC Return Partial View as JSON

Url.Action("Evil", model)

will generate a get query string but your ajax method is post and it will throw error status of 500(Internal Server Error). – Fereydoon Barikzehy Feb 14 at 9:51

Just Add "JsonRequestBehavior.AllowGet" on your Json object.

remove / reset inherited css from an element

"Resetting" styles for a specific element isn't possible, you'll have to overwrite all styles you don't want/need. If you do this with CSS directly or using JQuery to apply the styles (depends on what's easier for you, but I wouldn't recommend using JavaScript/JQuery for this, as it's completely unnecessary).

If your div is some kind of "widget" that can be included into other sites, you could try to wrap it into an iframe. This will "reset" the styles, because its content is another document, but maybe this affects how your widget works (or maybe breaks it completely) so this might not be possible in your case.

How to use addTarget method in swift 3

In swift 3 use this -

object?.addTarget(objectWhichHasMethod, action: #selector(classWhichHasMethod.yourMethod), for: someUIControlEvents)

For example(from my code) -

self.datePicker?.addTarget(self, action:#selector(InfoTableViewCell.datePickerValueChanged), for: .valueChanged)

Just give a : after method name if you want the sender as parameter.

Docker: unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx

I erroneously created Dockerfile.txt in my working directory leading to the above-mentioned error while build

The fix was to remove the .txt extension from the file.

The file name should be Dockerfile only without any extension.

Test file upload using HTTP PUT method

In my opinion the best tool for such testing is curl. Its --upload-file option uploads a file by PUT, which is exactly what you want (and it can do much more, like modifying HTTP headers, in case you need it):

curl http://myservice --upload-file file.txt

How to stop docker under Linux

In my case, it was neither systemd nor a cron job, but it was snap. So I had to run:

sudo snap stop docker
sudo snap remove docker

... and the last command actually never ended, I don't know why: this snap thing is really a pain. So I also ran:

sudo apt purge snap

:-)

What is the difference between a var and val definition in Scala?

Val means its final, cannot be reassigned

Whereas, Var can be reassigned later.

add elements to object array

You can't. However, you can replace the array with a new one which contains the extra element.

But it is easier and gives better performance to use an List<T> (uses interface IList) for this. List<T> does not resize the array every time you add an item - instead it doubles it when needed.

Try:

class Student
{
    IList<Subject> subjects = new List<Subject>();
}

class Subject
{
    string Name;
    string referenceBook;
}

Now you can say:

someStudent.subjects.Add(new Subject());

Reference — What does this symbol mean in PHP?

Magic constants: Although these are not just symbols but important part of this token family. There are eight magical constants that change depending on where they are used.

__LINE__: The current line number of the file.

__FILE__: The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, __FILE__ always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances.

__DIR__: The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory. (Added in PHP 5.3.0.)

__FUNCTION__: The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.

__CLASS__: The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased. The class name includes the namespace it was declared in (e.g. Foo\Bar). Note that as of PHP 5.4 __CLASS__ works also in traits. When used in a trait method, __CLASS__ is the name of the class the trait is used in.

__TRAIT__: The trait name. (Added in PHP 5.4.0) As of PHP 5.4 this constant returns the trait as it was declared (case-sensitive). The trait name includes the namespace it was declared in (e.g. Foo\Bar).

__METHOD__: The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive).

__NAMESPACE__: The name of the current namespace (case-sensitive). This constant is defined in compile-time (Added in PHP 5.3.0).

Source

How to use bootstrap datepicker

You should include bootstrap-datepicker.js after bootstrap.js and you should bind the datepicker to your control.

$(function(){
   $('.datepicker').datepicker({
      format: 'mm-dd-yyyy'
    });
});

How to call a method daily, at specific time, in C#?

As others have said you can use a console app to run when scheduled. What others haven't said is that you can this app trigger a cross process EventWaitHandle which you are waiting on in your main application.

Console App:

class Program
{
    static void Main(string[] args)
    {
        EventWaitHandle handle = 
            new EventWaitHandle(true, EventResetMode.ManualReset, "GoodMutexName");
        handle.Set();
    }
}

Main App:

private void Form1_Load(object sender, EventArgs e)
{
    // Background thread, will die with application
    ThreadPool.QueueUserWorkItem((dumby) => EmailWait());
}

private void EmailWait()
{
    EventWaitHandle handle = 
        new EventWaitHandle(false, EventResetMode.ManualReset, "GoodMutexName");

    while (true)
    {
        handle.WaitOne();

        SendEmail();

        handle.Reset();
    }
}

How to get current working directory in Java?

One way would be to use the system property System.getProperty("user.dir"); this will give you "The current working directory when the properties were initialized". This is probably what you want. to find out where the java command was issued, in your case in the directory with the files to process, even though the actual .jar file might reside somewhere else on the machine. Having the directory of the actual .jar file isn't that useful in most cases.

The following will print out the current directory from where the command was invoked regardless where the .class or .jar file the .class file is in.

public class Test
{
    public static void main(final String[] args)
    {
        final String dir = System.getProperty("user.dir");
        System.out.println("current dir = " + dir);
    }
}  

if you are in /User/me/ and your .jar file containing the above code is in /opt/some/nested/dir/ the command java -jar /opt/some/nested/dir/test.jar Test will output current dir = /User/me.

You should also as a bonus look at using a good object oriented command line argument parser. I highly recommend JSAP, the Java Simple Argument Parser. This would let you use System.getProperty("user.dir") and alternatively pass in something else to over-ride the behavior. A much more maintainable solution. This would make passing in the directory to process very easy to do, and be able to fall back on user.dir if nothing was passed in.

Multiple files upload in Codeigniter

I change upload method with images[] according to @Denmark.

    private function upload_files($path, $title, $files)
    {
        $config = array(
            'upload_path'   => $path,
            'allowed_types' => 'jpg|gif|png',
            'overwrite'     => 1,                       
        );

        $this->load->library('upload', $config);

        $images = array();

        foreach ($files['name'] as $key => $image) {
            $_FILES['images[]']['name']= $files['name'][$key];
            $_FILES['images[]']['type']= $files['type'][$key];
            $_FILES['images[]']['tmp_name']= $files['tmp_name'][$key];
            $_FILES['images[]']['error']= $files['error'][$key];
            $_FILES['images[]']['size']= $files['size'][$key];

            $fileName = $title .'_'. $image;

            $images[] = $fileName;

            $config['file_name'] = $fileName;

            $this->upload->initialize($config);

            if ($this->upload->do_upload('images[]')) {
                $this->upload->data();
            } else {
                return false;
            }
        }

        return $images;
    }

What is the difference between a static and const variable?

A constant value cannot change. A static variable exists to a function, or class, rather than an instance or object.

These two concepts are not mutually exclusive, and can be used together.

Grunt watch error - Waiting...Fatal error: watch ENOSPC

I ran into this error after my client PC crashed, the jest --watch command I was running on the server persisted, and I tried to run jest --watch again.

The addition to /etc/sysctl.conf described in the answers above worked around this issue, but it was also important to find my old process via ps aux | grep node and kill it.

JSON Structure for List of Objects

The second is almost correct:

{
    "foos" : [{
        "prop1":"value1",
        "prop2":"value2"
    }, {
        "prop1":"value3", 
        "prop2":"value4"
    }]
}

What to do with commit made in a detached head

This is what I did:

Basically, think of the detached HEAD as a new branch, without name. You can commit into this branch just like any other branch. Once you are done committing, you want to push it to the remote.

So the first thing you need to do is give this detached HEAD a name. You can easily do it like, while being on this detached HEAD:

git checkout -b some-new-branch

Now you can push it to remote like any other branch.

In my case, I also wanted to fast-forward this branch to master along with the commits I made in the detached HEAD (now some-new-branch). All I did was

git checkout master

git pull # To make sure my local copy of master is up to date

git checkout some-new-branch

git merge master // This added current state of master to my changes

Of course, I merged it later to master.

That's about it.

How to determine if OpenSSL and mod_ssl are installed on Apache2

If you have PHP installed on your server, you can chek it in runtime using "extension_loaded" funciontion. Just like this:

<?php
if (!extension_loaded('openssl')) {
    // no openssl extension loaded.
}
?>

Convert List(of object) to List(of string)

You mean something like this?

List<object> objects = new List<object>();
var strings = (from o in objects
              select o.ToString()).ToList();

Should MySQL have its timezone set to UTC?

This is a working example:

jdbc:mysql://localhost:3306/database?useUnicode=yes&characterEncoding=UTF-8&serverTimezone=Europe/Moscow

Java - escape string to prevent SQL injection

The only way to prevent SQL injection is with parameterized SQL. It simply isn't possible to build a filter that's smarter than the people who hack SQL for a living.

So use parameters for all input, updates, and where clauses. Dynamic SQL is simply an open door for hackers, and that includes dynamic SQL in stored procedures. Parameterize, parameterize, parameterize.

textarea character limit

This is entirely untested but it should do what you need.

Update : here's a jsfiddle to look at. Seems to be working. link

You would past it into a js file and reference it after your jquery reference. You would then call it like this..

$("textarea").characterCounter(200);

A brief explanation of what is going on..

On every keyup event the function is checking what type of key is pressed. If it is acceptable the the counter will check the count, trim any excess and prevent any further input once the limit is reached.

The plugin should handle pasting into the target too.

  ; (function ($) {
        $.fn.characterCounter = function (limit) {
            return this.filter("textarea, input:text").each(function () {
                var $this = $(this),
                  checkCharacters = function (event) {

                      if ($this.val().length > limit) {

                          // Trim the string as paste would allow you to make it 
                          // more than the limit.
                          $this.val($this.val().substring(0, limit))
                          // Cancel the original event
                          event.preventDefault();
                          event.stopPropagation();

                      }
                  };

                $this.keyup(function (event) {

                    // Keys "enumeration"
                    var keys = {
                        BACKSPACE: 8,
                        TAB: 9,
                        LEFT: 37,
                        UP: 38,
                        RIGHT: 39,
                        DOWN: 40
                    };

                    // which normalizes keycode and charcode.
                    switch (event.which) {

                        case keys.UP:
                        case keys.DOWN:
                        case keys.LEFT:
                        case keys.RIGHT:
                        case keys.TAB:
                            break;
                        default:
                            checkCharacters(event);
                            break;
                    }   

                });

                // Handle cut/paste.
                $this.bind("paste cut", function (event) {
                    // Delay so that paste value is captured.
                    setTimeout(function () { checkCharacters(event); event = null; }, 150);
                });
            });
        };
    } (jQuery));

SQL (MySQL) vs NoSQL (CouchDB)

Seems like only real solutions today revolve around scaling out or sharding. All modern databases (NoSQLs as well as NewSQLs) support horizontal scaling right out of the box, at the database layer, without the need for the application to have sharding code or something.

Unfortunately enough, for the trusted good-old MySQL, sharding is not provided "out of the box". ScaleBase (disclaimer: I work there) is a maker of a complete scale-out solution an "automatic sharding machine" if you like. ScaleBae analyzes your data and SQL stream, splits the data across DB nodes, and aggregates in runtime – so you won’t have to! And it's free download.

Don't get me wrong, NoSQLs are great, they're new, new is more choice and choice is always good!! But choosing NoSQL comes with a price, make sure you can pay it...

You can see here some more data about MySQL, NoSQL...: http://www.scalebase.com/extreme-scalability-with-mongodb-and-mysql-part-1-auto-sharding

Hope that helped.

How do I add more members to my ENUM-type column in MySQL?

The discussion I had with Asaph may be unclear to follow as we went back and forth quite a bit.

I thought that I might clarify the upshot of our discourse for others who might face similar situations in the future to benefit from:

ENUM-type columns are very difficult beasts to manipulate. I wanted to add two countries (Malaysia & Sweden) to the existing set of countries in my ENUM.

It seems that MySQL 5.1 (which is what I am running) can only update the ENUM by redefining the existing set in addition to what I want:

This did not work:

ALTER TABLE carmake CHANGE country country ENUM('Sweden','Malaysia') DEFAULT NULL;

The reason was that the MySQL statement was replacing the existing ENUM with another containing the entries 'Malaysia' and 'Sweden' only. MySQL threw up an error because the carmake table already had values like 'England' and 'USA' which were not part of the new ENUM's definition.

Surprisingly, the following did not work either:

ALTER TABLE carmake CHANGE country country ENUM('Australia','England','USA'...'Sweden','Malaysia') DEFAULT NULL;

It turns out that even the order of elements of the existing ENUM needs to be preserved while adding new members to it. So if my existing ENUM looks something like ENUM('England','USA'), then my new ENUM has to be defined as ENUM('England','USA','Sweden','Malaysia') and not ENUM('USA','England','Sweden','Malaysia'). This problem only becomes manifest when there are records in the existing table that use 'USA' or 'England' values.

BOTTOM LINE:

Only use ENUMs when you do not expect your set of members to change once defined. Otherwise, lookup tables are much easier to update and modify.

Get child node index

I've become fond of using indexOf for this. Because indexOf is on Array.prototype and parent.children is a NodeList, you have to use call(); It's kind of ugly but it's a one liner and uses functions that any javascript dev should be familiar with anyhow.

var child = document.getElementById('my_element');
var parent = child.parentNode;
// The equivalent of parent.children.indexOf(child)
var index = Array.prototype.indexOf.call(parent.children, child);

Database design for a survey

My design is shown below.

The latest create script is at https://gist.github.com/durrantm/1e618164fd4acf91e372

The script and the mysql workbench.mwb file are also available at
https://github.com/durrantm/survey enter image description here

What exactly does an #if 0 ..... #endif block do?

I'd like to add on for the #else case:

#if 0
   /* Code here will NOT be complied. */
#else
   /* Code will be compiled. */
#endif


#if 1
   /* Code will be complied. */
#else
   /* Code will NOT be compiled. */
#endif

VirtualBox error "Failed to open a session for the virtual machine"

Updating VirtualBox to newest version fixed my issue.

How Best to Compare Two Collections in Java and Act on Them?

You can use Java 8 streams, for example

set1.stream().filter(s -> set2.contains(s)).collect(Collectors.toSet());

or Sets class from Guava:

Set<String> intersection = Sets.intersection(set1, set2);
Set<String> difference = Sets.difference(set1, set2);
Set<String> symmetricDifference = Sets.symmetricDifference(set1, set2);
Set<String> union = Sets.union(set1, set2);

Fragments onResume from back stack

In my activity onCreate()

getSupportFragmentManager().addOnBackStackChangedListener(getListener());

Use this method to catch specific Fragment and call onResume()

private FragmentManager.OnBackStackChangedListener getListener()
    {
        FragmentManager.OnBackStackChangedListener result = new FragmentManager.OnBackStackChangedListener()
        {
            public void onBackStackChanged()
            {
                Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
                if (currentFragment instanceof YOURFRAGMENT) {
                    currentFragment.onResume();
                }
            }
        };

        return result;
    }

connecting to MySQL from the command line

Use the following command to get connected to your MySQL database

mysql -u USERNAME -h HOSTNAME -p

How to get rid of the "No bootable medium found!" error in Virtual Box?

It's Never late. This error shows that you have After Installation of OS in Virtual Box you Remove the ISO file from Virtual Box Setting or you change your OS ISO file location. Thus you can Solve your Problem bY following given steps or you can watch video at Link

  1. Open Virtual Box and Select you OS from List in Left side.
  2. Then Select Setting. (setting Windows will open)
  3. The Select on "Storage" From Left side Panel.
  4. Then select on "empty" disk Icon on Right side panel.
  5. Under "Attribute" Section you can See another Disk icon. select o it.
  6. Then Select on "Choose Virtual Optical Disk file" and Select your OS ISO file.
  7. Restart VirtualBox and Start you OS.

To watch Video click on Below link: Link

Formatting code snippets for blogging on Blogger

For my blog I use http://hilite.me/ to format source code. It supports lots of formats and outputs rather clean html. But if you have lots of code snippets then you have to do a lot of copy paste. For formatting Python code I've also used Pygments (blog post).

Installation failed with message Invalid File

follow some steps:

Clean Project
Rebuild Project
Invalidate Caches / Restart

Now run your project. Hope it will work.

It's work for me.

what does "error : a nonstatic member reference must be relative to a specific object" mean?

EncodeAndSend is not a static function, which means it can be called on an instance of the class CPMSifDlg. You cannot write this:

 CPMSifDlg::EncodeAndSend(/*...*/);  //wrong - EncodeAndSend is not static

It should rather be called as:

 CPMSifDlg dlg; //create instance, assuming it has default constructor!
 dlg.EncodeAndSend(/*...*/);   //correct 

How to add external fonts to android application

You can use the custom TextView for whole app with custom font here is an example for that

public class MyTextView extends TextView {

   Typeface normalTypeface = Typeface.createFromAsset(getContext().getAssets(), Constants.FONT_REGULAR);
   Typeface boldTypeface = Typeface.createFromAsset(getContext().getAssets(),  Constants.FONT_BOLD);

   public MyTextView(Context context, AttributeSet attrs, int defStyle) {
       super(context, attrs, defStyle);
   }

   public MyTextView(Context context, AttributeSet attrs) {
       super(context, attrs);
   }

   public MyTextView(Context context) {
       super(context);
   }

   public void setTypeface(Typeface tf, int style) {
       if (style == Typeface.BOLD) {
           super.setTypeface(boldTypeface/*, -1*/);
       } else {
           super.setTypeface(normalTypeface/*, -1*/);
       }
   }
}

How to inject JPA EntityManager using spring

The latest Spring + JPA versions solve this problem fundamentally. You can learn more how to use Spring and JPA togather in a separate thread

Change bullets color of an HTML list without using span

We can combine list-style-image with svgs, which we can inline in css! This method offers incredible control over the "bullets", which can become anything.

To get a red circle, just use the following css:

ul {
  list-style-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10" width="10" height="10"><circle fill="red" cx="5" cy="5" r="2"/></svg>');
}

But this is just the beginning. This allows us to do any crazy thing we want with those bullets. circles or rectangles are easy, but anything you can draw with svg you can stick in there! Check out the bullseye example below:

_x000D_
_x000D_
ul {_x000D_
  list-style-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10" width="10" height="10"><circle fill="red" cx="5" cy="5" r="5"/></svg>');_x000D_
}_x000D_
ul ul {_x000D_
  list-style-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10" width="10" height="10"><rect fill="red" x="0" y="0" height="10" width="10"/></svg>');_x000D_
}_x000D_
ul ul ul {_x000D_
  list-style-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10" width="10" height="10"><circle fill="red" cx="5" cy="5" r="3"/></svg>');_x000D_
}_x000D_
ul ul ul ul {_x000D_
  list-style-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10" width="10" height="10"><rect fill="red" x="2" y="2" height="4" width="4"/></svg>');_x000D_
}_x000D_
ul.bulls-eye {_x000D_
  list-style-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10" width="10" height="10"><circle fill="red" cx="5" cy="5" r="5"/><circle fill="white" cx="5" cy="5" r="4"/><circle fill="red" cx="5" cy="5" r="2"/></svg>');_x000D_
}_x000D_
ul.multi-color {_x000D_
  list-style-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 12" width="15" height="15"><circle fill="blue" cx="6" cy="6" r="6"/><circle fill="pink" cx="6" cy="6" r="4"/><circle fill="green" cx="6" cy="6" r="2"/></svg>');_x000D_
}
_x000D_
<ul>_x000D_
  <li>_x000D_
    Big circles!_x000D_
_x000D_
    <ul>_x000D_
      <li>Big rectangles!</li>_x000D_
      <li>b_x000D_
        <ul>_x000D_
          <li>Small circles!</li>_x000D_
          <li>c_x000D_
            <ul>_x000D_
              <li>Small rectangles!</li>_x000D_
              <li>b</li>_x000D_
            </ul>_x000D_
          </li>_x000D_
        </ul>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </li>_x000D_
  <li>b</li>_x000D_
</ul>_x000D_
_x000D_
<ul class="bulls-eye">_x000D_
  <li>Bulls</li>_x000D_
  <li>eyes.</li>_x000D_
</ul>_x000D_
_x000D_
<ul class="multi-color">_x000D_
  <li>Multi</li>_x000D_
  <li>color</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Width/height attributes

Some browsers require width and height attributes to be set on the <svg>, or they display nothing. At time of writing, recent versions of Firefox exhibit this problem. I've set both attributes in the examples.

Encodings

A recent comment reminded me of encodings for the data-uri. This was a pain-point for me recently, and I can share a bit of information I've researched.

The data-uri spec, which references the URI spec, says that the svg should be encoded according to the URI spec. That means all sorts of characters should be encoded, eg < becomes %3C.

Some sources suggest base64 encoding, which should fix encoding issues, however it will unnecessarily increase the size of the SVG, whereas URI encoding will not. I recommend URI encoding.

More info:

browser-support: >ie8

css tricks on svgs

mdn on svgs

How do you set the Content-Type header for an HttpClient request?

Some extra information about .NET Core (after reading erdomke's post about setting a private field to supply the content-type on a request that doesn't have content)...

After debugging my code, I can't see the private field to set via reflection - so I thought I'd try to recreate the problem.

I have tried the following code using .Net 4.6:

HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Get, @"myUrl");
httpRequest.Content = new StringContent(string.Empty, Encoding.UTF8, "application/json");

HttpClient client = new HttpClient();
Task<HttpResponseMessage> response =  client.SendAsync(httpRequest);  //I know I should have used async/await here!
var result = response.Result;

And, as expected, I get an aggregate exception with the content "Cannot send a content-body with this verb-type."

However, if i do the same thing with .NET Core (1.1) - I don't get an exception. My request was quite happily answered by my server application, and the content-type was picked up.

I was pleasantly surprised about that, and I hope it helps someone!

How to fix missing dependency warning when using useEffect React Hook?

You can set it directly as the useEffect callback:

useEffect(fetchBusinesses, [])

It will trigger only once, so make sure all the function's dependencies are correctly set (same as using componentDidMount/componentWillMount...)


Edit 02/21/2020

Just for completeness:

1. Use function as useEffect callback (as above)

useEffect(fetchBusinesses, [])

2. Declare function inside useEffect()

useEffect(() => {
  function fetchBusinesses() {
    ...
  }
  fetchBusinesses()
}, [])

3. Memoize with useCallback()

In this case, if you have dependencies in your function, you will have to include them in the useCallback dependencies array and this will trigger the useEffect again if the function's params change. Besides, it is a lot of boilerplate... So just pass the function directly to useEffect as in 1. useEffect(fetchBusinesses, []).

const fetchBusinesses = useCallback(() => {
  ...
}, [])
useEffect(() => {
  fetchBusinesses()
}, [fetchBusinesses])

4. Disable eslint's warning

useEffect(() => {
  fetchBusinesses()
}, []) // eslint-disable-line react-hooks/exhaustive-deps

How to exit an Android app programmatically?

just use the code in your backpress

                    Intent startMain = new Intent(Intent.ACTION_MAIN);
                    startMain.addCategory(Intent.CATEGORY_HOME);
                    startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(startMain);

How to list all properties of a PowerShell object

If you want to know what properties (and methods) there are:

Get-WmiObject -Class "Win32_computersystem" | Get-Member

I/O error(socket error): [Errno 111] Connection refused

Getting an ECONNREFUSED errno means that your kernel was refused a connection at the other end, so if it's a bug, it's either in your kernel or in the other end. What you can do is to trap the error in a very specific way and try again in a little while, since this seems to work:

# This is Python > 2.5 code
import errno, time

for attempt in range(MAXIMUM_NUMBER_OF_ATTEMPTS):
    try:
        # your urllib call here
    except EnvironmentError as exc: # replace " as " with ", " for Python<2.6
        if exc.errno == errno.ECONNREFUSED:
            time.sleep(A_COUPLE_OF_SECONDS)
        else:
            raise # re-raise otherwise
    else: # we tried, and we had no failure, so
        break
else: # we never broke out of the for loop
    raise RuntimeError("maximum number of unsuccessful attempts reached")

Replace the two all-caps constants with your favourite numbers.

Define global constants

Below changes works for me on Angular 2 final version:

export class AppSettings {
   public static API_ENDPOINT='http://127.0.0.1:6666/api/';
}

And then in the service:

import {Http} from 'angular2/http';
import {Message} from '../models/message';
import {Injectable} from 'angular2/core';
import {Observable} from 'rxjs/Observable';
import {AppSettings} from '../appSettings';
import 'rxjs/add/operator/map';

@Injectable()
export class MessageService {

    constructor(private http: Http) { }

    getMessages(): Observable<Message[]> {
        return this.http.get(AppSettings.API_ENDPOINT+'/messages')
            .map(response => response.json())
            .map((messages: Object[]) => {
                return messages.map(message => this.parseData(message));
            });
    }

    private parseData(data): Message {
        return new Message(data);
    }
}

Uses for the '&quot;' entity in HTML

Reason #1

There was a point where buggy/lazy implementations of HTML/XHTML renderers were more common than those that got it right. Many years ago, I regularly encountered rendering problems in mainstream browsers resulting from the use of unencoded quote chars in regular text content of HTML/XHTML documents. Though the HTML spec has never disallowed use of these chars in text content, it became fairly standard practice to encode them anyway, so that non-spec-compliant browsers and other processors would handle them more gracefully. As a result, many "old-timers" may still do this reflexively. It is not incorrect, though it is now probably unnecessary, unless you're targeting some very archaic platforms.

Reason #2

When HTML content is generated dynamically, for example, by populating an HTML template with simple string values from a database, it's necessary to encode each value before embedding it in the generated content. Some common server-side languages provided a single function for this purpose, which simply encoded all chars that might be invalid in some context within an HTML document. Notably, PHP's htmlspecialchars() function is one such example. Though there are optional arguments to htmlspecialchars() that will cause it to ignore quotes, those arguments were (and are) rarely used by authors of basic template-driven systems. The result is that all "special chars" are encoded everywhere they occur in the generated HTML, without regard for the context in which they occur. Again, this is not incorrect, it's simply unnecessary.

How to post data using HttpClient?

You need to use:

await client.PostAsync(uri, content);

Something like that:

var comment = "hello world";
var questionId = 1;

var formContent = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("comment", comment), 
    new KeyValuePair<string, string>("questionId", questionId) 
});

var myHttpClient = new HttpClient();
var response = await myHttpClient.PostAsync(uri.ToString(), formContent);

And if you need to get the response after post, you should use:

var stringContent = await response.Content.ReadAsStringAsync();

Hope it helps ;)

Uri not Absolute exception getting while calling Restful Webservice

The problem is likely that you are calling URLEncoder.encode() on something that already is a URI.

How to center a button within a div?

Super simple answer that will apply to most cases is to just make set the margin to 0 auto and set the display to block. You can see how I centered my button in my demo on CodePen

enter image description here

Scrolling to an Anchor using Transition/CSS3

I guess it might be possible to set some kind of hardcore transition to the top style of a #container div to move your entire page in the desired direction when clicking your anchor. Something like adding a class that has top:-2000px.

I did use JQuery because I'm to lazy too use native JS, but it is not necessary for what I did.

This is probably not the best possible solution because the top content just moves towards the top and you can't get it back easily, you should definitely use JQuery if you really need that scroll animation.

DEMO

When is it acceptable to call GC.Collect?

Another reason is when you have a SerialPort opened on a USB COM port, and then the USB device is unplugged. Because the SerialPort was opened, the resource holds a reference to the previously connected port in the system's registry. The system's registry will then contain stale data, so the list of available ports will be wrong. Therefore the port must be closed.

Calling SerialPort.Close() on the port calls Dispose() on the object, but it remains in memory until garbage collection actually runs, causing the registry to remain stale until the garbage collector decides to release the resource.

From https://stackoverflow.com/a/58810699/8685342:

try
{
    if (port != null)
        port.Close(); //this will throw an exception if the port was unplugged
}
catch (Exception ex) //of type 'System.IO.IOException'
{
    System.GC.Collect();
    System.GC.WaitForPendingFinalizers();
}

port = null;

Can't Load URL: The domain of this URL isn't included in the app's domains

I had the same problem, and it came from a wrong client_id / Facebook App ID.

Did you switch your Facebook app to "public" or "online ? When you do so, Facebook creates a new app with a new App ID.

You can compare the "client_id" parameter value in the url with the one in your Facebook dashboard.

Also Make sure your app is public. Click on + Add product Now go to products => Facebook Login Now do the following:

Valid OAuth redirect URIs : example.com/

How to view unallocated free space on a hard disk through terminal

This is an old question, but I wanted to give my answer as well.

Since we're talking about free available space, we should talk about sectors, since no partitioning or sizing of sectors is done.

For us human beings this doesn't make much sense. To have human-readable information we must translate this number into bytes. So, we have a disk already partitioned and we want to know how much space we may use. I personally don't like the parted solution because my brain-memory for commands is already taken. There is also cfdisk, which gives you free space. But I think fdisk is the quickest solution: it's plain and simple, with nothing to install: execute fdisk /dev/sdx and then enter v into the interactive shell. It will gives you the number of sectors still free.

2004-54-0 [17:03:33][root@minimac:~]$> fdisk /dev/sda
Welcome to fdisk (util-linux 2.23.2).
..
Command (m for help): v
Remaining 1713 unallocated 512-byte sectors

We still have 1713 sectors at 512 bytes each. So, because you love terminal (in 2012, who knows now?) we do echo $(((1713*512)/1024))k, which is 1713 sectors multiplied for 512 bytes (divided by 1024 to have KB), which gives 856k.. not even 900 KB.. and I need another disk..

How to identify object types in java

You can compare class tokens to each other, so you could use value.getClass() == Integer.class. However, the simpler and more canonical way is to use instanceof :

    if (value instanceof Integer) {
        System.out.println("This is an Integer");
    } else if(value instanceof String) {
        System.out.println("This is a String");
    } else if(value instanceof Float) {
        System.out.println("This is a Float");
    }

Notes:

  • the only difference between the two is that comparing class tokens detects exact matches only, while instanceof C matches for subclasses of C too. However, in this case all the classes listed are final, so they have no subclasses. Thus instanceof is probably fine here.
  • as JB Nizet stated, such checks are not OO design. You may be able to solve this problem in a more OO way, e.g.

    System.out.println("This is a(n) " + value.getClass().getSimpleName());
    

How do I remove a CLOSE_WAIT socket connection

You can forcibly close sockets with ss command; the ss command is a tool used to dump socket statistics and displays information in similar fashion (although simpler and faster) to netstat.

To kill any socket in CLOSE_WAIT state, run this (as root)

$ ss --tcp state CLOSE-WAIT --kill

Adding a line break in MySQL INSERT INTO text

INSERT INTO test VALUES('a line\nanother line');

\n just works fine here

Python URLLib / URLLib2 POST

u = urllib2.urlopen('http://myserver/inout-tracker', data)
h.request('POST', '/inout-tracker/index.php', data, headers)

Using the path /inout-tracker without a trailing / doesn't fetch index.php. Instead the server will issue a 302 redirect to the version with the trailing /.

Doing a 302 will typically cause clients to convert a POST to a GET request.

Undefined symbols for architecture i386

well i found a solution to this problem for who want to work with xCode 4. All what you have to do is importing frameworks from the SimulatorSDK folder /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk/System/Library/Frameworks

i don't know if it works when you try to test your app on a real iDevice, but i'm sure that it works on simulator.

ENJOY

How to use multiple LEFT JOINs in SQL?

The required SQL will be some like:-

SELECT * FROM cd
LEFT JOIN ab ON ab.sht = cd.sht
LEFT JOIN aa ON aa.sht = cd.sht
....

Hope it helps.

Differences between key, superkey, minimal superkey, candidate key and primary key

Primary key is a subset of super key. Which is uniquely define and other field are depend on it. In a table their can be just one primary key and rest sub set are candidate key or alternate keys.

How to access to the parent object in c#

Why not change the constructor on Production to let you pass in a reference at construction time:

public class Meter
{
   private int _powerRating = 0; 
   private Production _production;

   public Meter()
   {
      _production = new Production(this);
   }
}

In the Production constructor you can assign this to a private field or a property. Then Production will always have access to is parent.

How to print a specific row of a pandas DataFrame?

To print a specific row we have couple of pandas method

  1. loc - It only get label i.e column name or Features
  2. iloc - Here i stands for integer, actually row number
  3. ix - It is a mix of label as well as integer

How to use for specific row

  1. loc
df.loc[row,column]

For first row and all column

df.loc[0,:]

For first row and some specific column

df.loc[0,'column_name']
  1. iloc

For first row and all column

df.iloc[0,:]

For first row and some specific column i.e first three cols

df.iloc[0,0:3]

Removing Spaces from a String in C?

I came across a variation to this question where you need to reduce multiply spaces into one space "represent" the spaces.

This is my solution:

char str[] = "Put Your string Here.....";

int copyFrom = 0, copyTo = 0;

printf("Start String %s\n", str);

while (str[copyTo] != 0) {
    if (str[copyFrom] == ' ') {
        str[copyTo] = str[copyFrom];
        copyFrom++;
        copyTo++;

        while ((str[copyFrom] == ' ') && (str[copyFrom] !='\0')) {
            copyFrom++;
        }
    }

    str[copyTo] = str[copyFrom];

    if (str[copyTo] != '\0') {
        copyFrom++;
        copyTo++;
    }
}

printf("Final String %s\n", str);

Hope it helps :-)

How to make <label> and <input> appear on the same line on an HTML form?

Wrap the label and the input within a bootstraps div

<div class ="row">
  <div class="col-md-4">Name:</div>
  <div class="col-md-8"><input type="text"></div>
</div>

Get a timestamp in C in microseconds?

You have two choices for getting a microsecond timestamp. The first (and best) choice, is to use the timeval type directly:

struct timeval GetTimeStamp() {
    struct timeval tv;
    gettimeofday(&tv,NULL);
    return tv;
}

The second, and for me less desirable, choice is to build a uint64_t out of a timeval:

uint64_t GetTimeStamp() {
    struct timeval tv;
    gettimeofday(&tv,NULL);
    return tv.tv_sec*(uint64_t)1000000+tv.tv_usec;
}

JavaScript click event listener on class

With modern JavaScript it can be done like this:

_x000D_
_x000D_
const divs = document.querySelectorAll('.a');

divs.forEach(el => el.addEventListener('click', event => {
  console.log(event.target.getAttribute("data-el"));
}));
_x000D_
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Example</title>
  <style>
    .a {
      background-color:red;
      height: 33px;
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      cursor: pointer;
    }
    
    .b {
      background-color:#00AA00;
      height: 50px;
      display: flex;
      align-items: center;
      margin-bottom: 10px;
    }
  </style>
</head>
<body>
  <div class="a" data-el="1">1</div>
  <div class="b" data-el="no-click-handler">2</div>
  <div class="a" data-el="3">11</div>
</body>
</html>
_x000D_
_x000D_
_x000D_

  1. Gets all elements by class name
  2. Loops over all elements with using forEach
  3. Attach an event listener on each element
  4. Uses event.target to retrieve more information for specific element

Error: free(): invalid next size (fast):

If you are trying to allocate space for an array of pointers, such as

char** my_array_of_strings;  // or some array of pointers such as int** or even void**

then you will need to consider word size (8 bytes in a 64-bit system, 4 bytes in a 32-bit system) when allocating space for n pointers. The size of a pointer is the same of your word size.

So while you may wish to allocate space for n pointers, you are actually going to need n times 8 or 4 (for 64-bit or 32-bit systems, respectively)

To avoid overflowing your allocated memory for n elements of 8 bytes:

my_array_of_strings = (char**) malloc( n * 8 );  // for 64-bit systems
my_array_of_strings = (char**) malloc( n * 4 );  // for 32-bit systems

This will return a block of n pointers, each consisting of 8 bytes (or 4 bytes if you're using a 32-bit system)

I have noticed that Linux will allow you to use all n pointers when you haven't compensated for word size, but when you try to free that memory it realizes its mistake and it gives out that rather nasty error. And it is a bad one, when you overflow allocated memory, many security issues lie in wait.

How do I get logs/details of ansible-playbook module executions?

The playbook script task will generate stdout just like the non-playbook command, it just needs to be saved to a variable using register. Once we've got that, the debug module can print to the playbook output stream.

tasks:
- name: Hello yourself
  script: test.sh
  register: hello

- name: Debug hello
  debug: var=hello

- name: Debug hello.stdout as part of a string
  debug: "msg=The script's stdout was `{{ hello.stdout }}`."

Output should look something like this:

TASK: [Hello yourself] ******************************************************** 
changed: [MyTestHost]

TASK: [Debug hello] *********************************************************** 
ok: [MyTestHost] => {
    "hello": {
        "changed": true, 
        "invocation": {
            "module_args": "test.sh", 
            "module_name": "script"
        }, 
        "rc": 0, 
        "stderr": "", 
        "stdout": "Hello World\r\n", 
        "stdout_lines": [
            "Hello World"
        ]
    }
}

TASK: [Debug hello.stdout as part of a string] ******************************** 
ok: [MyTestHost] => {
    "msg": "The script's stdout was `Hello World\r\n`."
}

Datatables on-the-fly resizing

I got this to work as follows:

First ensure that in your dataTable definition your aoColumns array includes sWidth data expressed as a % not fixed pixels or ems. Then ensure you have set the bAutoWidth property to false Then add this little but of JS:

update_table_size = function(a_datatable) {
  if (a_datatable == null) return;
  var dtb;
  if (typeof a_datatable === 'string') dtb = $(a_datatable)
  else dtb = a_datatable;
  if (dtb == null) return;

  dtb.css('width', dtb.parent().width());
  dtb.fnAdjustColumSizing();
}

$(window).resize(function() {
  setTimeout(function(){update_table_size(some_table_selector_or_table_ref)}, 250);
});

Works a treat and my table cells handle the white-space: wrap; CSS (which wasn't working without setting the sWidth, and was what led me to this question.)

Run chrome in fullscreen mode on Windows

Running chrome.exe --start-fullscreen --app=https://google.com will not get you Chrome in fullscreen, but in kiosk mode.

However, running chrome --start-fullscreen --app=https://google.com (notice : it's chrome instead of chrome.exe) worked in my case.

JavaScript: Class.method vs. Class.prototype.method

When you create more than one instance of MyClass , you will still only have only one instance of publicMethod in memory but in case of privilegedMethod you will end up creating lots of instances and staticMethod has no relationship with an object instance.

That's why prototypes save memory.

Also, if you change the parent object's properties, is the child's corresponding property hasn't been changed, it'll be updated.

OS specific instructions in CMAKE: How to?

You have some special words from CMAKE, take a look:

if(${CMAKE_SYSTEM_NAME} STREQUAL "Linux")
    // do something for Linux
else
    // do something for other OS

Pretty-Print JSON in Java

Update: new JsonParser().parse(...) is @deprecated


Based on the javadoc for Gson 2.8.6:

No need to instantiate this class, use the static methods instead.

JsonParser static methods:

JsonParser.parseString?(jsonString);
JsonParser.parseReader?(reader);

Packages:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParser;

Example:

private Gson GSON = new GsonBuilder().setPrettyPrinting().create();
public static String getPerfectJSON(String unformattedJSON) {
    String perfectJSON = GSON.toJson(JsonParser.parseString(unformattedJSON));
    return perfectJSON;
}

Google Gson dependency using Maven:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.6</version>
</dependency>

Reference:

psql: FATAL: Ident authentication failed for user "postgres"

The following steps work for a fresh install of postgres 9.1 on Ubuntu 12.04. (Worked for postgres 9.3.9 on Ubuntu 14.04 too.)

By default, postgres creates a user named 'postgres'. We log in as her, and give her a password.

$ sudo -u postgres psql
\password
Enter password: ...
...

Logout of psql by typing \q or ctrl+d. Then we connect as 'postgres'. The -h localhost part is important: it tells the psql client that we wish to connect using a TCP connection (which is configured to use password authentication), and not by a PEER connection (which does not care about the password).

$ psql -U postgres -h localhost

SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column

For the people stumbling across this question and getting a similar error message in regards to an nvarchar instead of money:

The given value of type String from the data source cannot be converted to type nvarchar of the specified target column.

This could be caused by a too-short column.

For example, if your column is defined as nvarchar(20) and you have a 40 character string, you may get this error.

Source

document .click function for touch device

can you use jqTouch or jquery mobile ? there it's much easier to handle touch events. If not then you need to simulate click on touch device, follow this articles:

iphone-touch-events-in-javascript

A touch demo

More in this thread

How to use gitignore command in git

If you dont have a .gitignore file, first use:

touch .gitignore

then this command to add lines in your gitignore file:

echo 'application/cache' >> .gitignore

Be careful about new lines

Convert a string to integer with decimal in Python

"Convert" only makes sense when you change from one data type to another without loss of fidelity. The number represented by the string is a float and will lose precision upon being forced into an int.

You want to round instead, probably (I hope that the numbers don't represent currency because then rounding gets a whole lot more complicated).

round(float('23.45678'))

Python Flask, how to set content type

As simple as this

x = "some data you want to return"
return x, 200, {'Content-Type': 'text/css; charset=utf-8'}

Hope it helps

Update: Use this method because it will work with both python 2.x and python 3.x

and secondly it also eliminates multiple header problem.

from flask import Response
r = Response(response="TEST OK", status=200, mimetype="application/xml")
r.headers["Content-Type"] = "text/xml; charset=utf-8"
return r

Generate a random point within a circle (uniformly)

Solution in Java and the distribution example (2000 points)

public void getRandomPointInCircle() {
    double t = 2 * Math.PI * Math.random();
    double r = Math.sqrt(Math.random());
    double x = r * Math.cos(t);
    double y = r * Math.sin(t);
    System.out.println(x);
    System.out.println(y);
}

Distribution 2000 points

based on previus solution https://stackoverflow.com/a/5838055/5224246 from @sigfpe

can't multiply sequence by non-int of type 'float'

for i in growthRates:  
    fund = fund * (1 + 0.01 * growthRates) + depositPerYear

should be:

for i in growthRates:  
    fund = fund * (1 + 0.01 * i) + depositPerYear

You are multiplying 0.01 with the growthRates list object. Multiplying a list by an integer is valid (it's overloaded syntactic sugar that allows you to create an extended a list with copies of its element references).

Example:

>>> 2 * [1,2]
[1, 2, 1, 2]

Programmatically set left drawable in a TextView

A Kotlin extension + some padding around the drawable

fun TextView.addDrawable(drawable: Int) {
val imgDrawable = ContextCompat.getDrawable(context, drawable)
compoundDrawablePadding = 32
setCompoundDrawablesWithIntrinsicBounds(imgDrawable, null, null, null)
}

Java Array Sort descending?

This worked for me:

package doublearraysort;

import java.util.Arrays;
import java.util.Collections;

public class Gpa {


    public static void main(String[] args) {
        // initializing unsorted double array
        Double[] dArr = new Double[] {                 
            new Double(3.2),
            new Double(1.2),
            new Double(4.7),
            new Double(3.3),
            new Double(4.6),
           };
        // print all the elements available in list
        for (double number : dArr) {
            System.out.println("GPA = " + number);
        }

        // sorting the array
        Arrays.sort(dArr, Collections.reverseOrder());

        // print all the elements available in list again
        System.out.println("The sorted GPA Scores are:");
        for (double number : dArr) {
            System.out.println("GPA = " + number);
        }
    }
}

Output:

GPA = 3.2
GPA = 1.2
GPA = 4.7
GPA = 3.3
GPA = 4.6
The sorted GPA Scores are:
GPA = 4.7
GPA = 4.6
GPA = 3.3
GPA = 3.2
GPA = 1.2

Bootstrap 4 Dropdown Menu not working?

It's an issue with popper.js file. What I found at the official site was that bundle files include popper in itself but not jquery. I managed to fix it by adding link to these files:

bootstrap.bundle.js
bootstrap.bundle.min.js

I removed popper.js however since it comes within the bundle file.

Editable 'Select' element

Similar to answer above but without the absolute positioning:

<select style="width: 200px; float: left;" onchange="this.nextElementSibling.value=this.value">
    <option></option>
    <option>1</option>
    <option>2</option>
    <option>3</option> 
</select>
<input style="width: 185px; margin-left: -199px; margin-top: 1px; border: none; float: left;"/>

So create a input box and put it over the top of the combobox

How to get div height to auto-adjust to background size?

The best solution i can think of is by specifying your width and height in percent . This will allow you to rezise your screen based on your monitor size. its more of responsive layout..

For an instance. you have

<br/>
<div> . //This you set the width percent to %100
    <div> //This you set the width percent to any amount . if you put it by 50% , it will be half
    </div>
 </div>

This is the best option if you would want a responsive layout, i wouldnt recommend float , in certain cases float is okay to use. but in most cases , we avoid using float as it will affect a quite of number of things when you are doing cross-browser testing.

Hope this helps :)

Toggle Class in React

For anybody reading this in 2019, after React 16.8 was released, take a look at the React Hooks. It really simplifies handling states in components. The docs are very well written with an example of exactly what you need.

Uninstall Node.JS using Linux command line?

If you installed from source, you can issue the following command:

sudo make uninstall

If you followed the instructions on https://github.com/nodejs/node/wiki to install to your $HOME/local/node, then you have to type the following before the line above:

./configure --prefix=$HOME/local/node

Longer object length is not a multiple of shorter object length?

Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.

In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.

Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.

Cannot assign requested address using ServerSocket.socketBind

I came across this error when copying configurations from one server to another.

I had the old host's hostname in my ${JETTY_BASE}/start.ini jetty.host property. Setting the correct jetty.host property value solved the issue for me.

Hope this helps someone in the future who has to work on multiple servers at once.

What is getattr() exactly and how do I use it?

For me, getattr is easiest to explain this way:

It allows you to call methods based on the contents of a string instead of typing the method name.

For example, you cannot do this:

obj = MyObject()
for x in ['foo', 'bar']:
    obj.x()

because x is not of the type builtin, but str. However, you CAN do this:

obj = MyObject()
for x in ['foo', 'bar']:
    getattr(obj, x)()

It allows you to dynamically connect with objects based on your input. I've found it useful when dealing with custom objects and modules.

MySql Error: 1364 Field 'display_name' doesn't have default value

MySQL is most likely in STRICT mode.

Try running SET GLOBAL sql_mode='' or edit your my.cnf to make sure you aren't setting STRICT_ALL_TABLES or the like.

Casting a variable using a Type variable

How could you do that? You need a variable or field of type T where you can store the object after the cast, but how can you have such a variable or field if you know T only at runtime? So, no, it's not possible.

Type type = GetSomeType();
Object @object = GetSomeObject();

??? xyz = @object.CastTo(type); // How would you declare the variable?

xyz.??? // What methods, properties, or fields are valid here?

jQuery Validation plugin: disable validation for specified submit buttons

Here is the simplest version, hope it helps someone,

$('#cancel-button').click(function() {
    var $form = $(this).closest('form');
    $form.find('*[data-validation]').attr('data-validation', null);
    $form.get(0).submit();
});

Set a div width, align div center and text align left

All of these answers should suffice. However if you don't have a defined width, auto margins will not work.

I have found this nifty little trick to centre some of the more stubborn elements (Particularly images).

.div {
   position: absolute;
   left: 0;
   right: 0;
   margin-left: 0;
   margin-right: 0;
}

Function for C++ struct

Yes, a struct is identical to a class except for the default access level (member-wise and inheritance-wise). (and the extra meaning class carries when used with a template)

Every functionality supported by a class is consequently supported by a struct. You'd use methods the same as you'd use them for a class.

struct foo {
  int bar;
  foo() : bar(3) {}   //look, a constructor
  int getBar() 
  { 
    return bar; 
  }
};

foo f;
int y = f.getBar(); // y is 3

Project vs Repository in GitHub

The conceptual difference in my understanding it that a project can contain many repo's and that are independent of each other, while simultaneously a repo may contain many projects. Repo's being just a storage place for code while a project being a collection of tasks for a certain feature.

Does that make sense? A large repo can have many projects being worked on by different people at the same time (lots of difference features being added to a monolith), a large project may have many small repos that are separate but part of the same project that interact with each other - microservices? Its a personal take on what you want to do. I think that repo (storage) vs project (tasks) is the main difference - if i am wrong please let me know / explain! Thanks.

Difference between .dll and .exe?

An exe is an executible program whereas A DLL is a file that can be loaded and executed by programs dynamically.

Running bash script from within python

Adding an answer because I was directed here after asking how to run a bash script from python. You receive an error OSError: [Errno 2] file not found if your script takes in parameters. Lets say for instance your script took in a sleep time parameter: subprocess.call("sleep.sh 10") will not work, you must pass it as an array: subprocess.call(["sleep.sh", 10])

How to find schema name in Oracle ? when you are connected in sql session using read only user

How about the following 3 statements?

-- change to your schema

ALTER SESSION SET CURRENT_SCHEMA=yourSchemaName;

-- check current schema

SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL;

-- generate drop table statements

SELECT 'drop table ', table_name, 'cascade constraints;' FROM ALL_TABLES WHERE OWNER = 'yourSchemaName';

COPY the RESULT and PASTE and RUN.

login failed for user 'sa'. The user is not associated with a trusted SQL Server connection. (Microsoft SQL Server, Error: 18452) in sql 2008

Go to Start > Programs > Microsoft SQL Server > Enterprise Manager

Right-click the SQL Server instance name > Select Properties from the context menu > Select Security node in left navigation bar

Under Authentication section, select SQL Server and Windows Authentication

Note: The server must be stopped and re-started before this will take effect

Error 18452 (not associated with a trusted sql server connection)

Managing large binary files with Git

In my opinion, if you're likely to often modify those large files, or if you intend to make a lot of git clone or git checkout, then you should seriously consider using another Git repository (or maybe another way to access those files).

But if you work like we do, and if your binary files are not often modified, then the first clone/checkout will be long, but after that it should be as fast as you want (considering your users keep using the first cloned repository they had).

How can I build multiple submit buttons django form?

It's an old question now, nevertheless I had the same issue and found a solution that works for me: I wrote MultiRedirectMixin.

from django.http import HttpResponseRedirect

class MultiRedirectMixin(object):
    """
    A mixin that supports submit-specific success redirection.
     Either specify one success_url, or provide dict with names of 
     submit actions given in template as keys
     Example: 
       In template:
         <input type="submit" name="create_new" value="Create"/>
         <input type="submit" name="delete" value="Delete"/>
       View:
         MyMultiSubmitView(MultiRedirectMixin, forms.FormView):
             success_urls = {"create_new": reverse_lazy('create'),
                               "delete": reverse_lazy('delete')}
    """
    success_urls = {}  

    def form_valid(self, form):
        """ Form is valid: Pick the url and redirect.
        """

        for name in self.success_urls:
            if name in form.data:
                self.success_url = self.success_urls[name]
                break

        return HttpResponseRedirect(self.get_success_url())

    def get_success_url(self):
        """
        Returns the supplied success URL.
        """
        if self.success_url:
            # Forcing possible reverse_lazy evaluation
            url = force_text(self.success_url)
        else:
            raise ImproperlyConfigured(
                _("No URL to redirect to. Provide a success_url."))
        return url

ASP.NET document.getElementById('<%=Control.ClientID%>'); returns null

Gotcha!

You have to use RegisterStartupScript instead of RegisterClientScriptBlock

Here My Example.

MasterPage:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MasterPage.master.cs"
    Inherits="prueba.MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script type="text/javascript">

        function confirmCallBack() {
            var a = document.getElementById('<%= Page.Master.FindControl("ContentPlaceHolder1").FindControl("Button1").ClientID %>');

            alert(a.value);

        }

    </script>

    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>

WebForm1.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true"
    CodeBehind="WebForm1.aspx.cs" Inherits="prueba.WebForm1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" />
</asp:Content>

WebForm1.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace prueba
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "js", "confirmCallBack();", true);

        }
    }
}

SQL Server Management Studio – tips for improving the TSQL coding process

If you drag from Object Explorer Columns node for a table it puts a CSV list of columns in the Query Window for you

Fake "click" to activate an onclick method

Once you have selected an element you can call click()

document.getElementById('link').click();

see: https://developer.mozilla.org/En/DOM/Element.click

I don't remember if this works on IE, but it should. I don't have a windows machine nearby.

Matplotlib scatterplot; colour as a function of a third variable

Sometimes you may need to plot color precisely based on the x-value case. For example, you may have a dataframe with 3 types of variables and some data points. And you want to do following,

  • Plot points corresponding to Physical variable 'A' in RED.
  • Plot points corresponding to Physical variable 'B' in BLUE.
  • Plot points corresponding to Physical variable 'C' in GREEN.

In this case, you may have to write to short function to map the x-values to corresponding color names as a list and then pass on that list to the plt.scatter command.

x=['A','B','B','C','A','B']
y=[15,30,25,18,22,13]

# Function to map the colors as a list from the input list of x variables
def pltcolor(lst):
    cols=[]
    for l in lst:
        if l=='A':
            cols.append('red')
        elif l=='B':
            cols.append('blue')
        else:
            cols.append('green')
    return cols
# Create the colors list using the function above
cols=pltcolor(x)

plt.scatter(x=x,y=y,s=500,c=cols) #Pass on the list created by the function here
plt.grid(True)
plt.show()

Coloring scatter plot as a function of x variable

How many times does each value appear in a column?

You can use CountIf. Put the following code in B1 and drag down the whole column

=COUNTIF(A:A,A1)

It will look like this:

enter image description here

.gitignore exclude folder but include specific subfolder

Add an additional answer:

!/.vs/              <== include this folder to source control, folder only, nothing else
/.vs/*              <== but ignore all files and sub-folder inside this folder
!/.vs/ProjectSettings.json <== but include this file to source control
!/.vs/config/       <== then include this folder to source control, folder only, nothing else
!/.vs/config/*      <== then include all files inside the folder

here is result:

enter image description here

getMinutes() 0-9 - How to display two digit numbers?

.length is undefined because getMinutes is returning a number, not a string. numbers don't have a length property. You could do

var m = "" + date.getMinutes();

to make it a string, then check the length (you would want to check for length === 1, not 0).

Using only CSS, show div on hover over <a>

Based on the main answer, this is an example, useful to display an information tooltip when clicking on a ? near a link:

_x000D_
_x000D_
document.onclick = function() { document.getElementById("tooltip").style.display = 'none'; };_x000D_
_x000D_
document.getElementById("tooltip").onclick = function(e) { e.stopPropagation(); }_x000D_
_x000D_
document.getElementById("help").onclick = function(e) { document.getElementById("tooltip").style.display = 'block';_x000D_
e.stopPropagation(); };
_x000D_
#help { opacity: 0; margin-left: 0.1em; padding: 0.4em; }_x000D_
    _x000D_
a:hover + #help, #help:hover { opacity: 0.5; cursor: pointer; }_x000D_
_x000D_
#tooltip { border: 1px solid black; display: none; padding: 0.75em; width: 50%; text-align: center; font-family: sans-serif; font-size:0.8em; }
_x000D_
<a href="">Delete all obsolete informations</a><span id="help">?</span>_x000D_
<div id="tooltip">All data older than 2 weeks will be deleted.</div>
_x000D_
_x000D_
_x000D_

What is the difference between XAMPP or WAMP Server & IIS?

WAMP is an acronym for Windows (OS), Apache (web-server), MySQL (database), PHP (language).

XAMPP and WampServer are both free packages of WAMP, with additional applications/tools, put together by different people. There are also other WAMPs such as UniformServer. And there are commercial WAMPs such as WampDeveloper (what I use).

Their differences are in the format/structure of the package, the configurations, and the included management applications.

IIS is a web-server application just like Apache is, except it's made by Microsoft and is Windows only (Apache runs on both Windows and Linux). IIS is also more geared towards using ASP.NET (vs. PHP) and "SQL Server" (vs. MySQL), though it can use PHP and MySQL too.

How to pass macro definition from "make" command line arguments (-D) to C source code?

Call make this way

make CFLAGS=-Dvar=42

because you do want to override your Makefile's CFLAGS, and not just the environment (which has a lower priority with regard to Makefile variables).

How to use ng-repeat without an html element

You might want to flatten the data within your controller:

function MyCtrl ($scope) {
  $scope.myData = [[1,2,3], [4,5,6], [7,8,9]];
  $scope.flattened = function () {
    var flat = [];
    $scope.myData.forEach(function (item) {
      flat.concat(item);
    }
    return flat;
  }
}

And then in the HTML:

<table>
  <tbody>
    <tr ng-repeat="item in flattened()"><td>{{item}}</td></tr>
  </tbody>
</table>

Where is virtualenvwrapper.sh after pip install?

For RPM-based distributions(like Fedora 19), after running the sudo pip install virtualenvwrapper command, you may find the file at:

/usr/bin/virtualenvwrapper.sh

Curl : connection refused

Try curl -v http://localhost:8080/ instead of 127.0.0.1

How to compare arrays in C#?

You're comparing the object references, and they are not the same. You need to compare the array contents.

.NET2 solution

An option is iterating through the array elements and call Equals() for each element. Remember that you need to override the Equals() method for the array elements, if they are not the same object reference.

An alternative is using this generic method to compare two generic arrays:

static bool ArraysEqual<T>(T[] a1, T[] a2)
{
    if (ReferenceEquals(a1, a2))
        return true;

    if (a1 == null || a2 == null)
        return false;

    if (a1.Length != a2.Length)
        return false;

    var comparer = EqualityComparer<T>.Default;
    for (int i = 0; i < a1.Length; i++)
    {
        if (!comparer.Equals(a1[i], a2[i])) return false;
    }
    return true;
}

.NET 3.5 or higher solution

Or use SequenceEqual if Linq is available for you (.NET Framework >= 3.5)

How to drop all tables from the database with manage.py CLI in Django?

use "python manage.py sqlflush" command in windows 10 for others type manage.py

Another git process seems to be running in this repository

Had the same problem using SourceTree. But there were no any index.lock file on my host at all. I've found packed-refs.lock file, and after deleting it, the problem was solved.

How do I see what character set a MySQL database / table / column is?

To see default collation of the database:

USE db_name;
SELECT @@character_set_database, @@collation_database;

To see collation of the table:

SHOW TABLE STATUS where name like 'table_name';

To see collation of the columns:

SHOW FULL COLUMNS FROM table_name;

To see the default character set of a table

SHOW CREATE TABLE table_name;

history.replaceState() example?

history.pushState pushes the current page state onto the history stack, and changes the URL in the address bar. So, when you go back, that state (the object you passed) are returned to you.

Currently, that is all it does. Any other page action, such as displaying the new page or changing the page title, must be done by you.

The W3C spec you link is just a draft, and browser may implement it differently. Firefox, for example, ignores the title parameter completely.

Here is a simple example of pushState that I use on my website.

(function($){
    // Use AJAX to load the page, and change the title
    function loadPage(sel, p){
        $(sel).load(p + ' #content', function(){
            document.title = $('#pageData').data('title');
        });
    }

    // When a link is clicked, use AJAX to load that page
    // but use pushState to change the URL bar
    $(document).on('click', 'a', function(e){
        e.preventDefault();
        history.pushState({page: this.href}, '', this.href);
        loadPage('#frontPage', this.href);
    });

    // This event is triggered when you visit a page in the history
    // like when yu push the "back" button
    $(window).on('popstate', function(e){
        loadPage('#frontPage', location.pathname);
        console.log(e.originalEvent.state);
    });
}(jQuery));

PHP header redirect 301 - what are the implications?

Make sure you die() after your redirection, and make sure you do your redirect AS SOON AS POSSIBLE while your script executes. It makes sure that no more database queries (if some) are not wasted for nothing. That's the one tip I can give you

For search engines, 301 is the best response code

Replace a string in shell script using a variable

To let your shell expand the variable, you need to use double-quotes like

sed -i "s#12345678#$replace#g" file.txt

This will break if $replace contain special sed characters (#, \). But you can preprocess $replace to quote them:

replace_quoted=$(printf '%s' "$replace" | sed 's/[#\]/\\\0/g')
sed -i "s#12345678#$replace_quoted#g" file.txt

Inner join with count() on three tables

It makes more sense to join the item with the orders than with the people !

SELECT
    people.pe_name,
    COUNT(distinct orders.ord_id) AS num_orders,
    COUNT(items.item_id) AS num_items
FROM
    people
    INNER JOIN orders ON orders.pe_id = people.pe_id
         INNER JOIN items ON items.ord_id = orders.ord_id
GROUP BY
    people.pe_id;

Joining the items with the people provokes a lot of doublons. For example, the cake items in order 3 will be linked with the order 2 via the join between the people, and you don't want this to happen !!

So :

1- You need a good understanding of your schema. Items are link to orders, and not to people.

2- You need to count distinct orders for one person, else you will count as many items as orders.

kill a process in bash

It is not clear to me what you mean by "escape an executable which is running", but ctrl-z will put a process into the background and return control to the command line. You can then use the fg command to bring the program back into the foreground.

How can I find matching values in two arrays?

Done as a answer so I can do formatting...

This is the the process you need to go through. Looping through an array for the specifics.

create an empty array
loop through array1, element by element. {
  loop through array2, element by element {
    if array1.element == array2.element {
      add to your new array
    }
  }
}

new Runnable() but no new thread?

Shouldn't creating a new Runnable class make a new second thread?

No. new Runnable does not create second Thread.

What is the purpose of the Runnable class here apart from being able to pass a Runnable class to postAtTime?

Runnable is posted to Handler. This task runs in the thread, which is associated with Handler.

If Handler is associated with UI Thread, Runnable runs in UI Thread.

If Handler is associated with other HandlerThread, Runnable runs in HandlerThread


To explicitly associate Handler to your MainThread ( UI Thread), write below code.

Handler  mHandler = new Handler(Looper.getMainLooper();

If you write is as below, it uses HandlerThread Looper.

HandlerThread handlerThread = new HandlerThread("HandlerThread");
handlerThread.start();
Handler requestHandler = new Handler(handlerThread.getLooper());

Trim to remove white space

No need for jQuery

JavaScript does have a native .trim() method.

var name = "    John Smith  ";
name = name.trim();

console.log(name); // "John Smith"

Example Here

String.prototype.trim()

The trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).

JavaScript hashmap equivalent

Adding yet another solution: HashMap is pretty much the first class I ported from Java to JavaScript. You could say there is a lot of overhead, but the implementation is almost 100% equal to Java's implementation and includes all interfaces and subclasses.

The project can be found here: https://github.com/Airblader/jsava I'll also attach the (current) source code for the HashMap class, but as stated it also depends on the super class, etc. The OOP framework used is qooxdoo.

Please note that this code is already out-dated and refer to the GitHub project for the current work. As of writing this, there is also an ArrayList implementation.

qx.Class.define( 'jsava.util.HashMap', {
    extend: jsava.util.AbstractMap,
    implement: [jsava.util.Map, jsava.io.Serializable, jsava.lang.Cloneable],

    construct: function () {
        var args = Array.prototype.slice.call( arguments ),
            initialCapacity = this.self( arguments ).DEFAULT_INITIAL_CAPACITY,
            loadFactor = this.self( arguments ).DEFAULT_LOAD_FACTOR;

        switch( args.length ) {
            case 1:
                if( qx.Class.implementsInterface( args[0], jsava.util.Map ) ) {
                    initialCapacity = Math.max( ((args[0].size() / this.self( arguments ).DEFAULT_LOAD_FACTOR) | 0) + 1,
                        this.self( arguments ).DEFAULT_INITIAL_CAPACITY );
                    loadFactor = this.self( arguments ).DEFAULT_LOAD_FACTOR;
                } else {
                    initialCapacity = args[0];
                }
                break;
            case 2:
                initialCapacity = args[0];
                loadFactor = args[1];
                break;
        }

        if( initialCapacity < 0 ) {
            throw new jsava.lang.IllegalArgumentException( 'Illegal initial capacity: ' + initialCapacity );
        }
        if( initialCapacity > this.self( arguments ).MAXIMUM_CAPACITY ) {
            initialCapacity = this.self( arguments ).MAXIMUM_CAPACITY;
        }
        if( loadFactor <= 0 || isNaN( loadFactor ) ) {
            throw new jsava.lang.IllegalArgumentException( 'Illegal load factor: ' + loadFactor );
        }

        var capacity = 1;
        while( capacity < initialCapacity ) {
            capacity <<= 1;
        }

        this._loadFactor = loadFactor;
        this._threshold = (capacity * loadFactor) | 0;
        this._table = jsava.JsavaUtils.emptyArrayOfGivenSize( capacity, null );
        this._init();
    },

    statics: {
        serialVersionUID: 1,

        DEFAULT_INITIAL_CAPACITY: 16,
        MAXIMUM_CAPACITY: 1 << 30,
        DEFAULT_LOAD_FACTOR: 0.75,

        _hash: function (hash) {
            hash ^= (hash >>> 20) ^ (hash >>> 12);
            return hash ^ (hash >>> 7) ^ (hash >>> 4);
        },

        _indexFor: function (hashCode, length) {
            return hashCode & (length - 1);
        },

        Entry: qx.Class.define( 'jsava.util.HashMap.Entry', {
            extend: jsava.lang.Object,
            implement: [jsava.util.Map.Entry],

            construct: function (hash, key, value, nextEntry) {
                this._value = value;
                this._next = nextEntry;
                this._key = key;
                this._hash = hash;
            },

            members: {
                _key: null,
                _value: null,
                /** @type jsava.util.HashMap.Entry */
                _next: null,
                /** @type Number */
                _hash: 0,

                getKey: function () {
                    return this._key;
                },

                getValue: function () {
                    return this._value;
                },

                setValue: function (newValue) {
                    var oldValue = this._value;
                    this._value = newValue;
                    return oldValue;
                },

                equals: function (obj) {
                    if( obj === null || !qx.Class.implementsInterface( obj, jsava.util.HashMap.Entry ) ) {
                        return false;
                    }

                    /** @type jsava.util.HashMap.Entry */
                    var entry = obj,
                        key1 = this.getKey(),
                        key2 = entry.getKey();
                    if( key1 === key2 || (key1 !== null && key1.equals( key2 )) ) {
                        var value1 = this.getValue(),
                            value2 = entry.getValue();
                        if( value1 === value2 || (value1 !== null && value1.equals( value2 )) ) {
                            return true;
                        }
                    }

                    return false;
                },

                hashCode: function () {
                    return (this._key === null ? 0 : this._key.hashCode()) ^
                        (this._value === null ? 0 : this._value.hashCode());
                },

                toString: function () {
                    return this.getKey() + '=' + this.getValue();
                },

                /**
                 * This method is invoked whenever the value in an entry is
                 * overwritten by an invocation of put(k,v) for a key k that's already
                 * in the HashMap.
                 */
                _recordAccess: function (map) {
                },

                /**
                 * This method is invoked whenever the entry is
                 * removed from the table.
                 */
                _recordRemoval: function (map) {
                }
            }
        } )
    },

    members: {
        /** @type jsava.util.HashMap.Entry[] */
        _table: null,
        /** @type Number */
        _size: 0,
        /** @type Number */
        _threshold: 0,
        /** @type Number */
        _loadFactor: 0,
        /** @type Number */
        _modCount: 0,
        /** @implements jsava.util.Set */
        __entrySet: null,

        /**
         * Initialization hook for subclasses. This method is called
         * in all constructors and pseudo-constructors (clone, readObject)
         * after HashMap has been initialized but before any entries have
         * been inserted.  (In the absence of this method, readObject would
         * require explicit knowledge of subclasses.)
         */
        _init: function () {
        },

        size: function () {
            return this._size;
        },

        isEmpty: function () {
            return this._size === 0;
        },

        get: function (key) {
            if( key === null ) {
                return this.__getForNullKey();
            }

            var hash = this.self( arguments )._hash( key.hashCode() );
            for( var entry = this._table[this.self( arguments )._indexFor( hash, this._table.length )];
                 entry !== null; entry = entry._next ) {
                /** @type jsava.lang.Object */
                var k;
                if( entry._hash === hash && ((k = entry._key) === key || key.equals( k )) ) {
                    return entry._value;
                }
            }

            return null;
        },

        __getForNullKey: function () {
            for( var entry = this._table[0]; entry !== null; entry = entry._next ) {
                if( entry._key === null ) {
                    return entry._value;
                }
            }

            return null;
        },

        containsKey: function (key) {
            return this._getEntry( key ) !== null;
        },

        _getEntry: function (key) {
            var hash = (key === null) ? 0 : this.self( arguments )._hash( key.hashCode() );
            for( var entry = this._table[this.self( arguments )._indexFor( hash, this._table.length )];
                 entry !== null; entry = entry._next ) {
                /** @type jsava.lang.Object */
                var k;
                if( entry._hash === hash
                    && ( ( k = entry._key ) === key || ( key !== null && key.equals( k ) ) ) ) {
                    return entry;
                }
            }

            return null;
        },

        put: function (key, value) {
            if( key === null ) {
                return this.__putForNullKey( value );
            }

            var hash = this.self( arguments )._hash( key.hashCode() ),
                i = this.self( arguments )._indexFor( hash, this._table.length );
            for( var entry = this._table[i]; entry !== null; entry = entry._next ) {
                /** @type jsava.lang.Object */
                var k;
                if( entry._hash === hash && ( (k = entry._key) === key || key.equals( k ) ) ) {
                    var oldValue = entry._value;
                    entry._value = value;
                    entry._recordAccess( this );
                    return oldValue;
                }
            }

            this._modCount++;
            this._addEntry( hash, key, value, i );
            return null;
        },

        __putForNullKey: function (value) {
            for( var entry = this._table[0]; entry !== null; entry = entry._next ) {
                if( entry._key === null ) {
                    var oldValue = entry._value;
                    entry._value = value;
                    entry._recordAccess( this );
                    return oldValue;
                }
            }

            this._modCount++;
            this._addEntry( 0, null, value, 0 );
            return null;
        },

        __putForCreate: function (key, value) {
            var hash = (key === null) ? 0 : this.self( arguments )._hash( key.hashCode() ),
                i = this.self( arguments )._indexFor( hash, this._table.length );
            for( var entry = this._table[i]; entry !== null; entry = entry._next ) {
                /** @type jsava.lang.Object */
                var k;
                if( entry._hash === hash
                    && ( (k = entry._key) === key || ( key !== null && key.equals( k ) ) ) ) {
                    entry._value = value;
                    return;
                }
            }

            this._createEntry( hash, key, value, i );
        },

        __putAllForCreate: function (map) {
            var iterator = map.entrySet().iterator();
            while( iterator.hasNext() ) {
                var entry = iterator.next();
                this.__putForCreate( entry.getKey(), entry.getValue() );
            }
        },

        _resize: function (newCapacity) {
            var oldTable = this._table,
                oldCapacity = oldTable.length;
            if( oldCapacity === this.self( arguments ).MAXIMUM_CAPACITY ) {
                this._threshold = Number.MAX_VALUE;
                return;
            }

            var newTable = jsava.JsavaUtils.emptyArrayOfGivenSize( newCapacity, null );
            this._transfer( newTable );
            this._table = newTable;
            this._threshold = (newCapacity * this._loadFactor) | 0;
        },

        _transfer: function (newTable) {
            var src = this._table,
                newCapacity = newTable.length;
            for( var j = 0; j < src.length; j++ ) {
                var entry = src[j];
                if( entry !== null ) {
                    src[j] = null;
                    do {
                        var next = entry._next,
                            i = this.self( arguments )._indexFor( entry._hash, newCapacity );
                        entry._next = newTable[i];
                        newTable[i] = entry;
                        entry = next;
                    } while( entry !== null );
                }
            }
        },

        putAll: function (map) {
            var numKeyToBeAdded = map.size();
            if( numKeyToBeAdded === 0 ) {
                return;
            }

            if( numKeyToBeAdded > this._threshold ) {
                var targetCapacity = (numKeyToBeAdded / this._loadFactor + 1) | 0;
                if( targetCapacity > this.self( arguments ).MAXIMUM_CAPACITY ) {
                    targetCapacity = this.self( arguments ).MAXIMUM_CAPACITY;
                }

                var newCapacity = this._table.length;
                while( newCapacity < targetCapacity ) {
                    newCapacity <<= 1;
                }
                if( newCapacity > this._table.length ) {
                    this._resize( newCapacity );
                }
            }

            var iterator = map.entrySet().iterator();
            while( iterator.hasNext() ) {
                var entry = iterator.next();
                this.put( entry.getKey(), entry.getValue() );
            }
        },

        remove: function (key) {
            var entry = this._removeEntryForKey( key );
            return entry === null ? null : entry._value;
        },

        _removeEntryForKey: function (key) {
            var hash = (key === null) ? 0 : this.self( arguments )._hash( key.hashCode() ),
                i = this.self( arguments )._indexFor( hash, this._table.length ),
                prev = this._table[i],
                entry = prev;

            while( entry !== null ) {
                var next = entry._next,
                    /** @type jsava.lang.Object */
                        k;
                if( entry._hash === hash
                    && ( (k = entry._key) === key || ( key !== null && key.equals( k ) ) ) ) {
                    this._modCount++;
                    this._size--;
                    if( prev === entry ) {
                        this._table[i] = next;
                    } else {
                        prev._next = next;
                    }
                    entry._recordRemoval( this );
                    return entry;
                }
                prev = entry;
                entry = next;
            }

            return entry;
        },

        _removeMapping: function (obj) {
            if( obj === null || !qx.Class.implementsInterface( obj, jsava.util.Map.Entry ) ) {
                return null;
            }

            /** @implements jsava.util.Map.Entry */
            var entry = obj,
                key = entry.getKey(),
                hash = (key === null) ? 0 : this.self( arguments )._hash( key.hashCode() ),
                i = this.self( arguments )._indexFor( hash, this._table.length ),
                prev = this._table[i],
                e = prev;

            while( e !== null ) {
                var next = e._next;
                if( e._hash === hash && e.equals( entry ) ) {
                    this._modCount++;
                    this._size--;
                    if( prev === e ) {
                        this._table[i] = next;
                    } else {
                        prev._next = next;
                    }
                    e._recordRemoval( this );
                    return e;
                }
                prev = e;
                e = next;
            }

            return e;
        },

        clear: function () {
            this._modCount++;
            var table = this._table;
            for( var i = 0; i < table.length; i++ ) {
                table[i] = null;
            }
            this._size = 0;
        },

        containsValue: function (value) {
            if( value === null ) {
                return this.__containsNullValue();
            }

            var table = this._table;
            for( var i = 0; i < table.length; i++ ) {
                for( var entry = table[i]; entry !== null; entry = entry._next ) {
                    if( value.equals( entry._value ) ) {
                        return true;
                    }
                }
            }

            return false;
        },

        __containsNullValue: function () {
            var table = this._table;
            for( var i = 0; i < table.length; i++ ) {
                for( var entry = table[i]; entry !== null; entry = entry._next ) {
                    if( entry._value === null ) {
                        return true;
                    }
                }
            }

            return false;
        },

        clone: function () {
            /** @type jsava.util.HashMap */
            var result = null;
            try {
                result = this.base( arguments );
            } catch( e ) {
                if( !qx.Class.isSubClassOf( e.constructor, jsava.lang.CloneNotSupportedException ) ) {
                    throw e;
                }
            }

            result._table = jsava.JsavaUtils.emptyArrayOfGivenSize( this._table.length, null );
            result.__entrySet = null;
            result._modCount = 0;
            result._size = 0;
            result._init();
            result.__putAllForCreate( this );

            return result;
        },

        _addEntry: function (hash, key, value, bucketIndex) {
            var entry = this._table[bucketIndex];
            this._table[bucketIndex] = new (this.self( arguments ).Entry)( hash, key, value, entry );
            if( this._size++ >= this._threshold ) {
                this._resize( 2 * this._table.length );
            }
        },

        _createEntry: function (hash, key, value, bucketIndex) {
            var entry = this._table[bucketIndex];
            this._table[bucketIndex] = new (this.self( arguments ).Entry)( hash, key, value, entry );
            this._size++;
        },

        keySet: function () {
            var keySet = this._keySet;
            return keySet !== null ? keySet : ( this._keySet = new this.KeySet( this ) );
        },

        values: function () {
            var values = this._values;
            return values !== null ? values : ( this._values = new this.Values( this ) );
        },

        entrySet: function () {
            return this.__entrySet0();
        },

        __entrySet0: function () {
            var entrySet = this.__entrySet;
            return entrySet !== null ? entrySet : ( this.__entrySet = new this.EntrySet( this ) );
        },

        /** @private */
        HashIterator: qx.Class.define( 'jsava.util.HashMap.HashIterator', {
            extend: jsava.lang.Object,
            implement: [jsava.util.Iterator],

            type: 'abstract',

            /** @protected */
            construct: function (thisHashMap) {
                this.__thisHashMap = thisHashMap;
                this._expectedModCount = this.__thisHashMap._modCount;
                if( this.__thisHashMap._size > 0 ) {
                    var table = this.__thisHashMap._table;
                    while( this._index < table.length && ( this._next = table[this._index++] ) === null ) {
                        // do nothing
                    }
                }
            },

            members: {
                __thisHashMap: null,

                /** @type jsava.util.HashMap.Entry */
                _next: null,
                /** @type Number */
                _expectedModCount: 0,
                /** @type Number */
                _index: 0,
                /** @type jsava.util.HashMap.Entry */
                _current: null,

                hasNext: function () {
                    return this._next !== null;
                },

                _nextEntry: function () {
                    if( this.__thisHashMap._modCount !== this._expectedModCount ) {
                        throw new jsava.lang.ConcurrentModificationException();
                    }

                    var entry = this._next;
                    if( entry === null ) {
                        throw new jsava.lang.NoSuchElementException();
                    }

                    if( (this._next = entry._next) === null ) {
                        var table = this.__thisHashMap._table;
                        while( this._index < table.length && ( this._next = table[this._index++] ) === null ) {
                            // do nothing
                        }
                    }

                    this._current = entry;
                    return entry;
                },

                remove: function () {
                    if( this._current === null ) {
                        throw new jsava.lang.IllegalStateException();
                    }

                    if( this.__thisHashMap._modCount !== this._expectedModCount ) {
                        throw new jsava.lang.ConcurrentModificationException();
                    }

                    var key = this._current._key;
                    this._current = null;
                    this.__thisHashMap._removeEntryForKey( key );
                    this._expectedModCount = this.__thisHashMap._modCount;
                }
            }
        } ),

        _newKeyIterator: function () {
            return new this.KeyIterator( this );
        },

        _newValueIterator: function () {
            return new this.ValueIterator( this );
        },

        _newEntryIterator: function () {
            return new this.EntryIterator( this );
        },

        /** @private */
        ValueIterator: qx.Class.define( 'jsava.util.HashMap.ValueIterator', {
            extend: jsava.util.HashMap.HashIterator,

            construct: function (thisHashMap) {
                this.base( arguments, thisHashMap );
            },

            members: {
                next: function () {
                    return this._nextEntry()._value;
                }
            }
        } ),

        /** @private */
        KeyIterator: qx.Class.define( 'jsava.util.HashMap.KeyIterator', {
            extend: jsava.util.HashMap.HashIterator,

            construct: function (thisHashMap) {
                this.base( arguments, thisHashMap );
            },

            members: {
                next: function () {
                    return this._nextEntry().getKey();
                }
            }
        } ),

        /** @private */
        EntryIterator: qx.Class.define( 'jsava.util.HashMap.EntryIterator', {
            extend: jsava.util.HashMap.HashIterator,

            construct: function (thisHashMap) {
                this.base( arguments, thisHashMap );
            },

            members: {
                next: function () {
                    return this._nextEntry();
                }
            }
        } ),

        /** @private */
        KeySet: qx.Class.define( 'jsava.util.HashMap.KeySet', {
            extend: jsava.util.AbstractSet,

            construct: function (thisHashMap) {
                this.base( arguments );
                this.__thisHashMap = thisHashMap;
            },

            members: {
                __thisHashMap: null,

                iterator: function () {
                    return this.__thisHashMap._newKeyIterator();
                },

                size: function () {
                    return this.__thisHashMap._size;
                },

                contains: function (obj) {
                    return this.__thisHashMap.containsKey( obj );
                },

                remove: function (obj) {
                    return this.__thisHashMap._removeEntryForKey( obj ) !== null;
                },

                clear: function () {
                    this.__thisHashMap.clear();
                }
            }
        } ),

        /** @private */
        Values: qx.Class.define( 'jsava.util.HashMap.Values', {
            extend: jsava.util.AbstractCollection,

            construct: function (thisHashMap) {
                this.base( arguments );
                this.__thisHashMap = thisHashMap;
            },

            members: {
                __thisHashMap: null,

                iterator: function () {
                    return this.__thisHashMap._newValueIterator();
                },

                size: function () {
                    return this.__thisHashMap._size;
                },

                contains: function (obj) {
                    return this.__thisHashMap.containsValue( obj );
                },

                clear: function () {
                    this.__thisHashMap.clear();
                }
            }
        } ),

        /** @private */
        EntrySet: qx.Class.define( 'jsava.util.HashMap.EntrySet', {
            extend: jsava.util.AbstractSet,

            construct: function (thisHashMap) {
                this.base( arguments );
                this.__thisHashMap = thisHashMap;
            },

            members: {
                __thisHashMap: null,

                iterator: function () {
                    return this.__thisHashMap._newEntryIterator();
                },

                size: function () {
                    return this.__thisHashMap._size;
                },

                contains: function (obj) {
                    if( obj === null || !qx.Class.implementsInterface( obj, jsava.util.Map.Entry ) ) {
                        return false;
                    }

                    /** @implements jsava.util.Map.Entry */
                    var entry = obj,
                        candidate = this.__thisHashMap._getEntry( entry.getKey() );
                    return candidate !== null && candidate.equals( entry );
                },

                remove: function (obj) {
                    return this.__thisHashMap._removeMapping( obj ) !== null;
                },

                clear: function () {
                    this.__thisHashMap.clear();
                }
            }
        } )
    }
} );

How to install "make" in ubuntu?

I have no idea what linux distribution "ubuntu centOS" is. Ubuntu and CentOS are two different distributions.

To answer the question in the header: To install make in ubuntu you have to install build-essentials

sudo apt-get install build-essential

Creating C formatted strings (not printing them)

Use sprintf.

int sprintf ( char * str, const char * format, ... );

Write formatted data to string Composes a string with the same text that would be printed if format was used on printf, but instead of being printed, the content is stored as a C string in the buffer pointed by str.

The size of the buffer should be large enough to contain the entire resulting string (see snprintf for a safer version).

A terminating null character is automatically appended after the content.

After the format parameter, the function expects at least as many additional arguments as needed for format.

Parameters:

str

Pointer to a buffer where the resulting C-string is stored. The buffer should be large enough to contain the resulting string.

format

C string that contains a format string that follows the same specifications as format in printf (see printf for details).

... (additional arguments)

Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string (or a pointer to a storage location, for n). There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function.

Example:

// Allocates storage
char *hello_world = (char*)malloc(13 * sizeof(char));
// Prints "Hello world!" on hello_world
sprintf(hello_world, "%s %s!", "Hello", "world");

Inconsistent accessibility: property type is less accessible

Your Delivery class is internal (the default visibility for classes), however the property (and presumably the containing class) are public, so the property is more accessible than the Delivery class. You need to either make Delivery public, or restrict the visibility of the thelivery property.

Set SSH connection timeout

The problem may be that ssh is trying to connect to all the different IPs that www.google.com resolves to. For example on my machine:

# ssh -v -o ConnectTimeout=1 -o ConnectionAttempts=1 www.google.com
OpenSSH_5.9p1, OpenSSL 0.9.8t 18 Jan 2012
debug1: Connecting to www.google.com [173.194.43.20] port 22.
debug1: connect to address 173.194.43.20 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.19] port 22.
debug1: connect to address 173.194.43.19 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.18] port 22.
debug1: connect to address 173.194.43.18 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.17] port 22.
debug1: connect to address 173.194.43.17 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.16] port 22.
debug1: connect to address 173.194.43.16 port 22: Connection timed out
ssh: connect to host www.google.com port 22: Connection timed out

If I run it with a specific IP, it returns much faster.

EDIT: I've timed it (with time) and the results are:

  • www.google.com - 5.086 seconds
  • 173.94.43.16 - 1.054 seconds

How to uninstall Ruby from /usr/local?

sudo make uninstall did the trick for me using the Ruby 2.4 tar from the official downloads page.

C# '@' before a String

It means to interpret the string literally (that is, you cannot escape any characters within the string if you use the @ prefix). It enhances readability in cases where it can be used.

For example, if you were working with a UNC path, this:

@"\\servername\share\folder"

is nicer than this:

"\\\\servername\\share\\folder"

How to hide form code from view code/inspect element browser?

While I don't think there is a way to fully do this you can take a few measures to stop almost everyone from viewing the HTML.

You can first of all try and stop the inspect menu by doing the following:

<body oncontextmenu="return false" onkeydown="return false;" onmousedown="return false;">

I would also suggest using the method that Jonas gave of using his javascript and putting what you don't want people to see in a div with id="element-to-hide" and his given js script to furthermore stop people from inspecting.

I'm pretty sure that it's quite hard to get past that. But then someone can just type view-source:www.exapmle.com and that will show them the source. So you will then probably want to encrypt the HTML(I would advise using a website that gives you an extended security option). There are plenty of good websites that do this for free (eg:http://www.smartgb.com/free_encrypthtml.php) and use extended security which you can't usually unencrypt through HTML un encryptors.

This will basically encrypt your HTML so if you view the source using the method I showed above you will just get encrypted HTML(that is also extremely difficult to unencrypt if you used the extended security option). But you can view the unencrypted HTML through inspecting but we have already blocked that(to a very reasonable extent)

Ok so you can't fully hide the HTML but you can do an extremely good job at stopping people seeing it.(If you think about it most people don't care about looking at a page's HTML, some people don't even know about inspecting and viewing the source and the people who do probably won't be bothered or won't be able to get past theses implications! So probably no one will see you HTML)

(Hope this helps!)

Python Array with String Indices

What you want is called an associative array. In python these are called dictionaries.

Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.

myDict = {}
myDict["john"] = "johns value"
myDict["jeff"] = "jeffs value"

Alternative way to create the above dict:

myDict = {"john": "johns value", "jeff": "jeffs value"}

Accessing values:

print(myDict["jeff"]) # => "jeffs value"

Getting the keys (in Python v2):

print(myDict.keys()) # => ["john", "jeff"]

In Python 3, you'll get a dict_keys, which is a view and a bit more efficient (see views docs and PEP 3106 for details).

print(myDict.keys()) # => dict_keys(['john', 'jeff']) 

If you want to learn about python dictionary internals, I recommend this ~25 min video presentation: https://www.youtube.com/watch?v=C4Kc8xzcA68. It's called the "The Mighty Dictionary".

Capitalize first letter. MySQL

This should work nicely:

UPDATE tb_Company SET CompanyIndustry = 
CONCAT(UPPER(LEFT(CompanyIndustry, 1)), SUBSTRING(CompanyIndustry, 2))

Get current NSDate in timestamp format

If you need time stamp as a string.

time_t result = time(NULL);                
NSString *timeStampString = [@(result) stringValue];

Click event on select option element in chrome

I know that this code snippet works for recognizing an option click (at least in Chrome and FF). Furthermore, it works if the element wasn't there on DOM load. I usually use this when I input sections of inputs into a single select element and I don't want the section title to be clicked.

$(document).on('click', 'option[value="disableme"]', function(){
    $('option[value="disableme"]').prop("selected", false);
});

JQuery show/hide when hover

This code also works.

_x000D_
_x000D_
$(".circle").hover(function() {$(this).hide(200).show(200);});
_x000D_
.circle{_x000D_
    width:100px;_x000D_
    height:100px;_x000D_
    border-radius:50px;_x000D_
    font-size:20px;_x000D_
    color:black;_x000D_
    line-height:100px;_x000D_
    text-align:center;_x000D_
    background:yellow_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>_x000D_
<div class="circle">hover me</div>
_x000D_
_x000D_
_x000D_

Eclipse won't compile/run java file

right click somewhere on the file or in project explorer and choose 'run as'->'java application'

HTTP Status 500 - Servlet.init() for servlet Dispatcher threw exception

You map your dispatcher on *.do:

<servlet-mapping>
   <servlet-name>Dispatcher</servlet-name>
   <url-pattern>*.do</url-pattern>
</servlet-mapping>

but your controller is mapped on an url without .do:

@RequestMapping("/editPresPage")

Try changing this to:

@RequestMapping("/editPresPage.do")

How to horizontally center a floating element of a variable width?

for 50% element

width: 50%;
display: block;
float: right;
margin-right: 25%;

MongoDB query with an 'or' condition

db.Lead.find(

{"name": {'$regex' : '.*' + "Ravi" + '.*'}},
{
"$or": [{
    'added_by':"[email protected]"
}, {
    'added_by':"[email protected]"
}]
}

);

twitter bootstrap navbar fixed top overlapping site

I just wrapped the navbar in a

<div width="100%">
<div class="nav-? ??">
...
</nav>
</div>

No fancy hocus pocus but it worked..

How to disable/enable select field using jQuery?

Your select doesn't have an ID, only a name. You'll need to modify your selector:

$("#pizza").on("click", function(){
  $("select[name='pizza_kind']").prop("disabled", !this.checked);
});

Demo: http://jsbin.com/imokuj/2/edit

What's the best way to iterate an Android Cursor?

Initially cursor is not on the first row show using moveToNext() you can iterate the cursor when record is not exist then it return false,unless it return true,

while (cursor.moveToNext()) {
    ...
}

SSH to AWS Instance without key pairs

Answer to Question 1

Here's what I did on a Ubuntu EC2:

A) Login as root using the keypairs

B) Setup the necessary users and their passwords with

# sudo adduser USERNAME
# sudo passwd USERNAME

C) Edit /etc/ssh/sshd_config setting

For a valid user to login with no key

PasswordAuthentication yes

Also want root to login also with no key

PermitRootLogin yes

D) Restart the ssh daemon with

# sudo service ssh restart

just change ssh to sshd if you are using centOS

Now you can login into your ec2 instance without key pairs.

How to find a value in an array of objects in JavaScript?

We use object-scan for most of our data processing. It's conceptually very simple, but allows for a lot of cool stuff. Here is how you would solve your question

_x000D_
_x000D_
// const objectScan = require('object-scan');

const findDinner = (dinner, data) => objectScan(['*'], {
  abort: true,
  rtn: 'value',
  filterFn: ({ value }) => value.dinner === dinner
})(data);

const data = { 1: { name: 'bob', dinner: 'pizza' }, 2: { name: 'john', dinner: 'sushi' }, 3: { name: 'larry', dinner: 'hummus' } };

console.log(findDinner('sushi', data));
// => { name: 'john', dinner: 'sushi' }
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
_x000D_
_x000D_

Disclaimer: I'm the author of object-scan

Error: [$injector:unpr] Unknown provider: $routeProvider

In angular 1.4 +, in addition to adding the dependency

angular.module('myApp', ['ngRoute'])

,we also need to reference the separate angular-route.js file

<script src="angular.js">
<script src="angular-route.js">

see https://docs.angularjs.org/api/ngRoute

How do I prevent a form from being resized by the user?

To prevent users from resizing, set the FormBoderStyle to Fixed3D or FixedDialog from properties window or from code

frmYour.BorderStyle = System.WinForms.FormBorderStyle.Fixed3D

And set the WindowState property to Maximized, set the MaximizeBox and MinimizeBox properties to false.

To prevent the user from moving around, override WndProc

Protected Overrides Sub WndProc(ByRef m As Message)
        Const WM_NCLBUTTONDOWN As Integer = 161
        Const WM_SYSCOMMAND As Integer = 274
        Const HTCAPTION As Integer = 2
        Const SC_MOVE As Integer = 61456

        If (m.Msg = WM_SYSCOMMAND) And (m.WParam.ToInt32() = SC_MOVE) Then
            Return
        End If

        If (m.Msg = WM_NCLBUTTONDOWN) And (m.WParam.ToInt32() = HTCAPTION) Then
            Return
        End If

        MyBase.WndProc(m)
    End Sub

Search for highest key/index in an array

This should work fine

$arr = array( 1 => "A", 10 => "B", 5 => "C" );
max(array_keys($arr));

How do I make curl ignore the proxy?

First, I listed the current proxy setting with

env | sort | less

(should be something like http_proxy=http://wpad.local.machine.location:port number)

Then I tried setting

export http_proxy=";" 

which gave this error message:

curl: (5) Couldn't resolve proxy ';'

Tried

export http_proxy="" && curl http://servername:portnumber/destinationpath/ -d 55

and it worked!

PS! Remember to set http-proxy back to its original settings with

export http_proxy=http://wpad.local.machine.location:port number

When should we call System.exit in Java

The method never returns because it's the end of the world and none of your code is going to be executed next.

Your application, in your example, would exit anyway at the same spot in the code, but, if you use System.exit. you have the option of returning a custom code to the enviroment, like, say

System.exit(42);

Who is going to make use of your exit code? A script that called the application. Works in Windows, Unix and all other scriptable environments.

Why return a code? To say things like "I did not succeed", "The database did not answer".

To see how to get the value od an exit code and use it in a unix shell script or windows cmd script, you might check this answer on this site

error LNK2005, already defined?

If you want both to reference the same variable, one of them should have int k;, and the other should have extern int k;

For this situation, you typically put the definition (int k;) in one .cpp file, and put the declaration (extern int k;) in a header, to be included wherever you need access to that variable.

If you want each k to be a separate variable that just happen to have the same name, you can either mark them as static, like: static int k; (in all files, or at least all but one file). Alternatively, you can us an anonymous namespace:

namespace { 
   int k;
};

Again, in all but at most one of the files.

In C, the compiler generally isn't quite so picky about this. Specifically, C has a concept of a "tentative definition", so if you have something like int k; twice (in either the same or separate source files) each will be treated as a tentative definition, and there won't be a conflict between them. This can be a bit confusing, however, because you still can't have two definitions that both include initializers--a definition with an initializer is always a full definition, not a tentative definition. In other words, int k = 1; appearing twice would be an error, but int k; in one place and int k = 1; in another would not. In this case, the int k; would be treated as a tentative definition and the int k = 1; as a definition (and both refer to the same variable).

How does "FOR" work in cmd batch file?

for /f iterates per line input, so in your program will only output first path.

your program treats %PATH% as one-line input, and deliminate by ;, put first result to %%g, then output %%g (first deliminated path).

How to split a string of space separated numbers into integers?

Just use strip() to remove empty spaces and apply explicit int conversion on the variable.

Ex:

a='1  ,  2, 4 ,6 '
f=[int(i.strip()) for i in a]

LINQ to SQL - How to select specific columns and return strongly typed list

Basically you are doing it the right way. However, you should use an instance of the DataContext for querying (it's not obvious that DataContext is an instance or the type name from your query):

var result = (from a in new DataContext().Persons
              where a.Age > 18
              select new Person { Name = a.Name, Age = a.Age }).ToList();

Apparently, the Person class is your LINQ to SQL generated entity class. You should create your own class if you only want some of the columns:

class PersonInformation {
   public string Name {get;set;}
   public int Age {get;set;}
}

var result = (from a in new DataContext().Persons
              where a.Age > 18
              select new PersonInformation { Name = a.Name, Age = a.Age }).ToList();

You can freely swap var with List<PersonInformation> here without affecting anything (as this is what the compiler does).

Otherwise, if you are working locally with the query, I suggest considering an anonymous type:

var result = (from a in new DataContext().Persons
              where a.Age > 18
              select new { a.Name, a.Age }).ToList();

Note that in all of these cases, the result is statically typed (it's type is known at compile time). The latter type is a List of a compiler generated anonymous class similar to the PersonInformation class I wrote above. As of C# 3.0, there's no dynamic typing in the language.

UPDATE:

If you really want to return a List<Person> (which might or might not be the best thing to do), you can do this:

var result = from a in new DataContext().Persons
             where a.Age > 18
             select new { a.Name, a.Age };

List<Person> list = result.AsEnumerable()
                          .Select(o => new Person {
                                           Name = o.Name, 
                                           Age = o.Age
                          }).ToList();

You can merge the above statements too, but I separated them for clarity.

Why catch and rethrow an exception in C#?

In the example in the code you have posted there is, in fact, no point in catching the exception as there is nothing done on the catch it is just re-thown, in fact it does more harm than good as the call stack is lost.

You would, however catch an exception to do some logic (for example closing sql connection of file lock, or just some logging) in the event of an exception the throw it back to the calling code to deal with. This would be more common in a business layer than front end code as you may want the coder implementing your business layer to handle the exception.

To re-iterate though the There is NO point in catching the exception in the example you posted. DON'T do it like that!

How do I check if an array includes a value in JavaScript?

If you are using JavaScript 1.6 or later (Firefox 1.5 or later) you can use Array.indexOf. Otherwise, I think you are going to end up with something similar to your original code.

Notepad++ incrementally replace

Not sure about regex, but there is a way for you to do this in Notepad++, although it isn't very flexible.

In the example that you gave, hold Alt and select the column of numbers that you wish to change. Then go to Edit->Column Editor and select the Number to Insert radio button in the window that appears. Then specify your initial number and increment, and hit OK. It should write out the incremented numbers.

Note: this also works with the Multi-editing feature (selecting several locations while maintaining Ctrl key pressed).

This is, however, not anywhere near the flexibility that most people would find useful. Notepad++ is great, but if you want a truly powerful editor that can do things like this with ease, I'd say use Vim.

How to secure database passwords in PHP?

Put the database password in a file, make it read-only to the user serving the files.

Unless you have some means of only allowing the php server process to access the database, this is pretty much all you can do.

Do Git tags only apply to the current branch?

When calling just git tag <TAGNAME> without any additional parameters, Git will create a new tag from your current HEAD (i.e. the HEAD of your current branch). When adding additional commits into this branch, the branch HEAD will keep up with those new commits, while the tag always refers to the same commit.

When calling git tag <TAGNAME> <COMMIT> you can even specify which commit to use for creating the tag.

Regardless, a tag is still simply a "pointer" to a certain commit (not a branch).

How can I use the apply() function for a single column?

Let me try a complex computation using datetime and considering nulls or empty spaces. I am reducing 30 years on a datetime column and using apply method as well as lambda and converting datetime format. Line if x != '' else x will take care of all empty spaces or nulls accordingly.

df['Date'] = df['Date'].fillna('')
df['Date'] = df['Date'].apply(lambda x : ((datetime.datetime.strptime(str(x), '%m/%d/%Y') - datetime.timedelta(days=30*365)).strftime('%Y%m%d')) if x != '' else x)

NPM doesn't install module dependencies

I suspect you're facing the issue where your package.json file is not in the same directory as your Gruntfile.js. When you run your grunt xxx commands, you get error an message like:

Local Npm module "xxx" not found. Is it installed?

For now, the solution is:

  • Create package.json in the same directory as Gruntfile.js
  • Define the modules required by your grunt project
  • Execute npm install to load them locally
  • Now the required grunt command should work.

IMHO, it is sad that we cannot have grunt resolve modules loaded from a parent npm module (i.e. package.json in a parent directory within the same project). The discussion here seems to indicate that it was done to avoid loading "global" modules but I think what we want is loading from "my project" modules instead.

'git status' shows changed files, but 'git diff' doesn't

I've just run in a similar issue. git diff file showed nothing because I added file to the Git index with some part of its name in uppercase: GeoJSONContainer.js.

Afterwards, I've renamed it to GeoJsonContainer.js and changes stopped being tracked. git diff GeoJsonContainer.js was showing nothing. I had to remove the file from the index with a force flag, and add the file again:

git rm -f GeoJSONContainer.js
git add GeoJSONContainer.js

Angular IE Caching issue for $http

I get it resolved appending datetime as an random number:

$http.get("/your_url?rnd="+new Date().getTime()).success(function(data, status, headers, config) {
    console.log('your get response is new!!!');
});

Is there a function to round a float in C or do I need to write my own?

As Rob mentioned, you probably just want to print the float to 1 decimal place. In this case, you can do something like the following:

#include <stdio.h>
#include <stdlib.h>

int main()
{
  float conver = 45.592346543;
  printf("conver is %0.1f\n",conver);
  return 0;
}

If you want to actually round the stored value, that's a little more complicated. For one, your one-decimal-place representation will rarely have an exact analog in floating-point. If you just want to get as close as possible, something like this might do the trick:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main()
{
  float conver = 45.592346543;
  printf("conver is %0.1f\n",conver);

  conver = conver*10.0f;
  conver = (conver > (floor(conver)+0.5f)) ? ceil(conver) : floor(conver);
  conver = conver/10.0f;

  //If you're using C99 or better, rather than ANSI C/C89/C90, the following will also work.
  //conver = roundf(conver*10.0f)/10.0f;

  printf("conver is now %f\n",conver);
  return 0;
}

I doubt this second example is what you're looking for, but I included it for completeness. If you do require representing your numbers in this way internally, and not just on output, consider using a fixed-point representation instead.

Why GDB jumps unpredictably between lines and prints variables as "<value optimized out>"?

You pretty much can't set the value of found. Debugging optimized programs is rarely worth the trouble, the compiler can rearrange the code in ways that it'll in no way correspond to the source code (other than producing the same result), thus confusing debuggers to no end.

C/C++ line number

You could use a macro with the same behavior as printf(), except that it also includes debug information such as function name, class, and line number:

#include <cstdio>  //needed for printf
#define print(a, args...) printf("%s(%s:%d) " a,  __func__,__FILE__, __LINE__, ##args)
#define println(a, args...) print(a "\n", ##args)

These macros should behave identically to printf(), while including java stacktrace-like information. Here's an example main:

void exampleMethod() {
    println("printf() syntax: string = %s, int = %d", "foobar", 42);
}

int main(int argc, char** argv) {
    print("Before exampleMethod()...\n");
    exampleMethod();
    println("Success!");
}

Which results in the following output:

main(main.cpp:11) Before exampleMethod()...
exampleMethod(main.cpp:7) printf() syntax: string = foobar, int = 42
main(main.cpp:13) Success!