Programs & Examples On #Worksheet function

A worksheet function is represented by a keyword in an Excel formula that performs some action on input and returns output to the calling procedure, either a worksheet cell or another function.

Convert date field into text in Excel

If that is one table and have nothing to do with this - the simplest solution can be copy&paste to notepad then copy&paste back to excel :P

Self-reference for cell, column and row in worksheet functions

My current Column is calculated by:

Method 1:

=LEFT(ADDRESS(ROW(),COLUMN(),4,1),LEN(ADDRESS(ROW(),COLUMN(),4,1))-LEN(ROW()))

Method 2:

=LEFT(ADDRESS(ROW(),COLUMN(),4,1),INT((COLUMN()-1)/26)+1)

My current Row is calculated by:

=RIGHT(ADDRESS(ROW(),COLUMN(),4,1),LEN(ROW()))

so an indirect link to Sheet2!My Column but a different row, specified in Column A on my row is:

Method 1:

=INDIRECT("Sheet2!"&LEFT(ADDRESS(ROW(),COLUMN(),4,1),LEN(ADDRESS(ROW(),COLUMN(),4,1))-LEN(ROW()))&INDIRECT(ADDRESS(ROW(),1,4,1)))

Method 2:

=INDIRECT("Sheet2!"&LEFT(ADDRESS(ROW(),COLUMN(),4,1),INT((COLUMN()-1)/26)+1)&INDIRECT(ADDRESS(ROW(),1,4,1)))

So if A6=3 and my row is 6 and my Col is C returns contents of "Sheet2!C3"

So if A7=1 and my row is 7 and my Col is D returns contents of "Sheet2!D1"

Compare data of two Excel Columns A & B, and show data of Column A that do not exist in B

Suppose you have data in A1:A10 and B1:B10 and you want to highlight which values in A1:A10 do not appear in B1:B10.

Try as follows:

  1. Format > Conditional Formating...
  2. Select 'Formula Is' from drop down menu
  3. Enter the following formula:

    =ISERROR(MATCH(A1,$B$1:$B$10,0))

  4. Now select the format you want to highlight the values in col A that do not appear in col B

This will highlight any value in Col A that does not appear in Col B.

Converting a string to a date in a cell

Have you tried the =DateValue() function?

To include time value, just add the functions together:

=DateValue(A1)+TimeValue(A1)

How to show current user name in a cell?

This displays the name of the current user:

Function Username() As String
    Username = Application.Username
End Function

The property Application.Username holds the name entered with the installation of MS Office.

Enter this formula in a cell:

=Username()

Excel Reference To Current Cell

Inside tables you can use [@] which (unfortunately) Excel automatically expands to Table1[@] but it does work. (I'm using Excel 2010)

For example when having two columns [Change] and [Balance], putting this in the [Balance] column:

=OFFSET([@], -1, 0) + [Change]

Note of course that this depends on the order of the rows (just like most any other solution), so it's a bit fragile.

IF statement: how to leave cell blank if condition is false ("" does not work)

The formula in C1

=IF(A1=1,B1,"")

is either giving an answer of "" (which isn't treated as blank) or the contents of B1.

If you want the formula in D1 to show TRUE if C1 is "" and FALSE if C1 has something else in then use the formula

=IF(C2="",TRUE,FALSE)

instead of ISBLANK

WorksheetFunction.CountA - not working post upgrade to Office 2010

This answer from another forum solved the problem.

(substitute your own range for the "I:I" shown here)

Re: CountA not working in VBA

Should be:

Nonblank = Application.WorksheetFunction.CountA(Range("I:I"))

You have to refer to ranges in the vba format, not the in-excel format.

Excel function to get first word from sentence in other cell

If you want to cater to 1-word cell, use this... based upon astander's

=IFERROR(LEFT(A1,SEARCH(" ",A1)-1),A1)

How to find the first and second maximum number?

If you want the second highest number you can use

=LARGE(E4:E9;2)

although that doesn't account for duplicates so you could get the same result as the Max

If you want the largest number that is smaller than the maximum number you can use this version

=LARGE(E4:E9;COUNTIF(E4:E9;MAX(E4:E9))+1)

I want to compare two lists in different worksheets in Excel to locate any duplicates

Without VBA...

If you can use a helper column, you can use the MATCH function to test if a value in one column exists in another column (or in another column on another worksheet). It will return an Error if there is no match

To simply identify duplicates, use a helper column

Assume data in Sheet1, Column A, and another list in Sheet2, Column A. In your helper column, row 1, place the following formula:

=If(IsError(Match(A1, 'Sheet2'!A:A,False)),"","Duplicate")

Drag/copy this forumla down, and it should identify the duplicates.

To highlight cells, use conditional formatting:

With some tinkering, you can use this MATCH function in a Conditional Formatting rule which would highlight duplicate values. I would probably do this instead of using a helper column, although the helper column is a great way to "see" results before you make the conditional formatting rule.

Something like:

=NOT(ISERROR(MATCH(A1, 'Sheet2'!A:A,FALSE)))

Conditional formatting for Excel 2010

For Excel 2007 and prior, you cannot use conditional formatting rules that reference other worksheets. In this case, use the helper column and set your formatting rule in column A like:

=B1="Duplicate"

This screenshot is from the 2010 UI, but the same rule should work in 2007/2003 Excel.

Conditional formatting using helper column for rule

How to import data from one sheet to another

Saw this thread while looking for something else and I know it is super old, but I wanted to add my 2 cents.

NEVER USE VLOOKUP. It's one of the worst performing formulas in excel. Use index match instead. It even works without sorting data, unless you have a -1 or 1 in the end of the match formula (explained more below)

Here is a link with the appropriate formulas.

The Sheet 2 formula would be this: =IF(A2="","",INDEX(Sheet1!B:B,MATCH($A2,Sheet1!$A:$A,0)))

  • IF(A2="","", means if A2 is blank, return a blank value
  • INDEX(Sheet1!B:B, is saying INDEX B:B where B:B is the data you want to return. IE the name column.
  • Match(A2, is saying to Match A2 which is the ID you want to return the Name for.
  • Sheet1!A:A, is saying you want to match A2 to the ID column in the previous sheet
  • ,0)) is specifying you want an exact value. 0 means return an exact match to A2, -1 means return smallest value greater than or equal to A2, 1 means return the largest value that is less than or equal to A2. Keep in mind -1 and 1 have to be sorted.

More information on the Index/Match formula

Other fun facts: $ means absolute in a formula. So if you specify $B$1 when filling a formula down or over keeps that same value. If you over $B1, the B remains the same across the formula, but if you fill down, the 1 increases with the row count. Likewise, if you used B$1, filling to the right will increment the B, but keep the reference of row 1.

I also included the use of indirect in the second section. What indirect does is allow you to use the text of another cell in a formula. Since I created a named range sheet1!A:A = ID, sheet1!B:B = Name, and sheet1!C:C=Price, I can use the column name to have the exact same formula, but it uses the column heading to change the search criteria.

Good luck! Hope this helps.

Filter an array using a formula (without VBA)

Sounds like you're just trying to do a classic two-column lookup. http://www.dailydoseofexcel.com/archives/2009/04/21/vlookup-on-two-columns/

Tons of solutions for this, most simple is probably the following (which doesn't require an array formula):

=SUMPRODUCT((Lookup!A:A=Param!A1)*(Lookup!B:B=Param!B1)*(Lookup!C:C))

To translate your specific example, you would use:

=SUMPRODUCT((A1:A3=A2)*(B1:B3="B")*(C1:C3))

Refer to a cell in another worksheet by referencing the current worksheet's name?

Still using indirect. Say your A1 cell is your variable that will contain the name of the referenced sheet (Jan). If you go by:

=INDIRECT(CONCATENATE("'",A1," Item'", "!J3"))

Then you will have the 'Jan Item'!J3 value.

`IF` statement with 3 possible answers each based on 3 different ranges

Your formula should be of the form =IF(X2 >= 85,0.559,IF(X2 >= 80,0.327,IF(X2 >=75,0.255,0))). This simulates the ELSE-IF operand Excel lacks. Your formulas were using two conditions in each, but the second parameter of the IF formula is the value to use if the condition evaluates to true. You can't chain conditions in that manner.

Use string value from a cell to access worksheet of same name

This will only work to column Z, but you can drag this horizontally and vertically.

=INDIRECT("'"&$D$2&"'!"&CHAR((COLUMN()+64))&ROW())

Get values from other sheet using VBA

Try

 ThisWorkbook.Sheets("name of sheet 2").Range("A1")

to access a range in sheet 2 independently of where your code is or which sheet is currently active. To make sheet 2 the active sheet, try

 ThisWorkbook.Sheets("name of sheet 2").Activate

If you just need the sum of a row in a different sheet, there is no need for using VBA at all. Enter a formula like this in sheet 1:

=SUM([Name-Of-Sheet2]!A1:D1)

How do I get the last character of a string using an Excel function?

Looks like the answer above was a little incomplete try the following:-

=RIGHT(A2,(LEN(A2)-(LEN(A2)-1)))

Obviously, this is for cell A2...

What this does is uses a combination of Right and Len - Len is the length of a string and in this case, we want to remove all but one from that... clearly, if you wanted the last two characters you'd change the -1 to -2 etc etc etc.

After the length has been determined and the portion of that which is required - then the Right command will display the information you need.

This works well combined with an IF statement - I use this to find out if the last character of a string of text is a specific character and remove it if it is. See, the example below for stripping out commas from the end of a text string...

=IF(RIGHT(A2,(LEN(A2)-(LEN(A2)-1)))=",",LEFT(A2,(LEN(A2)-1)),A2)

Have Excel formulas that return 0, make the result blank

I noticed this issue recently and it is frustrating that excel changes a blank string into a 0. I do not think that a formula should solve this issue because adding more logic to a complex formula may be cumbersome and might even end up breaking the original formula. I have two non formula options below.

If you want to keep the formulas in the cells and have them return 0 instead of "" use the following Click Path:

  1. File
  2. Options
  3. Advanced

Scroll to "Display options for this worksheet:"

  1. Deselect "Show a zero in cells that have zero value"

I also want to give a simple manual solution if you want to change a value (as opposed to a formula) from 0 to a blank string. This solution is better than Find and Replace because it will not replace a number like 101 with 11.

  1. Select all of your data
  2. On the data tab, click the filter logo

The Filter Logo itself

  1. Click on the pick list of the column with the undesired 0(s) to select only rows with the value "0" (Make sure to only clear the contents of cells containing contents with the exact value 0!)

enter image description here

  1. Select the data (which is only 0s), right click and select clear contents

The other data will remain if you used the filter properly and the back button is always there if something goes wrong. I understand option 2 is very manual and "unelegant" but it does successfully convert a 0 into a blank string and it may relieve a frustrated individual who does not want to use an if statement.

I personally learned something exploring this (very dry) excel issue today and I am personally using these methods moving forward. A quick macro of option 2 could be a good option if this is a frequent task for an intermediate excel user.

Case Function Equivalent in Excel

Sounds like a job for VLOOKUP!

You can put your 32 -> 1420 type mappings in a couple of columns somewhere, then use the VLOOKUP function to perform the lookup.

Get the last non-empty cell in a column in Google Sheets

To find the last non-empty cell you can use INDEX and MATCH functions like this:

=DAYS360(A2; INDEX(A:A; MATCH(99^99;A:A; 1)))

I think this is a little bit faster and easier.

Last non-empty cell in a column

If you know that there are not going to be empty cells in between, the fastest way is this.

=INDIRECT("O"&(COUNT(O:O,"<>""")))

It just counts the non-empty cells and refers to the appropriate cell.

It can be used for a specific range as well.

=INDIRECT("O"&(COUNT(O4:O34,"<>""")+3))

This returns the last non empty cell in the range O4:O34.

Concatenating date with a string in Excel

You can do it this simple way :

A1 = Mahi
A2 = NULL(blank)

Select A2 Right click on cell --> Format cells --> change to TEXT

Then put the date in A2 (A2 =31/07/1990)

Then concatenate it will work. No need of any formulae.

=CONCATENATE(A1,A2)

mahi31/07/1990

(This works on the empty cells ie.,Before entering the DATE value to cell you need to make it as TEXT).

Excel formula to get cell color

No, you can only get to the interior color of a cell by using a Macro. I am afraid. It's really easy to do (cell.interior.color) so unless you have a requirement that restricts you from using VBA, I say go for it.

Add target="_blank" in CSS

While waiting for the adoption of CSS3 targeting…

While waiting for the adoption of CSS3 targeting by the major browsers, one could run the following sed command once the (X)HTML has been created:

sed -i 's|href="http|target="_blank" href="http|g' index.html

It will add target="_blank" to all external hyperlinks. Variations are also possible.

EDIT

I use this at the end of the makefile which generates every web page on my site.

JavaScript: location.href to open in new window/tab?

You can open it in a new window with window.open('https://support.wwf.org.uk/earth_hour/index.php?type=individual');. If you want to open it in new tab open the current page in two tabs and then alllow the script to run so that both current page and the new page will be obtained.

Change Select List Option background colour on hover in html

Currently there is no way to apply a css to get your desired result . Why not use libraries like choosen or select2 . These allow you to style the way you want.

If you don want to use third party libraries then you can make a simple un-ordered list and play with some css.Here is thread you could follow

How to convert <select> dropdown into an unordered list using jquery?

VueJS conditionally add an attribute for an element

In html use

<input :required="condition" />

And define in data property like

data () {
   return {
      condition: false
   }
}

Getting all documents from one collection in Firestore

if you need to include the key of the document in the response, another alternative is:

async getMarker() {
    const snapshot = await firebase.firestore().collection('events').get()
    const documents = [];
    snapshot.forEach(doc => {
       documents[doc.id] = doc.data();
    });
    return documents;
}

How do I format a number in Java?

You and String.format() will be new best friends!

https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax

 String.format("%.2f", (double)value);

How can I define fieldset border color?

I added it for all fieldsets with

fieldset {
        border: 1px solid lightgray;
    }

I didnt work if I set it separately using for example

border-color : red

. Then a black line was drawn next to the red line.

How to get root view controller?

if you are trying to access the rootViewController you set in your appDelegate. try this:

Objective-C

YourViewController *rootController = (YourViewController*)[[(YourAppDelegate*)
                                   [[UIApplication sharedApplication]delegate] window] rootViewController];

Swift

let appDelegate  = UIApplication.sharedApplication().delegate as AppDelegate
let viewController = appDelegate.window!.rootViewController as YourViewController

Swift 3

let appDelegate  = UIApplication.shared.delegate as! AppDelegate
let viewController = appDelegate.window!.rootViewController as! YourViewController

Swift 4 & 4.2

let viewController = UIApplication.shared.keyWindow!.rootViewController as! YourViewController

Swift 5 & 5.1 & 5.2

let viewController = UIApplication.shared.windows.first!.rootViewController as! YourViewController

How do I debug Windows services in Visual Studio?

A Microsoft article explains how to debug a Windows service here and what part anyone can miss if they debug it by attaching to a process.

Below is my working code. I have followed the approach suggested by Microsoft.

Add this code to program.cs:

static void Main(string[] args)
{
    // 'If' block will execute when launched through Visual Studio
    if (Environment.UserInteractive)
    {
        ServiceMonitor serviceRequest = new ServiceMonitor();
        serviceRequest.TestOnStartAndOnStop(args);
    }
    else // This block will execute when code is compiled as a Windows application
    {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[]
        {
            new ServiceMonitor()
        };
        ServiceBase.Run(ServicesToRun);
    }
}

Add this code to the ServiceMonitor class.

internal void TestOnStartAndOnStop(string[] args)
{
    this.OnStart(args);
    Console.ReadLine();
    this.OnStop();
}

Now go to Project Properties, select tab "Application" and select Output Type as "Console Application" when debugging, or "Windows Application" when done with debugging, recompile and install your service.

Enter image description here

List<T> OrderBy Alphabetical Order

Do you need the list to be sorted in place, or just an ordered sequence of the contents of the list? The latter is easier:

var peopleInOrder = people.OrderBy(person => person.LastName);

To sort in place, you'd need an IComparer<Person> or a Comparison<Person>. For that, you may wish to consider ProjectionComparer in MiscUtil.

(I know I keep bringing MiscUtil up - it just keeps being relevant...)

Scroll Automatically to the Bottom of the Page

one liner to smooth scroll to the bottom

window.scrollTo({ left: 0, top: document.body.scrollHeight, behavior: "smooth" });

To scroll up simply set top to 0

Difference between UTF-8 and UTF-16?

They're simply different schemes for representing Unicode characters.

Both are variable-length - UTF-16 uses 2 bytes for all characters in the basic multilingual plane (BMP) which contains most characters in common use.

UTF-8 uses between 1 and 3 bytes for characters in the BMP, up to 4 for characters in the current Unicode range of U+0000 to U+1FFFFF, and is extensible up to U+7FFFFFFF if that ever becomes necessary... but notably all ASCII characters are represented in a single byte each.

For the purposes of a message digest it won't matter which of these you pick, so long as everyone who tries to recreate the digest uses the same option.

See this page for more about UTF-8 and Unicode.

(Note that all Java characters are UTF-16 code points within the BMP; to represent characters above U+FFFF you need to use surrogate pairs in Java.)

How to detect when facebook's FB.init is complete

Another way to check if FB has initialized is by using the following code:

ns.FBInitialized = function () {
    return typeof (FB) != 'undefined' && window.fbAsyncInit.hasRun;
};

Thus in your page ready event you could check ns.FBInitialized and defer the event to later phase by using setTimeOut.

How do I add a placeholder on a CharField in Django?

Great question. There are three solutions I know about:

Solution #1

Replace the default widget.

class SearchForm(forms.Form):  
    q = forms.CharField(
            label='Search',
            widget=forms.TextInput(attrs={'placeholder': 'Search'})
        )

Solution #2

Customize the default widget. If you're using the same widget that the field usually uses then you can simply customize that one instead of instantiating an entirely new one.

class SearchForm(forms.Form):  
    q = forms.CharField(label='Search')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['q'].widget.attrs.update({'placeholder': 'Search'})

Solution #3

Finally, if you're working with a model form then (in addition to the previous two solutions) you have the option to specify a custom widget for a field by setting the widgets attribute of the inner Meta class.

class CommentForm(forms.ModelForm):  
    class Meta:
        model = Comment
        widgets = {
            'body': forms.Textarea(attrs={'cols': 80, 'rows': 20})
        }

How do I install the ext-curl extension with PHP 7?

please try

sudo apt-get install php7.0-curl

Is a DIV inside a TD a bad idea?

I have faced the problem by placing a <div> inside <td>.

I was unable to identify the div using document.getElementById() if i place that inside td. But outside, it was working fine.

How to determine if string contains specific substring within the first X characters

A more explicit version is

found = Value1.StartsWith("abc", StringComparison.Ordinal);

It's best to always explicitly list the particular comparison you are doing. The String class can be somewhat inconsistent with the type of comparisons that are used.

C# error: Use of unassigned local variable

The compiler doesn't know that the Environment.Exit() is going to terminate the program; it just sees you executing a static method on a class. Just initialize queue to null when you declare it.

Queue queue = null;

Best way to Bulk Insert from a C# DataTable

Here's how I do it using a DataTable. This is a working piece of TEST code.

using (SqlConnection con = new SqlConnection(connStr))
{
    con.Open();

    // Create a table with some rows. 
    DataTable table = MakeTable();

    // Get a reference to a single row in the table. 
    DataRow[] rowArray = table.Select();

    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(con))
    {
        bulkCopy.DestinationTableName = "dbo.CarlosBulkTestTable";

        try
        {
            // Write the array of rows to the destination.
            bulkCopy.WriteToServer(rowArray);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

    }

}//using

Auto-loading lib files in Rails 4

Use config.to_prepare to load you monkey patches/extensions for every request in development mode.

config.to_prepare do |action_dispatcher|
 # More importantly, will run upon every request in development, but only once (during boot-up) in production and test.
 Rails.logger.info "\n--- Loading extensions for #{self.class} "
 Dir.glob("#{Rails.root}/lib/extensions/**/*.rb").sort.each do |entry|
   Rails.logger.info "Loading extension(s): #{entry}"
   require_dependency "#{entry}"
 end
 Rails.logger.info "--- Loaded extensions for #{self.class}\n"

end

how to show alternate image if source image is not found? (onerror working in IE but not in mozilla)

I think this is very nice and short

<img src="imagenotfound.gif" alt="Image not found" onerror="this.src='imagefound.gif';" />

But, be careful. The user's browser will be stuck in an endless loop if the onerror image itself generates an error.


EDIT To avoid endless loop, remove the onerror from it at once.

<img src="imagenotfound.gif" alt="Image not found" onerror="this.onerror=null;this.src='imagefound.gif';" />

By calling this.onerror=null it will remove the onerror then try to get the alternate image.


NEW I would like to add a jQuery way, if this can help anyone.

<script>
$(document).ready(function()
{
    $(".backup_picture").on("error", function(){
        $(this).attr('src', './images/nopicture.png');
    });
});
</script>

<img class='backup_picture' src='./images/nonexistent_image_file.png' />

You simply need to add class='backup_picture' to any img tag that you want a backup picture to load if it tries to show a bad image.

Update span tag value with JQuery

Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.

    $("legend").each(function() {
        var SoftwareItem = $(this).text();
        itemCost = GetItemCost(SoftwareItem);
        $("input:checked").each(function() {               
            var Component = $(this).next("label").text();
            itemCost += GetItemCost(Component);
        });            
        $(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
    });

How can I use Html.Action?

first, create a class to hold your parameters:

public class PkRk {
    public int pk { get; set; }
    public int rk { get; set; }
}

then, use the Html.Action passing the parameters:

Html.Action("PkRkAction", new { pkrk = new PkRk { pk=400, rk=500} })

and use in Controller:

public ActionResult PkRkAction(PkRk pkrk) {
    return PartialView(pkrk);
}

Value Change Listener to JTextField

If we use runnable method SwingUtilities.invokeLater() while using Document listener application is getting stuck sometimes and taking time to update the result(As per my experiment). Instead of that we can also use KeyReleased event for text field change listener as mentioned here.

usernameTextField.addKeyListener(new KeyAdapter() {
    public void keyReleased(KeyEvent e) {
        JTextField textField = (JTextField) e.getSource();
        String text = textField.getText();
        textField.setText(text.toUpperCase());
    }
});

Finding Variable Type in JavaScript

For builtin JS types you can use:

function getTypeName(val) {
    return {}.toString.call(val).slice(8, -1);
}

Here we use 'toString' method from 'Object' class which works different than the same method of another types.

Examples:

// Primitives
getTypeName(42);        // "Number"
getTypeName("hi");      // "String"
getTypeName(true);      // "Boolean"
getTypeName(Symbol('s'))// "Symbol"
getTypeName(null);      // "Null"
getTypeName(undefined); // "Undefined"

// Non-primitives
getTypeName({});            // "Object"
getTypeName([]);            // "Array"
getTypeName(new Date);      // "Date"
getTypeName(function() {}); // "Function"
getTypeName(/a/);           // "RegExp"
getTypeName(new Error);     // "Error"

If you need a class name you can use:

instance.constructor.name

Examples:

({}).constructor.name       // "Object"
[].constructor.name         // "Array"
(new Date).constructor.name // "Date"

function MyClass() {}
let my = new MyClass();
my.constructor.name         // "MyClass"

But this feature was added in ES2015.

Laravel Check If Related Model Exists

I had to completely refactor my code when I updated my PHP version to 7.2+ because of bad usage of the count($x) function. This is a real pain and its also extremely scary as there are hundreds usages, in different scenarios and there is no one rules fits all..

Rules I followed to refactor everything, examples:

$x = Auth::user()->posts->find(6); (check if user has a post id=6 using ->find())

[FAILS] if(count($x)) { return 'Found'; } 
[GOOD] if($x) { return 'Found'; }

$x = Auth::user()->profile->departments; (check if profile has some departments, there can have many departments)

[FAILS] if(count($x)) { return 'Found'; }
[GOOD] if($x->count()) { return 'Found'; }

$x = Auth::user()->profile->get(); (check if user has a profile after using a ->get())

[FAILS] if(count($x)) { return 'Found'; }
[GOOD] if($x->count()) { return 'Found'; }

Hopes this can help, even 5 years after the question has been asked, this stackoverflow post has helped me a lot!

Python dictionary get multiple values

No-one has mentioned the map function, which allows a function to operate element-wise on a list:

mydictionary = {'a': 'apple', 'b': 'bear', 'c': 'castle'}
keys = ['b', 'c']

values = list( map(mydictionary.get, keys) )

# values = ['bear', 'castle']

What are queues in jQuery?

To understand queue method, you have to understand how jQuery does animation. If you write multiple animate method calls one after the other, jQuery creates an 'internal' queue and adds these method calls to it. Then it runs those animate calls one by one.

Consider following code.

function nonStopAnimation()
{
    //These multiple animate calls are queued to run one after
    //the other by jQuery.
    //This is the reason that nonStopAnimation method will return immeidately
    //after queuing these calls. 
    $('#box').animate({ left: '+=500'}, 4000);
    $('#box').animate({ top: '+=500'}, 4000);
    $('#box').animate({ left: '-=500'}, 4000);

    //By calling the same function at the end of last animation, we can
    //create non stop animation. 
    $('#box').animate({ top: '-=500'}, 4000 , nonStopAnimation);
}

The 'queue'/'dequeue' method gives you control over this 'animation queue'.

By default the animation queue is named 'fx'. I have created a sample page here which has various examples which will illustrate how the queue method could be used.

http://jsbin.com/zoluge/1/edit?html,output

Code for above sample page:

$(document).ready(function() {
    $('#nonStopAnimation').click(nonStopAnimation);

    $('#stopAnimationQueue').click(function() {
        //By default all animation for particular 'selector'
        //are queued in queue named 'fx'.
        //By clearning that queue, you can stop the animation.
        $('#box').queue('fx', []);
    });

    $('#addAnimation').click(function() {
        $('#box').queue(function() {
            $(this).animate({ height : '-=25'}, 2000);
            //De-queue our newly queued function so that queues
            //can keep running.
            $(this).dequeue();
        });
    });

    $('#stopAnimation').click(function() {
        $('#box').stop();
    });

    setInterval(function() {
        $('#currentQueueLength').html(
         'Current Animation Queue Length for #box ' + 
          $('#box').queue('fx').length
        );
    }, 2000);
});

function nonStopAnimation()
{
    //These multiple animate calls are queued to run one after
    //the other by jQuery.
    $('#box').animate({ left: '+=500'}, 4000);
    $('#box').animate({ top: '+=500'}, 4000);
    $('#box').animate({ left: '-=500'}, 4000);
    $('#box').animate({ top: '-=500'}, 4000, nonStopAnimation);
}

Now you may ask, why should I bother with this queue? Normally, you wont. But if you have a complicated animation sequence which you want to control, then queue/dequeue methods are your friend.

Also see this interesting conversation on jQuery group about creating a complicated animation sequence.

http://groups.google.com/group/jquery-en/browse_thread/thread/b398ad505a9b0512/f4f3e841eab5f5a2?lnk=gst

Demo of the animation:

http://www.exfer.net/test/jquery/tabslide/

Let me know if you still have questions.

Android ListView in fragment example

Your Fragment can subclass ListFragment.
And onCreateView() from ListFragment will return a ListView you can then populate.

Return Type for jdbcTemplate.queryForList(sql, object, classType)

List<Map<String, Object>> List = getJdbcTemplate().queryForList(SELECT_ALL_CONVERSATIONS_SQL_FULL, new Object[] {userId, dateFrom, dateTo});
for (Map<String, Object> rowMap : resultList) {
    DTO dTO = new DTO();
    dTO.setrarchyID((Long) (rowMap.get("ID")));
}

$.focus() not working

For those with the problem of not working because you used "$(element).show()". I solved it the next way:

 var textbox = $("#otherOption");
 textbox.show("fast", function () {
    textbox[0].focus();
  });

So you dont need a timer, it will execute after the show method is completed.

How to Make Laravel Eloquent "IN" Query?

Syntax:

$data = Model::whereIn('field_name', [1, 2, 3])->get();

Use for Users Model

$usersList = Users::whereIn('id', [1, 2, 3])->get();

Getting Lat/Lng from Google marker

There are a lot of answers to this question, which never worked for me (including suggesting getPosition() which doesn't seem to be a method available for markers objects). The only method that worked for me in maps V3 is (simply) :

var lat = marker.lat();
var long = marker.lng();

Nested select statement in SQL Server

The answer provided by Joe Stefanelli is already correct.

SELECT name FROM (SELECT name FROM agentinformation) as a  

We need to make an alias of the subquery because a query needs a table object which we will get from making an alias for the subquery. Conceptually, the subquery results are substituted into the outer query. As we need a table object in the outer query, we need to make an alias of the inner query.

Statements that include a subquery usually take one of these forms:

  • WHERE expression [NOT] IN (subquery)
  • WHERE expression comparison_operator [ANY | ALL] (subquery)
  • WHERE [NOT] EXISTS (subquery)

Check for more subquery rules and subquery types.

More examples of Nested Subqueries.

  1. IN / NOT IN – This operator takes the output of the inner query after the inner query gets executed which can be zero or more values and sends it to the outer query. The outer query then fetches all the matching [IN operator] or non matching [NOT IN operator] rows.

  2. ANY – [>ANY or ANY operator takes the list of values produced by the inner query and fetches all the values which are greater than the minimum value of the list. The

e.g. >ANY(100,200,300), the ANY operator will fetch all the values greater than 100.

  1. ALL – [>ALL or ALL operator takes the list of values produced by the inner query and fetches all the values which are greater than the maximum of the list. The

e.g. >ALL(100,200,300), the ALL operator will fetch all the values greater than 300.

  1. EXISTS – The EXISTS keyword produces a Boolean value [TRUE/FALSE]. This EXISTS checks the existence of the rows returned by the sub query.

How to put comments in Django templates

This way can be helpful if you want to comment some Django Template format Code.

{#% include 'file.html' %#} (Right Way)

Following code still executes if commented with HTML Comment.

<!-- {% include 'file.html' %} --> (Wrong Way)

A JSONObject text must begin with '{' at 1 [character 2 line 1] with '{' error

Your JSON is perfectly valid. Try using these JSON classes to parse it. http://json.org/java/

struct.error: unpack requires a string argument of length 4

By default, on many platforms the short will be aligned to an offset at a multiple of 2, so there will be a padding byte added after the char.

To disable this, use: struct.unpack("=BH", data). This will use standard alignment, which doesn't add padding:

>>> struct.calcsize('=BH')
3

The = character will use native byte ordering. You can also use < or > instead of = to force little-endian or big-endian byte ordering, respectively.

How to assign a heredoc value to a variable in Bash?

assign a heredoc value to a variable

VAR="$(cat <<'VAREOF'
abc'asdf"
$(dont-execute-this)
foo"bar"''
VAREOF
)"

used as an argument of a command

echo "$(cat <<'SQLEOF'
xxx''xxx'xxx'xx  123123    123123
abc'asdf"
$(dont-execute-this)
foo"bar"''
SQLEOF
)"

Unzip files (7-zip) via cmd command

Doing the following in a command prompt works for me, also adding to my User environment variables worked fine as well:

set PATH=%PATH%;C:\Program Files\7-Zip\
echo %PATH%
7z

You should see as output (or something similar - as this is on my laptop running Windows 7):

C:\Users\Phillip>set PATH=%PATH%;C:\Program Files\7-Zip\

C:\Users\Phillip>echo %PATH%
C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Wi
ndows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\
WirelessCommon\;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\To
ols\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Fil
es (x86)\QuickTime\QTSystem\;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Notepad+
+;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files\7-Zip\

C:\Users\Phillip>7z

7-Zip [64] 9.20  Copyright (c) 1999-2010 Igor Pavlov  2010-11-18

Usage: 7z <command> [<switches>...] <archive_name> [<file_names>...]
       [<@listfiles...>]

<Commands>
  a: Add files to archive
  b: Benchmark
  d: Delete files from archive
  e: Extract files from archive (without using directory names)
  l: List contents of archive
  t: Test integrity of archive
  u: Update files to archive
  x: eXtract files with full paths
<Switches>
  -ai[r[-|0]]{@listfile|!wildcard}: Include archives
  -ax[r[-|0]]{@listfile|!wildcard}: eXclude archives
  -bd: Disable percentage indicator
  -i[r[-|0]]{@listfile|!wildcard}: Include filenames
  -m{Parameters}: set compression Method
  -o{Directory}: set Output directory
  -p{Password}: set Password
  -r[-|0]: Recurse subdirectories
  -scs{UTF-8 | WIN | DOS}: set charset for list files
  -sfx[{name}]: Create SFX archive
  -si[{name}]: read data from stdin
  -slt: show technical information for l (List) command
  -so: write data to stdout
  -ssc[-]: set sensitive case mode
  -ssw: compress shared files
  -t{Type}: Set type of archive
  -u[-][p#][q#][r#][x#][y#][z#][!newArchiveName]: Update options
  -v{Size}[b|k|m|g]: Create volumes
  -w[{path}]: assign Work directory. Empty path means a temporary directory
  -x[r[-|0]]]{@listfile|!wildcard}: eXclude filenames
  -y: assume Yes on all queries

What is the use of "object sender" and "EventArgs e" parameters?

Those two parameters (or variants of) are sent, by convention, with all events.

  • sender: The object which has raised the event
  • e an instance of EventArgs including, in many cases, an object which inherits from EventArgs. Contains additional information about the event, and sometimes provides ability for code handling the event to alter the event somehow.

In the case of the events you mentioned, neither parameter is particularly useful. The is only ever one page raising the events, and the EventArgs are Empty as there is no further information about the event.

Looking at the 2 parameters separately, here are some examples where they are useful.

sender

Say you have multiple buttons on a form. These buttons could contain a Tag describing what clicking them should do. You could handle all the Click events with the same handler, and depending on the sender do something different

private void HandleButtonClick(object sender, EventArgs e)
{
    Button btn = (Button)sender;
    if(btn.Tag == "Hello")
      MessageBox.Show("Hello")
    else if(btn.Tag == "Goodbye")
       Application.Exit();
    // etc.
}

Disclaimer : That's a contrived example; don't do that!

e

Some events are cancelable. They send CancelEventArgs instead of EventArgs. This object adds a simple boolean property Cancel on the event args. Code handling this event can cancel the event:

private void HandleCancellableEvent(object sender, CancelEventArgs e)
{
    if(/* some condition*/)
    {
       // Cancel this event
       e.Cancel = true;
    }
}

Expand/collapse section in UITableView in iOS

So, based on the 'button in header' solution, here is a clean and minimalist implementation:

  • you keep track of collapsed (or expanded) sections in a property
  • you tag the button with the section index
  • you set a selected state on that button to change the arrow direction (like ? and ?)

Here is the code:

@interface MyTableViewController ()
@property (nonatomic, strong) NSMutableIndexSet *collapsedSections;
@end

...

@implementation MyTableViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (!self)
        return;
    self.collapsedSections = [NSMutableIndexSet indexSet];
    return self;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // if section is collapsed
    if ([self.collapsedSections containsIndex:section])
        return 0;

    // if section is expanded
#warning incomplete implementation
    return [super tableView:tableView numberOfRowsInSection:section];
}

- (IBAction)toggleSectionHeader:(UIView *)sender
{
    UITableView *tableView = self.tableView;
    NSInteger section = sender.tag;

    MyTableViewHeaderFooterView *headerView = (MyTableViewHeaderFooterView *)[self tableView:tableView viewForHeaderInSection:section];

    if ([self.collapsedSections containsIndex:section])
    {
        // section is collapsed
        headerView.button.selected = YES;
        [self.collapsedSections removeIndex:section];
    }
    else
    {
        // section is expanded
        headerView.button.selected = NO;
        [self.collapsedSections addIndex:section];
    }

    [tableView beginUpdates];
    [tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];
    [tableView endUpdates];
}

@end

How do I declare and initialize an array in Java?

With local variable type inference you only have to specify the type once:

var values = new int[] { 1, 2, 3 };

Or

int[] values = { 1, 2, 3 }

Cocoa Touch: How To Change UIView's Border Color And Thickness?

You need to use view's layer to set border property. e.g:

#import <QuartzCore/QuartzCore.h>
...
view.layer.borderColor = [UIColor redColor].CGColor;
view.layer.borderWidth = 3.0f;

You also need to link with QuartzCore.framework to access this functionality.

ipynb import another ipynb file

Please make sure that you also add a __init__.py file in the package where all your other .ipynb files are located.

This is in addition to the nbviewer link that minrk and syi provided above.

I also had some similar problem and then I wrote the solution as well as a link to my public google drive folder which has a working example :)

My Stackoverflow post with step by step experimentation and Solution:

Jupyter Notebook: Import .ipynb file and access it's method in other .ipynb file giving error

Hope this will help others as well. Thanks all!

SQL subquery with COUNT help

Do you want to get the number of rows?

SELECT columnName, COUNT(*) AS row_count
FROM eventsTable
WHERE columnName = 'Business'
GROUP BY columnName

How to open the default webbrowser using java

I recast Brajesh Kumar's answer above into Clojure as follows:

(defn open-browser 
  "Open a new browser (window or tab) viewing the document at this `uri`."
  [uri]
  (if (java.awt.Desktop/isDesktopSupported)
    (let [desktop (java.awt.Desktop/getDesktop)]
      (.browse desktop (java.net.URI. uri)))
    (let [rt (java.lang.Runtime/getRuntime)]
      (.exec rt (str "xdg-open " uri)))))

in case it's useful to anyone.

Convert String to equivalent Enum value

I might've over-engineered my own solution without realizing that Type.valueOf("enum string") actually existed.

I guess it gives more granular control but I'm not sure it's really necessary.

public enum Type {
    DEBIT,
    CREDIT;

    public static Map<String, Type> typeMapping = Maps.newHashMap();
    static {
        typeMapping.put(DEBIT.name(), DEBIT);
        typeMapping.put(CREDIT.name(), CREDIT);
    }

    public static Type getType(String typeName) {
        if (typeMapping.get(typeName) == null) {
            throw new RuntimeException(String.format("There is no Type mapping with name (%s)"));
        }
        return typeMapping.get(typeName);
    }
}

I guess you're exchanging IllegalArgumentException for RuntimeException (or whatever exception you wish to throw) which could potentially clean up code.

Error in Python script "Expected 2D array, got 1D array instead:"?

I use the below approach.

reg = linear_model.LinearRegression()
reg.fit(df[['year']],df.income)

reg.predict([[2136]])

Why do people use Heroku when AWS is present? What distinguishes Heroku from AWS?

AWS / Heroku are both free for small hobby projects (to start with).

If you want to start an app right away, without much customization of the architecture, then choose Heroku.

If you want to focus on the architecture and to be able to use different web servers, then choose AWS. AWS is more time-consuming based on what service/product you choose, but can be worth it. AWS also comes with many plugin services and products.


Heroku

  • Platform as a Service (PAAS)
  • Good documentation
  • Has built-in tools and architecture.
  • Limited control over architecture while designing the app.
  • Deployment is taken care of (automatic via GitHub or manual via git commands or CLI).
  • Not time consuming.

AWS

  • Infrastructure as a Service (IAAS)
  • Versatile - has many products such as EC2, LAMBDA, EMR, etc.
  • Can use a Dedicated instance for more control over the architecture, such as choosing the OS, software version, etc. There is more than one backend layer.
  • Elastic Beanstalk is a feature similar to Heroku's PAAS.
  • Can use the automated deployment, or roll your own.

Initialize a long in Java

You need to add uppercase L at the end like so

long i = 12345678910L;

Same goes true for float with 3.0f

Which should answer both of your questions

How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?

    <sonar.language>java</sonar.language>
    <sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
    <sonar.jacoco.reportPath>${user.dir}/target/jacoco.exec</sonar.jacoco.reportPath>
    <sonar.jacoco.itReportPath>${user.dir}/target/jacoco-it.exec</sonar.jacoco.itReportPath>
    <sonar.exclusions>
        file:**/target/generated-sources/**,
        file:**/target/generated-test-sources/**,
        file:**/target/test-classes/**,
        file:**/model/*.java,
        file:**/*Config.java,
        file:**/*App.java
    </sonar.exclusions>

            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.7.9</version>
                <executions>
                    <execution>
                        <id>default-prepare-agent</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                        <configuration>
                            <destFile>${sonar.jacoco.reportPath}</destFile>
                            <append>true</append>
                            <propertyName>surefire.argLine</propertyName>
                        </configuration>
                    </execution>
                    <execution>
                        <id>default-prepare-agent-integration</id>
                        <goals>
                            <goal>prepare-agent-integration</goal>
                        </goals>
                        <configuration>
                            <destFile>${sonar.jacoco.itReportPath}</destFile>
                            <append>true</append>
                            <propertyName>failsafe.argLine</propertyName>
                        </configuration>
                    </execution>
                    <execution>
                        <id>default-report</id>
                        <goals>
                            <goal>report</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>default-report-integration</id>
                        <goals>
                            <goal>report-integration</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>             

Delete a row from a table by id

to Vilx-:

var table = row.parentNode;
while ( table && table.tagName != 'TABLE' )
    table = table.parentNode;

and what if row.parentNode is TBODY?

You should check it out first, and after that do while by .tBodies, probably

How to get label of select option with jQuery?

Created working Plunker for this. https://plnkr.co/edit/vR9aGoCwoOUL9tevIEen $('#console').append("<br/>"+$('#test_s :selected').text())

How to ssh connect through python Paramiko with ppk public key

Ok @Adam and @Kimvais were right, paramiko cannot parse .ppk files.

So the way to go (thanks to @JimB too) is to convert .ppk file to openssh private key format; this can be achieved using Puttygen as described here.

Then it's very simple getting connected with it:

import paramiko
ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect('<hostname>', username='<username>', password='<password>', key_filename='<path/to/openssh-private-key-file>')

stdin, stdout, stderr = ssh.exec_command('ls')
print stdout.readlines()
ssh.close()

R * not meaningful for factors ERROR

new[,2] is a factor, not a numeric vector. Transform it first

new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5

-didSelectRowAtIndexPath: not being called

Please check for UITapGestureRecognizer. In my case tapgesture was added for the view where tableview got placed, which is eating the user interaction of UITableview like didselect. After disabling tapgesture for the view, didselect delegate was triggered.

What is the difference between 'typedef' and 'using' in C++11?

The using syntax has an advantage when used within templates. If you need the type abstraction, but also need to keep template parameter to be possible to be specified in future. You should write something like this.

template <typename T> struct whatever {};

template <typename T> struct rebind
{
  typedef whatever<T> type; // to make it possible to substitue the whatever in future.
};

rebind<int>::type variable;

template <typename U> struct bar { typename rebind<U>::type _var_member; }

But using syntax simplifies this use case.

template <typename T> using my_type = whatever<T>;

my_type<int> variable;
template <typename U> struct baz { my_type<U> _var_member; }

Groovy String to Date

Below is the way we are going within our developing application.

import java.text.SimpleDateFormat

String newDateAdded = "2018-11-11T09:30:31"
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
Date dateAdded = dateFormat.parse(newDateAdded)

println(dateAdded)

The output looks like

Sun Nov 11 09:30:31 GMT 2018

In your example, we could adjust a bit to meet your need. If I were you, I will do:

String datePattern = "d/M/yyyy H:m:s"
String theDate = "28/09/2010 16:02:43"
SimpleDateFormat df = new SimpleDateFormat(datePattern)
println df.parse(theDate)

I hope this would help you much.

How can I find the first occurrence of a sub-string in a python string?

Quick Overview: index and find

Next to the find method there is as well index. find and index both yield the same result: returning the position of the first occurrence, but if nothing is found index will raise a ValueError whereas find returns -1. Speedwise, both have the same benchmark results.

s.find(t)    #returns: -1, or index where t starts in s
s.index(t)   #returns: Same as find, but raises ValueError if t is not in s

Additional knowledge: rfind and rindex:

In general, find and index return the smallest index where the passed-in string starts, and rfind and rindex return the largest index where it starts Most of the string searching algorithms search from left to right, so functions starting with r indicate that the search happens from right to left.

So in case that the likelihood of the element you are searching is close to the end than to the start of the list, rfind or rindex would be faster.

s.rfind(t)   #returns: Same as find, but searched right to left
s.rindex(t)  #returns: Same as index, but searches right to left

Source: Python: Visual QuickStart Guide, Toby Donaldson

The meaning of NoInitialContextException error

Most of the time these settings are also defined in a jndi.properties file. Do you have that one lying around somewhere?

Find unique rows in numpy.array

Yet another possible solution

np.vstack({tuple(row) for row in a})

The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "Scripts"

Also, you can add the following line to the _Layout.cshtml or _Layout.Mobile.cshtml:

@RenderSection("scripts", required: false)

How to find rows that have a value that contains a lowercase letter

SELECT * FROM my_table 
WHERE UPPER(some_field) != some_field

This should work with funny characters like åäöøüæï. You might need to use a language-specific utf-8 collation for the table.

Creating and playing a sound in swift

this is working with Swift 4 :

if let soundURL = Bundle.main.url(forResource: "note3", withExtension: "wav") {
                var mySound: SystemSoundID = 0
                AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
                // Play
                AudioServicesPlaySystemSound(mySound);
            }

How to reset the use/password of jenkins on windows?

This is for windows environment:

I got the Initial Admin password under C:\Users\Deepak("MyUser").jenkins\secrets\initialAdminPassword

I was able to login with user "admin" and above password. Then under Jenkins> people I edited the password of the user and clicked on apply to reflect the changes.

Get the selected value in a dropdown using jQuery.

Hello guys i am using this technique to get the values from the selected dropdown list and it is working like charm.

var methodvalue = $("#method option:selected").val(); 

What is &#39; and why does Google search replace it with apostrophe?

It's HTML character references for encoding a character by its decimal code point

Look at the ASCII table here and you'll see that 39 (hex 0x27, octal 47) is the code for apostrophe

ASCII table

How to remove all files from directory without removing directory in Node.js

There is package called rimraf that is very handy. It is the UNIX command rm -rf for node.

Nevertheless, it can be too powerful too because you can delete folders very easily using it. The following commands will delete the files inside the folder. If you remove the *, you will remove the log folder.

const rimraf = require('rimraf');
rimraf('./log/*', function () { console.log('done'); });

https://www.npmjs.com/package/rimraf

How do I make a splash screen?

I used threads to make the Flash Screen in android.

    import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

public class HomeScreen extends AppCompatActivity{
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen_home);

        Thread thread = new Thread(){
            public void run(){
                try {
                    Thread.sleep(3 * 1000);
                    Intent i = new Intent(HomeScreen.this, MainActivity.class);
                    startActivity(i);
                } catch (InterruptedException e) {
                }
            }
        };
        thread.start();
    }
}

How can I add JAR files to the web-inf/lib folder in Eclipse?

add the jar to WEB-INF/lib from file structure refresh the project, you should see the jar now visible under the WEB-INF/lib folder.

this is the best solution that worked for me

Redirect to new Page in AngularJS using $location

If you want to change ng-view you'll have to use the '#'

$window.location.href= "#operation";

Create an Android GPS tracking application

The source code for the Android mobile application open-gpstracker which you appreciated is available here.

You can checkout the code using SVN client application or via Git:

Debugging the source code will surely help you.

Hash string in c#

The fastest way, to get a hash string for password store purposes, is a following code:

    internal static string GetStringSha256Hash(string text)
    {
        if (String.IsNullOrEmpty(text))
            return String.Empty;

        using (var sha = new System.Security.Cryptography.SHA256Managed())
        {
            byte[] textData = System.Text.Encoding.UTF8.GetBytes(text);
            byte[] hash = sha.ComputeHash(textData);
            return BitConverter.ToString(hash).Replace("-", String.Empty);
        }
    }

Remarks:

  • if the method is invoked often, the creation of sha variable should be refactored into a class field;
  • output is presented as encoded hex string;

Text file in VBA: Open/Find Replace/SaveAs/Close File

This code will open and read lines of complete text file That variable "ReadedData" Holds the text line in memory

Open "C:\satheesh\myfile\Hello.txt" For Input As #1

do until EOF(1)   

       Input #1, ReadedData
loop**

Eclipse Indigo - Cannot install Android ADT Plugin

The Google Plugin for Eclipse depends on other specific Eclipse components, such as WST. Your installation of Eclipse may not yet include all of them, but they can be easily installed by following these instructions. Eclipse 3.7 (Indigo)

 Select Help > Install New Software...

Click the link for Available Software Sites.
Ensure there is an update site named Indigo. 

If this is not present, click Add... and 
enter http://download.eclipse.org/releases/indigo for the Location.

Now go through the installation steps; Eclipse should download and install 
the plugin's dependencies.

MySQL "between" clause not inclusive?

Hi this query works for me,

select * from person where dob between '2011-01-01' and '2011-01-31 23:59:59'

Abstract Class vs Interface in C++

I assume that with interface you mean a C++ class with only pure virtual methods (i.e. without any code), instead with abstract class you mean a C++ class with virtual methods that can be overridden, and some code, but at least one pure virtual method that makes the class not instantiable. e.g.:

class MyInterface
{
public:
  // Empty virtual destructor for proper cleanup
  virtual ~MyInterface() {}

  virtual void Method1() = 0;
  virtual void Method2() = 0;
};


class MyAbstractClass
{
public:
  virtual ~MyAbstractClass();

  virtual void Method1();
  virtual void Method2();
  void Method3();

  virtual void Method4() = 0; // make MyAbstractClass not instantiable
};

In Windows programming, interfaces are fundamental in COM. In fact, a COM component exports only interfaces (i.e. pointers to v-tables, i.e. pointers to set of function pointers). This helps defining an ABI (Application Binary Interface) that makes it possible to e.g. build a COM component in C++ and use it in Visual Basic, or build a COM component in C and use it in C++, or build a COM component with Visual C++ version X and use it with Visual C++ version Y. In other words, with interfaces you have high decoupling between client code and server code.

Moreover, when you want to build DLL's with a C++ object-oriented interface (instead of pure C DLL's), as described in this article, it's better to export interfaces (the "mature approach") instead of C++ classes (this is basically what COM does, but without the burden of COM infrastructure).

I'd use an interface if I want to define a set of rules using which a component can be programmed, without specifying a concrete particular behavior. Classes that implement this interface will provide some concrete behavior themselves.

Instead, I'd use an abstract class when I want to provide some default infrastructure code and behavior, and make it possible to client code to derive from this abstract class, overriding the pure virtual methods with some custom code, and complete this behavior with custom code. Think for example of an infrastructure for an OpenGL application. You can define an abstract class that initializes OpenGL, sets up the window environment, etc. and then you can derive from this class and implement custom code for e.g. the rendering process and handling user input:

// Abstract class for an OpenGL app.
// Creates rendering window, initializes OpenGL; 
// client code must derive from it 
// and implement rendering and user input.
class OpenGLApp
{
public:
  OpenGLApp();
  virtual ~OpenGLApp();
  ...

  // Run the app    
  void Run();


  // <---- This behavior must be implemented by the client ---->

  // Rendering
  virtual void Render() = 0;

  // Handle user input
  // (returns false to quit, true to continue looping)
  virtual bool HandleInput() = 0;

  // <--------------------------------------------------------->


private:
  //
  // Some infrastructure code
  //
  ... 
  void CreateRenderingWindow();
  void CreateOpenGLContext();
  void SwapBuffers();
};


class MyOpenGLDemo : public OpenGLApp
{
public:
  MyOpenGLDemo();
  virtual ~MyOpenGLDemo();

  // Rendering
  virtual void Render();  // implements rendering code

  // Handle user input
  virtual bool HandleInput(); // implements user input handling


  //  ... some other stuff
};

Breaking out of nested loops

for x in xrange(10):
    for y in xrange(10):
        print x*y
        if x*y > 50:
            break
    else:
        continue  # only executed if the inner loop did NOT break
    break  # only executed if the inner loop DID break

The same works for deeper loops:

for x in xrange(10):
    for y in xrange(10):
        for z in xrange(10):
            print x,y,z
            if x*y*z == 30:
                break
        else:
            continue
        break
    else:
        continue
    break

Get current time in hours and minutes

I have another solution for your question .

In the first when use date the output is like this :

Thu 28 Jan 2021 22:29:40 IST

Then if you want only to show current time in hours and minutes you can use this command :

date | cut -d " " -f5 | cut -d ":" -f1-2 

Then the output :

22:29

Convert ndarray from float64 to integer

While astype is probably the "best" option there are several other ways to convert it to an integer array. I'm using this arr in the following examples:

>>> import numpy as np
>>> arr = np.array([1,2,3,4], dtype=float)
>>> arr
array([ 1.,  2.,  3.,  4.])

The int* functions from NumPy

>>> np.int64(arr)
array([1, 2, 3, 4])

>>> np.int_(arr)
array([1, 2, 3, 4])

The NumPy *array functions themselves:

>>> np.array(arr, dtype=int)
array([1, 2, 3, 4])

>>> np.asarray(arr, dtype=int)
array([1, 2, 3, 4])

>>> np.asanyarray(arr, dtype=int)
array([1, 2, 3, 4])

The astype method (that was already mentioned but for completeness sake):

>>> arr.astype(int)
array([1, 2, 3, 4])

Note that passing int as dtype to astype or array will default to a default integer type that depends on your platform. For example on Windows it will be int32, on 64bit Linux with 64bit Python it's int64. If you need a specific integer type and want to avoid the platform "ambiguity" you should use the corresponding NumPy types like np.int32 or np.int64.

When to use throws in a Java method declaration?

In the example you gave, the method will never throw an IOException, therefore the declaration is wrong (but valid). My guess is that the original method threw the IOException, but it was then updated to handle the exception within but the declaration was not changed.

Which Protocols are used for PING?

ICMP means Internet Control Message Protocol and is always coupled with the IP protocol (There's 2 ICMP variants one for IPv4 and one for IPv6.)

echo request and echo response are the two operation codes of ICMP used to implement ping.

Besides the original ping program, ping might simply mean the action of checking if a remote node is responding, this might be done on several layers in a protocol stack - e.g. ARP ping for testing hosts on a local network. The term ping might be used on higher protocol layers and APIs as well, e.g. the act of checking if a database is up, done at the database layer protocol.

ICMP sits on top of IP. What you have below depends on the network you're on, and are not in themselves relevant to the operation of ping.

Listing all extras of an Intent

Here's what I used to get information on an undocumented (3rd-party) intent:

Bundle bundle = intent.getExtras();
if (bundle != null) {
    for (String key : bundle.keySet()) {
        Log.e(TAG, key + " : " + (bundle.get(key) != null ? bundle.get(key) : "NULL"));
    }
}

Make sure to check if bundle is null before the loop.

A CORS POST request works from plain JavaScript, but why not with jQuery?

Modify your Jquery in following way:

$.ajax({
            url: someurl,
            contentType: 'application/json',
            data: JSONObject,
            headers: { 'Access-Control-Allow-Origin': '*' }, //add this line
            dataType: 'json',
            type: 'POST',                
            success: function (Data) {....}
});

PHP: Best way to check if input is a valid number?

For PHP version 4 or later versions:

<?PHP
$input = 4;
if(is_numeric($input)){  // return **TRUE** if it is numeric
    echo "The input is numeric";
}else{
    echo "The input is not numeric";
}
?>

The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)

Just in case...
If you are using SoapUI Mock Service (as the Server), calling it from a C# WCF:

WCF --> SoapUI MockService

And in this case you are getting the same error:

The content type text/html; charset=UTF-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8).

Edit your Mock Response at SoapUI and add a Header to it: enter image description here

In my scenario, this fix the problem.

How to serialize a JObject without the formatting?

you can use JsonConvert.SerializeObject()

JsonConvert.SerializeObject(myObject) // myObject is returned by JObject.Parse() method

JsonConvert.SerializeObject()

JObject.Parse()

Correct way to quit a Qt program?

QApplication is derived from QCoreApplication and thereby inherits quit() which is a public slot of QCoreApplication, so there is no difference between QApplication::quit() and QCoreApplication::quit().

As we can read in the documentation of QCoreApplication::quit() it "tells the application to exit with return code 0 (success).". If you want to exit because you discovered file corruption then you may not want to exit with return code zero which means success, so you should call QCoreApplication::exit() because you can provide a non-zero returnCode which, by convention, indicates an error.

It is important to note that "if the event loop is not running, this function (QCoreApplication::exit()) does nothing", so in that case you should call exit(EXIT_FAILURE).

Programmatically Creating UILabel

For swift

var label = UILabel(frame: CGRect(x: 0, y: 0, width: 250, height: 50))
label.textAlignment = .left
label.text = "This is a Label"
self.view.addSubview(label)

Installing Apache Maven Plugin for Eclipse

Installing m2eclipse

All downloads are provided under the terms and conditions of the Eclipse Foundation Software User Agreement unless otherwise specified.

m2e is tested against Eclipse 4.2 (Juno) and 4.3 (Kepler).

See http://wiki.eclipse.org/M2E_updatesite_and_gittags for detailed information about available builds and m2e build repository layout.

m2e 1.3 and earlier version have been removed from the main m2e update site. These old releases are still available and can be installed from repositories documented in http://wiki.eclipse.org/M2E_updatesite_and_gittags

Please note that links below point at Eclipse p2 repositories; you must access them from Eclipse (see how). Update Sites Latest m2e release (recommended) http://download.eclipse.org/technology/m2e/releases m2e milestone builds towards version 1.5 http://download.eclipse.org/technology/m2e/milestones/1.5 Latest m2e 1.5 SNAPSHOT build (not tested, not hosted at eclipse.org) http://repository.takari.io:8081/nexus/content/sites/m2e.extras/m2e/1.5.0/N/LATEST/

Store JSON object in data attribute in HTML jQuery

There's a better way of storing JSON in the HTML:

HTML

<script id="some-data" type="application/json">{"param_1": "Value 1", "param_2": "Value 2"}</script>

JavaScript

JSON.parse(document.getElementById('some-data').textContent);

Conversion from Long to Double in Java

What do you mean by a long date type?

You can cast a long to a double:

double d = (double) 15552451L;

How do I multiply each element in a list by a number?

You can just use a list comprehension:

my_list = [1, 2, 3, 4, 5]
my_new_list = [i * 5 for i in my_list]

>>> print(my_new_list)
[5, 10, 15, 20, 25]

Note that a list comprehension is generally a more efficient way to do a for loop:

my_new_list = []
for i in my_list:
    my_new_list.append(i * 5)

>>> print(my_new_list)
[5, 10, 15, 20, 25]

As an alternative, here is a solution using the popular Pandas package:

import pandas as pd

s = pd.Series(my_list)

>>> s * 5
0     5
1    10
2    15
3    20
4    25
dtype: int64

Or, if you just want the list:

>>> (s * 5).tolist()
[5, 10, 15, 20, 25]

How can I make Bootstrap 4 columns all the same height?

You just have to use class="row-eq-height" with your class="row" to get equal height columns for previous bootstrap versions.

but with bootstrap 4 this comes natively.

check this link --http://getbootstrap.com.vn/examples/equal-height-columns/

How to get previous page url using jquery

If you are using PHP, you can check previous url using php script rather than javascript. Here is the code:

echo $_SERVER['HTTP_REFERER'];

Hope it helps even out of relevance :)

AWS S3: The bucket you are attempting to access must be addressed using the specified endpoint

None of the above answers fixed my issue.

The above answers are probably more likely the cause of your problem but my issue was that I was using the wrong bucket name. It was a valid bucket name, it just wasn't my bucket.

The bucket I was pointing to was in a different region that my lambda function so check your bucket name!

Printing 2D array in matrix format

like so:

long[,] arr = new long[4, 4] { { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 0, 0, 0, 0 }, { 1, 1, 1, 1 } };

var rowCount = arr.GetLength(0);
var colCount = arr.GetLength(1);
for (int row = 0; row < rowCount; row++)
{
    for (int col = 0; col < colCount; col++)               
        Console.Write(String.Format("{0}\t", arr[row,col]));
    Console.WriteLine();
} 

Box shadow for bottom side only

Specify negative value to spread value. This works for me:

box-shadow: 0 2px 3px -1px rgba(0, 0, 0, 0.1);

How do I uninstall nodejs installed from pkg (Mac OS X)?

Following previous posts, here is the full list I used

sudo npm uninstall npm -g
sudo rm -rf /usr/local/lib/node /usr/local/lib/node_modules /var/db/receipts/org.nodejs.*
sudo rm -rf /usr/local/include/node /Users/$USER/.npm
sudo rm /usr/local/bin/node
sudo rm /usr/local/share/man/man1/node.1
sudo rm /usr/local/lib/dtrace/node.d
brew install node

How to show Bootstrap table with sort icon

Use this icons with bootstrap (glyphicon):

<span class="glyphicon glyphicon-triangle-bottom"></span>
<span class="glyphicon glyphicon-triangle-top"></span>

http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_glyph_triangle-bottom&stacked=h

http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_glyph_triangle-bottom&stacked=h

How to write to files using utl_file in oracle

Here is a robust function for using UTL_File.putline that includes the necessary error handling. It also handles headers, footers and a few other exceptional cases.

PROCEDURE usp_OUTPUT_ToFileAscii(p_Path IN VARCHAR2, p_FileName IN VARCHAR2, p_Input IN refCursor, p_Header in VARCHAR2, p_Footer IN VARCHAR2, p_WriteMode VARCHAR2) IS

              vLine VARCHAR2(30000);
              vFile UTL_FILE.file_type; 
              vExists boolean;
              vLength number;
              vBlockSize number;
    BEGIN

        UTL_FILE.fgetattr(p_path, p_FileName, vExists, vLength, vBlockSize);

                 FETCH p_Input INTO vLine;
         IF p_input%ROWCOUNT > 0
         THEN
            IF vExists THEN
               vFile := UTL_FILE.FOPEN_NCHAR(p_Path, p_FileName, p_WriteMode);
            ELSE
               --even if the append flag is passed if the file doesn't exist open it with W.
                vFile := UTL_FILE.FOPEN(p_Path, p_FileName, 'W');
            END IF;
            --GET HANDLE TO FILE
            IF p_Header IS NOT NULL THEN 
              UTL_FILE.PUT_LINE(vFile, p_Header);
            END IF;
            UTL_FILE.PUT_LINE(vFile, vLine);
            DBMS_OUTPUT.PUT_LINE('Record count > 0');

             --LOOP THROUGH CURSOR VAR
             LOOP
                FETCH p_Input INTO vLine;

                EXIT WHEN p_Input%NOTFOUND;

                UTL_FILE.PUT_LINE(vFile, vLine);

             END LOOP;


             IF p_Footer IS NOT NULL THEN 
                UTL_FILE.PUT_LINE(vFile, p_Footer);
             END IF;

             CLOSE p_Input;
             UTL_FILE.FCLOSE(vFile);
        ELSE
          DBMS_OUTPUT.PUT_LINE('Record count = 0');

        END IF; 


    EXCEPTION
       WHEN UTL_FILE.INVALID_PATH THEN 
           DBMS_OUTPUT.PUT_LINE ('invalid_path'); 
           DBMS_OUTPUT.PUT_LINE(SQLERRM);
           RAISE;

       WHEN UTL_FILE.INVALID_MODE THEN 
           DBMS_OUTPUT.PUT_LINE ('invalid_mode'); 
           DBMS_OUTPUT.PUT_LINE(SQLERRM);
           RAISE;

       WHEN UTL_FILE.INVALID_FILEHANDLE THEN 
           DBMS_OUTPUT.PUT_LINE ('invalid_filehandle'); 
           DBMS_OUTPUT.PUT_LINE(SQLERRM);
           RAISE;

       WHEN UTL_FILE.INVALID_OPERATION THEN 
           DBMS_OUTPUT.PUT_LINE ('invalid_operation'); 
           DBMS_OUTPUT.PUT_LINE(SQLERRM);
           RAISE;

       WHEN UTL_FILE.READ_ERROR THEN  
           DBMS_OUTPUT.PUT_LINE ('read_error');
           DBMS_OUTPUT.PUT_LINE(SQLERRM);
           RAISE;

       WHEN UTL_FILE.WRITE_ERROR THEN 
          DBMS_OUTPUT.PUT_LINE ('write_error'); 
          DBMS_OUTPUT.PUT_LINE(SQLERRM);
           RAISE;

       WHEN UTL_FILE.INTERNAL_ERROR THEN 
          DBMS_OUTPUT.PUT_LINE ('internal_error'); 
          DBMS_OUTPUT.PUT_LINE(SQLERRM);
          RAISE;            
       WHEN OTHERS THEN
          DBMS_OUTPUT.PUT_LINE ('other write error'); 
          DBMS_OUTPUT.PUT_LINE(SQLERRM);
          RAISE;
    END;

How can I change my Cygwin home folder after installation?

Starting with Cygwin 1.7.34, the recommended way to do this is to add a custom db_home setting to /etc/nsswitch.conf. A common wish when doing this is to make your Cygwin home directory equal to your Windows user profile directory. This setting will do that:

db_home: windows

Or, equivalently:

db_home: /%H

You need to use the latter form if you want some variation on this scheme, such as to segregate your Cygwin home files into a subdirectory of your Windows user profile directory:

db_home: /%H/cygwin

There are several other alternative schemes for the windows option plus several other % tokens you can use instead of %H or in addition to it. See the nsswitch.conf syntax description in the Cygwin User Guide for details.

If you installed Cygwin prior to 1.7.34 or have run its mkpasswd utility so that you have an /etc/passwd file, you can change your Cygwin home directory by editing your user's entry in that file. Your home directory is the second-to-last element on your user's line in /etc/passwd

Whichever way you do it, this causes the HOME environment variable to be set during shell startup.²

See this FAQ item for more on the topic.


Footnotes:

  1. Consider moving /etc/passwd and /etc/group out of the way in order to use the new SAM/AD-based mechanism instead.

  2. While it is possible to simply set %HOME% via the Control Panel, it is officially discouraged. Not only does it unceremoniously override the above mechanisms, it doesn't always work, such as when running shell scripts via cron.

Open application after clicking on Notification

See below code. I am using that and it is opening my HomeActivity.

    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);

    Intent notificationIntent = new Intent(context, HomeActivity.class);

    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
            | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    PendingIntent intent = PendingIntent.getActivity(context, 0,
            notificationIntent, 0);

    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(0, notification);

Who is listening on a given TCP port on Mac OS X?

On the latest macOS version you can use this command:

lsof -nP -i4TCP:$PORT | grep LISTEN

If you find it hard to remember then maybe you should create a bash function and export it with a friendlier name like so

vi ~/.bash_profile

and then add the following lines to that file and save it.

function listening_on() {
    lsof -nP -i4TCP:"$1" | grep LISTEN
}

Now you can type listening_on 80 in your Terminal and see which process is listening on port 80.

Change SQLite database mode to read-write

(this error message is typically misleading, and is usually a general permissions error)

On Windows

  • If you're issuing SQL directly against the database, make sure whatever application you're using to run the SQL is running as administrator
  • If an application is attempting the update, the account that it uses to access the database may need permissions on the folder containing your database file. For example, if IIS is accessing the database, the IUSR and IIS_IUSRS may both need appropriate permissions (you can try this by temporarily giving these accounts full control over the folder, checking if this works, then tying down the permissions as appropriate)

Easy way to dismiss keyboard?

Even Simpler than Meagar's answer

overwrite touchesBegan:withEvent:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [textField resignFirstResponder];`
}

This will dismiss the keyboardwhen you touch anywhere in the background.

How to run a C# console application with the console hidden

Simple answer is that: Go to your console app's properties(project's properties).In the "Application" tab, just change the "Output type" to "Windows Application". That's all.

How do I read a specified line in a text file?

You could read line by line so you don't have to read the entire all at once (probably at all)

int i=0
while(!stream.eof() && i!=lineNum)
    stream.readLine()
    i++
line = stream.readLine()

How to set scope property with ng-init?

I had some trouble with $scope.$watch but after a lot of testing I found out that my data-ng-model="User.UserName" was badly named and after I changed it to data-ng-model="UserName" everything worked fine. I expect it to be the . in the name causing the issue.

Install Application programmatically on Android

UpdateNode provides an API for Android to install APK packages from inside another App.

You can just define your Update online and integrate the API into your App - that's it.
Currently the API is in Beta state, but you can already do some tests yourself.

Beside that, UpdateNode offers also displaying messages though the system - pretty useful if you want to tell something important to your users.

I am part of the client dev team and am using at least the message functionality for my own Android App.

See here a description how to integrate the API

How to detect simple geometric shapes using OpenCV

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

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

Below is my example in Python:

import numpy as np
import cv2

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

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

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

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

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

Below is the output:

enter image description here

Remember, it works only for regular shapes.

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

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

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

AttributeError: 'numpy.ndarray' object has no attribute 'append'

Use numpy.concatenate(list1 , list2) or numpy.append() Look into the thread at Append a NumPy array to a NumPy array.

Parser Error when deploy ASP.NET application

After a lot of searching ,i found the problem was in my project dll file .i cleaned and rebuild my project when there were compilation errors ... simple solution is to remove all compilation errors in all pages either by removing contents or commenting lines ,then clean and rebuild your project ... this will sort out your problem ..

How to extend available properties of User.Identity

I also had added on or extended additional columns into my AspNetUsers table. When I wanted to simply view this data I found many examples like the code above with "Extensions" etc... This really amazed me that you had to write all those lines of code just to get a couple values from the current users.

It turns out that you can query the AspNetUsers table like any other table:

 ApplicationDbContext db = new ApplicationDbContext();
 var user = db.Users.Where(x => x.UserName == User.Identity.Name).FirstOrDefault();

Which MIME type to use for a binary file that's specific to my program?

I'd recommend application/octet-stream as RFC2046 says "The "octet-stream" subtype is used to indicate that a body contains arbitrary binary data" and "The recommended action for an implementation that receives an "application/octet-stream" entity is to simply offer to put the data in a file[...]".

I think that way you will get better handling from arbitrary programs, that might barf when encountering your unknown mime type.

Generate class from database table

Set @TableName to the name of your table.

declare @TableName sysname = 'TableName'
declare @Result varchar(max) = 'public class ' + @TableName + '
{'

select @Result = @Result + '
    public ' + ColumnType + NullableSign + ' ' + ColumnName + ' { get; set; }
'
from
(
    select 
        replace(col.name, ' ', '_') ColumnName,
        column_id ColumnId,
        case typ.name 
            when 'bigint' then 'long'
            when 'binary' then 'byte[]'
            when 'bit' then 'bool'
            when 'char' then 'string'
            when 'date' then 'DateTime'
            when 'datetime' then 'DateTime'
            when 'datetime2' then 'DateTime'
            when 'datetimeoffset' then 'DateTimeOffset'
            when 'decimal' then 'decimal'
            when 'float' then 'double'
            when 'image' then 'byte[]'
            when 'int' then 'int'
            when 'money' then 'decimal'
            when 'nchar' then 'string'
            when 'ntext' then 'string'
            when 'numeric' then 'decimal'
            when 'nvarchar' then 'string'
            when 'real' then 'float'
            when 'smalldatetime' then 'DateTime'
            when 'smallint' then 'short'
            when 'smallmoney' then 'decimal'
            when 'text' then 'string'
            when 'time' then 'TimeSpan'
            when 'timestamp' then 'long'
            when 'tinyint' then 'byte'
            when 'uniqueidentifier' then 'Guid'
            when 'varbinary' then 'byte[]'
            when 'varchar' then 'string'
            else 'UNKNOWN_' + typ.name
        end ColumnType,
        case 
            when col.is_nullable = 1 and typ.name in ('bigint', 'bit', 'date', 'datetime', 'datetime2', 'datetimeoffset', 'decimal', 'float', 'int', 'money', 'numeric', 'real', 'smalldatetime', 'smallint', 'smallmoney', 'time', 'tinyint', 'uniqueidentifier') 
            then '?' 
            else '' 
        end NullableSign
    from sys.columns col
        join sys.types typ on
            col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id
    where object_id = object_id(@TableName)
) t
order by ColumnId

set @Result = @Result  + '
}'

print @Result

Sass Variable in CSS calc() function

To use $variables inside your calc() of the height property:

HTML:

<div></div>

SCSS:

$a: 4em;

div {
  height: calc(#{$a} + 7px);
  background: #e53b2c;
}

Difference between web reference and service reference?

Service references deal with endpoints and bindings, which are completely configurable. They let you point your client proxy to a WCF via any transport protocol (HTTP, TCP, Shared Memory, etc)

They are designed to work with WCF.

If you use a WebProxy, you are pretty much binding yourself to using WCF over HTTP

POST: sending a post request in a url itself

It is not possible to send POST parameters in the url in a starightforward manner. POST request in itself means sending information in the body.

I found a fairly simple way to do this. Use Postman by Google, which allows you to specify the content-type(a header field) as application/json and then provide name-value pairs as parameters.

You can find clear directions at [2020-09-04: broken link - see comment] http://docs.brightcove.com/en/video-cloud/player-management/guides/postman.html

Just use your url in the place of theirs.

Hope it helps

Spring Boot: How can I set the logging level with application.properties?

You can do that using your application.properties.

logging.level.=ERROR -> Sets the root logging level to error
...
logging.level.=DEBUG -> Sets the root logging level to DEBUG

logging.file=${java.io.tmpdir}/myapp.log -> Sets the absolute log file path to TMPDIR/myapp.log

A sane default set of application.properties regarding logging using profiles would be: application.properties:

spring.application.name=<your app name here>
logging.level.=ERROR
logging.file=${java.io.tmpdir}/${spring.application.name}.log

application-dev.properties:

logging.level.=DEBUG
logging.file=

When you develop inside your favourite IDE you just add a -Dspring.profiles.active=dev as VM argument to the run/debug configuration of your app.

This will give you error only logging in production and debug logging during development WITHOUT writing the output to a log file. This will improve the performance during development ( and save SSD drives some hours of operation ;) ).

How do you completely remove the button border in wpf?

You may already know that putting your Button inside of a ToolBar gives you this behavior, but if you want something that will work across ALL current themes with any sort of predictability, you'll need to create a new ControlTemplate.

Prashant's solution does not work with a Button not in a toolbar when the Button has focus. It also doesn't work 100% with the default theme in XP -- you can still see faint gray borders when your container Background is white.

Determine the number of rows in a range

Function ListRowCount(ByVal FirstCellName as String) as Long
    With thisworkbook.Names(FirstCellName).RefersToRange
        If isempty(.Offset(1,0).value) Then 
            ListRowCount = 1
        Else
            ListRowCount = .End(xlDown).row - .row + 1
        End If
    End With
End Function

But if you are damn sure there's nothing around the list, then just thisworkbook.Names(FirstCellName).RefersToRange.CurrentRegion.rows.count

How can I transition height: 0; to height: auto; using CSS?

Check out my post on a somewhat related question.

Basically, start at height: 0px;, and let it transition to an exact height computed by JavaScript.

function setInfoHeight() {
  $(window).on('load resize', function() {
    $('.info').each(function () {
      var current = $(this);
      var closed = $(this).height() == 0;
      current.show().height('auto').attr('h', current.height() );
      current.height(closed ? '0' : current.height());
    });
  });

Whenever the page loads/resized, the element with class info will get its h attribute updated. Then a button triggers the style="height: __" to set it to that previously set h value.

function moreInformation() {
  $('.icon-container').click(function() {
    var info = $(this).closest('.dish-header').next('.info'); // Just the one info
    var icon = $(this).children('.info-btn'); // Select the logo

    // Stop any ongoing animation loops. Without this, you could click button 10
    // times real fast, and watch an animation of the info showing and closing
    // for a few seconds after
    icon.stop();
    info.stop();

    // Flip icon and hide/show info
    icon.toggleClass('flip');

    // Metnod 1, animation handled by JS
    // info.slideToggle('slow');

    // Method 2, animation handled by CSS, use with setInfoheight function
    info.toggleClass('active').height(icon.is('.flip') ? info.attr('h') : '0');

  });
};

Here's the styling for the info class.

.info {
  padding: 0 1em;
  line-height: 1.5em;
  display: inline-block;
  overflow: hidden;
  height: 0px;
  transition: height 0.6s, padding 0.6s;
  &.active {
    border-bottom: $thin-line;
    padding: 1em;
  }
}

Styling might not be supported cross-browser. Here is the live example for this code:

CodePen

How to get value of checked item from CheckedListBox?

try:

  foreach (var item in chlCompanies.CheckedItems){
     item.Value //ID
     item.Text //CompanyName
  }

Differences between Oracle JDK and OpenJDK

Also for Java 8 an interesting performance benchmark for reactive (non-blocking) Spring Boot REST application being hosted on various JVMs by AMIS Technology Blog has been published in Nov 2018 showing that, among other differences:

  • OpenJDK has higher CPU usage than OracleJDK,
  • OpenJDK has slightly lower response time than OracleJDK,
  • OpenJDK has higher memory usage than OracleJDK,

For details please see the source article.

Of course YMMV, this is just one of the benchmarks.

Most Useful Attributes

If I were to do a code coverage crawl, I think these two would be top:

 [Serializable]
 [WebMethod]

What is C# equivalent of <map> in C++?

.NET Framework provides many collection classes too. You can use Dictionary in C#. Please find the below msdn link for details and samples http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

How can I count all the lines of code in a directory recursively?

I have BusyBox installed on my Windows system. So here is what I did.

ECHO OFF
for /r %%G in (*.php) do (
busybox grep . "%%G" | busybox wc -l
)

Redis: Show database size/size for keys

The solution from the comments deserves it's own answer:

redis-cli --bigkeys

Jersey stopped working with InjectionManagerFactory not found

Add this dependency:

<dependency>
    <groupId>org.glassfish.jersey.inject</groupId>
    <artifactId>jersey-hk2</artifactId>
    <version>2.28</version>
</dependency>

cf. https://stackoverflow.com/a/44536542/1070215

Make sure not to mix your Jersey dependency versions. This answer says version "2.28", but use whatever version your other Jersey dependency versions are.

Convert Pandas column containing NaNs to dtype `int`

If you want to use it when you chain methods, you can use assign:

df = (
     df.assign(col = lambda x: x['col'].astype('Int64'))
)

How do you debug PHP scripts?

Try Eclipse PDT to setup an Eclipse environment that has debugging features like you mentioned. The ability to step into the code is a much better way to debug then the old method of var_dump and print at various points to see where your flow goes wrong. When all else fails though and all I have is SSH and vim I still var_dump()/die() to find where the code goes south.

tkinter: Open a new window with a button prompt

Here's the nearly shortest possible solution to your question. The solution works in python 3.x. For python 2.x change the import to Tkinter rather than tkinter (the difference being the capitalization):

import tkinter as tk
#import Tkinter as tk  # for python 2
    
def create_window():
    window = tk.Toplevel(root)

root = tk.Tk()
b = tk.Button(root, text="Create new window", command=create_window)
b.pack()

root.mainloop()

This is definitely not what I recommend as an example of good coding style, but it illustrates the basic concepts: a button with a command, and a function that creates a window.

Cosine Similarity between 2 Number Lists

All the answers are great for situations where you cannot use NumPy. If you can, here is another approach:

def cosine(x, y):
    dot_products = np.dot(x, y.T)
    norm_products = np.linalg.norm(x) * np.linalg.norm(y)
    return dot_products / (norm_products + EPSILON)

Also bear in mind about EPSILON = 1e-07 to secure the division.

What are the "standard unambiguous date" formats for string-to-date conversion in R?

This works perfectly for me, not matter how the date was coded previously.

library(lubridate)
data$created_date1 <- mdy_hm(data$created_at)
data$created_date1 <- as.Date(data$created_date1)

Angular 2 ngfor first, last, index loop

By this you can get any index in *ngFor loop in ANGULAR ...

<ul>
  <li *ngFor="let object of myArray; let i = index; let first = first ;let last = last;">
    <div *ngIf="first">
       // write your code...
    </div>

    <div *ngIf="last">
       // write your code...
    </div>
  </li>
</ul>

We can use these alias in *ngFor

  • index : number : let i = index to get all index of object.
  • first : boolean : let first = first to get first index of object.
  • last : boolean : let last = last to get last index of object.
  • odd : boolean : let odd = odd to get odd index of object.
  • even : boolean : let even = even to get even index of object.

What’s the best way to check if a file exists in C++? (cross platform)

How about access?

#include <io.h>

if (_access(filename, 0) == -1)
{
    // File does not exist
}

How to get item's position in a list?

If your list got large enough and you only expected to find the value in a sparse number of indices, consider that this code could execute much faster because you don't have to iterate every value in the list.

lookingFor = 1
i = 0
index = 0
try:
  while i < len(testlist):
    index = testlist.index(lookingFor,i)
    i = index + 1
    print index
except ValueError: #testlist.index() cannot find lookingFor
  pass

If you expect to find the value a lot you should probably just append "index" to a list and print the list at the end to save time per iteration.

getApplication() vs. getApplicationContext()

Compare getApplication() and getApplicationContext().

getApplication returns an Application object which will allow you to manage your global application state and respond to some device situations such as onLowMemory() and onConfigurationChanged().

getApplicationContext returns the global application context - the difference from other contexts is that for example, an activity context may be destroyed (or otherwise made unavailable) by Android when your activity ends. The Application context remains available all the while your Application object exists (which is not tied to a specific Activity) so you can use this for things like Notifications that require a context that will be available for longer periods and independent of transient UI objects.

I guess it depends on what your code is doing whether these may or may not be the same - though in normal use, I'd expect them to be different.

Ignore 'Security Warning' running script from command line

This is touched in "PowerShell Execution Policies in Standard Images" on Lee Holmes' Blog and "PowerShell’s Security Guiding Principles" on the Windows Power Shell Blog .

Summary Some machines treat UNC paths as the big bad internet, so PowerShell treats them as remote files. You can either disable this feature on those servers (UncAsIntranet = 0,) or add the remote machines to your trusted hosts.

If you want to do neither, PowerShell v2 supports an -ExecutionPolicy parameter that does exactly what your pseudocode wants. PowerShell -ExecutionPolicy Bypass -File (...).

How to read a file line-by-line into a list?

Another option is numpy.genfromtxt, for example:

import numpy as np
data = np.genfromtxt("yourfile.dat",delimiter="\n")

This will make data a NumPy array with as many rows as are in your file.

XAMPP - Port 80 in use by "Unable to open process" with PID 4! 12

Another very easy option is to simply set Apache to listen on a different port. This can be done by clicking on the "Config" button on the same line as the "Apache" module, select the "httpd.conf" file in the dropdown, then change the "Listen 80" line to "Listen 8080". Save the file and close it.

Now it avoids Port 80 and uses Port 8080 instead without issue. The only additional thing you need to do is make sure to put localhost:8080 in the browser so the browser knows to look on Port 8080. Otherwise it defaults to Port 80 and won't find your local site.

This will also require you to restart Apache for the change to take effect.

Voila! Fixed.

Remove trailing newline from the elements of a string list

This can be done using list comprehensions as defined in PEP 202

[w.strip() for w in  ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']]

Transparent image - background color

If I understand you right, you can do this:

<img src="image.png" style="background-color:red;" />

In fact, you can even apply a whole background-image to the image, resulting in two "layers" without the need for multi-background support in the browser ;)

redistributable offline .NET Framework 3.5 installer for Windows 8

Microsoft .NET framework 3.5 can be installed on windows 10 without having installation media. The file you need is called microsoft-windows-netfx3-ondemand-package.cab. Just google it and you will get the download links. After downloading it, copy that file to C:\dotnet35 and run the following command.

Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:c:\dotnet35 /LimitAccess

Tested and worked in Windows 10 without any issue.

Getting HTML elements by their attribute names

Just another answer

Array.prototype.filter.call(
    document.getElementsByTagName('span'),
    function(el) {return el.getAttribute('property') == 'v.name';}
);

In future

Array.prototype.filter.call(
    document.getElementsByTagName('span'),
    (el) => el.getAttribute('property') == 'v.name'
)

3rd party edit

Intro

  • The call() method calls a function with a given this value and arguments provided individually.

  • The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Given this html markup

<span property="a">apple - no match</span>
<span property="v:name">onion - match</span>
<span property="b">root - match</span>
<span property="v:name">tomato - match</span>
<br />
<button onclick="findSpan()">find span</button>

you can use this javascript

function findSpan(){

    var spans = document.getElementsByTagName('span');
    var spansV = Array.prototype.filter.call(
         spans,
         function(el) {return el.getAttribute('property') == 'v:name';}
    );
    return spansV;
}

See demo

How can I regenerate ios folder in React Native project?

As @Alok mentioned in the comments, you can do react-native eject to generate the ios and android folders. But you will need an app.json in your project first.

{"name": "example", "displayName": "Example"}

Matplotlib different size subplots

I used pyplot's axes object to manually adjust the sizes without using GridSpec:

import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.2)
y = np.sin(x)

# definitions for the axes
left, width = 0.07, 0.65
bottom, height = 0.1, .8
bottom_h = left_h = left+width+0.02

rect_cones = [left, bottom, width, height]
rect_box = [left_h, bottom, 0.17, height]

fig = plt.figure()

cones = plt.axes(rect_cones)
box = plt.axes(rect_box)

cones.plot(x, y)

box.plot(y, x)

plt.show()

jquery select element by xpath

If you are debugging or similar - In chrome developer tools, you can simply use

$x('/html/.//div[@id="text"]')

Handle spring security authentication exceptions with @ExceptionHandler

Update: If you like and prefer to see the code directly, then I have two examples for you, one using standard Spring Security which is what you are looking for, the other one is using the equivalent of Reactive Web and Reactive Security:
- Normal Web + Jwt Security
- Reactive Jwt

The one that I always use for my JSON based endpoints looks like the following:

@Component
public class JwtAuthEntryPoint implements AuthenticationEntryPoint {

    @Autowired
    ObjectMapper mapper;

    private static final Logger logger = LoggerFactory.getLogger(JwtAuthEntryPoint.class);

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException e)
            throws IOException, ServletException {
        // Called when the user tries to access an endpoint which requires to be authenticated
        // we just return unauthorizaed
        logger.error("Unauthorized error. Message - {}", e.getMessage());

        ServletServerHttpResponse res = new ServletServerHttpResponse(response);
        res.setStatusCode(HttpStatus.UNAUTHORIZED);
        res.getServletResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        res.getBody().write(mapper.writeValueAsString(new ErrorResponse("You must authenticated")).getBytes());
    }
}

The object mapper becomes a bean once you add the spring web starter, but I prefer to customize it, so here is my implementation for ObjectMapper:

  @Bean
    public Jackson2ObjectMapperBuilder objectMapperBuilder() {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.modules(new JavaTimeModule());

        // for example: Use created_at instead of createdAt
        builder.propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);

        // skip null fields
        builder.serializationInclusion(JsonInclude.Include.NON_NULL);
        builder.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        return builder;
    }

The default AuthenticationEntryPoint you set in your WebSecurityConfigurerAdapter class:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// ............
   @Autowired
    private JwtAuthEntryPoint unauthorizedHandler;
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                .authorizeRequests()
                // .antMatchers("/api/auth**", "/api/login**", "**").permitAll()
                .anyRequest().permitAll()
                .and()
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);


        http.headers().frameOptions().disable(); // otherwise H2 console is not available
        // There are many ways to ways of placing our Filter in a position in the chain
        // You can troubleshoot any error enabling debug(see below), it will print the chain of Filters
        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    }
// ..........
}

Is there a float input type in HTML5?

The number type has a step value controlling which numbers are valid (along with max and min), which defaults to 1. This value is also used by implementations for the stepper buttons (i.e. pressing up increases by step).

Simply change this value to whatever is appropriate. For money, two decimal places are probably expected:

<input type="number" step="0.01">

(I'd also set min=0 if it can only be positive)

If you'd prefer to allow any number of decimal places, you can use step="any" (though for currencies, I'd recommend sticking to 0.01). In Chrome & Firefox, the stepper buttons will increment / decrement by 1 when using any. (thanks to Michal Stefanow's answer for pointing out any, and see the relevant spec here)

Here's a playground showing how various steps affect various input types:

_x000D_
_x000D_
<form>_x000D_
  <input type=number step=1 /> Step 1 (default)<br />_x000D_
  <input type=number step=0.01 /> Step 0.01<br />_x000D_
  <input type=number step=any /> Step any<br />_x000D_
  <input type=range step=20 /> Step 20<br />_x000D_
  <input type=datetime-local step=60 /> Step 60 (default)<br />_x000D_
  <input type=datetime-local step=1 /> Step 1<br />_x000D_
  <input type=datetime-local step=any /> Step any<br />_x000D_
  <input type=datetime-local step=0.001 /> Step 0.001<br />_x000D_
  <input type=datetime-local step=3600 /> Step 3600 (1 hour)<br />_x000D_
  <input type=datetime-local step=86400 /> Step 86400 (1 day)<br />_x000D_
  <input type=datetime-local step=70 /> Step 70 (1 min, 10 sec)<br />_x000D_
</form>
_x000D_
_x000D_
_x000D_


As usual, I'll add a quick note: remember that client-side validation is just a convenience to the user. You must also validate on the server-side!

Getting HTTP code in PHP using curl

curl_getinfo — Get information regarding a specific transfer

Check curl_getinfo

<?php
// Create a curl handle
$ch = curl_init('http://www.yahoo.com/');

// Execute
curl_exec($ch);

// Check if any error occurred
if(!curl_errno($ch))
{
 $info = curl_getinfo($ch);

 echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url'];
}

// Close handle
curl_close($ch);

What's the difference between @JoinColumn and mappedBy when using a JPA @OneToMany association

@JoinColumn could be used on both sides of the relationship. The question was about using @JoinColumn on the @OneToMany side (rare case). And the point here is in physical information duplication (column name) along with not optimized SQL query that will produce some additional UPDATE statements.

According to documentation:

Since many to one are (almost) always the owner side of a bidirectional relationship in the JPA spec, the one to many association is annotated by @OneToMany(mappedBy=...)

@Entity
public class Troop {
    @OneToMany(mappedBy="troop")
    public Set<Soldier> getSoldiers() {
    ...
}

@Entity
public class Soldier {
    @ManyToOne
    @JoinColumn(name="troop_fk")
    public Troop getTroop() {
    ...
} 

Troop has a bidirectional one to many relationship with Soldier through the troop property. You don't have to (must not) define any physical mapping in the mappedBy side.

To map a bidirectional one to many, with the one-to-many side as the owning side, you have to remove the mappedBy element and set the many to one @JoinColumn as insertable and updatable to false. This solution is not optimized and will produce some additional UPDATE statements.

@Entity
public class Troop {
    @OneToMany
    @JoinColumn(name="troop_fk") //we need to duplicate the physical information
    public Set<Soldier> getSoldiers() {
    ...
}

@Entity
public class Soldier {
    @ManyToOne
    @JoinColumn(name="troop_fk", insertable=false, updatable=false)
    public Troop getTroop() {
    ...
}

Find and replace specific text characters across a document with JS

Similar to @max-malik's answer, but without using jQuery, you can also do this using document.createTreeWalker:

_x000D_
_x000D_
button.addEventListener('click', e => {_x000D_
  const treeWalker = document.createTreeWalker(document.body);_x000D_
  while (treeWalker.nextNode()) {_x000D_
    const node = treeWalker.currentNode;_x000D_
    node.textContent = node.textContent.replace(/@/g, '$');_x000D_
  }_x000D_
})
_x000D_
<div>This is an @ that we are @ replacing.</div>_x000D_
<div>This is another @ that we are replacing.</div>_x000D_
<div>_x000D_
  <span>This is an @ in a span in @ div.</span>_x000D_
</div>_x000D_
<br>_x000D_
<input id="button" type="button" value="Replace @ with $" />
_x000D_
_x000D_
_x000D_

How to extract file name from path?

Function file_name_only(file_path As String) As String

Dim temp As Variant

temp = Split(file_path, Application.PathSeparator)

file_name_only = temp(UBound(temp))

End Function
  1. here you give your file name as input of the function
  2. the split function of VBA splits the path in different portion by using "\" as path separator & stores them in an array named "temp"
  3. the UBound() finds the max item number of array and finally assigns the result to "file_name_only" function

Hope this will be helpful.

How to remove folders with a certain name

To delete all directories with the name foo, run:

find -type d -name foo -a -prune -exec rm -rf {} \;

The other answers are missing an important thing: the -prune option. Without -prune, GNU find will delete the directory with the matching name and then try to recurse into it to find more directories that match. The -prune option tells it to not recurse into a directory that matched the conditions.

Show only two digit after decimal

First thing that should pop in a developer head while formatting a number into char sequence should be care of such details like do it will be possible to reverse the operation.

And other aspect is providing proper result. So you want to truncate the number or round it.

So before you start you should ask your self, am i interested on the value or not.

To achieve your goal you have multiple options but most of them refer to Format and Formatter, but i just suggest to look in this answer.

How do I refresh a DIV content?

For div refreshing without creating div inside yours with same id, you should use this inside your function

$("#yourDiv").load(" #yourDiv > *");

How to align an input tag to the center without specifying the width?

you can put in a table cell and then align the cell content.

<table>
   <tr>
     <td align="center">
        <input type="button" value="Some Button">
     </td>
   </tr>
</table>

multiple axis in matplotlib with different scales

if you want to do very quick plots with secondary Y-Axis then there is much easier way using Pandas wrapper function and just 2 lines of code. Just plot your first column then plot the second but with parameter secondary_y=True, like this:

df.A.plot(label="Points", legend=True)
df.B.plot(secondary_y=True, label="Comments", legend=True)

This would look something like below:

enter image description here

You can do few more things as well. Take a look at Pandas plotting doc.

Save PHP variables to a text file

Use serialize() on the variable, then save the string to a file. later you will be able to read the serialed var from the file and rebuilt the original var (wether it was a string or an array or an object)

How to set size for local image using knitr for markdown?

Here's some options that keep the file self-contained without retastering the image:

Wrap the image in div tags

<div style="width:300px; height:200px">
![Image](path/to/image)
</div>

Use a stylesheet

test.Rmd

---
title: test
output: html_document
css: test.css
---

## Page with an image {#myImagePage}

![Image](path/to/image)

test.css

#myImagePage img {
  width: 400px;
  height: 200px;
}

If you have more than one image you might need to use the nth-child pseudo-selector for this second option.

sed command with -i option failing on Mac, but works on Linux

Or, you can install the GNU version of sed in your Mac, called gsed, and use it using the standard Linux syntax.

For that, install gsed using ports (if you don't have it, get it at http://www.macports.org/) by running sudo port install gsed. Then, you can run sed -i 's/old_link/new_link/g' *

Add my custom http header to Spring RestTemplate request / extend RestTemplate

You can pass custom http headers with RestTemplate exchange method as below.

HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(new MediaType[] { MediaType.APPLICATION_JSON }));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-TP-DeviceID", "your value");

HttpEntity<RestRequest> entityReq = new HttpEntity<RestRequest>(request, headers);

RestTemplate template = new RestTemplate();

ResponseEntity<RestResponse> respEntity = template
    .exchange("RestSvcUrl", HttpMethod.POST, entityReq, RestResponse.class);

EDIT : Below is the updated code. This link has several ways of calling rest service with examples

RestTemplate restTemplate = new RestTemplate();

HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-TP-DeviceID", "your value");

HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

ResponseEntity<Mall[]> respEntity = restTemplate.exchange(url, HttpMethod.POST, entity, Mall[].class);

Mall[] resp = respEntity.getBody();

how to access master page control from content page

You cannot use var in a field, only on local variables.

But even this won't work:

Site master = Master as Site;

Because you cannot use this in a field and Master as Site is the same as this.Master as Site. So just initialize the field from Page_Init when the page is fully initialized and you can use this:

Site master = null;

protected void Page_Init(object sender, EventArgs e)
{            
    master = this.Master as Site;
}

How to create a responsive image that also scales up in Bootstrap 3

If setting a fixed width on the image is not an option, here's an alternative solution.

Having a parent div with display: table & table-layout: fixed. Then setting the image to display: table-cell and max-width to 100%. That way the image will fit to the width of its parent.

Example:

<style>
    .wrapper { float: left; clear: left; display: table; table-layout: fixed; }
    img.img-responsive { display: table-cell; max-width: 100%; }
</style>
<div class="wrapper col-md-3">
    <img class="img-responsive" src="https://www.google.co.uk/images/srpr/logo11w.png"/>
</div>

Fiddle: http://jsfiddle.net/5y62c4af/

MySQL "Group By" and "Order By"

Here's one approach:

SELECT cur.textID, cur.fromEmail, cur.subject, 
     cur.timestamp, cur.read
FROM incomingEmails cur
LEFT JOIN incomingEmails next
    on cur.fromEmail = next.fromEmail
    and cur.timestamp < next.timestamp
WHERE next.timestamp is null
and cur.toUserID = '$userID' 
ORDER BY LOWER(cur.fromEmail)

Basically, you join the table on itself, searching for later rows. In the where clause you state that there cannot be later rows. This gives you only the latest row.

If there can be multiple emails with the same timestamp, this query would need refining. If there's an incremental ID column in the email table, change the JOIN like:

LEFT JOIN incomingEmails next
    on cur.fromEmail = next.fromEmail
    and cur.id < next.id

How to delete an instantiated object Python?

object.__del__(self) is called when the instance is about to be destroyed.

>>> class Test:
...     def __del__(self):
...         print "deleted"
... 
>>> test = Test()
>>> del test
deleted

Object is not deleted unless all of its references are removed(As quoted by ethan)

Also, From Python official doc reference:

del x doesn’t directly call x.del() — the former decrements the reference count for x by one, and the latter is only called when x‘s reference count reaches zero

webpack: Module not found: Error: Can't resolve (with relative path)

Look the path for example this import is not correct import Navbar from '@/components/Navbar.vue' should look like this ** import Navbar from './components/Navbar.vue'**

Maven Out of Memory Build Failure

While building the project on Unix/Linux platform, set Maven options syntax as below. Notice that single qoutation signs, not double qoutation.

export MAVEN_OPTS='-Xmx512m -XX:MaxPermSize=128m'

Datatables - Search Box outside datatable

I had the same problem.

I tried all alternatives posted, but no work, I used a way that is not right but it worked perfectly.

Example search input

<input id="searchInput" type="text"> 

the jquery code

$('#listingData').dataTable({
  responsive: true,
  "bFilter": true // show search input
});
$("#listingData_filter").addClass("hidden"); // hidden search input

$("#searchInput").on("input", function (e) {
   e.preventDefault();
   $('#listingData').DataTable().search($(this).val()).draw();
});

Naming Conventions: What to name a boolean variable?

isBeforeTheLastItem

isInFrontOfTheLastItem

isTowardsTheFrontOfTheList

Maybe too wordy but they may help give you ideas.

Half circle with CSS (border, outline only)

I had a similar issue not long time ago and this was how I solved it

_x000D_
_x000D_
.rotated-half-circle {_x000D_
  /* Create the circle */_x000D_
  width: 40px;_x000D_
  height: 40px;_x000D_
  border: 10px solid black;_x000D_
  border-radius: 50%;_x000D_
  /* Halve the circle */_x000D_
  border-bottom-color: transparent;_x000D_
  border-left-color: transparent;_x000D_
  /* Rotate the circle */_x000D_
  transform: rotate(-45deg);_x000D_
}
_x000D_
<div class="rotated-half-circle"></div>
_x000D_
_x000D_
_x000D_

Row count where data exists

I've implemented it like this:

Public Function LastRowWithData(ByVal strCol As String, ByVal intRow As Integer) As Long
    Range(strCol & intRow).Select
    LastRowWithData= ActiveSheet.Cells(ActiveSheet.Rows.Count, strCol).End(xlUp).Row
End Function

How to Display Multiple Google Maps per page with API V3

I needed to load dynamic number of google maps, with dynamic locations. So I ended up with something like this. Hope it helps. I add LatLng as data-attribute on map div.

So, just create divs with class "maps". Every map canvas can than have a various IDs and LatLng like this. Of course you can set up various data attributes for zoom and so...

Maybe the code might be cleaner, but it works for me pretty well.

<div id="map123" class="maps" data-gps="46.1461154,17.1580882"></div>
<div id="map456" class="maps" data-gps="45.1461154,13.1080882"></div>

  <script>
      var map;
      function initialize() {
        // Get all map canvas with ".maps" and store them to a variable.
        var maps = document.getElementsByClassName("maps");

        var ids, gps, mapId = '';

        // Loop: Explore all elements with ".maps" and create a new Google Map object for them
        for(var i=0; i<maps.length; i++) {

          // Get ID of single div
          mapId = document.getElementById(maps[i].id);

          // Get LatLng stored in data attribute. 
          // !!! Make sure there is no space in data-attribute !!!
          // !!! and the values are separated with comma !!!
          gps = mapId.getAttribute('data-gps');

          // Convert LatLng to an array
          gps = gps.split(",");

          // Create new Google Map object for single canvas 
          map = new google.maps.Map(mapId, {
            zoom: 15,
            // Use our LatLng array bellow
            center: new google.maps.LatLng(parseFloat(gps[0]), parseFloat(gps[1])),
            mapTypeId: 'roadmap',
            mapTypeControl: true,
            zoomControlOptions: {
                position: google.maps.ControlPosition.RIGHT_TOP
            }
          });

          // Create new Google Marker object for new map
          var marker = new google.maps.Marker({
            // Use our LatLng array bellow
            position: new google.maps.LatLng(parseFloat(gps[0]), parseFloat(gps[1])),
            map: map
          });
        }
      }
  </script>

How to get current route in Symfony 2?

Symfony 2.0-2.1
Use this:

    $router = $this->get("router");
    $route = $router->match($this->getRequest()->getPathInfo());
    var_dump($route['_route']);

That one will not give you _internal.

Update for Symfony 2.2+: This is not working starting Symfony 2.2+. I opened a bug and the answer was "by design". If you wish to get the route in a sub-action, you must pass it in as an argument

{{ render(controller('YourBundle:Menu:menu', { '_locale': app.request.locale, 'route': app.request.attributes.get('_route') } )) }}

And your controller:

public function menuAction($route) { ... }

Why would you use String.Equals over ==?

It's entirely likely that a large portion of the developer base comes from a Java background where using == to compare strings is wrong and doesn't work.

In C# there's no (practical) difference (for strings) as long as they are typed as string.

If they are typed as object or T then see other answers here that talk about generic methods or operator overloading as there you definitely want to use the Equals method.

JNZ & CMP Assembly Instructions

At first it seems as if JNZ means jump if not Zero (0), as in jump if zero flag is 1/set.

But in reality it means Jump (if) not Zero (is set).

If 0 = not set and 1 = set then just remember:
JNZ Jumps if the zero flag is not set (0)

Using Ansible set_fact to create a dictionary from register results

I think I got there in the end.

The task is like this:

- name: Populate genders
  set_fact:
    genders: "{{ genders|default({}) | combine( {item.item.name: item.stdout} ) }}"
  with_items: "{{ people.results }}"

It loops through each of the dicts (item) in the people.results array, each time creating a new dict like {Bob: "male"}, and combine()s that new dict in the genders array, which ends up like:

{
    "Bob": "male",
    "Thelma": "female"
}

It assumes the keys (the name in this case) will be unique.


I then realised I actually wanted a list of dictionaries, as it seems much easier to loop through using with_items:

- name: Populate genders
  set_fact:
    genders: "{{ genders|default([]) + [ {'name': item.item.name, 'gender': item.stdout} ] }}"
  with_items: "{{ people.results }}"

This keeps combining the existing list with a list containing a single dict. We end up with a genders array like this:

[
    {'name': 'Bob', 'gender': 'male'},
    {'name': 'Thelma', 'gender': 'female'}
]

How to insert data into elasticsearch

I started off using curl, but since have migrated to use kibana. Here is some more information on the ELK stack from elastic.co (E elastic search, K kibana): https://www.elastic.co/elk-stack

With kibana your POST requests are a bit more simple:

POST /<INDEX_NAME>/<TYPE_NAME>
{
    "field": "value",
    "id": 1,
    "account_id": 213,
    "name": "kimchy"
}

When creating a service with sc.exe how to pass in context parameters?

A service creation example of using backslashes with many double quotes.

C:\Windows\system32>sc.exe create teagent binpath= "\"C:\Program Files\Tripwire\TE\Agent\bin\wrapper.exe\" -s \"C:\Program Files\Tripwire\TE\Agent\bin\agent.conf\"" DisplayName= "Tripwire Enterprise Agent"

[SC] CreateService SUCCESS

Inputting a default image in case the src attribute of an html <img> is not valid?

a simple img-element is not very flexible so i combined it with a picture-element. this way no CSS is needed. when an error occurs, all srcset's are set to the fallback version. a broken link image is not showing up. it does not load unneeded image versions. the picture-element supports responsive design and multiple fallbacks for types that are not supported by the browser.

<picture>
    <source id="s1" srcset="image1_not_supported_by_browser.webp" type="image/webp">
    <source id="s2" srcset="image2_broken_link.png" type="image/png">
    <img src="image3_fallback.jpg" alt="" onerror="this.onerror=null;document.getElementById('s1').srcset=document.getElementById('s2').srcset=this.src;">
</picture>

NameError: name 'reduce' is not defined in Python

You can add

from functools import reduce

before you use the reduce.

How to disable GCC warnings for a few lines of code

I know the question is about GCC, but for people looking for how to do this in other and/or multiple compilers…

TL;DR

You might want to take a look at Hedley, which is a public-domain single C/C++ header I wrote which does a lot of this stuff for you. I'll put a quick section about how to use Hedley for all this at the end of this post.

Disabling the warning

#pragma warning (disable: …) has equivalents in most compilers:

  • MSVC: #pragma warning(disable:4996)
  • GCC: #pragma GCC diagnostic ignored "-W…" where the ellipsis is the name of the warning; e.g., #pragma GCC diagnostic ignored "-Wdeprecated-declarations.
  • clang: #pragma clang diagnostic ignored "-W…". The syntax is basically the same as GCC's, and many of the warning names are the same (though many aren't).
  • Intel C Compiler: Use the MSVC syntax, but keep in mind that warning numbers are totally different. Example: #pragma warning(disable:1478 1786).
  • PGI/NVidia: There is a diag_suppress pragma: #pragma diag_suppress 1215,1444. Note that all warning numbers increased by one in 20.7 (the first NV HPC release).
  • TI: There is a diag_suppress pragma with the same syntax (but different warning numbers!) as PGI: pragma diag_suppress 1291,1718
  • Oracle Developer Studio (suncc): there is an error_messages pragma. Annoyingly, the warnings are different for the C and C++ compilers. Both of these disable basically the same warnings:
    • C: #pragma error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)
    • C++: #pragma error_messages(off,symdeprecated,symdeprecated2)
  • IAR: also uses diag_suppress like PGI and TI, but the syntax is different. Some of the warning numbers are the same, but I others have diverged: #pragma diag_suppress=Pe1444,Pe1215
  • Pelles C: similar to MSVC, though again the numbers are different #pragma warn(disable:2241)

For most compilers it is often a good idea to check the compiler version before trying to disable it, otherwise you'll just end up triggering another warning. For example, GCC 7 added support for the -Wimplicit-fallthrough warning, so if you care about GCC before 7 you should do something like

#if defined(__GNUC__) && (__GNUC__ >= 7)
#  pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
#endif

For clang and compilers based on clang such as newer versions of XL C/C++ and armclang, you can check to see if the compiler knows about a particular warning using the __has_warning() macro.

#if __has_warning("-Wimplicit-fallthrough")
#  pragma clang diagnostic ignored "-Wimplicit-fallthrough"
#endif

Of course you also have to check to see if the __has_warning() macro exists:

#if defined(__has_warning)
#  if __has_warning("-Wimplicit-fallthrough")
#    pragma clang diagnostic ignored "-Wimplicit-fallthrough"
#  endif
#endif

You may be tempted to do something like

#if !defined(__has_warning)
#  define __has_warning(warning)
#endif

So you can use __has_warning a bit more easily. Clang even suggests something similar for the __has_builtin() macro in their manual. Do not do this. Other code may check for __has_warning and fall back on checking compiler versions if it doesn't exist, and if you define __has_warning you'll break their code. The right way to do this is to create a macro in your namespace. For example:

#if defined(__has_warning)
#  define MY_HAS_WARNING(warning) __has_warning(warning)
#else
#  define MY_HAS_WARNING(warning) (0)
#endif

Then you can do stuff like

#if MY_HAS_WARNING(warning)
#  pragma clang diagnostic ignored "-Wimplicit-fallthrough"
#elif defined(__GNUC__) && (__GNUC__ >= 7)
#  pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
#endif

Pushing and popping

Many compilers also support a way to push and pop warnings onto a stack. For example, this will disable a warning on GCC for one line of code, then return it to its previous state:

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated"
call_deprecated_function();
#pragma GCC diagnostic pop

Of course there isn't a lot of agreement across compilers about the syntax:

  • GCC 4.6+: #pragma GCC diagnostic push / #pragma GCC diagnostic pop
  • clang: #pragma clang diagnostic push / #pragma diagnostic pop
  • Intel 13+ (and probably earlier): #pragma warning(push) / #pragma warning(pop)
  • MSVC 15+ (VS 9.0 / 2008): #pragma warning(push) / #pragma warning(pop)
  • ARM 5.6+: #pragma push / #pragma pop
  • TI 8.1+: #pragma diag_push / #pragma diag_pop
  • Pelles C 2.90+ (and probably earlier): #pragma warning(push) / #pragma warning(pop)

If memory serves, for some very old versions of GCC (like 3.x, IIRC) the push/pop pragmas had to be outside of the function.

Hiding the gory details

For most compilers it's possible to hide the logic behind macros using _Pragma, which was introduced in C99. Even in non-C99 mode, most compilers support _Pragma; the big exception is MSVC, which has its own __pragma keyword with a different syntax. The standard _Pragma takes a string, Microsoft's version doesn't:

#if defined(_MSC_VER)
#  define PRAGMA_FOO __pragma(foo)
#else
#  define PRAGMA_FOO _Pragma("foo")
#endif
PRAGMA_FOO

Is roughly equivalent, once preprocessed, to

#pragma foo

This lets us create macros so we can write code like

MY_DIAGNOSTIC_PUSH
MY_DIAGNOSTIC_DISABLE_DEPRECATED
call_deprecated_function();
MY_DIAGNOSTIC_POP

And hide away all the ugly version checks in the macro definitions.

The easy way: Hedley

Now that you understand the mechanics of how to do stuff like this portably while keeping your code clean, you understand what one of my projects, Hedley does. Instead of digging through tons of documentation and/or installing as many versions of as many compilers as you can to test with, you can just include Hedley (it is a single public domain C/C++ header) and be done with it. For example:

#include "hedley.h"

HEDLEY_DIAGNOSTIC_PUSH
HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
call_deprecated();
HEDLEY_DIAGNOSTIC_POP

Will disable the warning about calling a deprecated function on GCC, clang, ICC, PGI, MSVC, TI, IAR, ODS, Pelles, and possibly others (I probably won't bother updating this answer as I update Hedley). And, on compilers which aren't known to work, the macros will be preprocessed away to nothing, so your code will continue to work with any compiler. Of course HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED isn't the only warning Hedley knows about, nor is disabling warnings all Hedley can do, but hopefully you get the idea.

Specifying trust store information in spring boot application.properties

When everything sounded so complicated, this command worked for me:

keytool -genkey -alias foo -keystore cacerts -dname cn=test -storepass changeit -keypass changeit

When a developer is in trouble, I believe a simple working solution snippet is more than enough for him. Later he could diagnose the root cause and basic understanding related to the issue.

Bash function to find newest file matching pattern

Use the find command.

Assuming you're using Bash 4.2+, use -printf '%T+ %p\n' for file timestamp value.

find $DIR -type f -printf '%T+ %p\n' | sort -r | head -n 1 | cut -d' ' -f2

Example:

find ~/Downloads -type f -printf '%T+ %p\n' | sort -r | head -n 1 | cut -d' ' -f2

For a more useful script, see the find-latest script here: https://github.com/l3x/helpers

clear table jquery

  $('#myTable > tr').remove();

Average of multiple columns

This works in MariaDB:

SELECT Req_ID, (R1+R2+R3+R4+R5)/5 AS Average
FROM Request
GROUP BY Req_ID;

What does this thread join code mean?

let's say our main thread starts the threads t1 and t2. Now, when t1.join() is called, the main thread suspends itself till thread t1 dies and then resumes itself. Similarly, when t2.join() executes, the main thread suspends itself again till the thread t2 dies and then resumes.

So, this is how it works.

Also, the while loop was not really needed here.

How can I represent an 'Enum' in Python?

On 2013-05-10, Guido agreed to accept PEP 435 into the Python 3.4 standard library. This means that Python finally has builtin support for enumerations!

There is a backport available for Python 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4. It's on Pypi as enum34.

Declaration:

>>> from enum import Enum
>>> class Color(Enum):
...     red = 1
...     green = 2
...     blue = 3

Representation:

>>> print(Color.red)
Color.red
>>> print(repr(Color.red))
<Color.red: 1>

Iteration:

>>> for color in Color:
...   print(color)
...
Color.red
Color.green
Color.blue

Programmatic access:

>>> Color(1)
Color.red
>>> Color['blue']
Color.blue

For more information, refer to the proposal. Official documentation will probably follow soon.

How to trigger HTML button when you press Enter in textbox?

$(document).ready(function(){
    $('#TextBoxId').keypress(function(e){
      if(e.keyCode==13)
      $('#linkadd').click();
    });
});

How to iterate over arguments in a Bash script

Rewrite of a now-deleted answer by VonC.

Robert Gamble's succinct answer deals directly with the question. This one amplifies on some issues with filenames containing spaces.

See also: ${1:+"$@"} in /bin/sh

Basic thesis: "$@" is correct, and $* (unquoted) is almost always wrong. This is because "$@" works fine when arguments contain spaces, and works the same as $* when they don't. In some circumstances, "$*" is OK too, but "$@" usually (but not always) works in the same places. Unquoted, $@ and $* are equivalent (and almost always wrong).

So, what is the difference between $*, $@, "$*", and "$@"? They are all related to 'all the arguments to the shell', but they do different things. When unquoted, $* and $@ do the same thing. They treat each 'word' (sequence of non-whitespace) as a separate argument. The quoted forms are quite different, though: "$*" treats the argument list as a single space-separated string, whereas "$@" treats the arguments almost exactly as they were when specified on the command line. "$@" expands to nothing at all when there are no positional arguments; "$*" expands to an empty string — and yes, there's a difference, though it can be hard to perceive it. See more information below, after the introduction of the (non-standard) command al.

Secondary thesis: if you need to process arguments with spaces and then pass them on to other commands, then you sometimes need non-standard tools to assist. (Or you should use arrays, carefully: "${array[@]}" behaves analogously to "$@".)

Example:

    $ mkdir "my dir" anotherdir
    $ ls
    anotherdir      my dir
    $ cp /dev/null "my dir/my file"
    $ cp /dev/null "anotherdir/myfile"
    $ ls -Fltr
    total 0
    drwxr-xr-x   3 jleffler  staff  102 Nov  1 14:55 my dir/
    drwxr-xr-x   3 jleffler  staff  102 Nov  1 14:55 anotherdir/
    $ ls -Fltr *
    my dir:
    total 0
    -rw-r--r--   1 jleffler  staff  0 Nov  1 14:55 my file

    anotherdir:
    total 0
    -rw-r--r--   1 jleffler  staff  0 Nov  1 14:55 myfile
    $ ls -Fltr "./my dir" "./anotherdir"
    ./my dir:
    total 0
    -rw-r--r--   1 jleffler  staff  0 Nov  1 14:55 my file

    ./anotherdir:
    total 0
    -rw-r--r--   1 jleffler  staff  0 Nov  1 14:55 myfile
    $ var='"./my dir" "./anotherdir"' && echo $var
    "./my dir" "./anotherdir"
    $ ls -Fltr $var
    ls: "./anotherdir": No such file or directory
    ls: "./my: No such file or directory
    ls: dir": No such file or directory
    $

Why doesn't that work? It doesn't work because the shell processes quotes before it expands variables. So, to get the shell to pay attention to the quotes embedded in $var, you have to use eval:

    $ eval ls -Fltr $var
    ./my dir:
    total 0
    -rw-r--r--   1 jleffler  staff  0 Nov  1 14:55 my file

    ./anotherdir:
    total 0
    -rw-r--r--   1 jleffler  staff  0 Nov  1 14:55 myfile
    $ 

This gets really tricky when you have file names such as "He said, "Don't do this!"" (with quotes and double quotes and spaces).

    $ cp /dev/null "He said, \"Don't do this!\""
    $ ls
    He said, "Don't do this!"       anotherdir                      my dir
    $ ls -l
    total 0
    -rw-r--r--   1 jleffler  staff    0 Nov  1 15:54 He said, "Don't do this!"
    drwxr-xr-x   3 jleffler  staff  102 Nov  1 14:55 anotherdir
    drwxr-xr-x   3 jleffler  staff  102 Nov  1 14:55 my dir
    $ 

The shells (all of them) do not make it particularly easy to handle such stuff, so (funnily enough) many Unix programs do not do a good job of handling them. On Unix, a filename (single component) can contain any characters except slash and NUL '\0'. However, the shells strongly encourage no spaces or newlines or tabs anywhere in a path names. It is also why standard Unix file names do not contain spaces, etc.

When dealing with file names that may contain spaces and other troublesome characters, you have to be extremely careful, and I found long ago that I needed a program that is not standard on Unix. I call it escape (version 1.1 was dated 1989-08-23T16:01:45Z).

Here is an example of escape in use - with the SCCS control system. It is a cover script that does both a delta (think check-in) and a get (think check-out). Various arguments, especially -y (the reason why you made the change) would contain blanks and newlines. Note that the script dates from 1992, so it uses back-ticks instead of $(cmd ...) notation and does not use #!/bin/sh on the first line.

:   "@(#)$Id: delget.sh,v 1.8 1992/12/29 10:46:21 jl Exp $"
#
#   Delta and get files
#   Uses escape to allow for all weird combinations of quotes in arguments

case `basename $0 .sh` in
deledit)    eflag="-e";;
esac

sflag="-s"
for arg in "$@"
do
    case "$arg" in
    -r*)    gargs="$gargs `escape \"$arg\"`"
            dargs="$dargs `escape \"$arg\"`"
            ;;
    -e)     gargs="$gargs `escape \"$arg\"`"
            sflag=""
            eflag=""
            ;;
    -*)     dargs="$dargs `escape \"$arg\"`"
            ;;
    *)      gargs="$gargs `escape \"$arg\"`"
            dargs="$dargs `escape \"$arg\"`"
            ;;
    esac
done

eval delta "$dargs" && eval get $eflag $sflag "$gargs"

(I would probably not use escape quite so thoroughly these days - it is not needed with the -e argument, for example - but overall, this is one of my simpler scripts using escape.)

The escape program simply outputs its arguments, rather like echo does, but it ensures that the arguments are protected for use with eval (one level of eval; I do have a program which did remote shell execution, and that needed to escape the output of escape).

    $ escape $var
    '"./my' 'dir"' '"./anotherdir"'
    $ escape "$var"
    '"./my dir" "./anotherdir"'
    $ escape x y z
    x y z
    $ 

I have another program called al that lists its arguments one per line (and it is even more ancient: version 1.1 dated 1987-01-27T14:35:49). It is most useful when debugging scripts, as it can be plugged into a command line to see what arguments are actually passed to the command.

    $ echo "$var"
    "./my dir" "./anotherdir"
    $ al $var
    "./my
    dir"
    "./anotherdir"
    $ al "$var"
    "./my dir" "./anotherdir"
    $

[Added: And now to show the difference between the various "$@" notations, here is one more example:

$ cat xx.sh
set -x
al $@
al $*
al "$*"
al "$@"
$ sh xx.sh     *      */*
+ al He said, '"Don'\''t' do 'this!"' anotherdir my dir xx.sh anotherdir/myfile my dir/my file
He
said,
"Don't
do
this!"
anotherdir
my
dir
xx.sh
anotherdir/myfile
my
dir/my
file
+ al He said, '"Don'\''t' do 'this!"' anotherdir my dir xx.sh anotherdir/myfile my dir/my file
He
said,
"Don't
do
this!"
anotherdir
my
dir
xx.sh
anotherdir/myfile
my
dir/my
file
+ al 'He said, "Don'\''t do this!" anotherdir my dir xx.sh anotherdir/myfile my dir/my file'
He said, "Don't do this!" anotherdir my dir xx.sh anotherdir/myfile my dir/my file
+ al 'He said, "Don'\''t do this!"' anotherdir 'my dir' xx.sh anotherdir/myfile 'my dir/my file'
He said, "Don't do this!"
anotherdir
my dir
xx.sh
anotherdir/myfile
my dir/my file
$

Notice that nothing preserves the original blanks between the * and */* on the command line. Also, note that you can change the 'command line arguments' in the shell by using:

set -- -new -opt and "arg with space"

This sets 4 options, '-new', '-opt', 'and', and 'arg with space'.
]

Hmm, that's quite a long answer - perhaps exegesis is the better term. Source code for escape available on request (email to firstname dot lastname at gmail dot com). The source code for al is incredibly simple:

#include <stdio.h>
int main(int argc, char **argv)
{
    while (*++argv != 0)
        puts(*argv);
    return(0);
}

That's all. It is equivalent to the test.sh script that Robert Gamble showed, and could be written as a shell function (but shell functions didn't exist in the local version of Bourne shell when I first wrote al).

Also note that you can write al as a simple shell script:

[ $# != 0 ] && printf "%s\n" "$@"

The conditional is needed so that it produces no output when passed no arguments. The printf command will produce a blank line with only the format string argument, but the C program produces nothing.

MongoDB: How to update multiple documents with a single command?

MongoDB will find only one matching document which matches the query criteria when you are issuing an update command, whichever document matches first happens to be get updated, even if there are more documents which matches the criteria will get ignored.

so to overcome this we can specify "MULTI" option in your update statement, meaning update all those documnets which matches the query criteria. scan for all the documnets in collection finding those which matches the criteria and update :

db.test.update({"foo":"bar"},{"$set":{"test":"success!"}}, {multi:true} )

What's the difference between abstraction and encapsulation?

Encapsulation is used for 2 main reasons:

1.) Data hiding & protecting (the user of your class can't modify the data except through your provided methods).

2.) Combining the data and methods used to manipulate the data together into one entity (capsule). I think that the second reason is the answer your interviewer wanted to hear.

On the other hand, abstraction is needed to expose only the needed information to the user, and hiding unneeded details (for example, hiding the implementation of methods, so that the user is not affected if the implementation is changed).

Test if a vector contains a given element

Both the match() (returns the first appearance) and %in% (returns a Boolean) functions are designed for this.

v <- c('a','b','c','e')

'b' %in% v
## returns TRUE

match('b',v)
## returns the first location of 'b', in this case: 2

Send string to stdin

You can also use read like this

echo "enter your name"
read name
echo $name