Programs & Examples On #Accessory

Mode which allows Android-powered devices that cannot act as a USB host to still interact with USB hardware. In this mode, the attached Android USB accessory acts as the host, provides power to the USB bus, and enumerates connected devices.

Could not resolve '...' from state ''

As answered by Magus :

the full path must me specified

Abstract states can be used to add a prefix to all child state urls. But note that abstract still needs a ui-view for its children to populate. To do so you can simply add it inline.

.state('app', {
   url: "/app",
   abstract: true,
   template: '<ui-view/>'
})

For more information see documentation : https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views

Add swipe to delete UITableViewCell

    import UIKit

    class ViewController: UIViewController ,UITableViewDelegate,UITableViewDataSource
    {
      var items: String[] = ["We", "Heart", "Swift","omnamay shivay","om namay bhagwate vasudeva nama"]
        var cell : UITableViewCell
}




    @IBOutlet var tableview:UITableView

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.


    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }




    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
        return self.items.count;
    }


    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {

        var cell = tableView.dequeueReusableCellWithIdentifier("CELL") as? UITableViewCell

        if !cell {
            cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "CELL")}



        cell!.textLabel.text = self.items[indexPath.row]

        return cell
        }
    func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool {
        return true
    }

    func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {
        if (editingStyle == UITableViewCellEditingStyle.Delete) {
            // handle delete (by removing the data from your array and updating the tableview)


            if let tv=tableView
            {



             items.removeAtIndex(indexPath!.row)
                tv.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)



        }
    }
}


}

Custom edit view in UITableViewCell while swipe left. Objective-C or Swift

Just copy paste the code below!

-(NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {

       UITableViewRowAction *editAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"Clona" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath){
          //insert your editAction here
       }];
       editAction.backgroundColor = [UIColor blueColor];

       UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"Delete"  handler:^(UITableViewRowAction *action, NSIndexPath *indexPath){
          //insert your deleteAction here
       }];
       deleteAction.backgroundColor = [UIColor redColor];
return @[deleteAction,editAction];
}

Xcode error - Thread 1: signal SIGABRT

You are trying to load a XIB named DetailViewController, but no such XIB exists or it's not member of your current target.

How to pass prepareForSegue: an object

In Swift 4.2 I would do something like that:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let yourVC = segue.destination as? YourViewController {
        yourVC.yourData = self.someData
    }
}

How to force keyboard with numbers in mobile website in Android

IMPORTANT NOTE

I am posting this as an answer, not a comment, as it is rather important info and it will attract more attention in this format.

As other fellows pointed, you can force a device to show you a numeric keyboard with type="number" / type="tel", but I must emphasize that you have to be extremely cautious with this.

If someone expects a number beginning with zeros, such as 000222, then she is likely to have trouble, as some browsers (desktop Chrome, for instance) will send to the server 222, which is not what she wants.

About type="tel" I can't say anything similar but personally I do not use it, as its behavior on different telephones can vary. I have confined myself to the simple pattern="[0-9]*" which do not work in Android

How can I calculate an md5 checksum of a directory?

Checksum all files, including both content and their filenames

grep -ar -e . /your/dir | md5sum | cut -c-32

Same as above, but only including *.py files

grep -ar -e . --include="*.py" /your/dir | md5sum | cut -c-32

You can also follow symlinks if you want

grep -aR -e . /your/dir | md5sum | cut -c-32

Other options you could consider using with grep

-s, --no-messages         suppress error messages
-D, --devices=ACTION      how to handle devices, FIFOs and sockets;
-Z, --null                print 0 byte after FILE name
-U, --binary              do not strip CR characters at EOL (MSDOS/Windows)

Android Service needs to run always (Never pause or stop)

If you already have a service and want it to work all the time, you need to add 2 things:

  1. in the service itself:

    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }
    
  2. In the manifest:

    android:launchMode="singleTop"
    

No need to add bind unless you need it in the service.

Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)

why is it that even managed languages provide a finally-block despite resources being deallocated automatically by the garbage collector anyway?

Actually, languages based on Garbage collectors need "finally" more. A garbage collector does not destroy your objects in a timely manner, so it can not be relied upon to clean up non-memory related issues correctly.

In terms of dynamically-allocated data, many would argue that you should be using smart-pointers.

However...

RAII moves the responsibility of exception safety from the user of the object to the designer

Sadly this is its own downfall. Old C programming habits die hard. When you're using a library written in C or a very C style, RAII won't have been used. Short of re-writing the entire API front-end, that's just what you have to work with. Then the lack of "finally" really bites.

Finding the direction of scrolling in a UIScrollView?

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
NSLog(@"px %f py %f",velocity.x,velocity.y);}

Use this delegate method of scrollview.

If y co-ordinate of velocity is +ve scroll view scrolls downwards and if it is -ve scrollview scrolls upwards. Similarly left and right scroll can be detected using x co-ordinate.

How to do the Recursive SELECT query in MySQL?

If you want to be able to have a SELECT without problems of the parent id having to be lower than child id, a function could be used. It supports also multiple children (as a tree should do) and the tree can have multiple heads. It also ensure to break if a loop exists in the data.

I wanted to use dynamic SQL to be able to pass the table/columns names, but functions in MySQL don't support this.

DELIMITER $$

CREATE FUNCTION `isSubElement`(pParentId INT, pId INT) RETURNS int(11)
DETERMINISTIC    
READS SQL DATA
BEGIN
DECLARE isChild,curId,curParent,lastParent int;
SET isChild = 0;
SET curId = pId;
SET curParent = -1;
SET lastParent = -2;

WHILE lastParent <> curParent AND curParent <> 0 AND curId <> -1 AND curParent <> pId AND isChild = 0 DO
    SET lastParent = curParent;
    SELECT ParentId from `test` where id=curId limit 1 into curParent;

    IF curParent = pParentId THEN
        SET isChild = 1;
    END IF;
    SET curId = curParent;
END WHILE;

RETURN isChild;
END$$

Here, the table test has to be modified to the real table name and the columns (ParentId,Id) may have to be adjusted for your real names.

Usage :

SET @wantedSubTreeId = 3;
SELECT * FROM test WHERE isSubElement(@wantedSubTreeId,id) = 1 OR ID = @wantedSubTreeId;

Result :

3   7   k
5   3   d
9   3   f
1   5   a

SQL for test creation :

CREATE TABLE IF NOT EXISTS `test` (
  `Id` int(11) NOT NULL,
  `ParentId` int(11) DEFAULT NULL,
  `Name` varchar(300) NOT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

insert into test (id, parentid, name) values(3,7,'k');
insert into test (id, parentid, name) values(5,3,'d');
insert into test (id, parentid, name) values(9,3,'f');
insert into test (id, parentid, name) values(1,5,'a');
insert into test (id, parentid, name) values(6,2,'o');
insert into test (id, parentid, name) values(2,8,'c');

EDIT : Here is a fiddle to test it yourself. It forced me to change the delimiter using the predefined one, but it works.

INSERT INTO @TABLE EXEC @query with SQL Server 2000

The documentation is misleading.
I have the following code running in production

DECLARE @table TABLE (UserID varchar(100))
DECLARE @sql varchar(1000)
SET @sql = 'spSelUserIDList'
/* Will also work
   SET @sql = 'SELECT UserID FROM UserTable'
*/

INSERT INTO @table
EXEC(@sql)

SELECT * FROM @table

filedialog, tkinter and opening files

The exception you get is telling you filedialog is not in your namespace. filedialog (and btw messagebox) is a tkinter module, so it is not imported just with from tkinter import *

>>> from tkinter import *
>>> filedialog
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
NameError: name 'filedialog' is not defined
>>> 

you should use for example:

>>> from tkinter import filedialog
>>> filedialog
<module 'tkinter.filedialog' from 'C:\Python32\lib\tkinter\filedialog.py'>
>>>

or

>>> import tkinter.filedialog as fdialog

or

>>> from tkinter.filedialog import askopenfilename

So this would do for your browse button:

from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror

class MyFrame(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.master.title("Example")
        self.master.rowconfigure(5, weight=1)
        self.master.columnconfigure(5, weight=1)
        self.grid(sticky=W+E+N+S)

        self.button = Button(self, text="Browse", command=self.load_file, width=10)
        self.button.grid(row=1, column=0, sticky=W)

    def load_file(self):
        fname = askopenfilename(filetypes=(("Template files", "*.tplate"),
                                           ("HTML files", "*.html;*.htm"),
                                           ("All files", "*.*") ))
        if fname:
            try:
                print("""here it comes: self.settings["template"].set(fname)""")
            except:                     # <- naked except is a bad idea
                showerror("Open Source File", "Failed to read file\n'%s'" % fname)
            return


if __name__ == "__main__":
    MyFrame().mainloop()

enter image description here

jQuery event to trigger action when a div is made visible

I did a simple setinterval function to achieve this. If element with class div1 is visible, it sets div2 to be visible. I know not a good method, but a simple fix.

setInterval(function(){
  if($('.div1').is(':visible')){
    $('.div2').show();
  }
  else {
    $('.div2').hide();
  }      
}, 100);

Python: Get the first character of the first string in a list?

Get the first character of a bare python string:

>>> mystring = "hello"
>>> print(mystring[0])
h
>>> print(mystring[:1])
h
>>> print(mystring[3])
l
>>> print(mystring[-1])
o
>>> print(mystring[2:3])
l
>>> print(mystring[2:4])
ll

Get the first character from a string in the first position of a python list:

>>> myarray = []
>>> myarray.append("blah")
>>> myarray[0][:1]
'b'
>>> myarray[0][-1]
'h'
>>> myarray[0][1:3]
'la'

Many people get tripped up here because they are mixing up operators of Python list objects and operators of Numpy ndarray objects:

Numpy operations are very different than python list operations.

Wrap your head around the two conflicting worlds of Python's "list slicing, indexing, subsetting" and then Numpy's "masking, slicing, subsetting, indexing, then numpy's enhanced fancy indexing".

These two videos cleared things up for me:

"Losing your Loops, Fast Numerical Computing with NumPy" by PyCon 2015: https://youtu.be/EEUXKG97YRw?t=22m22s

"NumPy Beginner | SciPy 2016 Tutorial" by Alexandre Chabot LeClerc: https://youtu.be/gtejJ3RCddE?t=1h24m54s

Replacement for "rename" in dplyr

You can actually use plyr's rename function as part of dplyr chains. I think every function that a) takes a data.frame as the first argument and b) returns a data.frame works for chaining. Here is an example:

library('plyr')
library('dplyr')

DF = data.frame(var=1:5)

DF %>%
    # `rename` from `plyr`
    rename(c('var'='x')) %>%
    # `mutate` from `dplyr` (note order in which libraries are loaded)
    mutate(x.sq=x^2)

#   x x.sq
# 1 1    1
# 2 2    4
# 3 3    9
# 4 4   16
# 5 5   25

UPDATE: The current version of dplyr supports renaming directly as part of the select function (see Romain Francois post above). The general statement about using non-dplyr functions as part of dplyr chains is still valid though and rename is an interesting example.

Laravel 5.1 - Checking a Database Connection

Try just getting the underlying PDO instance. If that fails, then Laravel was unable to connect to the database!

// Test database connection
try {
    DB::connection()->getPdo();
} catch (\Exception $e) {
    die("Could not connect to the database.  Please check your configuration. error:" . $e );
}

Styling the last td in a table with css

Not a direct answer to your question, but using <tfoot> might help you achieve what you need, and of course you can style tfoot.

REST API error return good practices

The main choice is do you want to treat the HTTP status code as part of your REST API or not.

Both ways work fine. I agree that, strictly speaking, one of the ideas of REST is that you should use the HTTP Status code as a part of your API (return 200 or 201 for a successful operation and a 4xx or 5xx depending on various error cases.) However, there are no REST police. You can do what you want. I have seen far more egregious non-REST APIs being called "RESTful."

At this point (August, 2015) I do recommend that you use the HTTP Status code as part of your API. It is now much easier to see the return code when using frameworks than it was in the past. In particular, it is now easier to see the non-200 return case and the body of non-200 responses than it was in the past.

The HTTP Status code is part of your api

  1. You will need to carefully pick 4xx codes that fit your error conditions. You can include a rest, xml, or plaintext message as the payload that includes a sub-code and a descriptive comment.

  2. The clients will need to use a software framework that enables them to get at the HTTP-level status code. Usually do-able, not always straight-forward.

  3. The clients will have to distinguish between HTTP status codes that indicate a communications error and your own status codes that indicate an application-level issue.

The HTTP Status code is NOT part of your api

  1. The HTTP status code will always be 200 if your app received the request and then responded (both success and error cases)

  2. ALL of your responses should include "envelope" or "header" information. Typically something like:

    envelope_ver: 1.0
    status:  # use any codes you like. Reserve a code for success. 
    msg: "ok" # A human string that reflects the code. Useful for debugging.
    data: ...  # The data of the response, if any.
  3. This method can be easier for clients since the status for the response is always in the same place (no sub-codes needed), no limits on the codes, no need to fetch the HTTP-level status-code.

Here's a post with a similar idea: http://yuiblog.com/blog/2008/10/15/datatable-260-part-one/

Main issues:

  1. Be sure to include version numbers so you can later change the semantics of the api if needed.

  2. Document...

How to find the Vagrant IP?

I did at VagrantFile:

REMOTE_IP = %x{/usr/local/bin/vagrant ssh-config | /bin/grep -i HostName | /usr/bin/cut -d\' \' -f4}
run "ping #{REMOTE_IP}"

As you can see, I used the "%x{}" ruby function.

JAVA_HOME directory in Linux

On the Terminal, type:

echo "$JAVA_HOME"

If you are not getting anything, then your environment variable JAVA_HOME has not been set. You can try using "locate java" to try and discover where your installation of Java is located.

how to remove the bold from a headline?

you can simply do like that in the html part:

<span>Heading Text</span>

and in the css you can make it as an h1 block using display:

span{
display:block;
font-size:20px;
}

you will get it as a h1 without bold ,
if you want it bold just add this to the css:

font-weight:bold;

Aborting a shell script if any command returns a non-zero value

Run it with -e or set -e at the top.

Also look at set -u.

How to unpackage and repackage a WAR file

Non programmatically, you can just open the archive using the 7zip UI to add/remove or extract/replace files without the structure changing. I didn't know it was a problem using other things until now :)

jquery equivalent for JSON.stringify

There is no such functionality in jQuery. Use JSON.stringify or alternatively any jQuery plugin with similar functionality (e.g jquery-json).

.Contains() on a list of custom class objects

By default reference types have reference equality (i.e. two instances are only equal if they are the same object).

You need to override Object.Equals (and Object.GetHashCode to match) to implement your own equality. (And it is then good practice to implement an equality, ==, operator.)

Python non-greedy regexes

You seek the all-powerful *?

From the docs, Greedy versus Non-Greedy

the non-greedy qualifiers *?, +?, ??, or {m,n}? [...] match as little text as possible.

Check if number is prime number

Prime numbers are numbers that are bigger than one and cannot be divided evenly by any other number except 1 and itself.

@This program will show you the given number is prime or not, and will show you for non prime number that it's divisible by (a number) which is rather than 1 or itself?@

        Console.Write("Please Enter a number: ");
        int number = int.Parse(Console.ReadLine());
        int count = 2; 
        // this is initial count number which is greater than 1

        bool prime = true;
        // used Boolean value to apply condition correctly

        int sqrtOfNumber = (int)Math.Sqrt(number); 
        // square root of input number this would help to simplify the looping.  

        while (prime && count <= sqrtOfNumber)
        {
            if ( number % count == 0)
            {
            Console.WriteLine($"{number} isn't prime and it divisible by 
                                      number {count}");  // this will generate a number isn't prime and it is divisible by a number which is rather than 1 or itself and this line will proves why it's not a prime number.
                prime = false;
            }
            
            count++;
            
        }
        if (prime && number > 1)
        
        {
            Console.WriteLine($"{number} is a prime number");
        }
        else if (prime == true)
        // if input is 1 or less than 1 then this code will generate
        {
            Console.WriteLine($"{number} isn't a prime");
        }
        

Right way to write JSON deserializer in Spring or extend it

I was trying to @Autowire a Spring-managed service into my Deserializer. Somebody tipped me off to Jackson using the new operator when invoking the serializers/deserializers. This meant no auto-wiring of Jackson's instance of my Deserializer. Here's how I was able to @Autowire my service class into my Deserializer:

context.xml

<mvc:annotation-driven>
  <mvc:message-converters>
    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
      <property name="objectMapper" ref="objectMapper" />
    </bean>
  </mvc:message-converters>
</mvc>
<bean id="objectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
    <!-- Add deserializers that require autowiring -->
    <property name="deserializersByType">
        <map key-type="java.lang.Class">
            <entry key="com.acme.Anchor">
                <bean class="com.acme.AnchorDeserializer" />
            </entry>
        </map>
    </property>
</bean>

Now that my Deserializer is a Spring-managed bean, auto-wiring works!

AnchorDeserializer.java

public class AnchorDeserializer extends JsonDeserializer<Anchor> {
    @Autowired
    private AnchorService anchorService;
    public Anchor deserialize(JsonParser parser, DeserializationContext context)
             throws IOException, JsonProcessingException {
        // Do stuff
    }
}

AnchorService.java

@Service
public class AnchorService {}

Update: While my original answer worked for me back when I wrote this, @xi.lin's response is exactly what is needed. Nice find!

Asynchronous Process inside a javascript for loop

async await is here (ES7), so you can do this kind of things very easily now.

  var i;
  var j = 10;
  for (i = 0; i < j; i++) {
    await asycronouseProcess();
    alert(i);
  }

Remember, this works only if asycronouseProcess is returning a Promise

If asycronouseProcess is not in your control then you can make it return a Promise by yourself like this

function asyncProcess() {
  return new Promise((resolve, reject) => {
    asycronouseProcess(()=>{
      resolve();
    })
  })
}

Then replace this line await asycronouseProcess(); by await asyncProcess();

Understanding Promises before even looking into async await is must (Also read about support for async await)

Angular 2 router.navigate

_x000D_
_x000D_
import { ActivatedRoute } from '@angular/router';_x000D_
_x000D_
export class ClassName {_x000D_
  _x000D_
  private router = ActivatedRoute;_x000D_
_x000D_
    constructor(r: ActivatedRoute) {_x000D_
        this.router =r;_x000D_
    }_x000D_
_x000D_
onSuccess() {_x000D_
     this.router.navigate(['/user_invitation'],_x000D_
         {queryParams: {email: loginEmail, code: userCode}});_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
Get this values:_x000D_
---------------_x000D_
_x000D_
ngOnInit() {_x000D_
    this.route_x000D_
        .queryParams_x000D_
        .subscribe(params => {_x000D_
            let code = params['code'];_x000D_
            let userEmail = params['email'];_x000D_
        });_x000D_
}
_x000D_
_x000D_
_x000D_

Ref: https://angular.io/docs/ts/latest/api/router/index/NavigationExtras-interface.html

How to create custom button in Android using XML Styles

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

   <solid 
       android:color="#ffffffff"/>

   <size 
       android:width="@dimen/shape_circle_width"
        android:height="@dimen/shape_circle_height"/>
</shape>

1.add this in your drawable

2.set as background to your button

Boolean vs boolean in Java

One observation: (though this can be thought of side effect)

boolean being a primitive can either say yes or no.

Boolean is an object (it can refer to either yes or no or 'don't know' i.e. null)

How do I deserialize a complex JSON object in C# .NET?

If you use C# 2010 or newer, you can use dynamic type:

dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonstring);

Then you can access attributes and arrays in dynamic object using dot notation:

string nemo = json.response[0].images[0].report.nemo;

Waiting until two async blocks are executed before starting another block

Accepted answer in swift:

let group = DispatchGroup()

group.async(group: DispatchQueue.global(qos: .default), execute: {
    // block1
    print("Block1")
    Thread.sleep(forTimeInterval: 5.0)
    print("Block1 End")
})


group.async(group: DispatchQueue.global(qos: .default), execute: {
    // block2
    print("Block2")
    Thread.sleep(forTimeInterval: 8.0)
    print("Block2 End")
})

dispatch_group_notify(group, DispatchQueue.global(qos: .default), {
    // block3
    print("Block3")
})

// only for non-ARC projects, handled automatically in ARC-enabled projects.
dispatch_release(group)

How to connect to a remote Windows machine to execute commands using python?

I don't know WMI but if you want a simple Server/Client, You can use this simple code from tutorialspoint

Server:

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
while True:
   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   c.send('Thank you for connecting')
   c.close()                # Close the connection 

Client

#!/usr/bin/python           # This is client.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.

s.connect((host, port))
print s.recv(1024)
s.close                     # Close the socket when done

it also have all the needed information for simple client/server applications.

Just convert the server and use some simple protocol to call a function from python.

P.S: i'm sure there are a lot of better options, it's just a simple one if you want...

EventListener Enter Key

You could listen to the 'keydown' event and then check for an enter key.

Your handler would be like:

function (e) {
  if (13 == e.keyCode) {
     ... do whatever ...
  }
}

How to open a file for both reading and writing?

Here's how you read a file, and then write to it (overwriting any existing data), without closing and reopening:

with open(filename, "r+") as f:
    data = f.read()
    f.seek(0)
    f.write(output)
    f.truncate()

How to put text over images in html?

You can create a div with the exact same size as the image.

<div class="imageContainer">Some Text</div>

use the css background-image property to show the image

 .imageContainer {
       width:200px; 
       height:200px; 
       background-image: url(locationoftheimage);
 }

more here

note: this slichtly tampers the semantics of your document. If needed use javascript to inject the div in the place of a real image.

Can't access 127.0.0.1

Just one command did the work

netsh http add iplisten 127.0.0.1

window.onload vs $(document).ready()

A Windows load event fires when all the content on your page is fully loaded including the DOM (document object model) content and asynchronous JavaScript, frames and images. You can also use body onload=. Both are the same; window.onload = function(){} and <body onload="func();"> are different ways of using the same event.

jQuery $document.ready function event executes a bit earlier than window.onload and is called once the DOM(Document object model) is loaded on your page. It will not wait for the images, frames to get fully load.

Taken from the following article: how $document.ready() is different from window.onload()

Determining if a number is prime

//simple function to determine if a number is a prime number
//to state if it is a prime number


#include <iostream>

using namespace std;


int isPrime(int x);  //functioned defined after int main()


int main()
{
 int y;
    cout<<"enter value"<<endl;

    cin>>y;

    isPrime(y);    

  return 0;

 } //end of main function


//-------------function

  int isPrime(int x)
 {
   int counter =0;
     cout<<"factors of "<<x<<" are "<<"\n\n";    //print factors of the number

     for (int i =0; i<=x; i++)

     {
       for (int j =0; j<=x; j++)

         {
           if (i * j == x)      //check if the number has multiples;
                {

                  cout<<i<<" ,  ";  //output provided for the reader to see the
                                    // muliples
                  ++counter;        //counts the number of factors

                 }


          }


    }
  cout<<"\n\n";

  if(counter>2) 
     { 
      cout<<"value is not a prime number"<<"\n\n";
     }

  if(counter<=2)
     {
       cout<<"value is a prime number"<<endl;
     }
 }

How to use mysql JOIN without ON condition?

There are several ways to do a cross join or cartesian product:

SELECT column_names FROM table1 CROSS JOIN table2;

SELECT column_names FROM table1, table2;

SELECT column_names FROM table1 JOIN table2;

Neglecting the on condition in the third case is what results in a cross join.

IntelliJ - show where errors are

I ran into the problem of not having set my sources root folder (project window--right click folder, mark directory as > sources root). If you don't set this IDEA doesn't parse the file.

Python/Json:Expecting property name enclosed in double quotes

import ast

inpt = {'http://example.org/about': {'http://purl.org/dc/terms/title':
                                     [{'type': 'literal', 'value': "Anna's Homepage"}]}}

json_data = ast.literal_eval(json.dumps(inpt))

print(json_data)

this will solve the problem.

#1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’

Late to the party, but in case this happens with a WORDPRESS installation :

#1273 - Unknown collation: 'utf8mb4_unicode_520_ci

In phpmyadmin, under export method > Format-specific options( custom export )

Set to : MYSQL40

If you will try to import now, you now might get another error message :

1064 - You have an error in your SQL syntax; .....

That is because The older TYPE option that was synonymous with ENGINE was removed in MySQL 5.5.

Open your .sql file , search and replace all instances

from TYPE= to ENGINE=

Now the import should go smoothly.

enumerate() for dictionary in python

Just thought I'd add, if you'd like to enumerate over the index, key, and values of a dictionary, your for loop should look like this:

for index, (key, value) in enumerate(your_dict.items()):
    print(index, key, value)

Escaping quotation marks in PHP

You can use the PHP function addslashes() to any string to make it compatible

Regex date validation for yyyy-mm-dd

A simple one would be

\d{4}-\d{2}-\d{2}

Regular expression visualization

Debuggex Demo

but this does not restrict month to 1-12 and days from 1 to 31.

There are more complex checks like in the other answers, by the way pretty clever ones. Nevertheless you have to check for a valid date, because there are no checks for if a month has 28, 30, or 31 days.

@RequestBody and @ResponseBody annotations in Spring

There is a whole Section in the docs called 16.3.3.4 Mapping the request body with the @RequestBody annotation. And one called 16.3.3.5 Mapping the response body with the @ResponseBody annotation. I suggest you consult those sections. Also relevant: @RequestBody javadocs, @ResponseBody javadocs

Usage examples would be something like this:

Using a JavaScript-library like JQuery, you would post a JSON-Object like this:

{ "firstName" : "Elmer", "lastName" : "Fudd" }

Your controller method would look like this:

// controller
@ResponseBody @RequestMapping("/description")
public Description getDescription(@RequestBody UserStats stats){
    return new Description(stats.getFirstName() + " " + stats.getLastname() + " hates wacky wabbits");
}

// domain / value objects
public class UserStats{
    private String firstName;
    private String lastName;
    // + getters, setters
}
public class Description{
    private String description;
    // + getters, setters, constructor
}

Now if you have Jackson on your classpath (and have an <mvc:annotation-driven> setup), Spring would convert the incoming JSON to a UserStats object from the post body (because you added the @RequestBody annotation) and it would serialize the returned object to JSON (because you added the @ResponseBody annotation). So the Browser / Client would see this JSON result:

{ "description" : "Elmer Fudd hates wacky wabbits" }

See this previous answer of mine for a complete working example: https://stackoverflow.com/a/5908632/342852

Note: RequestBody / ResponseBody is of course not limited to JSON, both can handle multiple formats, including plain text and XML, but JSON is probably the most used format.


Update

Ever since Spring 4.x, you usually won't use @ResponseBody on method level, but rather @RestController on class level, with the same effect.

Here is a quote from the official Spring MVC documentation:

@RestController is a composed annotation that is itself meta-annotated with @Controller and @ResponseBody to indicate a controller whose every method inherits the type-level @ResponseBody annotation and, therefore, writes directly to the response body versus view resolution and rendering with an HTML template.

Kill some processes by .exe file name

If you have the process ID (PID) you can kill this process as follow:

Process processToKill = Process.GetProcessById(pid);
processToKill.Kill();

Best way to find if an item is in a JavaScript array?

As of ECMAScript 2016 you can use includes()

arr.includes(obj);

If you want to support IE or other older browsers:

function include(arr,obj) {
    return (arr.indexOf(obj) != -1);
}

EDIT: This will not work on IE6, 7 or 8 though. The best workaround is to define it yourself if it's not present:

  1. Mozilla's (ECMA-262) version:

       if (!Array.prototype.indexOf)
       {
    
            Array.prototype.indexOf = function(searchElement /*, fromIndex */)
    
         {
    
    
         "use strict";
    
         if (this === void 0 || this === null)
           throw new TypeError();
    
         var t = Object(this);
         var len = t.length >>> 0;
         if (len === 0)
           return -1;
    
         var n = 0;
         if (arguments.length > 0)
         {
           n = Number(arguments[1]);
           if (n !== n)
             n = 0;
           else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
             n = (n > 0 || -1) * Math.floor(Math.abs(n));
         }
    
         if (n >= len)
           return -1;
    
         var k = n >= 0
               ? n
               : Math.max(len - Math.abs(n), 0);
    
         for (; k < len; k++)
         {
           if (k in t && t[k] === searchElement)
             return k;
         }
         return -1;
       };
    
     }
    
  2. Daniel James's version:

     if (!Array.prototype.indexOf) {
       Array.prototype.indexOf = function (obj, fromIndex) {
         if (fromIndex == null) {
             fromIndex = 0;
         } else if (fromIndex < 0) {
             fromIndex = Math.max(0, this.length + fromIndex);
         }
         for (var i = fromIndex, j = this.length; i < j; i++) {
             if (this[i] === obj)
                 return i;
         }
         return -1;
       };
     }
    
  3. roosteronacid's version:

     Array.prototype.hasObject = (
       !Array.indexOf ? function (o)
       {
         var l = this.length + 1;
         while (l -= 1)
         {
             if (this[l - 1] === o)
             {
                 return true;
             }
         }
         return false;
       } : function (o)
       {
         return (this.indexOf(o) !== -1);
       }
     );
    

How can I check if a string contains ANY letters from the alphabet?

Regex should be a fast approach:

re.search('[a-zA-Z]', the_string)

Android How to adjust layout in Full Screen Mode when softkeyboard is visible

Don't use:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

because works bad. Instead of that, use:

fun setFullScreen(fullScreen: Boolean) {
        val decorView = getWindow().getDecorView()
        val uiOptions : Int
        if(fullScreen){
            uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN // this hide statusBar
            toolbar.visibility = View.GONE // if you use toolbar
            tabs.visibility = View.GONE // if you use tabLayout
        } else {
            uiOptions = View.SYSTEM_UI_FLAG_VISIBLE // this show statusBar
            toolbar.visibility = View.VISIBLE
            tabs.visibility = View.VISIBLE
        }
        decorView.setSystemUiVisibility(uiOptions)
    }

Why does the PHP json_encode function convert UTF-8 strings to hexadecimal entities?

json_encode($text, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);

How can I dismiss the on screen keyboard?

To dismiss the keyboard (1.7.8+hotfix.2 and above) just call the method below:

FocusScope.of(context).unfocus();

Once the FocusScope.of(context).unfocus() method already check if there is focus before dismiss the keyboard it's not needed to check it. But in case you need it just call another context method: FocusScope.of(context).hasPrimaryFocus

How to add multiple jar files in classpath in linux

Say you have multiple jar files a.jar,b.jar and c.jar. To add them to classpath while compiling you need to do

$javac -cp .:a.jar:b.jar:c.jar HelloWorld.java

To run do

$java -cp .:a.jar:b.jar:c.jar HelloWorld

How to get diff between all files inside 2 folders that are on the web?

You urls are not in the same repository, so you can't do it with the svn diff command.

svn: 'http://svn.boost.org/svn/boost/sandbox/boost/extension' isn't in the same repository as 'http://cloudobserver.googlecode.com/svn'

Another way you could do it, is export each repos using svn export, and then use the diff command to compare the 2 directories you exported.

// Export repositories
svn export http://svn.boost.org/svn/boost/sandbox/boost/extension/ repos1
svn export http://cloudobserver.googlecode.com/svn/branches/v0.4/Boost.Extension.Tutorial/libs/boost/extension/ repos2

// Compare exported directories
diff repos1 repos2 > file.diff

how to check if a datareader is null or empty

This

Example:

objCar.StrDescription = (objSqlDataReader["fieldDescription"].GetType() != typeof(DBNull)) ? (String)objSqlDataReader["fieldDescription"] : "";

How to add parameters to an external data query in Excel which can't be displayed graphically?

Excel's interface for SQL Server queries will not let you have a custom parameters.  A way around this is to create a generic Microsoft Query, then add parameters, then paste your parametorized query in the connection's properties.  Here are the detailed steps for Excel 2010:

  1. Open Excel
  2. Goto Data tab
  3. From the From Other Sources button choose From Microsoft Query
  4. The "Choose Data Source" window will appear.  Choose a datasource and click OK.
  5. The Query Qizard
    1. Choose Column: window will appear.  The goal is to create a generic query. I recommend choosing one column from a small table.
    2. Filter Data: Just click Next
    3. Sort Order: Just click Next
    4. Finish: Just click Finish.
  6. The "Import Data" window will appear:
    1. Click the Properties... button.
      1. Choose the Definition tab
      2. In the "Command text:" section add a WHERE clause that includes Excel parameters.  It's important to add all the parameters that you want now.  For example, if I want two parameters I could add this:
        WHERE 1 = ? and 2 = ?
      3. Click OK to get back to the "Import Data" window
    2. Choose PivotTable Report
    3. Click OK
  7. You will be prompted to enter the parameters value for each parameter.
  8. Once you have enter the parameters you will be at your pivot table
  9. Go batck to the Data tab and click the connections Properties button
    1. Click the Definition tab
    2. In the "Command text:" section, Paste in the real SQL Query that you want with the same number of parameters that you defined earlier.
    3. Click the Parameters... button 
      1. enter the Prompt values for each parameter
      2. Click OK
    4. Click OK to close the properties window
  10. Congratulations, you now have parameters.

How to negate specific word in regex?

I wish to complement the accepted answer and contribute to the discussion with my late answer.

@ChrisVanOpstal shared this regex tutorial which is a great resource for learning regex.

However, it was really time consuming to read through.

I made a cheatsheet for mnemonic convenience.

This reference is based on the braces [], (), and {} leading each class, and I find it easy to recall.

Regex = {
 'single_character': ['[]', '.', {'negate':'^'}],
 'capturing_group' : ['()', '|', '\\', 'backreferences and named group'],
 'repetition'      : ['{}', '*', '+', '?', 'greedy v.s. lazy'],
 'anchor'          : ['^', '\b', '$'],
 'non_printable'   : ['\n', '\t', '\r', '\f', '\v'],
 'shorthand'       : ['\d', '\w', '\s'],
 }

Accurate way to measure execution times of php scripts

You can use the microtime function for this. From the documentation:

microtime — Return current Unix timestamp with microseconds


If get_as_float is set to TRUE, then microtime() returns a float, which represents the current time in seconds since the Unix epoch accurate to the nearest microsecond.

Example usage:

$start = microtime(true);
while (...) {

}
$time_elapsed_secs = microtime(true) - $start;

Print a list of space-separated elements in Python 3

Although the accepted answer is absolutely clear, I just wanted to check efficiency in terms of time.

The best way is to print joined string of numbers converted to strings.

print(" ".join(list(map(str,l))))

Note that I used map instead of loop. I wrote a little code of all 4 different ways to compare time:

import time as t

a, b = 10, 210000
l = list(range(a, b))
tic = t.time()
for i in l:
    print(i, end=" ")

print()
tac = t.time()
t1 = (tac - tic) * 1000
print(*l)
toe = t.time()
t2 = (toe - tac) * 1000
print(" ".join([str(i) for i in l]))
joe = t.time()
t3 = (joe - toe) * 1000
print(" ".join(list(map(str, l))))
toy = t.time()
t4 = (toy - joe) * 1000
print("Time",t1,t2,t3,t4)

Result:

Time 74344.76 71790.83 196.99 153.99

The output was quite surprising to me. Huge difference of time in cases of 'loop method' and 'joined-string method'.

Conclusion: Do not use loops for printing list if size is too large( in order of 10**5 or more).

Iterating through array - java

You can import the lib org.apache.commons.lang.ArrayUtils

There is a static method where you can pass in an int array and a value to check for.

contains(int[] array, int valueToFind) Checks if the value is in the given array.

ArrayUtils.contains(intArray, valueToFind);

ArrayUtils API

Which is best data type for phone number in MySQL and what should Java type mapping for it be?

  1. String
  2. Varchar

This is my opinion for my database as recommended by my mentor

Escape sequence \f - form feed - what exactly is it?

From wiki page

12 (form feed, \f, ^L), to cause a printer to eject paper to the top of the next page, or a video terminal to clear the screen.

or more details here.

It seems that this symbol is rather obsolete now and the way it is processed may be(?) implementation dependent. At least for me your code gives the following output (xcode gcc 4.2, gdb console):

hello
    goodbye

Angular2 set value for formGroup

As pointed out in comments, this feature wasn't supported at the time this question was asked. This issue has been resolved in angular 2 rc5

How to pass parameters or arguments into a gradle task

Its nothing more easy.

run command: ./gradlew clean -PjobId=9999

and

in gradle use: println(project.gradle.startParameter.projectProperties)

You will get clue.

What's the Kotlin equivalent of Java's String[]?

you can use too:

val frases = arrayOf("texto01","texto02 ","anotherText","and ")

for example.

Radio buttons and label to display in same line

Note: Traditionally the use of the label tag is for menus. eg:

<menu>
<label>Option 1</label>
<input type="radio" id="opt1">

<label>Option 2</label>
<input type="radio" id="opt2">

<label>Option 3</label>
<input type="radio" id="opt3">  
</menu>

What is a "callback" in C and how are they implemented?

It is lot easier to understand an idea through example. What have been told about callback function in C so far are great answers, but probably the biggest benefit of using the feature is to keep the code clean and uncluttered.

Example

The following C code implements quick sorting. The most interesting line in the code below is this one, where we can see the callback function in action:

qsort(arr,N,sizeof(int),compare_s2b);

The compare_s2b is the name of function which qsort() is using to call the function. This keeps qsort() so uncluttered (hence easier to maintain). You just call a function by name from inside another function (of course, the function prototype declaration, at the least, must precde before it can be called from another function).

The Complete Code

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

int arr[]={56,90,45,1234,12,3,7,18};
//function prototype declaration 

int compare_s2b(const void *a,const void *b);

int compare_b2s(const void *a,const void *b);

//arranges the array number from the smallest to the biggest
int compare_s2b(const void* a, const void* b)
{
    const int* p=(const int*)a;
    const int* q=(const int*)b;

    return *p-*q;
}

//arranges the array number from the biggest to the smallest
int compare_b2s(const void* a, const void* b)
{
    const int* p=(const int*)a;
    const int* q=(const int*)b;

    return *q-*p;
}

int main()
{
    printf("Before sorting\n\n");

    int N=sizeof(arr)/sizeof(int);

    for(int i=0;i<N;i++)
    {
        printf("%d\t",arr[i]);
    }

    printf("\n");

    qsort(arr,N,sizeof(int),compare_s2b);

    printf("\nSorted small to big\n\n");

    for(int j=0;j<N;j++)
    {
        printf("%d\t",arr[j]);
    }

    qsort(arr,N,sizeof(int),compare_b2s);

    printf("\nSorted big to small\n\n");

    for(int j=0;j<N;j++)
    {
        printf("%d\t",arr[j]);
    }

    exit(0);
}

str_replace with array

Easy and better than str_replace:

<?php
$arr = array(
    "http://" => "http://www.",
    "w" => "W",
    "d" => "D");

    $word = "http://desiweb.ir";
    echo strtr($word,$arr);
?>

strtr PHP doc here

Calculate difference in keys contained in two Python dictionaries

If you want a built-in solution for a full comparison with arbitrary dict structures, @Maxx's answer is a good start.

import unittest

test = unittest.TestCase()
test.assertEqual(dictA, dictB)

Angular 4 img src is not found

@Annk you can make a variable in the __component.ts file

myImage : string = "http://example.com/path/image.png";

and inside the __.component.html file you can use one of those 3 methods :

1 .

<div> <img src="{{myImage}}"> </div>

2 .

<div> <img [src]="myImage"/> </div>

3 .

<div> <img bind-src="myImage"/> </div>

Can't bind to 'formControl' since it isn't a known property of 'input' - Angular2 Material Autocomplete issue

Start by adding a regular matInput to your template. Let's assume you're using the formControl directive from ReactiveFormsModule to track the value of the input.

Reactive forms provide a model-driven approach to handling form inputs whose values change over time. This guide shows you how to create and update a simple form control, progress to using multiple controls in a group, validate form values, and implement more advanced forms.

import { FormsModule, ReactiveFormsModule } from "@angular/forms"; //this to use ngModule

...

imports: [
    BrowserModule,
    AppRoutingModule,
    HttpModule,
    FormsModule,
    RouterModule,
    ReactiveFormsModule,
    BrowserAnimationsModule,
    MaterialModule],

X-Frame-Options: ALLOW-FROM in firefox and chrome

For Chrome, instead of

response.AppendHeader("X-Frame-Options", "ALLOW-FROM " + host);

you need to add Content-Security-Policy

string selfAuth = System.Web.HttpContext.Current.Request.Url.Authority;
string refAuth = System.Web.HttpContext.Current.Request.UrlReferrer.Authority;
response.AppendHeader("Content-Security-Policy", "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: *.msecnd.net vortex.data.microsoft.com " + selfAuth + " " + refAuth);

to the HTTP-response-headers.
Note that this assumes you checked on the server whether or not refAuth is allowed.
And also, note that you need to do browser-detection in order to avoid adding the allow-from header for Chrome (outputs error on console).

For details, see my answer here.

Add items to comboBox in WPF

Scenario 1 - you don't have a data-source for the items
You can just populate the ComboBox with static values as follows -
From XAML:

<ComboBox Height="23" Name="comboBox1" Width="120">
        <ComboBoxItem Content="X"/>
        <ComboBoxItem Content="Y"/>
        <ComboBoxItem Content="Z"/>
</ComboBox>  

Or, from CodeBehind:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    comboBox1.Items.Add("X");
    comboBox1.Items.Add("Y");
    comboBox1.Items.Add("Z");
}  

Scenario 2.a - you have a data-source, and the items never get changed
You can use the data-source to populate the ComboBox. Any IEnumerable type can be used as the data-source. You need to assign it to the ItemsSource property of the ComboBox and that'll do just fine (it's up to you how you populate the IEnumerable).

Scenario 2.b - you have a data-source, and the items might get changed
You should use an ObservableCollection<T> as the data-source and assign it to the ItemsSource property of the ComboBox (it's up to you how you populate the ObservableCollection<T>). Using an ObservableCollection<T> ensures that whenever an item is added to or removed from the data-source, the change will reflect immediately on the UI.

what do <form action="#"> and <form method="post" action="#"> do?

Apparently, action was required prior to HTML5 (and # was just a stand in), but you no longer have to use it.

See The Action Attribute:

When specified with no attributes, as below, the data is sent to the same page that the form is present on:

<form>

SQL 'LIKE' query using '%' where the search criteria contains '%'

Use an escape clause:

select *
  from (select '123abc456' AS result from dual
        union all
        select '123abc%456' AS result from dual
       )
  WHERE result LIKE '%abc\%%' escape '\'

Result

123abc%456

You can set your escape character to whatever you want. In this case, the default '\'. The escaped '\%' becomes a literal, the second '%' is not escaped, so again wild card.

See List of special characters for SQL LIKE clause

Set Session variable using javascript in PHP

I solved this question using Ajax. What I do is make an ajax call to a PHP page where the value that passes will be saved in session.

The example that I am going to show you, what I do is that when you change the value of the number of items to show in a datatable, that value is saved in session.

$('#table-campus').on( 'length.dt', function ( e, settings, len ) {
    $.ajax ({
       data:        {"numElems": len},
       url:        '../../Utiles/GuardarNumElems.php',
       type:        'post'
    }); 
});

And the GuardarNumElems.php is as following:

<?php    
    session_start();

    if(isset ($_POST['numElems'] )){
        $numElems = $_POST['numElems'];        
        $_SESSION['elems_table'] = $numElems;
    }else{
        $_SESSION['elems_table'] = 25;
    } 
?>

Connecting to smtp.gmail.com via command line

For OSX' terminal:

openssl s_client -connect smtp.gmail.com:25 -starttls smtp 

Convert Text to Uppercase while typing in Text box

I had the same problem with Visual Studio 2008 and solved adding the following event handler to the textbox:

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if ((e.KeyChar >= 'a') && (e.KeyChar <= 'z'))
        {
            int iPos = textBox1.SelectionStart;
            int iLen = textBox1.SelectionLength;
            textBox1.Text = textBox1.Text.Remove(iPos, iLen).Insert(iPos, Char.ToUpper(e.KeyChar).ToString());
            textBox1.SelectionStart = iPos + 1;
            e.Handled = true;
        }
    }

It works even if you type a lowercase character in a textbox where some characters are selected. I don't know if the code works with a Multiline textbox.

Select columns from result set of stored procedure

For SQL Server, I find that this works fine:

Create a temp table (or permanent table, doesn't really matter), and do a insert into statement against the stored procedure. The result set of the SP should match the columns in your table, otherwise you'll get an error.

Here's an example:

DECLARE @temp TABLE (firstname NVARCHAR(30), lastname nvarchar(50));

INSERT INTO @temp EXEC dbo.GetPersonName @param1,@param2;
-- assumption is that dbo.GetPersonName returns a table with firstname / lastname columns

SELECT * FROM @temp;

That's it!

JavaScript Chart.js - Custom data formatting to display on tooltip

You want to specify a custom tooltip template in your chart options, like this :

 // String - Template string for single tooltips
 tooltipTemplate: "<%if (label){%><%=label %>: <%}%><%= value + ' %' %>",
 // String - Template string for multiple tooltips
 multiTooltipTemplate: "<%= value + ' %' %>",

This way you can add a '%' sign after your values if that's what you want.

Here's a jsfiddle to illustrate this.

Note that tooltipTemplate applies if you only have one dataset, multiTooltipTemplate applies if you have several datasets.

This options are mentioned in the global chart configuration section of the documentation. Do have a look, it's worth checking for all the other options that can be customized in there.

Note that Your datasets should only contain numeric values. (No % signs or other stuff there).

check if "it's a number" function in Oracle

Assuming that the ID column in myTable is not declared as a NUMBER (which seems like an odd choice and likely to be problematic), you can write a function that tries to convert the (presumably VARCHAR2) ID to a number, catches the exception, and returns a 'Y' or an 'N'. Something like

CREATE OR REPLACE FUNCTION is_number( p_str IN VARCHAR2 )
  RETURN VARCHAR2 DETERMINISTIC PARALLEL_ENABLE
IS
  l_num NUMBER;
BEGIN
  l_num := to_number( p_str );
  RETURN 'Y';
EXCEPTION
  WHEN value_error THEN
    RETURN 'N';
END is_number;

You can then embed that call in a query, i.e.

SELECT (CASE WHEN is_number( myTable.id ) = 'Y' AND myTable.id > 0 
               THEN 'Number > 0'
             ELSE 'Something else'
         END) some_alias
  FROM myTable

Note that although PL/SQL has a boolean data type, SQL does not. So while you can declare a function that returns a boolean, you cannot use such a function in a SQL query.

How to fill 100% of remaining height?

This can be done with tables:

<table cellpadding="0" cellspacing="0" width="100%" height="100%">
    <tr height="0%"><td>
        <div id="full">
            <!--contents of 1 -->
        </div>
    </td></tr>
    <tr><td>
        <div id="someid">
            <!--contents of 2 -->
        </div>
    </td></tr>
</table>

Then apply css to make someid fill the remaining space:

#someid {
    height: 100%;
}

Now, I can just hear the angry shouts from the crowd, "Oh noes, he's using tables! Feed him to the lions!" Please hear me out.

Unlike the accepted answer which accomplishes nothing aside from making the container div the full height of the page, this solution makes div #2 fill the remaining space as requested in the question. If you need that second div to fill the full height allotted to it, this is currently the only way to do it.

But feel free to prove me wrong, of course! CSS is always better.

Convert seconds to Hour:Minute:Second

In java you can use this way.

   private String getHmaa(long seconds) {
    String string;
    int hours = (int) seconds / 3600;
    int remainder = (int) seconds - hours * 3600;
    int mins = remainder / 60;
    //remainder = remainder - mins * 60;
    //int secs = remainder;

    if (hours < 12 && hours > 0) {
        if (mins < 10) {
            string = String.valueOf((hours < 10 ? "0" + hours : hours) + ":" + (mins > 0 ? "0" + mins : "0") + " AM");
        } else {
            string = String.valueOf((hours < 10 ? "0" + hours : hours) + ":" + (mins > 0 ? mins : "0") + " AM");
        }
    } else if (hours >= 12) {
        if (mins < 10) {
            string = String.valueOf(((hours - 12) < 10 ? "0" + (hours - 12) : ((hours - 12) == 12 ? "0" : (hours - 12))) + ":" + (mins > 0 ? "0" + mins : "0") + ((hours - 12) == 12 ? " AM" : " PM"));
        } else {
            string = String.valueOf(((hours - 12) < 10 ? "0" + (hours - 12) : ((hours - 12) == 12 ? "0" : (hours - 12))) + ":" + (mins > 0 ? mins : "0") + ((hours - 12) == 12 ? " AM" : " PM"));
        }
    } else {
        if (mins < 10) {
            string = String.valueOf("0" + ":" + (mins > 0 ? "0" + mins : "0") + " AM");
        } else {
            string = String.valueOf("0" + ":" + (mins > 0 ? mins : "0") + " AM");
        }
    }
    return string;
}

How to kill a while loop with a keystroke?

From following this thread down the rabbit hole, I came to this, works on Win10 and Ubuntu 20.04. I wanted more than just killing the script, and to use specific keys, and it had to work in both MS and Linux..

import _thread
import time
import sys
import os

class _Getch:
    """Gets a single character from standard input.  Does not echo to the screen."""
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            self.impl = _GetchUnix()

    def __call__(self): return self.impl()

class _GetchUnix:
    def __init__(self):
        import tty, sys

    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

class _GetchWindows:
    def __init__(self):
        import msvcrt

    def __call__(self):
        import msvcrt
        msvcrt_char = msvcrt.getch()
        return msvcrt_char.decode("utf-8")

def input_thread(key_press_list):
    char = 'x'
    while char != 'q': #dont keep doing this after trying to quit, or 'stty sane' wont work
        time.sleep(0.05)
        getch = _Getch()
        char = getch.impl()
        pprint("getch: "+ str(char))
        key_press_list.append(char)

def quitScript():
    pprint("QUITTING...")
    time.sleep(0.2) #wait for the thread to die
    os.system('stty sane')
    sys.exit()

def pprint(string_to_print): #terminal is in raw mode so we need to append \r\n
    print(string_to_print, end="\r\n")

def main():
    key_press_list = []
    _thread.start_new_thread(input_thread, (key_press_list,))
    while True:
        #do your things here
        pprint("tick")
        time.sleep(0.5)

        if key_press_list == ['q']:
            key_press_list.clear()
            quitScript()

        elif key_press_list == ['j']:
            key_press_list.clear()
            pprint("knock knock..")

        elif key_press_list:
            key_press_list.clear()

main()

pip install mysql-python fails with EnvironmentError: mysql_config not found

sometimes the error depends on the actual cause. we had a case where mysql-python was installed through the python-mysqldb debian package.

a developer who didn't know this, accidentally ran pip uninstall mysql-python and then failed to recover with pip install mysql-python giving the above error.

pip uninstall mysql-python had destroyed the debian package contents, and of course pip install mysql-python failed because the debian package didn't need any dev files.

the correct solution in that case was apt-get install --reinstall python-mysqldb which restored mysql-python to its original state.

"query function not defined for Select2 undefined error"

I also had this problem make sure that you don't initialize the select2 twice.

Animation CSS3: display + opacity

Based on Michaels answer this is the actual CSS code to use

.parent:hover .child
{
    display: block;

    -webkit-animation: fadeInFromNone 0.5s ease-out;
    -moz-animation: fadeInFromNone 0.5s ease-out;
    -o-animation: fadeInFromNone 0.5s ease-out;
    animation: fadeInFromNone 0.5s ease-out;
}

@-webkit-keyframes fadeInFromNone {
    0% {
        display: none;
        opacity: 0;
    }

    1% {
        display: block;
        opacity: 0;
    }

    100% {
        display: block;
        opacity: 1;
    }
}

@-moz-keyframes fadeInFromNone {
    0% {
        display: none;
        opacity: 0;
    }

    1% {
        display: block;
        opacity: 0;
    }

    100% {
        display: block;
        opacity: 1;
    }
}

@-o-keyframes fadeInFromNone {
    0% {
        display: none;
        opacity: 0;
    }

    1% {
        display: block;
        opacity: 0;
    }

    100% {
        display: block;
        opacity: 1;
    }
}

@keyframes fadeInFromNone {
    0% {
        display: none;
        opacity: 0;
    }

    1% {
        display: block;
        opacity: 0;
    }

    100% {
        display: block;
        opacity: 1;
    }
}

How to check if an integer is in a given range?

ValueRange range = java.time.temporal.ValueRange.of(minValue, maxValue);
range.isValidIntValue(x);

it returns true if minValue <= x <= MaxValue - i.e within the range

it returns false if x < minValue or x > maxValue - i.e outofrange

Use with if condition as shown below:

int value = 10;
if(ValueRange.of(0, 100).isValidIntValue(value)) {
    System.out.println("Value is with in the Range.");
} else {
    System.out.println("Value is out of the Range.");
}

below program checks, if any of the passed integer value in the hasTeen method is within the range of 13(inclusive) to 19(Inclusive)


import java.time.temporal.ValueRange;    
public class TeenNumberChecker {

    public static void main(String[] args) {
        System.out.println(hasTeen(9, 99, 19));
        System.out.println(hasTeen(23, 15, 42));
        System.out.println(hasTeen(22, 23, 34));

    }

    public static boolean hasTeen(int firstNumber, int secondNumber, int thirdNumber) {

        ValueRange range = ValueRange.of(13, 19);
        System.out.println("*********Int validation Start ***********");
        System.out.println(range.isIntValue());
        System.out.println(range.isValidIntValue(firstNumber));
        System.out.println(range.isValidIntValue(secondNumber));
        System.out.println(range.isValidIntValue(thirdNumber));
        System.out.println(range.isValidValue(thirdNumber));
        System.out.println("**********Int validation End**************");

        if (range.isValidIntValue(firstNumber) || range.isValidIntValue(secondNumber) || range.isValidIntValue(thirdNumber)) {
            return true;
        } else
            return false;
    }
}

******OUTPUT******

true as 19 is part of range

true as 15 is part of range

false as all three value passed out of range

What is .Net Framework 4 extended?

Got this from Bing. Seems Microsoft has removed some features from the core framework and added it to a separate optional(?) framework component.

To quote from MSDN (http://msdn.microsoft.com/en-us/library/cc656912.aspx)

The .NET Framework 4 Client Profile does not include the following features. You must install the .NET Framework 4 to use these features in your application:

* ASP.NET
* Advanced Windows Communication Foundation (WCF) functionality
* .NET Framework Data Provider for Oracle
* MSBuild for compiling

Read a file line by line with VB.NET

Replaced the reader declaration with this one and now it works!

Dim reader As New StreamReader(filetoimport.Text, Encoding.Default)

Encoding.Default represents the ANSI code page that is set under Windows Control Panel.

R data formats: RData, Rda, Rds etc

Rda is just a short name for RData. You can just save(), load(), attach(), etc. just like you do with RData.

Rds stores a single R object. Yet, beyond that simple explanation, there are several differences from a "standard" storage. Probably this R-manual Link to readRDS() function clarifies such distinctions sufficiently.

So, answering your questions:

  • The difference is not about the compression, but serialization (See this page)
  • Like shown in the manual page, you may wanna use it to restore a certain object with a different name, for instance.
  • You may readRDS() and save(), or load() and saveRDS() selectively.

What should I use to open a url instead of urlopen in urllib3

In urlip3 there's no .urlopen, instead try this:

import requests
html = requests.get(url)

How to find and replace with regex in excel

If you want a formula to do it then:

=IF(ISNUMBER(SEARCH("*texts are *",A1)),LEFT(A1,FIND("texts are ",A1) + 9) & "WORD",A1)

This will do it. Change `"WORD" To the word you want.

Force table column widths to always be fixed regardless of contents

You can also work with "overflow: hidden" or "overflow-x: hidden" (for just the width). This requires a defined width (and/or height?) and maybe a "display: block" as well.

"Overflow:Hidden" hides the whole content, which does not fit into the defined box.

Example:

http://jsfiddle.net/NAJvp/

HTML:

<table border="1">
    <tr>
        <td><div>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</div></td>
        <td>bbb</td>
        <td>cccc</td>
    </tr>
</table>

CSS:

td div { width: 100px; overflow-y: hidden; }

EDIT: Shame on me, I've seen, you already use "overflow". I guess it doesn't work, because you don't set "display: block" to your element ...

OpenCV - DLL missing, but it's not?

Copy all .dll from /bin in System32

Declaring an unsigned int in Java

Just made this piece of code, wich converts "this.altura" from negative to positive number. Hope this helps someone in need

       if(this.altura < 0){    

                        String aux = Integer.toString(this.altura);
                        char aux2[] = aux.toCharArray();
                        aux = "";
                        for(int con = 1; con < aux2.length; con++){
                            aux += aux2[con];
                        }
                        this.altura = Integer.parseInt(aux);
                        System.out.println("New Value: " + this.altura);
                    }

ASP.NET MVC5/IIS Express unable to debug - Code Not Running

The following steps fix the problem for VS 2015 and VS 2017:


Close VS.

Navigate to the folder of the solution and delete the hidden .vs folder.

open VS.

Hit F5 and IIS Express should load as normal, allowing you to debug.

How to display scroll bar onto a html table

Something like this?

http://jsfiddle.net/TweNm/

The idea is to wrap the <table> in a non-statically positioned <div> which has an overflow:auto CSS property. Then position the elements in the <thead> absolutely.

_x000D_
_x000D_
#table-wrapper {_x000D_
  position:relative;_x000D_
}_x000D_
#table-scroll {_x000D_
  height:150px;_x000D_
  overflow:auto;  _x000D_
  margin-top:20px;_x000D_
}_x000D_
#table-wrapper table {_x000D_
  width:100%;_x000D_
_x000D_
}_x000D_
#table-wrapper table * {_x000D_
  background:yellow;_x000D_
  color:black;_x000D_
}_x000D_
#table-wrapper table thead th .text {_x000D_
  position:absolute;   _x000D_
  top:-20px;_x000D_
  z-index:2;_x000D_
  height:20px;_x000D_
  width:35%;_x000D_
  border:1px solid red;_x000D_
}
_x000D_
<div id="table-wrapper">_x000D_
  <div id="table-scroll">_x000D_
    <table>_x000D_
        <thead>_x000D_
            <tr>_x000D_
                <th><span class="text">A</span></th>_x000D_
                <th><span class="text">B</span></th>_x000D_
                <th><span class="text">C</span></th>_x000D_
            </tr>_x000D_
        </thead>_x000D_
        <tbody>_x000D_
          <tr> <td>1, 0</td> <td>2, 0</td> <td>3, 0</td> </tr>_x000D_
          <tr> <td>1, 1</td> <td>2, 1</td> <td>3, 1</td> </tr>_x000D_
          <tr> <td>1, 2</td> <td>2, 2</td> <td>3, 2</td> </tr>_x000D_
          <tr> <td>1, 3</td> <td>2, 3</td> <td>3, 3</td> </tr>_x000D_
          <tr> <td>1, 4</td> <td>2, 4</td> <td>3, 4</td> </tr>_x000D_
          <tr> <td>1, 5</td> <td>2, 5</td> <td>3, 5</td> </tr>_x000D_
          <tr> <td>1, 6</td> <td>2, 6</td> <td>3, 6</td> </tr>_x000D_
          <tr> <td>1, 7</td> <td>2, 7</td> <td>3, 7</td> </tr>_x000D_
          <tr> <td>1, 8</td> <td>2, 8</td> <td>3, 8</td> </tr>_x000D_
          <tr> <td>1, 9</td> <td>2, 9</td> <td>3, 9</td> </tr>_x000D_
          <tr> <td>1, 10</td> <td>2, 10</td> <td>3, 10</td> </tr>_x000D_
          <!-- etc... -->_x000D_
          <tr> <td>1, 99</td> <td>2, 99</td> <td>3, 99</td> </tr>_x000D_
        </tbody>_x000D_
    </table>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to cast an object in Objective-C

((SelectionListViewController *)myEditController).list

More examples:

int i = (int)19.5f; // (precision is lost)
id someObject = [NSMutableArray new]; // you don't need to cast id explicitly

Recursive mkdir() system call on Unix

Here's another take on mkpath(), using recursion, which is both small and readable. It makes use of strdupa() to avoid altering the given dir string argument directly and to avoid using malloc() & free(). Make sure to compile with -D_GNU_SOURCE to activate strdupa() ... meaning this code only works on GLIBC, EGLIBC, uClibc, and other GLIBC compatible C libraries.

int mkpath(char *dir, mode_t mode)
{
    if (!dir) {
        errno = EINVAL;
        return 1;
    }

    if (strlen(dir) == 1 && dir[0] == '/')
        return 0;

    mkpath(dirname(strdupa(dir)), mode);

    return mkdir(dir, mode);
}

After input both here and from Valery Frolov, in the Inadyn project, the following revised version of mkpath() has now been pushed to libite

int mkpath(char *dir, mode_t mode)
{
    struct stat sb;

    if (!dir) {
        errno = EINVAL;
        return 1;
    }

    if (!stat(dir, &sb))
        return 0;

    mkpath(dirname(strdupa(dir)), mode);

    return mkdir(dir, mode);
}

It uses one more syscall, but otoh the code is more readable now.

HTTP Error 503, the service is unavailable

You can also try the following.

Right-click on the site and 'Basic Settings...' Click on 'Connect As...' Click on Specific User and give the new credentials.

Now it should work.

Move / Copy File Operations in Java

Interesting observation: Tried to copy the same file via various java classes and printed time in nano seconds.

Duration using FileOutputStream byte stream: 4 965 078

Duration using BufferedOutputStream: 1 237 206

Duration using (character text Reader: 2 858 875

Duration using BufferedReader(Buffered character text stream: 1 998 005

Duration using (Files NIO copy): 18 351 115

when using Files Nio copy option it took almost 18 times longer!!! Nio is the slowest option to copy files and BufferedOutputStream looks like the fastest. I used the same simple text file for each class.

How to write a UTF-8 file with Java?

All of the answers given here wont work since java's UTF-8 writing is bugged.

http://tripoverit.blogspot.com/2007/04/javas-utf-8-and-unicode-writing-is.html

How do you run CMD.exe under the Local System Account?

Using Secure Desktop to run cmd.exe as system

We can get kernel access through CMD in Windows XP/Vista/7/8.1 easily by attaching a debugger:

REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\osk.exe" /v Debugger /t REG_SZ /d "C:\windows\system32\cmd.exe"
  1. Run CMD as Administrator

  2. Then use this command in Elevated:

     CMD REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\osk.exe" /v Debugger /t REG_SZ /d "C:\windows\system32\cmd.exe"
    
  3. Then run osk (onscreenkeyboard). It still does not run with system Integrity level if you check through process explorer, but if you can use OSK in service session, it will run as NT Authority\SYSTEM

so I had the idea you have to run it on Secure Desktop.

Start any file as Administrator. When UAC prompts appear, just press Win+U and start OSK and it will start CMD instead. Then in the elevated prompt, type whoami and you will get NT Authority\System. After that, you can start Explorer from the system command shell and use the System profile, but you are somewhat limited what you can do on the network through SYSTEM privileges for security reasons. I will add more explanation later as I discovered it a year ago.

A Brief Explanation of how this happens

Running Cmd.exe Under Local System Account Without Using PsExec. This method runs Debugger Trap technique that was discovered earlier, well this technique has its own benefits it can be used to trap some crafty/malicious worm or malware in the debugger and run some other exe instead to stop the spread or damage temporary. here this registry key traps onscreen keyboard in windows native debugger and runs cmd.exe instead but cmd will still run with Logged on users privileges, however if we run cmd in session0 we can get system shell. so we add here another idea we span the cmd on secure desktop remember secure desktop runs in session 0 under system account and we get system shell. So whenever you run anything as elevated, you have to answer the UAC prompt and UAC prompts on dark, non interactive desktop and once you see it you have to press Win+U and then select OSK you will get CMD.exe running under Local system privileges. There are even more ways to get local system access with CMD

How can I calculate the number of years between two dates?

Sleek foundation javascript function.

 function calculateAge(birthday) { // birthday is a date
   var ageDifMs = Date.now() - birthday;
   var ageDate = new Date(ageDifMs); // miliseconds from epoch
   return Math.abs(ageDate.getUTCFullYear() - 1970);
 }

Set form backcolor to custom color

With Winforms you can use Form.BackColor to do this.
From within the Form's code:

BackColor = Color.LightPink;

If you mean a WPF Window you can use the Background property.
From within the Window's code:

Background = Brushes.LightPink;

document .click function for touch device

As stated above, using 'click touchstart' will get the desired result. If you console.log(e) your clicks though, you may find that when jquery recognizes touch as a click - you will get 2 actions from click and touchstart. The solution bellow worked for me.

//if its a mobile device use 'touchstart'
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
    deviceEventType = 'touchstart'
} else {
//If its not a mobile device use 'click'
    deviceEventType = 'click'
}

$(document).on(specialEventType, function(e){
    //code here
});

Serialize JavaScript object into JSON string

Well, the type of an element is not standardly serialized, so you should add it manually. For example

var myobject = new MyClass1("5678999", "text");
var toJSONobject = { objectType: myobject.constructor, objectProperties: myobject };
console.log(JSON.stringify(toJSONobject));

Good luck!

edit: changed typeof to the correct .constructor. See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/constructor for more information on the constructor property for Objects.

Open URL in same window and in same tab

You need to use the name attribute:

window.open("https://www.youraddress.com","_self")

Edit: Url should be prepended with protocol. Without it tries to open relative url. Tested in Chrome 59, Firefox 54 and IE 11.

Android ListView in fragment example

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

Reset IntelliJ UI to Default

All above answers are correct, but you loose configuration settings.

But if your IDE's only themes or fonts are changed or some UI related issues and you want to restore to default theme, then just delete

${user.home}/.IntelliJIdea13/config/options/options.xml

file while IDE is not running, then after next restart IDE's theme will gets reset to default.

Node.js project naming conventions for files & folders

Use kebab-case for all package, folder and file names.

Why?

You should imagine that any folder or file might be extracted to its own package some day. Packages cannot contain uppercase letters.

New packages must not have uppercase letters in the name. https://docs.npmjs.com/files/package.json#name

Therefore, camelCase should never be used. This leaves snake_case and kebab-case.

kebab-case is by far the most common convention today. The only use of underscores is for internal node packages, and this is simply a convention from the early days.

How can I insert multiple rows into oracle with a sequence value?

It does not work because sequence does not work in following scenarios:

  • In a WHERE clause
  • In a GROUP BY or ORDER BY clause
  • In a DISTINCT clause
  • Along with a UNION or INTERSECT or MINUS
  • In a sub-query

Source: http://www.orafaq.com/wiki/ORA-02287

However this does work:

insert into table_name
            (col1, col2)
  select my_seq.nextval, inner_view.*
    from (select 'some value' someval
            from dual
          union all
          select 'another value' someval
            from dual) inner_view;

Try it out:

create table table_name(col1 varchar2(100), col2 varchar2(100));

create sequence vcert.my_seq
start with 1
increment by 1
minvalue 0;

select * from  table_name;

Absolute Positioning & Text Alignment

The div doesn't take up all the available horizontal space when absolutely positioned. Explicitly setting the width to 100% will solve the problem:

HTML

<div id="my-div">I want to be centered</div>?

CSS

#my-div {
   position: absolute;
   bottom: 15px;
   text-align: center;
   width: 100%;
}

?

ImageView - have height match width?

I don't think there's any way you can do it in XML layout file, and I don't think android:scaleType attribute will work like you want it to be.
The only way would be to do it programmatically. You can set the width to fill_parent and can either take screen width as the height of the View or can use View.getWidth() method.

How to get the selected row values of DevExpress XtraGrid?

All you have to do is use the GetFocusedRowCellValue method of the gridView control and put it into the RowClick event.

For example:

private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
{
    if (this.gvCodigoNombres.GetFocusedRowCellValue("EMP_dni") == null)
        return;
    MessageBox.Show(""+this.gvCodigoNombres.GetFocusedRowCellValue("EMP_dni").ToString());            
}

Right to Left support for Twitter Bootstrap 3

in every version of bootstrap,you can do it manually

  1. set rtl direction to your body
  2. in bootstrap.css file, look for ".col-sm-9{float:left}" expression,change it to float:right

this do most things that you want for rtl

Sorting a list with stream.sorted() in Java

This might help for people ending up here searching how to sort list alphabetically.

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class SortService {
    public static void main(String[] args) {
        List<TestData> test = new ArrayList<>();
        test.add(prepareTestData("Asmin",1));
        test.add(prepareTestData("saurav",4));
        test.add(prepareTestData("asmin",2));
        test.add(prepareTestData("Saurav",3));

        test.forEach(data-> System.out.println(data));
        /** Output
         *  TestData(name=Asmin, id=1)
         *  TestData(name=saurav, id=4)
         *  TestData(name=asmin, id=2)
         *  TestData(name=Saurav, id=3)
         */

        test.sort(Comparator.comparing(TestData::getName,String::compareToIgnoreCase));
        test.forEach(data-> System.out.println(data));
        /**Sorted Output
         * TestData(name=Asmin, id=1)
         * TestData(name=asmin, id=2)
         * TestData(name=saurav, id=4)
         * TestData(name=Saurav, id=3)
         */
    }
    private static TestData prepareTestData(String name, int id){
        TestData testData= new TestData();
        testData.setId(id);
        testData.setName(name);
        return testData;
    }
}

@Getter
@Setter
@ToString
class TestData{
    private String name;
    private int id;
}

How and when to use ‘async’ and ‘await’

To be honest I still think the best explanation is the one about future and promises on the Wikipedia: http://en.wikipedia.org/wiki/Futures_and_promises

The basic idea is that you have a separate pool of threads that execute tasks asynchronously. When using it. The object does however make the promise that it will execute the operation at some time and give you the result when you request it. This means that it will block when you request the result and hasn't finished, but execute in the thread pool otherwise.

From there you can optimize things: some operations can be implemented async and you can optimize things like file IO and network communication by batching together subsequent requests and/or reordering them. I'm not sure if this is already in the task framework of Microsoft - but if it isn't that would be one of the first things I would add.

You can actually implement the future pattern sort-of with yields in C# 4.0. If you want to know how it works exactly, I can recommend this link that does a decent job: http://code.google.com/p/fracture/source/browse/trunk/Squared/TaskLib/ . However, if you start toying with it yourself, you will notice that you really need language support if you want to do all the cool things -- which is exactly what Microsoft did.

tsc is not recognized as internal or external command

In the VSCode file tasks.json, the "command": "tsc" will try to find the tsc windows command script in some folder that it deems to be your modules folder.

If you know where the command npm install -g typescript or npm install typescript is saving to, I would recommend replacing:

"command": "tsc"

with

"command": "D:\\Projects\\TS\\Tutorial\\node_modules\\.bin\\tsc"

where D:\\...\\bin is the folder that contains my tsc windows executable

Will determine where my vscode is natively pointing to right now to find the tsc and fix it I guess.

How to debug Javascript with IE 8

This won't help you step through code or break on errors, but it's a useful way to get the same debug console for your project on all browsers.

myLog = function() {
    if (!myLog._div) { myLog.createDiv(); }

    var logEntry = document.createElement('span');
    for (var i=0; i < arguments.length; i++) {
        logEntry.innerHTML += myLog.toJson(arguments[i]) + '<br />';
    }
    logEntry.innerHTML += '<br />';

    myLog._div.appendChild(logEntry);
}
myLog.createDiv = function() {
    myLog._div = document.body.appendChild(document.createElement('div'));
    var props = {
        position:'absolute', top:'10px', right:'10px', background:'#333', border:'5px solid #333', 
        color: 'white', width: '400px', height: '300px', overflow: 'auto', fontFamily: 'courier new',
        fontSize: '11px', whiteSpace: 'nowrap'
    }
    for (var key in props) { myLog._div.style[key] = props[key]; }
}
myLog.toJSON = function(obj) {
    if (typeof window.uneval == 'function') { return uneval(obj); }
    if (typeof obj == 'object') {
        if (!obj) { return 'null'; }
        var list = [];
        if (obj instanceof Array) {
            for (var i=0;i < obj.length;i++) { list.push(this.toJson(obj[i])); }
            return '[' + list.join(',') + ']';
        } else {
            for (var prop in obj) { list.push('"' + prop + '":' + this.toJson(obj[prop])); }
            return '{' + list.join(',') + '}';
        }
    } else if (typeof obj == 'string') {
        return '"' + obj.replace(/(["'])/g, '\\$1') + '"';
    } else {
        return new String(obj);
    }
}

myLog('log statement');
myLog('logging an object', { name: 'Marcus', likes: 'js' });

This is put together pretty hastily and is a bit sloppy, but it's useful nonetheless and can be improved easily!

Where can I find MySQL logs in phpMyAdmin?

Open your PHPMyAdmin, don't select any database and look for Binary Log tab . You can select different logs from a drop down list and press GO Button to view them.

MongoDB: Is it possible to make a case-insensitive query?

You can use Case Insensitive Indexes:

The following example creates a collection with no default collation, then adds an index on the name field with a case insensitive collation. International Components for Unicode

/* strength: CollationStrength.Secondary
* Secondary level of comparison. Collation performs comparisons up to secondary * differences, such as diacritics. That is, collation performs comparisons of 
* base characters (primary differences) and diacritics (secondary differences). * Differences between base characters takes precedence over secondary 
* differences.
*/
db.users.createIndex( { name: 1 }, collation: { locale: 'tr', strength: 2 } } )

To use the index, queries must specify the same collation.

db.users.insert( [ { name: "Oguz" },
                            { name: "oguz" },
                            { name: "OGUZ" } ] )

// does not use index, finds one result
db.users.find( { name: "oguz" } )

// uses the index, finds three results
db.users.find( { name: "oguz" } ).collation( { locale: 'tr', strength: 2 } )

// does not use the index, finds three results (different strength)
db.users.find( { name: "oguz" } ).collation( { locale: 'tr', strength: 1 } )

or you can create a collection with default collation:

db.createCollection("users", { collation: { locale: 'tr', strength: 2 } } )
db.users.createIndex( { name : 1 } ) // inherits the default collation

Redis: How to access Redis log file

Found it with:

sudo tail /var/log/redis/redis-server.log -n 100

So if the setup was more standard that should be:

sudo tail /var/log/redis_6379.log -n 100

This outputs the last 100 lines of the file.

Where your log file is located is in your configs that you can access with:

redis-cli CONFIG GET *

The log file may not always be shown using the above. In that case use

tail -f `less  /etc/redis/redis.conf | grep logfile|cut -d\  -f2`

What's the difference between the Window.Loaded and Window.ContentRendered events

This is not about the difference between Window.ContentRendered and Window.Loaded but about what how the Window.Loaded event can be used:

I use it to avoid splash screens in all applications which need a long time to come up.

    // initializing my main window
    public MyAppMainWindow()
    {
        InitializeComponent();

        // Set the event
        this.ContentRendered += MyAppMainWindow_ContentRendered;
    }

    private void MyAppMainWindow_ContentRendered(object sender, EventArgs e)
    {
        // ... comes up quick when the controls are loaded and rendered

        // unset the event
        this.ContentRendered -= MyAppMainWindow_ContentRendered;

        // ... make the time comsuming init stuff here
    }

What is the standard naming convention for html/css ids and classes?

There isn't one.

I use underscores all the time, due to hyphens messing up the syntax highlighting of my text editor (Gedit), but that's personal preference.

I've seen all these conventions used all over the place. Use the one that you think is best - the one that looks nicest/easiest to read for you, as well as easiest to type because you'll be using it a lot. For example, if you've got your underscore key on the underside of the keyboard (unlikely, but entirely possible), then stick to hyphens. Just go with what is best for yourself. Additionally, all 3 of these conventions are easily readable. If you're working in a team, remember to keep with the team-specified convention (if any).

Update 2012

I've changed how I program over time. I now use camel case (thisIsASelector) instead of hyphens now; I find the latter rather ugly. Use whatever you prefer, which may easily change over time.

Update 2013

It looks like I like to mix things up yearly... After switching to Sublime Text and using Bootstrap for a while, I've gone back to dashes. To me now they look a lot cleaner than un_der_scores or camelCase. My original point still stands though: there isn't a standard.

Update 2015

An interesting corner case with conventions here is Rust. I really like the language, but the compiler will warn you if you define stuff using anything other than underscore_case. You can turn the warning off, but it's interesting the compiler strongly suggests a convention by default. I imagine in larger projects it leads to cleaner code which is no bad thing.

Update 2016 (you asked for it)

I've adopted the BEM standard for my projects going forward. The class names end up being quite verbose, but I think it gives good structure and reusability to the classes and CSS that goes with them. I suppose BEM is actually a standard (so my no becomes a yes perhaps) but it's still up to you what you decide to use in a project. Most importantly: be consistent with what you choose.

Update 2019 (you asked for it)

After writing no CSS for quite a while, I started working at a place that uses OOCSS in one of their products. I personally find it pretty unpleasant to litter classes everywhere, but not having to jump between HTML and CSS all the time feels quite productive.

I'm still settled on BEM, though. It's verbose, but the namespacing makes working with it in React components very natural. It's also great for selecting specific elements when browser testing.

OOCSS and BEM are just some of the CSS standards out there. Pick one that works for you - they're all full of compromises because CSS just isn't that good.

Update 2020

A boring update this year. I'm still using BEM. My position hasn't really changed from the 2019 update for the reasons listed above. Use what works for you that scales with your team size and hides as much or as little of CSS' poor featureset as you like.

Jdbctemplate query for string: EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0

Since getJdbcTemplate().queryForMap expects minimum size of one but when it returns null it shows EmptyResultDataAccesso fix dis when can use below logic

Map<String, String> loginMap =null;
try{
    loginMap = getJdbcTemplate().queryForMap(sql, new Object[] {CustomerLogInInfo.getCustLogInEmail()});
}
catch(EmptyResultDataAccessException ex){
    System.out.println("Exception.......");
    loginMap =null;
}
if(loginMap==null || loginMap.isEmpty()){
    return null;
}
else{
    return loginMap;
}

Split string with string as delimiter

@ECHO OFF
SETLOCAL
SET "string=string1 by string2.txt"
SET "string=%string:* by =%"
ECHO +%string%+

GOTO :EOF

The above SET command will remove the unwanted data. Result shown between + to demonstrate absence of spaces.

Formula: set var=%somevar:*string1=string2%

will assign to var the value of somevar with all characters up to string1 replaced by string2. The enclosing quotes in a set command ensure that any stray trailing spaces on the line are not included in the value assigned.

Toggle show/hide on click with jQuery

this will work for u

   $("#button-name").click(function(){
        $('#toggle-id').slideToggle('slow');
    });

querying WHERE condition to character length?

SELECT *
   FROM   my_table
   WHERE  substr(my_field,1,5) = "abcde";

UDP vs TCP, how much faster is it?

When speaking of "what is faster" - there are at least two very different aspects: throughput and latency.

If speaking about throughput - TCP's flow control (as mentioned in other answers), is extremely important and doing anything comparable over UDP, while certainly possible, would be a Big Headache(tm). As a result - using UDP when you need throughput, rarely qualifies as a good idea (unless you want to get an unfair advantage over TCP).

However, if speaking about latencies - the whole thing is completely different. While in the absence of packet loss TCP and UDP behave extremely similar (any differences, if any, being marginal) - after the packet is lost, the whole pattern changes drastically.

After any packet loss, TCP will wait for retransmit for at least 200ms (1sec per paragraph 2.4 of RFC6298, but practical modern implementations tend to reduce it to 200ms). Moreover, with TCP, even those packets which did reach destination host - will not be delivered to your app until the missing packet is received (i.e., the whole communication is delayed by ~200ms) - BTW, this effect, known as Head-of-Line Blocking, is inherent to all reliable ordered streams, whether TCP or reliable+ordered UDP. To make things even worse - if the retransmitted packet is also lost, then we'll be speaking about delay of ~600ms (due to so-called exponential backoff, 1st retransmit is 200ms, and second one is 200*2=400ms). If our channel has 1% packet loss (which is not bad by today's standards), and we have a game with 20 updates per second - such 600ms delays will occur on average every 8 minutes. And as 600ms is more than enough to get you killed in a fast-paced game - well, it is pretty bad for gameplay. These effects are exactly why gamedevs often prefer UDP over TCP.

However, when using UDP to reduce latencies - it is important to realize that merely "using UDP" is not sufficient to get substantial latency improvement, it is all about HOW you're using UDP. In particular, while RUDP libraries usually avoid that "exponential backoff" and use shorter retransmit times - if they are used as a "reliable ordered" stream, they still have to suffer from Head-of-Line Blocking (so in case of a double packet loss, instead of that 600ms we'll get about 1.5*2*RTT - or for a pretty good 80ms RTT, it is a ~250ms delay, which is an improvement, but it is still possible to do better). On the other hand, if using techniques discussed in http://gafferongames.com/networked-physics/snapshot-compression/ and/or http://ithare.com/udp-from-mog-perspective/#low-latency-compression , it IS possible to eliminate Head-of-Line blocking entirely (so for a double-packet loss for a game with 20 updates/second, the delay will be 100ms regardless of RTT).

And as a side note - if you happen to have access only to TCP but no UDP (such as in browser, or if your client is behind one of 6-9% of ugly firewalls blocking UDP) - there seems to be a way to implement UDP-over-TCP without incurring too much latencies, see here: http://ithare.com/almost-zero-additional-latency-udp-over-tcp/ (make sure to read comments too(!)).

Force Internet Explorer to use a specific Java Runtime Environment install?

I'd give all the responses here a try first. But I wanted to just throw in what I do, just in case these do not work for you.

I've tried to solve the same problem you're having before, and in the end, what I decided on doing is to have only one JRE installed on my system at a given time. I do have about 10 different JDKs (1.3 through 1.6, and from various vendors - Sun, Oracle, IBM), since I do need it for development, but only one standalone JRE.

This has worked for me on my Windows 2000 + IE 6 computer at home, as well as my Windows XP + Multiple IE computer at work.

How to get a value inside an ArrayList java

Assuming your Car class has a getter method for price, you can simply use

System.out.println (car.get(i).getPrice());

where i is the index of the element.

You can also use

Car c = car.get(i);
System.out.println (c.getPrice());

You also need to return totalprice from your function if you need to store it

main

public static void processCar(ArrayList<Car> cars){
    int totalAmount=0;
    for (int i=0; i<cars.size(); i++){
        int totalprice= cars.get(i).computeCars ();
        totalAmount=+ totalprice; 
    }
}

And change the return type of your function

public int computeCars (){
    int  totalprice= price+tax;
    System.out.println (name + "\t" +totalprice+"\t"+year );
    return  totalprice; 
 }

Git resolve conflict using --ours/--theirs for all files

git diff --name-only --diff-filter=U | xargs git checkout --theirs

Seems to do the job. Note that you have to be cd'ed to the root directory of the git repo to achieve this.

Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot

SQL Server may be able to suggest the right data type for you (even when it does not choose the right type by default) - clicking the "Suggest Types" button (shown in your screenshot above) allows you to have SQL Server scan the source and suggest a data type for the field that's throwing an error. In my case, choosing to scan 20000 rows to generate the suggestions, and using the resulting suggested data type, fixed the issue.

Converting Integers to Roman Numerals - Java

I think my solution is one of the more concise ones:

private static String convertToRoman(int mInt) {
    String[] rnChars = { "M",  "CM", "D", "C",  "XC", "L",  "X", "IX", "V", "I" };
    int[] rnVals = {  1000, 900, 500, 100, 90, 50, 10, 9, 5, 1 };
    String retVal = "";

    for (int i = 0; i < rnVals.length; i++) {
        int numberInPlace = mInt / rnVals[i];
        if (numberInPlace == 0) continue;
        retVal += numberInPlace == 4 && i > 0? rnChars[i] + rnChars[i - 1]:
            new String(new char[numberInPlace]).replace("\0",rnChars[i]);
        mInt = mInt % rnVals[i];
    }
    return retVal;
}

How can I set up an editor to work with Git on Windows?

Notepad++ works just fine, although I choose to stick with Notepad, -m, or even sometimes the built-in "edit."

The problem you are encountering using Notepad++ is related to how Git is launching the editor executable. My solution to this is to set environment variable EDITOR to a batch file, rather than the actual editor executable, that does the following:

start /WAIT "E:\PortableApps\Notepad++Portable\Notepad++Portable.exe" %*

/WAIT tells the command line session to halt until the application exits, thus you will be able to edit to your heart's content while Git happily waits for you. %* passes all arguments to the batch file through to Notepad++.

C:\src> echo %EDITOR%
C:\tools\runeditor.bat

How to get the current time in milliseconds in C Programming

There is no portable way to get resolution of less than a second in standard C So best you can do is, use the POSIX function gettimeofday().

Does bootstrap have builtin padding and margin classes?

Bootstrap versions before 4 and 5 do not define ml, mr, pl, and pr.

Bootstrap versions 4 and 5 define the classes of ml, mr, pl, and pr.

For example:

mr--1
ml--1
pr--1
pl--1

How to watch and compile all TypeScript sources?

Create a file named tsconfig.json in your project root and include following lines in it:

{
    "compilerOptions": {
        "emitDecoratorMetadata": true,
        "module": "commonjs",
        "target": "ES5",
        "outDir": "ts-built",
        "rootDir": "src"
    }
}

Please note that outDir should be the path of the directory to receive compiled JS files, and rootDir should be the path of the directory containing your source (.ts) files.

Open a terminal and run tsc -w, it'll compile any .ts file in src directory into .js and store them in ts-built directory.

How to get a cross-origin resource sharing (CORS) post request working

For some reason, a question about GET requests was merged with this one, so I'll respond to it here.

This simple function will asynchronously get an HTTP status reply from a CORS-enabled page. If you run it, you'll see that only a page with the proper headers returns a 200 status if accessed via XMLHttpRequest -- whether GET or POST is used. Nothing can be done on the client side to get around this except possibly using JSONP if you just need a json object.

The following can be easily modified to get the data held in the xmlHttpRequestObject object:

_x000D_
_x000D_
function checkCorsSource(source) {_x000D_
  var xmlHttpRequestObject;_x000D_
  if (window.XMLHttpRequest) {_x000D_
    xmlHttpRequestObject = new XMLHttpRequest();_x000D_
    if (xmlHttpRequestObject != null) {_x000D_
      var sUrl = "";_x000D_
      if (source == "google") {_x000D_
        var sUrl = "https://www.google.com";_x000D_
      } else {_x000D_
        var sUrl = "https://httpbin.org/get";_x000D_
      }_x000D_
      document.getElementById("txt1").innerHTML = "Request Sent...";_x000D_
      xmlHttpRequestObject.open("GET", sUrl, true);_x000D_
      xmlHttpRequestObject.onreadystatechange = function() {_x000D_
        if (xmlHttpRequestObject.readyState == 4 && xmlHttpRequestObject.status == 200) {_x000D_
          document.getElementById("txt1").innerHTML = "200 Response received!";_x000D_
        } else {_x000D_
          document.getElementById("txt1").innerHTML = "200 Response failed!";_x000D_
        }_x000D_
      }_x000D_
      xmlHttpRequestObject.send();_x000D_
    } else {_x000D_
      window.alert("Error creating XmlHttpRequest object. Client is not CORS enabled");_x000D_
    }_x000D_
  }_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
  <title>Check if page is cors</title>_x000D_
</head>_x000D_
<body>_x000D_
  <p>A CORS-enabled source has one of the following HTTP headers:</p>_x000D_
  <ul>_x000D_
    <li>Access-Control-Allow-Headers: *</li>_x000D_
    <li>Access-Control-Allow-Headers: x-requested-with</li>_x000D_
  </ul>_x000D_
  <p>Click a button to see if the page allows CORS</p>_x000D_
  <form name="form1" action="" method="get">_x000D_
    <input type="button" name="btn1" value="Check Google Page" onClick="checkCorsSource('google')">_x000D_
    <input type="button" name="btn1" value="Check Cors Page" onClick="checkCorsSource('cors')">_x000D_
  </form>_x000D_
  <p id="txt1" />_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

PHP max_input_vars

Yes, add it to the php.ini, restart apache and it should work.

You can test it on the fly if you want to with ini_set("max_input_vars",100)

ASP.NET Custom Validator Client side & Server Side validation not firing

Client-side validation was not being executed at all on my web form and I had no idea why. It turns out the problem was the name of the javascript function was the same as the server control ID.

So you can't do this...

<script>
  function vld(sender, args) { args.IsValid = true; }
</script>
<asp:CustomValidator runat="server" id="vld" ClientValidationFunction="vld" />

But this works:

<script>
  function validate_vld(sender, args) { args.IsValid = true; }
</script>
<asp:CustomValidator runat="server" id="vld" ClientValidationFunction="validate_vld" />

I'm guessing it conflicts with internal .NET Javascript?

Why is the default value of the string type null instead of an empty string?

Habib is right -- because string is a reference type.

But more importantly, you don't have to check for null each time you use it. You probably should throw a ArgumentNullException if someone passes your function a null reference, though.

Here's the thing -- the framework would throw a NullReferenceException for you anyway if you tried to call .ToUpper() on a string. Remember that this case still can happen even if you test your arguments for null since any property or method on the objects passed to your function as parameters may evaluate to null.

That being said, checking for empty strings or nulls is a common thing to do, so they provide String.IsNullOrEmpty() and String.IsNullOrWhiteSpace() for just this purpose.

How to execute a stored procedure within C# program

This is code for executing stored procedures with and with out parameters via reflection. Do note that the objects property names need to match the parameters of the stored procedure.

private static string ConnString = ConfigurationManager.ConnectionStrings["SqlConnection"].ConnectionString;
    private SqlConnection Conn = new SqlConnection(ConnString);

    public void ExecuteStoredProcedure(string procedureName)
    {
        SqlConnection sqlConnObj = new SqlConnection(ConnString);

        SqlCommand sqlCmd = new SqlCommand(procedureName, sqlConnObj);
        sqlCmd.CommandType = CommandType.StoredProcedure;

        sqlConnObj.Open();
        sqlCmd.ExecuteNonQuery();
        sqlConnObj.Close();
    }

    public void ExecuteStoredProcedure(string procedureName, object model)
    {
        var parameters = GenerateSQLParameters(model);
        SqlConnection sqlConnObj = new SqlConnection(ConnString);

        SqlCommand sqlCmd = new SqlCommand(procedureName, sqlConnObj);
        sqlCmd.CommandType = CommandType.StoredProcedure;

        foreach (var param in parameters)
        {
            sqlCmd.Parameters.Add(param);
        }

        sqlConnObj.Open();
        sqlCmd.ExecuteNonQuery();
        sqlConnObj.Close();
    }

    private List<SqlParameter> GenerateSQLParameters(object model)
    {
        var paramList = new List<SqlParameter>();
        Type modelType = model.GetType();
        var properties = modelType.GetProperties();
        foreach (var property in properties)
        {
            if (property.GetValue(model) == null)
            {
                paramList.Add(new SqlParameter(property.Name, DBNull.Value));
            }
            else
            {
                paramList.Add(new SqlParameter(property.Name, property.GetValue(model)));
            }
        }
        return paramList;

    }

Disable LESS-CSS Overwriting calc()

Here's a cross-browser less mixin for using CSS's calc with any property:

.calc(@prop; @val) {
  @{prop}: calc(~'@{val}');
  @{prop}: -moz-calc(~'@{val}');
  @{prop}: -webkit-calc(~'@{val}');
  @{prop}: -o-calc(~'@{val}');
}

Example usage:

.calc(width; "100% - 200px");

And the CSS that's output:

width: calc(100% - 200px);
width: -moz-calc(100% - 200px);
width: -webkit-calc(100% - 200px);
width: -o-calc(100% - 200px);

A codepen of this example: http://codepen.io/patrickberkeley/pen/zobdp

Efficiently sorting a numpy array in descending order?

Here is a quick trick

In[3]: import numpy as np
In[4]: temp = np.random.randint(1,10, 10)
In[5]: temp
Out[5]: array([5, 4, 2, 9, 2, 3, 4, 7, 5, 8])

In[6]: sorted = np.sort(temp)
In[7]: rsorted = list(reversed(sorted))
In[8]: sorted
Out[8]: array([2, 2, 3, 4, 4, 5, 5, 7, 8, 9])

In[9]: rsorted
Out[9]: [9, 8, 7, 5, 5, 4, 4, 3, 2, 2]

Making an image act like a button

You could implement a JavaScript block which contains a function with your needs.

<div style="position: absolute; left: 10px; top: 40px;"> 
    <img src="logg.png" width="114" height="38" onclick="DoSomething();" />
</div>

How to convert array to a string using methods other than JSON?

Display array in beautiful way:

function arrayDisplay($input)
{
    return implode(
        ', ',
        array_map(
            function ($v, $k) {
                return sprintf("%s => '%s'", $k, $v);
            },
            $input,
            array_keys($input)
        )
    );
}

$arr = array('foo'=>'bar',
              'baz'=>'boom',
              'cow'=>'milk',
              'php'=>'hypertext processor');

echo arrayDisplay($arr);

Displays:

foo => 'bar', baz => 'boom', cow => 'milk', php => 'hypertext processor'

Datatable vs Dataset

There are some optimizations you can use when filling a DataTable, such as calling BeginLoadData(), inserting the data, then calling EndLoadData(). This turns off some internal behavior within the DataTable, such as index maintenance, etc. See this article for further details.

How to serialize Object to JSON?

Easy way to do it without annotations is to use Gson library

Simple as that:

Gson gson = new Gson();
String json = gson.toJson(listaDePontos);

Why is Event.target not Element in Typescript?

With typescript we can leverage type aliases, like so:

type KeyboardEvent = {
  target: HTMLInputElement,
  key: string,
};
const onKeyPress = (e: KeyboardEvent) => {
  if ('Enter' === e.key) { // Enter keyboard was pressed!
    submit(e.target.value);
    e.target.value = '';
    return;
  }
  // continue handle onKeyPress input events...
};

CodeIgniter - how to catch DB errors?

an example that worked for me:

$query = "some buggy sql statement";

$this->db->db_debug = false;

if(!@$this->db->query($query))
{
    $error = $this->db->error();
    // do something in error case
}else{
    // do something in success case
}
...

Best

jQuery has deprecated synchronous XMLHTTPRequest

It was mentioned as a comment by @henri-chan, but I think it deserves some more attention:

When you update the content of an element with new html using jQuery/javascript, and this new html contains <script> tags, those are executed synchronously and thus triggering this error. Same goes for stylesheets.

You know this is happening when you see (multiple) scripts or stylesheets being loaded as XHR in the console window. (firefox).

Accessing @attribute from SimpleXML

If you're looking for a list of these attributes though, XPath will be your friend

print_r($xml->xpath('@token'));

FCM getting MismatchSenderId

I spent hours on this and finally figured it out. This problem happens if service account your sender application is using differs from the service account your receiver is using.

You can find out your receiver service account via Firebase -> Project Overview -> Project Settings -> Service Accounts and generate a new key and use that key when you are initializing your FirebaseApp in the sender:

FileInputStream serviceAccount = new FileInputStream("YOUR_PATH_TO_GENERATED_KEY.json");
GoogleCredentials googleCredentials = GoogleCredentials.fromStream(serviceAccount);
FirebaseOptions options = new FirebaseOptions.Builder().setCredentials(googleCredentials).build();
firebaseApp =  FirebaseApp.initializeApp(options);

This initialization need to be done once before you send push notifications.

In my case, I had done everything correctly and I still had this problem. I had made some changes in the "google-services.json" used in the receiver app and I noticed AndroidStudio was not using my new file. The solution was so simple:

AndroidStudio -> Build -> Clean Project and Build -> Rebuild Project

Is it possible to set ENV variables for rails development environment in my code?

Script for loading of custom .env file: Add the following lines to /config/environment.rb, between the require line, and the Application.initialize line:

# Load the app's custom environment variables here, so that they are loaded before environments/*.rb

app_environment_variables = File.join(Rails.root, 'config', 'local_environment.env')
if File.exists?(app_environment_variables)
  lines = File.readlines(app_environment_variables)
  lines.each do |line|
    line.chomp!
    next if line.empty? or line[0] == '#'
    parts = line.partition '='
    raise "Wrong line: #{line} in #{app_environment_variables}" if parts.last.empty?
    ENV[parts.first] = parts.last
  end
end

And config/local_environment.env (you will want to .gitignore it) will look like:

# This is ignored comment
DATABASE_URL=mysql2://user:[email protected]:3307/database
RACK_ENV=development

(Based on solution of @user664833)

What is the difference between a process and a thread?

Coming from the embedded world, I would like to add that the concept of processes only exists in "big" processors (desktop CPUs, ARM Cortex A-9) that have MMU (memory management unit) , and operating systems that support using MMUs (such as Linux). With small/old processors and microcontrollers and small RTOS operating system (real time operating system), such as freeRTOS, there is no MMU support and thus no processes but only threads.

Threads can access each others memory, and they are scheduled by OS in an interleaved manner so they appear to run in parallel (or with multi-core they really run in parallel).

Processes, on the other hand, live in their private sandbox of virtual memory, provided and guarded by MMU. This is handy because it enables:

  1. keeping buggy process from crashing the entire system.
  2. Maintaining security by making other processes data invisible and unreachable. The actual work inside the process is taken care by one or more threads.

Use component from another module

SOLVED HOW TO USE A COMPONENT DECLARED IN A MODULE IN OTHER MODULE.

Based on Royi Namir explanation (Thank you so much). There is a missing part to reuse a component declared in a Module in any other module while lazy loading is used.

1st: Export the component in the module which contains it:

@NgModule({
  declarations: [TaskCardComponent],
  imports: [MdCardModule],
  exports: [TaskCardComponent] <== this line
})
export class TaskModule{}

2nd: In the module where you want to use TaskCardComponent:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MdCardModule } from '@angular2-material/card';

@NgModule({
  imports: [
   CommonModule,
   MdCardModule
   ],
  providers: [],
  exports:[ MdCardModule ] <== this line
})
export class TaskModule{}

Like this the second module imports the first module which imports and exports the component.

When we import the module in the second module we need to export it again. Now we can use the first component in the second module.

docker command not found even though installed with apt-get

sudo apt-get install docker # DO NOT do this

is a different library on ubuntu.

Use sudo apt-get install docker-ce to install the correct docker.

Best way to reset an Oracle sequence to the next value in an existing column?

If you can count on having a period of time where the table is in a stable state with no new inserts going on, this should do it (untested):

DECLARE
  last_used  NUMBER;
  curr_seq   NUMBER;
BEGIN
  SELECT MAX(pk_val) INTO last_used FROM your_table;

  LOOP
    SELECT your_seq.NEXTVAL INTO curr_seq FROM dual;
    IF curr_seq >= last_used THEN EXIT;
    END IF;
  END LOOP;
END;

This enables you to get the sequence back in sync with the table, without dropping/recreating/re-granting the sequence. It also uses no DDL, so no implicit commits are performed. Of course, you're going to have to hunt down and slap the folks who insist on not using the sequence to populate the column...

How to change JAVA.HOME for Eclipse/ANT

Simply, to enforce JAVA version to Ant in Eclipse:

Use RunAs option on Ant file then select External Tool Configuration in JRE tab define your JDK/JRE version you want to use.

How to label each equation in align environment?

like this

\begin{align} 

x_{\rm L} & = L \int{\cos\theta\left(\xi\right) d\xi}, \label{eq_1} \\\\

y_{\rm L} & = L \int{\sin\theta\left(\xi\right) d\xi}, \nonumber

\end{align}

How do I publish a UDP Port on Docker?

Use the -p flag and add /udp suffix to the port number.

-p 53160:53160/udp

Full command

sudo docker run -p 53160:53160 \
    -p 53160:53160/udp -p 58846:58846 \ 
    -p 8112:8112 -t -i aostanin/deluge /start.sh

If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.

You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile (EXPOSE does not publish the port):

EXPOSE 8285/udp

Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)

typescript - cloning object

Try this:

let copy = (JSON.parse(JSON.stringify(objectToCopy)));

It is a good solution until you are using very large objects or your object has unserializable properties.

In order to preserve type safety you could use a copy function in the class you want to make copies from:

getCopy(): YourClassName{
    return (JSON.parse(JSON.stringify(this)));
}

or in a static way:

static createCopy(objectToCopy: YourClassName): YourClassName{
    return (JSON.parse(JSON.stringify(objectToCopy)));
}

XAMPP - MySQL shutdown unexpectedly

I also faced this issue and this is how I solved.
1. Make sure xampp is not under sub-directory. For example, it should be C:\xampp
2. You might need to run as administrator in running the application.

Hope this will work!

How to give a pandas/matplotlib bar graph custom colors

You can specify the color option as a list directly to the plot function.

from matplotlib import pyplot as plt
from itertools import cycle, islice
import pandas, numpy as np  # I find np.random.randint to be better

# Make the data
x = [{i:np.random.randint(1,5)} for i in range(10)]
df = pandas.DataFrame(x)

# Make a list by cycling through the colors you care about
# to match the length of your data.
my_colors = list(islice(cycle(['b', 'r', 'g', 'y', 'k']), None, len(df)))

# Specify this list of colors as the `color` option to `plot`.
df.plot(kind='bar', stacked=True, color=my_colors)

To define your own custom list, you can do a few of the following, or just look up the Matplotlib techniques for defining a color item by its RGB values, etc. You can get as complicated as you want with this.

my_colors = ['g', 'b']*5 # <-- this concatenates the list to itself 5 times.
my_colors = [(0.5,0.4,0.5), (0.75, 0.75, 0.25)]*5 # <-- make two custom RGBs and repeat/alternate them over all the bar elements.
my_colors = [(x/10.0, x/20.0, 0.75) for x in range(len(df))] # <-- Quick gradient example along the Red/Green dimensions.

The last example yields the follow simple gradient of colors for me:

enter image description here

I didn't play with it long enough to figure out how to force the legend to pick up the defined colors, but I'm sure you can do it.

In general, though, a big piece of advice is to just use the functions from Matplotlib directly. Calling them from Pandas is OK, but I find you get better options and performance calling them straight from Matplotlib.

working with negative numbers in python

Try this on your TA:

# Simulate multiplying two N-bit two's-complement numbers
# into a 2N-bit accumulator
# Use shift-add so that it's O(base_2_log(N)) not O(N)

for numa, numb in ((3, 5), (-3, 5), (3, -5), (-3, -5), (-127, -127)):
    print numa, numb,
    accum = 0
    negate = False
    if numa < 0:
        negate = True
        numa = -numa
    while numa:
        if numa & 1:
            accum += numb
        numa >>= 1
        numb <<= 1
    if negate:
        accum = -accum
    print accum

output:

3 5 15
-3 5 -15
3 -5 -15
-3 -5 15
-127 -127 16129

Generating random integer from a range

In this thread rejection sampling was already discussed, but I wanted to suggest one optimization based on the fact that rand() % 2^something does not introduce any bias as already mentioned above.

The algorithm is really simple:

  • calculate the smallest power of 2 greater than the interval length
  • randomize one number in that "new" interval
  • return that number if it is less than the length of the original interval
    • reject otherwise

Here's my sample code:

int randInInterval(int min, int max) {
    int intervalLen = max - min + 1;
    //now calculate the smallest power of 2 that is >= than `intervalLen`
    int ceilingPowerOf2 = pow(2, ceil(log2(intervalLen)));

    int randomNumber = rand() % ceilingPowerOf2; //this is "as uniform as rand()"

    if (randomNumber < intervalLen)
        return min + randomNumber;      //ok!
    return randInInterval(min, max);    //reject sample and try again
} 

This works well especially for small intervals, because the power of 2 will be "nearer" to the real interval length, and so the number of misses will be smaller.

PS
Obviously avoiding the recursion would be more efficient (no need to calculate over and over the log ceiling..) but I thought it was more readable for this example.

Installing Apple's Network Link Conditioner Tool

Update on the answer December 2019 Xcode 11.1.2

Apple has moved Network Link Conditioner Tool to additional tools for Xcode

Go to the below link

https://developer.apple.com/download/more/?q=Additional%20Tools

enter image description here

Install the dmg file, select hardware from installer

enter image description here

select Network Link conditioner prefpane enter image description here

Cannot issue data manipulation statements with executeQuery()

@Modifying
@Transactional
@Query(value = "delete from cart_item where cart_cart_id=:cart", nativeQuery = true)
public void deleteByCart(@Param("cart") int cart); 

Do not forget to add @Modifying and @Transnational before @query. it works for me.

To delete the record with some condition using native query with JPA the above mentioned annotations are important.

Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

As mentioned above the following would solve the problem: mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

However in my case the provider did this [0..1] or [0..*] serialization rather as a bug and I could not enforce fixing. On the other hand it did not want to impact my strict mapper for all other cases which needs to be validated strictly.

So I did a Jackson NASTY HACK (which should not be copied in general ;-) ), especially because my SingleOrListElement had only few properties to patch:

@JsonProperty(value = "SingleOrListElement", access = JsonProperty.Access.WRITE_ONLY)
private Object singleOrListElement; 

public List<SingleOrListElement> patch(Object singleOrListElement) {
  if (singleOrListElement instanceof List) {
    return (ArrayList<SingleOrListElement>) singleOrListElement;
  } else {
    LinkedHashMap map = (LinkedHashMap) singleOrListElement;
    return Collections.singletonList(SingletonList.builder()
                            .property1((String) map.get("p1"))
                            .property2((Integer) map.get("p2"))
                            .build());
  }

How to format a number 0..9 to display with 2 digits (it's NOT a date)

If you need to print the number you can use printf

System.out.printf("%02d", num);

You can use

String.format("%02d", num);

or

(num < 10 ? "0" : "") + num;

or

(""+(100+num)).substring(1);

When to use in vs ref vs out

out is more constraint version of ref.

In a method body, you need to assign to all out parameters before leaving the method. Also an values assigned to an out parameter is ignored, whereas ref requires them to be assigned.

So out allows you to do:

int a, b, c = foo(out a, out b);

where ref would require a and b to be assigned.

Bootstrap 3 Flush footer to bottom. not fixed

There is a simplified solution from bootstrap here (where you don't need to create a new class): http://getbootstrap.com/examples/sticky-footer-navbar/

When you open that page, right click on a browser and "View Source" and open the sticky-footer-navbar.css file (http://getbootstrap.com/examples/sticky-footer-navbar/sticky-footer-navbar.css)

you can see that you only need this CSS

/* Sticky footer styles
-------------------------------------------------- */
html {
  position: relative;
  min-height: 100%;
}
body {
  /* Margin bottom by footer height */
  margin-bottom: 60px;
}
.footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  /* Set the fixed height of the footer here */
  height: 60px;
  background-color: #f5f5f5;
}

for this HTML

<html>
    ...
    <body>
        <!-- Begin page content -->
        <div class="container">
        </div>
        ...

        <footer class="footer">
        </footer>
    </body>
</html>

How do you change the document font in LaTeX?

As second says, most of the "design" decisions made for TeX documents are backed up by well researched usability studies, so changing them should be undertaken with care. It is, however, relatively common to replace Computer Modern with Times (also a serif face).

Try \usepackage{times}.

Class vs. static method in JavaScript

Just additional notes. Using class ES6, When we create static methods..the Javacsript engine set the descriptor attribute a lil bit different from the old-school "static" method

function Car() {

}

Car.brand = function() {
  console.log('Honda');
}

console.log(
  Object.getOwnPropertyDescriptors(Car)
);

it sets internal attribute (descriptor property) for brand() to

..
brand: [object Object] {
    configurable: true,
    enumerable: true,
    value: ..
    writable: true

}
..

compared to

class Car2 {
   static brand() {
     console.log('Honda');
   }
}

console.log(
  Object.getOwnPropertyDescriptors(Car2)
);

that sets internal attribute for brand() to

..
brand: [object Object] {
    configurable: true,
    enumerable: false,
    value:..
    writable: true
  }

..

see that enumerable is set to false for static method in ES6.

it means you cant use the for-in loop to check the object

for (let prop in Car) {
  console.log(prop); // brand
}

for (let prop in Car2) {
  console.log(prop); // nothing here
}

static method in ES6 is treated like other's class private property (name, length, constructor) except that static method is still writable thus the descriptor writable is set to true { writable: true }. it also means that we can override it

Car2.brand = function() {
   console.log('Toyota');
};

console.log(
  Car2.brand() // is now changed to toyota
);

NameError: global name 'xrange' is not defined in Python 3

I agree with the last answer.But there is another way to solve this problem.You can download the package named future,such as pip install future.And in your .py file input this "from past.builtins import xrange".This method is for the situation that there are many xranges in your file.

How can I show a combobox in Android?

In android it is called a Spinner you can take a look at the tutorial here.

Hello, Spinner

And this is a very vague question, you should try to be more descriptive of your problem.

Angular: date filter adds timezone, how to output UTC?

The date filter always formats the dates using the local timezone. You'll have to write your own filter, based on the getUTCXxx() methods of Date, or on a library like moment.js.

Static image src in Vue.js template

@Pantelis answer somehow steered me to a solution for a similar misunderstanding. A message board project I'm working on needs to show an optional image. I was having fits trying to get the src=imagefile to concatenate a fixed path and variable filename string until I saw the quirky use of "''" quotes :-)

<template id="symp-tmpl">
  <div>
    <div v-for="item in items" style="clear: both;">
      <div v-if="(item.imagefile !== '[none]')">
        <img v-bind:src="'/storage/userimages/' + item.imagefile">
      </div>
      sub: <span>@{{ item.subject }}</span>
      <span v-if="(login == item.author)">[edit]</span>
      <br>@{{ item.author }}
      <br>msg: <span>@{{ item.message }}</span>
    </div>
  </div>
</template>

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1922-1' for key 'IDX_STOCK_PRODUCT'

the message means you are doing another insert with the same combination of columns that are part of the IDX_STOCK_PRODUCT, which seams to be defined as UNIQUE. If it is so, it doesn't allow to enter same combination (it seems like it consists of two fields) twice.

If you are inserting records, make sure you are picking brand new record id or that the combination of record id and the other column is unique.

Without detailed table structure and your code, we can hardly guess whats going wrong.

Using PowerShell credentials without being prompted for a password

There is another way, but...

DO NOT DO THIS IF YOU DO NOT WANT YOUR PASSWORD IN THE SCRIPT FILE (It isn't a good idea to store passwords in scripts, but some of us just like to know how.)

Ok, that was the warning, here's the code:

$username = "John Doe"
$password = "ABCDEF"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr

$cred will have the credentials from John Doe with the password "ABCDEF".

Alternative means to get the password ready for use:

$password = convertto-securestring -String "notverysecretpassword" -AsPlainText -Force

Counting number of lines, words, and characters in a text file

in.next(); is consuming all the lines in the first while(). After the end of your first while loop, there are no more characters to be read at the input stream.

You should nest your character and word-counting within a while loop counting lines.

UITableView Separator line

Try this:

UIImageView *separator = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"separator.png"]];
[cell.contentView addSubview: separator];

That's an example of how I got it to work pretty well.

Remember to set the separator style for the table view to none.

Update TensorFlow

For anaconda installation, first pick a channel which has the latest version of tensorflow binary. Usually, the latest versions are available at the channel conda-forge. Then simply do:

conda update -f -c conda-forge tensorflow

This will upgrade your existing tensorflow installation to the very latest version available. As of this writing, the latest version is 1.4.0-py36_0

Is there a "do ... while" loop in Ruby?

I found the following snippet while reading the source for Tempfile#initialize in the Ruby core library:

begin
  tmpname = File.join(tmpdir, make_tmpname(basename, n))
  lock = tmpname + '.lock'
  n += 1
end while @@cleanlist.include?(tmpname) or
  File.exist?(lock) or File.exist?(tmpname)

At first glance, I assumed the while modifier would be evaluated before the contents of begin...end, but that is not the case. Observe:

>> begin
?>   puts "do {} while ()" 
>> end while false
do {} while ()
=> nil

As you would expect, the loop will continue to execute while the modifier is true.

>> n = 3
=> 3
>> begin
?>   puts n
>>   n -= 1
>> end while n > 0
3
2
1
=> nil

While I would be happy to never see this idiom again, begin...end is quite powerful. The following is a common idiom to memoize a one-liner method with no params:

def expensive
  @expensive ||= 2 + 2
end

Here is an ugly, but quick way to memoize something more complex:

def expensive
  @expensive ||=
    begin
      n = 99
      buf = "" 
      begin
        buf << "#{n} bottles of beer on the wall\n" 
        # ...
        n -= 1
      end while n > 0
      buf << "no more bottles of beer" 
    end
end

Originally written by Jeremy Voorhis. The content has been copied here because it seems to have been taken down from the originating site. Copies can also be found in the Web Archive and at Ruby Buzz Forum. -Bill the Lizard

Subversion ignoring "--password" and "--username" options

Do you actually have the single quotes in your command? I don't think they are necessary. Plus, I think you also need --no-auth-cache and --non-interactive

Here is what I use (no single quotes)

--non-interactive --no-auth-cache --username XXXX --password YYYY

See the Client Credentials Caching documentation in the svnbook for more information.

How do I convert hh:mm:ss.000 to milliseconds in Excel?

Rather than doing string manipulation, you can use the HOUR, MINUTE, SECOND functions to break apart the time. You can then multiply by 60*60*1000, 60*1000, and 1000 respectively to get milliseconds.

How to loop and render elements in React-native?

If u want a direct/ quick away, without assing to variables:

{
 urArray.map((prop, key) => {
     console.log(emp);
     return <Picker.Item label={emp.Name} value={emp.id} />;
 })
}

Gradle to execute Java class (without modifying build.gradle)

Expanding on First Zero's answer, I'm guess you want something where you can also run gradle build without errors.

Both gradle build and gradle -PmainClass=foo runApp work with this:

task runApp(type:JavaExec) {
    classpath = sourceSets.main.runtimeClasspath

    main = project.hasProperty("mainClass") ? project.getProperty("mainClass") : "package.MyDefaultMain"
}

where you set your default main class.

Cannot construct instance of - Jackson

You cannot instantiate an abstract class, Jackson neither. You should give Jackson information on how to instantiate MyAbstractClass with a concrete type.

See this answer on stackoverflow: Jackson JSON library: how to instantiate a class that contains abstract fields

And maybe also see Jackson Polymorphic Deserialization

Is there a limit on an Excel worksheet's name length?

I just tested a couple paths using Excel 2013 on on Windows 7. I found the overall pathname limit to be 213 and the basename length to be 186. At least the error dialog for exceeding basename length is clear: basename error

And trying to move a not-too-long basename to a too-long-pathname is also very clear:enter image description here

The pathname error is deceptive, though. Quite unhelpful:enter image description here

This is a lazy Microsoft restriction. There's no good reason for these arbitrary length limits, but in the end, it’s a real bug in the error dialog.

Read entire file in Scala?

For emulating Ruby syntax (and convey the semantics) of opening and reading a file, consider this implicit class (Scala 2.10 and upper),

import java.io.File

def open(filename: String) = new File(filename)

implicit class RichFile(val file: File) extends AnyVal {
  def read = io.Source.fromFile(file).getLines.mkString("\n")
}

In this way,

open("file.txt").read

Java replace all square brackets in a string

You're currently trying to remove the exact string [] - two square brackets with nothing between them. Instead, you want to remove all [ and separately remove all ].

Personally I would avoid using replaceAll here as it introduces more confusion due to the regex part - I'd use:

String replaced = original.replace("[", "").replace("]", "");

Only use the methods which take regular expressions if you really want to do full pattern matching. When you just want to replace all occurrences of a fixed string, replace is simpler to read and understand.

(There are alternative approaches which use the regular expression form and really match patterns, but I think the above code is significantly simpler.)

Stack smashing detected

What could be the possible reasons for this and how do I rectify it?

One scenario would be in the following example:

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

void swap ( char *a , char *b );
void revSTR ( char *const src );

int main ( void ){
    char arr[] = "A-B-C-D-E";

    revSTR( arr );
    printf("ARR = %s\n", arr );
}

void swap ( char *a , char *b ){
    char tmp = *a;
    *a = *b;
    *b = tmp;
}

void revSTR ( char *const src ){
    char *start = src;
    char *end   = start + ( strlen( src ) - 1 );

    while ( start < end ){
        swap( &( *start ) , &( *end ) );
        start++;
        end--;
    }
}

In this program you can reverse a String or a part of the string if you for example call reverse() with something like this:

reverse( arr + 2 );

If you decide to pass the length of the array like this:

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

void swap ( char *a , char *b );
void revSTR ( char *const src, size_t len );

int main ( void ){
    char arr[] = "A-B-C-D-E";
    size_t len = strlen( arr );

    revSTR( arr, len );
    printf("ARR = %s\n", arr );
}

void swap ( char *a , char *b ){
    char tmp = *a;
    *a = *b;
    *b = tmp;
}

void revSTR ( char *const src, size_t len ){
    char *start = src;
    char *end   = start + ( len - 1 );

    while ( start < end ){
        swap( &( *start ) , &( *end ) );
        start++;
        end--;
    }
}

Works fine too.

But when you do this:

revSTR( arr + 2, len );

You get get:

==7125== Command: ./program
==7125== 
ARR = A-
*** stack smashing detected ***: ./program terminated
==7125== 
==7125== Process terminating with default action of signal 6 (SIGABRT)
==7125==    at 0x4E6F428: raise (raise.c:54)
==7125==    by 0x4E71029: abort (abort.c:89)
==7125==    by 0x4EB17E9: __libc_message (libc_fatal.c:175)
==7125==    by 0x4F5311B: __fortify_fail (fortify_fail.c:37)
==7125==    by 0x4F530BF: __stack_chk_fail (stack_chk_fail.c:28)
==7125==    by 0x400637: main (program.c:14)

And this happens because in the first code, the length of arr is checked inside of revSTR() which is fine, but in the second code where you pass the length:

revSTR( arr + 2, len );

the Length is now longer then the actually length you pass when you say arr + 2.

Length of strlen ( arr + 2 ) != strlen ( arr ).

Difference between Hashing a Password and Encrypting it

As correct as the other answers may be, in the context that the quote was in, hashing is a tool that may be used in securing information, encryption is a process that takes information and makes it very difficult for unauthorized people to read/use.

Using JavaMail with TLS

We actually have some notification code in our product that uses TLS to send mail if it is available.

You will need to set the Java Mail properties. You only need the TLS one but you might need SSL if your SMTP server uses SSL.

Properties props = new Properties();
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth", "true");  // If you need to authenticate
// Use the following if you need SSL
props.put("mail.smtp.socketFactory.port", d_port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");

You can then either pass this to a JavaMail Session or any other session instantiator like Session.getDefaultInstance(props).