Programs & Examples On #Spring modules

Modules for the Spring application development framework.

Mailx send html message

There are many different versions of mail around. When you go beyond mail -s subject to1@address1 to2@address2

  • With some mailx implementations, e.g. from mailutils on Ubuntu or Debian's bsd-mailx, it's easy, because there's an option for that.

    mailx -a 'Content-Type: text/html' -s "Subject" to@address <test.html
    
  • With the Heirloom mailx, there's no convenient way. One possibility to insert arbitrary headers is to set editheaders=1 and use an external editor (which can be a script).

    ## Prepare a temporary script that will serve as an editor.
    
    ## This script will be passed to ed.
    temp_script=$(mktemp)
    cat <<'EOF' >>"$temp_script"
    1a
    Content-Type: text/html
    .
    $r test.html
    w
    q
    EOF
    ## Call mailx, and tell it to invoke the editor script
    EDITOR="ed -s $temp_script" heirloom-mailx -S editheaders=1 -s "Subject" to@address <<EOF
    ~e
    .
    EOF
    rm -f "$temp_script"
    
  • With a general POSIX mailx, I don't know how to get at headers.

If you're going to use any mail or mailx, keep in mind that

  • This isn't portable even within a given Linux distribution. For example, both Ubuntu and Debian have several alternatives for mail and mailx.

  • When composing a message, mail and mailx treats lines beginning with ~ as commands. If you pipe text into mail, you need to arrange for this text not to contain lines beginning with ~.

If you're going to install software anyway, you might as well install something more predictable than mail/Mail/mailx. For example, mutt. With Mutt, you can supply most headers in the input with the -H option, but not Content-Type, which needs to be set via a mutt option.

mutt -e 'set content_type=text/html' -s 'hello' 'to@address' <test.html

Or you can invoke sendmail directly. There are several versions of sendmail out there, but they all support sendmail -t to send a mail in the simplest fashion, reading the list of recipients from the mail. (I think they don't all support Bcc:.) On most systems, sendmail isn't in the usual $PATH, it's in /usr/sbin or /usr/lib.

cat <<'EOF' - test.html | /usr/sbin/sendmail -t
To: to@address
Subject: hello
Content-Type: text/html

EOF

Getting the parent of a directory in Bash

This would go up to the parent folder

cd ../

Match the path of a URL, minus the filename extension

This general URL match allows you to select parts of a URL:

if (preg_match('/\\b(?P<protocol>https?|ftp):\/\/(?P<domain>[-A-Z0-9.]+)(?P<file>\/[-A-Z0-9+&@#\/%=~_|!:,.;]*)?(?P<parameters>\\?[-A-Z0-9+&@#\/%=~_|!:,.;]*)?/i', $subject, $regs)) {
    $result = $regs['file'];
    //or you can append the $regs['parameters'] too
} else {
    $result = "";
}

python dictionary sorting in descending order based on values

Whenever one has a dictionary where the values are integers, the Counter data structure is often a better choice to represent the data than a dictionary.

If you already have a dictionary, a counter can easily be formed by:

c = Counter(d['123'])

as an example from your data.

The most_common function allows easy access to descending order of the items in the counter

The more complete writeup on the Counter data structure is at https://docs.python.org/2/library/collections.html

Find multiple files and rename them in Linux

For renaming recursively I use the following commands:

find -iname \*.* | rename -v "s/ /-/g"

How can I print a quotation mark in C?

In C programming language, \ is used to print some of the special characters which has sepcial meaning in C. Those special characters are listed below

\\ - Backslash
\' - Single Quotation Mark
\" - Double Quatation Mark
\n - New line
\r - Carriage Return
\t - Horizontal Tab
\b - Backspace
\f - Formfeed
\a - Bell(beep) sound

HTML5 Canvas vs. SVG vs. div

Knowing the differences between SVG and Canvas would be helpful in selecting the right one.

Canvas

SVG

  • Resolution independent
  • Support for event handlers
  • Best suited for applications with large rendering areas (Google Maps)
  • Slow rendering if complex (anything that uses the DOM a lot will be slow)
  • Not suited for game application

angular 2 sort and filter

Here is a simple filter pipe for array of objects that contain attributes with string values (ES6)

filter-array-pipe.js

import {Pipe} from 'angular2/core';

// # Filter Array of Objects
@Pipe({ name: 'filter' })
export class FilterArrayPipe {
  transform(value, args) {
    if (!args[0]) {
      return value;
    } else if (value) {
      return value.filter(item => {
        for (let key in item) {
          if ((typeof item[key] === 'string' || item[key] instanceof String) && 
              (item[key].indexOf(args[0]) !== -1)) {
            return true;
          }
        }
      });
    }
  }
}

Your component

myobjComponent.js

import {Component} from 'angular2/core';
import {HTTP_PROVIDERS, Http} from 'angular2/http';
import {FilterArrayPipe} from 'filter-array-pipe';

@Component({
  templateUrl: 'myobj.list.html',
  providers: [HTTP_PROVIDERS],
  pipes: [FilterArrayPipe]
})
export class MyObjList {
  static get parameters() {
    return [[Http]];
  }
  constructor(_http) {
    _http.get('/api/myobj')
      .map(res => res.json())
      .subscribe(
        data => this.myobjs = data,
        err => this.logError(err))
      );
  }
  resetQuery(){
    this.query = '';
  }
}

In your template

myobj.list.html

<input type="text" [(ngModel)]="query" placeholder="... filter" > 
<div (click)="resetQuery()"> <span class="icon-cross"></span> </div>
</div>
<ul><li *ngFor="#myobj of myobjs| filter:query">...<li></ul>

Create text file and fill it using bash

Assuming you mean UNIX shell commands, just run

echo >> file.txt

echo prints a newline, and the >> tells the shell to append that newline to the file, creating if it doesn't already exist.

In order to properly answer the question, though, I'd need to know what you would want to happen if the file already does exist. If you wanted to replace its current contents with the newline, for example, you would use

echo > file.txt

EDIT: and in response to Justin's comment, if you want to add the newline only if the file didn't already exist, you can do

test -e file.txt || echo > file.txt

At least that works in Bash, I'm not sure if it also does in other shells.

How to extract text from a PDF file?

Look at this code:

import PyPDF2
pdf_file = open('sample.pdf', 'rb')
read_pdf = PyPDF2.PdfFileReader(pdf_file)
number_of_pages = read_pdf.getNumPages()
page = read_pdf.getPage(0)
page_content = page.extractText()
print page_content.encode('utf-8')

The output is:

!"#$%#$%&%$&'()*%+,-%./01'*23%4
5'%1$#26%3/%7/))/8%&)/26%8#3"%3"*%313/9#&)
%

Using the same code to read a pdf from 201308FCR.pdf .The output is normal.

Its documentation explains why:

def extractText(self):
    """
    Locate all text drawing commands, in the order they are provided in the
    content stream, and extract the text.  This works well for some PDF
    files, but poorly for others, depending on the generator used.  This will
    be refined in the future.  Do not rely on the order of text coming out of
    this function, as it will change if this function is made more
    sophisticated.
    :return: a unicode string object.
    """

percentage of two int?

Two options:

Do the division after the multiplication:

int n = 25;
int v = 100;
int percent = n * 100 / v;

Convert an int to a float before dividing

int n = 25;
int v = 100;
float percent = n * 100f / v;
//Or:
//  float percent = (float) n * 100 / v;
//  float percent = n * 100 / (float) v;

Importing .py files in Google Colab

A easy way is

  1. type in from google.colab import files uploaded = files.upload()
  2. copy the code
  3. paste in colab cell

Uninstall Django completely

open the CMD and use this command :

**

pip uninstall django

**

it will easy uninstalled .

What is the App_Data folder used for in Visual Studio?

App_Data is essentially a storage point for file-based data stores (as opposed to a SQL server database store for example). Some simple sites make use of it for content stored as XML for example, typically where hosting charges for a DB are expensive.

onchange event on input type=range is not triggering in firefox while dragging

Apparently Chrome and Safari are wrong: onchange should only be triggered when the user releases the mouse. To get continuous updates, you should use the oninput event, which will capture live updates in Firefox, Safari and Chrome, both from the mouse and the keyboard.

However, oninput is not supported in IE10, so your best bet is to combine the two event handlers, like this:

<span id="valBox"></span>
<input type="range" min="5" max="10" step="1" 
   oninput="showVal(this.value)" onchange="showVal(this.value)">

Check out this Bugzilla thread for more information.

Should I call Close() or Dispose() for stream objects?

A quick jump into Reflector.NET shows that the Close() method on StreamWriter is:

public override void Close()
{
    this.Dispose(true);
    GC.SuppressFinalize(this);
}

And StreamReader is:

public override void Close()
{
    this.Dispose(true);
}

The Dispose(bool disposing) override in StreamReader is:

protected override void Dispose(bool disposing)
{
    try
    {
        if ((this.Closable && disposing) && (this.stream != null))
        {
            this.stream.Close();
        }
    }
    finally
    {
        if (this.Closable && (this.stream != null))
        {
            this.stream = null;
            /* deleted for brevity */
            base.Dispose(disposing);
        }
    }
}

The StreamWriter method is similar.

So, reading the code it is clear that that you can call Close() & Dispose() on streams as often as you like and in any order. It won't change the behaviour in any way.

So it comes down to whether or not it is more readable to use Dispose(), Close() and/or using ( ... ) { ... }.

My personal preference is that using ( ... ) { ... } should always be used when possible as it helps you to "not run with scissors".

But, while this helps correctness, it does reduce readability. In C# we already have plethora of closing curly braces so how do we know which one actually performs the close on the stream?

So I think it is best to do this:

using (var stream = ...)
{
    /* code */

    stream.Close();
}

It doesn't affect the behaviour of the code, but it does aid readability.

How to print a query string with parameter values when using Hibernate

if you are using hibernate 3.2.xx use

log4j.logger.org.hibernate.SQL=trace

instead of

log4j.logger.org.hibernate.SQL=debug 

Python: Ignore 'Incorrect padding' error when base64 decoding

There are two ways to correct the input data described here, or, more specifically and in line with the OP, to make Python module base64's b64decode method able to process the input data to something without raising an un-caught exception:

  1. Append == to the end of the input data and call base64.b64decode(...)
  2. If that raises an exception, then

    i. Catch it via try/except,

    ii. (R?)Strip any = characters from the input data (N.B. this may not be necessary),

    iii. Append A== to the input data (A== through P== will work),

    iv. Call base64.b64decode(...) with those A==-appended input data

The result from Item 1. or Item 2. above will yield the desired result.

Caveats

This does not guarantee the decoded result will be what was originally encoded, but it will (sometimes?) give the OP enough to work with:

Even with corruption I want to get back to the binary because I can still get some useful info from the ASN.1 stream").

See What we know and Assumptions below.

TL;DR

From some quick tests of base64.b64decode(...)

  1. it appears that it ignores non-[A-Za-z0-9+/] characters; that includes ignoring =s unless they are the last character(s) in a parsed group of four, in which case the =s terminate the decoding (a=b=c=d= gives the same result as abc=, and a==b==c== gives the same result as ab==).

  2. It also appears that all characters appended are ignored after the point where base64.b64decode(...) terminates decoding e.g. from an = as the fourth in a group.

As noted in several comments above, there are either zero, or one, or two, =s of padding required at the end of input data for when the [number of parsed characters to that point modulo 4] value is 0, or 3, or 2, respectively. So, from items 3. and 4. above, appending two or more =s to the input data will correct any [Incorrect padding] problems in those cases.

HOWEVER, decoding cannot handle the case where the [total number of parsed characters modulo 4] is 1, because it takes a least two encoded characters to represent the first decoded byte in a group of three decoded bytes. In uncorrupted encoded input data, this [N modulo 4]=1 case never happens, but as the OP stated that characters may be missing, it could happen here. That is why simply appending =s will not always work, and why appending A== will work when appending == does not. N.B. Using [A] is all but arbitrary: it adds only cleared (zero) bits to the decoded, which may or not be correct, but then the object here is not correctness but completion by base64.b64decode(...) sans exceptions.

What we know from the OP and especially subsequent comments is

  • It is suspected that there are missing data (characters) in the Base64-encoded input data
  • The Base64 encoding uses the standard 64 place-values plus padding: A-Z; a-z; 0-9; +; /; = is padding. This is confirmed, or at least suggested, by the fact that openssl enc ... works.

Assumptions

  • The input data contain only 7-bit ASCII data
  • The only kind of corruption is missing encoded input data
  • The OP does not care about decoded output data at any point after that corresponding to any missing encoded input data

Github

Here is a wrapper to implement this solution:

https://github.com/drbitboy/missing_b64

How to use Simple Ajax Beginform in Asp.net MVC 4?

All This Work :)

Model

  public partial class ClientMessage
    {
        public int IdCon { get; set; } 
        public string Name { get; set; }
        public string Email { get; set; }  
    }

Controller

   public class TestAjaxBeginFormController : Controller{  

 projectNameEntities db = new projectNameEntities();

        public ActionResult Index(){  
            return View();
        }

        [HttpPost] 
        public ActionResult GetClientMessages(ClientMessage Vm) {
            var model = db.ClientMessages.Where(x => x.Name.Contains(Vm.Name));
            return PartialView("_PartialView", model);
        } 
}

View index.cshtml

@model  projectName.Models.ClientMessage 
@{ 
    Layout = null;
}

<script src="~/Scripts/jquery-1.9.1.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script>
    //\\\\\\\ JS  retrun message SucccessPost or FailPost
    function SuccessMessage() {
        alert("Succcess Post");
    }
    function FailMessage() {
        alert("Fail Post");
    } 
</script>

<h1>Page Index</h1> 

@using (Ajax.BeginForm("GetClientMessages", "TestAjaxBeginForm", null , new AjaxOptions
{
    HttpMethod = "POST",
    OnSuccess = "SuccessMessage",
    OnFailure = "FailMessage" ,
    UpdateTargetId = "resultTarget"  
}, new { id = "MyNewNameId" })) // set new Id name for  Form
{
    @Html.AntiForgeryToken()

    @Html.EditorFor(x => x.Name) 
     <input type="submit" value="Search" /> 

}


<div id="resultTarget">  </div>

View _PartialView.cshtml

@model  IEnumerable<projectName.Models.ClientMessage >
<table> 

@foreach (var item in Model) { 

    <tr> 
        <td>@Html.DisplayFor(modelItem => item.IdCon)</td>
        <td>@Html.DisplayFor(modelItem => item.Name)</td>
        <td>@Html.DisplayFor(modelItem => item.Email)</td>
    </tr>

}

</table>

jQuery UI Dialog window loaded within AJAX style jQuery UI Tabs

Neither of the first two answers worked for me with multiple elements that can open dialogs that point to different pages.

This feels like the cleanest solution, only creates the dialog object once on load and then uses the events to open/close/display appropriately:

$(function () {
      var ajaxDialog = $('<div id="ajax-dialog" style="display:hidden"></div>').appendTo('body');
      ajaxDialog.dialog({autoOpen: false});
      $('a.ajax-dialog-opener').live('click', function() {
          // load remote content
          ajaxDialog.load(this.href);
          ajaxDialog.dialog("open");
          //prevent the browser from following the link
          return false;
      });
}); 

Notepad++ incrementally replace


Solutions suggested above will work only if data is aligned..
See solution in the link using PythonScript Notepad++ plugin, It Works great!

stackoverflow Find/Replace but Increment Value

Troubleshooting BadImageFormatException

For .NET Core, there is a Visual Studio 2017 bug that can cause the project properties Build page to show the incorrect platform target. Once you discover that the problem is, the workarounds are pretty easy. You can change the target to some other value and then change it back.

Alternatively, you can add a runtime identifier to the .csproj. If you need your .exe to run as x86 so that it can load a x86 native DLL, add this element within a PropertyGroup:

<RuntimeIdentifier>win-x86</RuntimeIdentifier>

A good place to put this is right after the TargetFramework or TargetFrameworks element.

How to iterate over the files of a certain directory, in Java?

If you have the directory name in myDirectoryPath,

import java.io.File;
...
  File dir = new File(myDirectoryPath);
  File[] directoryListing = dir.listFiles();
  if (directoryListing != null) {
    for (File child : directoryListing) {
      // Do something with child
    }
  } else {
    // Handle the case where dir is not really a directory.
    // Checking dir.isDirectory() above would not be sufficient
    // to avoid race conditions with another process that deletes
    // directories.
  }

Proper way to declare custom exceptions in modern Python?

"Proper way to declare custom exceptions in modern Python?"

This is fine, unless your exception is really a type of a more specific exception:

class MyException(Exception):
    pass

Or better (maybe perfect), instead of pass give a docstring:

class MyException(Exception):
    """Raise for my specific kind of exception"""

Subclassing Exception Subclasses

From the docs

Exception

All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from this class.

That means that if your exception is a type of a more specific exception, subclass that exception instead of the generic Exception (and the result will be that you still derive from Exception as the docs recommend). Also, you can at least provide a docstring (and not be forced to use the pass keyword):

class MyAppValueError(ValueError):
    '''Raise when my specific value is wrong'''

Set attributes you create yourself with a custom __init__. Avoid passing a dict as a positional argument, future users of your code will thank you. If you use the deprecated message attribute, assigning it yourself will avoid a DeprecationWarning:

class MyAppValueError(ValueError):
    '''Raise when a specific subset of values in context of app is wrong'''
    def __init__(self, message, foo, *args):
        self.message = message # without this you may get DeprecationWarning
        # Special attribute you desire with your Error, 
        # perhaps the value that caused the error?:
        self.foo = foo         
        # allow users initialize misc. arguments as any other builtin Error
        super(MyAppValueError, self).__init__(message, foo, *args) 

There's really no need to write your own __str__ or __repr__. The builtin ones are very nice, and your cooperative inheritance ensures that you use it.

Critique of the top answer

Maybe I missed the question, but why not:

class MyException(Exception):
    pass

Again, the problem with the above is that in order to catch it, you'll either have to name it specifically (importing it if created elsewhere) or catch Exception, (but you're probably not prepared to handle all types of Exceptions, and you should only catch exceptions you are prepared to handle). Similar criticism to the below, but additionally that's not the way to initialize via super, and you'll get a DeprecationWarning if you access the message attribute:

Edit: to override something (or pass extra args), do this:

class ValidationError(Exception):
    def __init__(self, message, errors):

        # Call the base class constructor with the parameters it needs
        super(ValidationError, self).__init__(message)

        # Now for your custom code...
        self.errors = errors

That way you could pass dict of error messages to the second param, and get to it later with e.errors

It also requires exactly two arguments to be passed in (aside from the self.) No more, no less. That's an interesting constraint that future users may not appreciate.

To be direct - it violates Liskov substitutability.

I'll demonstrate both errors:

>>> ValidationError('foo', 'bar', 'baz').message

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    ValidationError('foo', 'bar', 'baz').message
TypeError: __init__() takes exactly 3 arguments (4 given)

>>> ValidationError('foo', 'bar').message
__main__:1: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
'foo'

Compared to:

>>> MyAppValueError('foo', 'FOO', 'bar').message
'foo'

Can't connect to MySQL server on 'localhost' (10061) after Installation

In Windows 7

  1. press Windows+R it opens Run
  2. Enter services.msc
  3. Find out mysql right click and start
  4. if mysql was not found
    1. Run cmd as administrator
    2. goto C:\Program Files (x86)\MySQL\MySQL Server 5.6\bin directory(to go back use cd..) and type mysqld.exe --install
  5. follow step 3

That's all

How can I convert a string to an int in Python?

Perhaps the following, then your calculator can use arbitrary number base (e.g. hex, binary, base 7! etc): (untested)

def convert(str):
    try:
        base = 10  # default
        if ':' in str:
            sstr = str.split(':')
            base, str = int(sstr[0]), sstr[1]
        val = int(str, base)
    except ValueError:
        val = None

    return val

val = convert(raw_input("Enter value:"))
# 10     : Decimal
# 16:a   : Hex, 10
# 2:1010 : Binary, 10

How to get Wikipedia content using Wikipedia's API?

I do it this way:

https://en.wikipedia.org/w/api.php?action=opensearch&search=bee&limit=1&format=json

The response you get is an array with the data, easy to parse:

[
  "bee",
  [
    "Bee"
  ],
  [
    "Bees are flying insects closely related to wasps and ants, known for their role in pollination and, in the case of the best-known bee species, the European honey bee, for producing honey and beeswax."
  ],
  [
    "https://en.wikipedia.org/wiki/Bee"
  ]
]

To get just the first paragraph limit=1 is what you need.

Setting up a git remote origin

Using SSH

git remote add origin ssh://login@IP/path/to/repository

Using HTTP

git remote add origin http://IP/path/to/repository

However having a simple git pull as a deployment process is usually a bad idea and should be avoided in favor of a real deployment script.

AngularJS - get element attributes values

If you are using Angular2+ following code will help

You can use following syntax to get attribute value from html element

//to retrieve html element

const element = fixture.debugElement.nativeElement.querySelector('name of element'); // example a, h1, p

//get attribute value from that element

  const attributeValue = element.attributeName // like textContent/href

Set transparent background of an imageview on Android

In Android Studio it is very simple to adjust color and opacity using a built-in tool:

Android Adjust Color Opacity

can we use xpath with BeautifulSoup?

Nope, BeautifulSoup, by itself, does not support XPath expressions.

An alternative library, lxml, does support XPath 1.0. It has a BeautifulSoup compatible mode where it'll try and parse broken HTML the way Soup does. However, the default lxml HTML parser does just as good a job of parsing broken HTML, and I believe is faster.

Once you've parsed your document into an lxml tree, you can use the .xpath() method to search for elements.

try:
    # Python 2
    from urllib2 import urlopen
except ImportError:
    from urllib.request import urlopen
from lxml import etree

url =  "http://www.example.com/servlet/av/ResultTemplate=AVResult.html"
response = urlopen(url)
htmlparser = etree.HTMLParser()
tree = etree.parse(response, htmlparser)
tree.xpath(xpathselector)

There is also a dedicated lxml.html() module with additional functionality.

Note that in the above example I passed the response object directly to lxml, as having the parser read directly from the stream is more efficient than reading the response into a large string first. To do the same with the requests library, you want to set stream=True and pass in the response.raw object after enabling transparent transport decompression:

import lxml.html
import requests

url =  "http://www.example.com/servlet/av/ResultTemplate=AVResult.html"
response = requests.get(url, stream=True)
response.raw.decode_content = True
tree = lxml.html.parse(response.raw)

Of possible interest to you is the CSS Selector support; the CSSSelector class translates CSS statements into XPath expressions, making your search for td.empformbody that much easier:

from lxml.cssselect import CSSSelector

td_empformbody = CSSSelector('td.empformbody')
for elem in td_empformbody(tree):
    # Do something with these table cells.

Coming full circle: BeautifulSoup itself does have very complete CSS selector support:

for cell in soup.select('table#foobar td.empformbody'):
    # Do something with these table cells.

.NET 4.0 has a new GAC, why?

I also wanted to know why 2 GAC and found the following explanation by Mark Miller in the comments section of .NET 4.0 has 2 Global Assembly Cache (GAC):

Mark Miller said... June 28, 2010 12:13 PM

Thanks for the post. "Interference issues" was intentionally vague. At the time of writing, the issues were still being investigated, but it was clear there were several broken scenarios.

For instance, some applications use Assemby.LoadWithPartialName to load the highest version of an assembly. If the highest version was compiled with v4, then a v2 (3.0 or 3.5) app could not load it, and the app would crash, even if there were a version that would have worked. Originally, we partitioned the GAC under it's original location, but that caused some problems with windows upgrade scenarios. Both of these involved code that had already shipped, so we moved our (version-partitioned GAC to another place.

This shouldn't have any impact to most applications, and doesn't add any maintenance burden. Both locations should only be accessed or modified using the native GAC APIs, which deal with the partitioning as expected. The places where this does surface are through APIs that expose the paths of the GAC such as GetCachePath, or examining the path of mscorlib loaded into managed code.

It's worth noting that we modified GAC locations when we released v2 as well when we introduced architecture as part of the assembly identity. Those added GAC_MSIL, GAC_32, and GAC_64, although all still under %windir%\assembly. Unfortunately, that wasn't an option for this release.

Hope it helps future readers.

How to check Oracle database for long running queries

select sq.PARSING_SCHEMA_NAME, sq.LAST_LOAD_TIME, sq.ELAPSED_TIME, sq.ROWS_PROCESSED, ltrim(sq.sql_text), sq.SQL_FULLTEXT
  from v$sql sq, v$session se
 order by sq.ELAPSED_TIME desc, sq.LAST_LOAD_TIME desc;

Meaning of "487 Request Terminated"

It's the response code a SIP User Agent Server (UAS) will send to the client after the client sends a CANCEL request for the original unanswered INVITE request (yet to receive a final response).

Here is a nice CANCEL SIP Call Flow illustration.

Checking if element exists with Python Selenium

A) Yes. The easiest way to check if an element exists is to simply call find_element inside a try/catch.

B) Yes, I always try to identify elements without using their text for 2 reasons:

  1. the text is more likely to change and;
  2. if it is important to you, you won't be able to run your tests against localized builds.

solution either:

  1. You can use xpath to find a parent or ancestor element that has an ID or some other unique identifier and then find it's child/descendant that matches or;
  2. you could request an ID or name or some other unique identifier for the link itself.

For the follow up questions, using try/catch is how you can tell if an element exists or not and good examples of waits can be found here: http://seleniumhq.org/docs/04_webdriver_advanced.html

How to easily get network path to the file you are working on?

Right click on the ribbon and choose Customize the ribbon. From the Choose commands from: drop down, select Commands not in the ribbon.

That is where I found the Document location command.

SELECT inside a COUNT

You can move the count() inside your sub-select:

SELECT a AS current_a, COUNT(*) AS b,
   ( SELECT COUNT(*) FROM t WHERE a = current_a AND c = 'const' ) as d,
   from t group by a order by b desc

Smooth scrolling with just pure css

You need to use the target selector.

Here is a fiddle with another example: http://jsfiddle.net/YYPKM/3/

List files in local git repo?

Try this command:

git ls-files 

This lists all of the files in the repository, including those that are only staged but not yet committed.

http://www.kernel.org/pub/software/scm/git/docs/git-ls-files.html

SecurityException: Permission denied (missing INTERNET permission?)

NOTE: I wrote this answer in Jun 2013, so it's bit dated nowadays. Many things changed in Android platform since version 6 (Marshmallow, released late 2015), making the whole problem more/less obsolete. However I believe this post can still be worth reading as general problem analysis approach example.


Exception you are getting (SecurityException: Permission denied (missing INTERNET permission?)), clearly indicates that you are not allowed to do networking. That's pretty indisputable fact. But how can this happen? Usually it's either due to missing <uses-permission android:name="android.permission.INTERNET" /> entry in your AndroidManifest.xml file or, as internet permission is granted at installation not at run time, by long standing, missed bug in Android framework that causes your app to be successfully installed, but without expected permission grant.

My Manifest is correct, so how can this happen?

Theoretically, presence of uses-permission in Manifest perfectly fulfills the requirement and from developer standpoint is all that's needed to be done to be able to do networking. Moreover, since permissions are shown to the user during installation, the fact your app ended installed on user's device means s/he granted what you asked for (otherwise installation is cancelled), so assumption that if your code is executed then all requested permissions are granted is valid. And once granted, user cannot revoke the permission other way than uninstalling the app completely as standard Android framework (from AOSP) offers no such feature at the moment.

But things are getting more tricky if you also do not mind your app running on rooted devices too. There're tools available in Google Play your users can install to control permission granted to installed apps at run-time - for example: Permissions Denied and others. This can also be done with CyanogenMod, vendor brand (i.e. LG's) or other custom ROM, featuring various type of "privacy managers" or similar tools.

So if app is blocked either way, it's basically blocked intentionally by the user and if so, it is really more user problem in this case (or s/he do not understand what certain options/tools really do and what would be the consequences) than yours, because standard SDK (and most apps are written with that SDK in mind) simply does not behave that way. So I strongly doubt this problem occurs on "standard", non-rooted device with stock (or vendor like Samsung, HTC, Sony etc) ROM.

I do not want to crash...

Properly implemented permission management and/org blocking must deal with the fact that most apps may not be ready for the situation where access to certain features is both granted and not accessible at the same time, as this is kind of contradiction where app uses manifest to request access at install time. Access control done right should must make all things work as before, and still limit usability using techniques in scope of expected behavior of the feature. For example, when certain permission is granted (i.e. GPS, Internet access) such feature can be made available from the app/user perspective (i.e. you can turn GPS on. or try to connect), the altered implementation can provide no real data - i.e. GPS can always return no coordinates, like when you are indoor or have no satellite "fix". Internet access can granted as before, but you can make no successful connection as there's no data coverage or routing. Such scenarios should be expected in normal usage as well, therefore it should be handled by the apps already. As this simply can happen during normal every day usage, any crash in such situation should be most likely be related to application bugs.

We lack too much information about the environment on which this problem occurs to diagnose problem w/o guessing, but as kind of solution, you may consider using setDefaultUncaughtExceptionHandler() to catch such unexpected exceptions in future and i.e. simply show user detailed information what permission your app needs instead of just crashing. Please note that using this will most likely conflict with tools like Crittercism, ACRA and others, so be careful if you use any of these.

Notes

Please be aware that android.permission.INTERNET is not the only networking related permission you may need to declare in manifest in attempt to successfully do networking. Having INTERNET permission granted simply allows applications to open network sockets (which is basically fundamental requirement to do any network data transfer). But in case your network stack/library would like to get information about networks as well, then you will also need android.permission.ACCESS_NETWORK_STATE in your Manifest (which is i.e. required by HttpUrlConnection client (see tutorial).


Addendum (2015-07-16)

Please note that Android 6 (aka Marshmallow) introduced completely new permission management mechanism called Runtime Permissions. It gives user more control on what permission are granted (also allows selective grant) or lets one revoke already granted permissions w/o need to app removal:

This [...] introduces a new permissions model, where users can now directly manage app permissions at runtime. This model gives users improved visibility and control over permissions, while streamlining the installation and auto-update processes for app developers. Users can grant or revoke permissions individually for installed apps.

However, the changes do not affect INTERNET or ACCESS_NETWORK_STATE permissions, which are considered "Normal" permissions. The user does not need to explicitly grant these permission.

See behavior changes description page for details and make sure your app will behave correctly on newer systems too. It's is especially important when your project set targetSdk to at least 23 as then you must support new permissions model (detailed documentation). If you are not ready, ensure you keep targetSdk to at most 22 as this ensures even new Android will use old permission system when your app is installed.

OpenCV with Network Cameras

I enclosed C++ code for grabbing frames. It requires OpenCV version 2.0 or higher. The code uses cv::mat structure which is preferred to old IplImage structure.

#include "cv.h"
#include "highgui.h"
#include <iostream>

int main(int, char**) {
    cv::VideoCapture vcap;
    cv::Mat image;

    const std::string videoStreamAddress = "rtsp://cam_address:554/live.sdp"; 
    /* it may be an address of an mjpeg stream, 
    e.g. "http://user:pass@cam_address:8081/cgi/mjpg/mjpg.cgi?.mjpg" */

    //open the video stream and make sure it's opened
    if(!vcap.open(videoStreamAddress)) {
        std::cout << "Error opening video stream or file" << std::endl;
        return -1;
    }

    //Create output window for displaying frames. 
    //It's important to create this window outside of the `for` loop
    //Otherwise this window will be created automatically each time you call
    //`imshow(...)`, which is very inefficient. 
    cv::namedWindow("Output Window");

    for(;;) {
        if(!vcap.read(image)) {
            std::cout << "No frame" << std::endl;
            cv::waitKey();
        }
        cv::imshow("Output Window", image);
        if(cv::waitKey(1) >= 0) break;
    }   
}

Update You can grab frames from H.264 RTSP streams. Look up your camera API for details to get the URL command. For example, for an Axis network camera the URL address might be:

// H.264 stream RTSP address, where 10.10.10.10 is an IP address 
// and 554 is the port number
rtsp://10.10.10.10:554/axis-media/media.amp

// if the camera is password protected
rtsp://username:[email protected]:554/axis-media/media.amp

Resizable table columns with jQuery

Here's a short complete html example. See demo http://jsfiddle.net/CU585/

<!DOCTYPE html><html><head><title>resizable columns</title>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/themes/smoothness/jquery-ui.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/jquery-ui.min.js"></script>
<style>
th {border: 1px solid black;}
table{border-collapse: collapse;}
.ui-icon, .ui-widget-content .ui-icon {background-image: none;}
</style>
<body>
<table>
<tr><th>head 1</th><th>head 2</th></tr><tr><td>a1</td><td>b1</td></tr></table><script>
$( "th" ).resizable();
</script></body></html>

Android background music service

way too late for the party here but i will still add my $0.02, Google has released a free sample called universal music player with which you can learn to stream music across all android platforms(auto, watch,mobile,tv..) it uses service to play music in the background, do check it out very helpful. here's the link to the project
https://github.com/googlesamples/android-UniversalMusicPlayer

How can I solve equations in Python?

There are two ways to approach this problem: numerically and symbolically.

To solve it numerically, you have to first encode it as a "runnable" function - stick a value in, get a value out. For example,

def my_function(x):
    return 2*x + 6

It is quite possible to parse a string to automatically create such a function; say you parse 2x + 6 into a list, [6, 2] (where the list index corresponds to the power of x - so 6*x^0 + 2*x^1). Then:

def makePoly(arr):
    def fn(x):
        return sum(c*x**p for p,c in enumerate(arr))
    return fn

my_func = makePoly([6, 2])
my_func(3)    # returns 12

You then need another function which repeatedly plugs an x-value into your function, looks at the difference between the result and what it wants to find, and tweaks its x-value to (hopefully) minimize the difference.

def dx(fn, x, delta=0.001):
    return (fn(x+delta) - fn(x))/delta

def solve(fn, value, x=0.5, maxtries=1000, maxerr=0.00001):
    for tries in xrange(maxtries):
        err = fn(x) - value
        if abs(err) < maxerr:
            return x
        slope = dx(fn, x)
        x -= err/slope
    raise ValueError('no solution found')

There are lots of potential problems here - finding a good starting x-value, assuming that the function actually has a solution (ie there are no real-valued answers to x^2 + 2 = 0), hitting the limits of computational accuracy, etc. But in this case, the error minimization function is suitable and we get a good result:

solve(my_func, 16)    # returns (x =) 5.000000000000496

Note that this solution is not absolutely, exactly correct. If you need it to be perfect, or if you want to try solving families of equations analytically, you have to turn to a more complicated beast: a symbolic solver.

A symbolic solver, like Mathematica or Maple, is an expert system with a lot of built-in rules ("knowledge") about algebra, calculus, etc; it "knows" that the derivative of sin is cos, that the derivative of kx^p is kpx^(p-1), and so on. When you give it an equation, it tries to find a path, a set of rule-applications, from where it is (the equation) to where you want to be (the simplest possible form of the equation, which is hopefully the solution).

Your example equation is quite simple; a symbolic solution might look like:

=> LHS([6, 2]) RHS([16])

# rule: pull all coefficients into LHS
LHS, RHS = [lh-rh for lh,rh in izip_longest(LHS, RHS, 0)], [0]

=> LHS([-10,2]) RHS([0])

# rule: solve first-degree poly
if RHS==[0] and len(LHS)==2:
    LHS, RHS = [0,1], [-LHS[0]/LHS[1]]

=> LHS([0,1]) RHS([5])

and there is your solution: x = 5.

I hope this gives the flavor of the idea; the details of implementation (finding a good, complete set of rules and deciding when each rule should be applied) can easily consume many man-years of effort.

Passing by reference in C

Your example works because you are passing the address of your variable to a function that manipulates its value with the dereference operator.

While C does not support reference data types, you can still simulate passing-by-reference by explicitly passing pointer values, as in your example.

The C++ reference data type is less powerful but considered safer than the pointer type inherited from C. This would be your example, adapted to use C++ references:

void f(int &j) {
  j++;
}

int main() {
  int i = 20;
  f(i);
  printf("i = %d\n", i);

  return 0;
}

Dark color scheme for Eclipse

Checkout this color scheme I created for Eclipse PDT. It is based on the Vim Zenburn color scheme developed by slinky

JavaScript seconds to time string with format hh:mm:ss

You can use the following function to convert time (in seconds) to HH:MM:SS format :

var convertTime = function (input, separator) {
    var pad = function(input) {return input < 10 ? "0" + input : input;};
    return [
        pad(Math.floor(input / 3600)),
        pad(Math.floor(input % 3600 / 60)),
        pad(Math.floor(input % 60)),
    ].join(typeof separator !== 'undefined' ?  separator : ':' );
}

Without passing a separator, it uses : as the (default) separator :

time = convertTime(13551.9941351); // --> OUTPUT = 03:45:51

If you want to use - as a separator, just pass it as the second parameter:

time = convertTime(1126.5135155, '-'); // --> OUTPUT = 00-18-46

Demo

_x000D_
_x000D_
var convertTime = function (input, separator) {
    var pad = function(input) {return input < 10 ? "0" + input : input;};
    return [
        pad(Math.floor(input / 3600)),
        pad(Math.floor(input % 3600 / 60)),
        pad(Math.floor(input % 60)),
    ].join(typeof separator !== 'undefined' ?  separator : ':' );
}

document.body.innerHTML = '<pre>' + JSON.stringify({
    5.3515555 : convertTime(5.3515555),
    126.2344452 : convertTime(126.2344452, '-'),
    1156.1535548 : convertTime(1156.1535548, '.'),
    9178.1351559 : convertTime(9178.1351559, ':'),
    13555.3515135 : convertTime(13555.3515135, ',')
}, null, '\t') +  '</pre>';
_x000D_
_x000D_
_x000D_

See also this Fiddle.

Timeout jQuery effects

Update: As of jQuery 1.4 you can use the .delay( n ) method. http://api.jquery.com/delay/

$('.notice').fadeIn().delay(2000).fadeOut('slow'); 

Note: $.show() and $.hide() by default are not queued, so if you want to use $.delay() with them, you need to configure them that way:

$('.notice')
    .show({duration: 0, queue: true})
    .delay(2000)
    .hide({duration: 0, queue: true});

You could possibly use the Queue syntax, this might work:

jQuery(function($){ 

var e = $('.notice'); 
e.fadeIn(); 
e.queue(function(){ 
  setTimeout(function(){ 
    e.dequeue(); 
  }, 2000 ); 
}); 
e.fadeOut('fast'); 

}); 

or you could be really ingenious and make a jQuery function to do it.

(function($){ 

  jQuery.fn.idle = function(time)
  { 
      var o = $(this); 
      o.queue(function()
      { 
         setTimeout(function()
         { 
            o.dequeue(); 
         }, time);
      });
  };
})(jQuery);

which would ( in theory , working on memory here ) permit you do to this:

$('.notice').fadeIn().idle(2000).fadeOut('slow'); 

Can gcc output C code after preprocessing?

Run:

gcc -E <file>.c

or

g++ -E <file>.cpp

Typescript - multidimensional array initialization

You can do the following (which I find trivial, but its actually correct). For anyone trying to find how to initialize a two-dimensional array in TypeScript (like myself).

Let's assume that you want to initialize a two-dimensional array, of any type. You can do the following

const myArray: any[][] = [];

And later, when you want to populate it, you can do the following:

myArray.push([<your value goes here>]);

A short example of the above can be the following:

const myArray: string[][] = [];
myArray.push(["value1", "value2"]);

"Unable to get the VLookup property of the WorksheetFunction Class" error

Try below code

I will recommend to use error handler while using vlookup because error might occur when the lookup_value is not found.

Private Sub ComboBox1_Change()


    On Error Resume Next
    Ret = Application.WorksheetFunction.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)
    On Error GoTo 0

    If Ret <> "" Then MsgBox Ret


End Sub

OR

 On Error Resume Next

    Result = Application.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)

    If Result = "Error 2042" Then
        'nothing found
    ElseIf cell <> Result Then
        MsgBox cell.Value
    End If

    On Error GoTo 0

Count frequency of words in a list and sort by frequency

One way would be to make a list of lists, with each sub-list in the new list containing a word and a count:

list1 = []    #this is your original list of words
list2 = []    #this is a new list

for word in list1:
    if word in list2:
        list2.index(word)[1] += 1
    else:
        list2.append([word,0])

Or, more efficiently:

for word in list1:
    try:
        list2.index(word)[1] += 1
    except:
        list2.append([word,0])

This would be less efficient than using a dictionary, but it uses more basic concepts.

What does "collect2: error: ld returned 1 exit status" mean?

The ld returned 1 exit status error is the consequence of previous errors. In your example there is an earlier error - undefined reference to 'clrscr' - and this is the real one. The exit status error just signals that the linking step in the build process encountered some errors. Normally exit status 0 means success, and exit status > 0 means errors.

When you build your program, multiple tools may be run as separate steps to create the final executable. In your case one of those tools is ld, which first reports the error it found (clrscr reference missing), and then it returns the exit status. Since the exit status is > 0, it means an error and is reported.

In many cases tools return as the exit status the number of errors they encountered. So if ld tool finds two errors, its exit status would be 2.

Removing ul indentation with CSS

This code will remove the indentation and list bullets.

ul {
    padding: 0;
    list-style-type: none;
}

http://jsfiddle.net/qeqtK/2/

Convert RGB values to Integer

To get individual colour values you can use Color like following for pixel(x,y).

import java.awt.Color;
import java.awt.image.BufferedImage;

Color c = new Color(buffOriginalImage.getRGB(x,y));
int red = c.getRed();
int green = c.getGreen();
int blue = c.getBlue();

The above will give you the integer values of Red, Green and Blue in range of 0 to 255.

To set the values from RGB you can do so by:

Color myColour = new Color(red, green, blue);
int rgb = myColour.getRGB();

//Change the pixel at (x,y) ti rgb value
image.setRGB(x, y, rgb);

Please be advised that the above changes the value of a single pixel. So if you need to change the value entire image you may need to iterate over the image using two for loops.

When does Git refresh the list of remote branches?

The OP did not ask for cleanup for all remotes, rather for all branches of default remote.

So git fetch --prune is what should be used.

Setting git config remote.origin.prune true makes --prune automatic. In that case just git fetch will also prune stale remote branches from the local copy. See also Automatic prune with Git fetch or pull.

Note that this does not clean local branches that are no longer tracking a remote branch. See How to prune local tracking branches that do not exist on remote anymore for that.

"Cannot update paths and switch to branch at the same time"

If you have a typo in your branchname you'll get this same error.

Python script to convert from UTF-8 to ASCII

UTF-8 is a superset of ASCII. Either your UTF-8 file is ASCII, or it can't be converted without loss.

Open button in new window?

You can acheive this using window.open() method, passing _blank as one of the parameter. You can refer the below links which has more information on this.

http://www.w3schools.com/jsref/met_win_open.asp

http://msdn.microsoft.com/en-us/library/ms536651(v=vs.85).aspx

Hope this will help you.

python replace single backslash with double backslash

Maybe a syntax error in your case, you may change the line to:

directory = str(r"C:\Users\Josh\Desktop\20130216").replace('\\','\\\\')

which give you the right following output:

C:\\Users\\Josh\\Desktop\\20130216

What is an idiomatic way of representing enums in Go?

As of Go 1.4, the go generate tool has been introduced together with the stringer command that makes your enum easily debuggable and printable.

How to "EXPIRE" the "HSET" child key in redis?

You can use Sorted Set in redis to get a TTL container with timestamp as score. For example, whenever you insert a event string into the set you can set its score to the event time. Thus you can get data of any time window by calling zrangebyscore "your set name" min-time max-time

Moreover, we can do expire by using zremrangebyscore "your set name" min-time max-time to remove old events.

The only drawback here is you have to do housekeeping from an outsider process to maintain the size of the set.

How to make HTML element resizable using pure Javascript?

what about a pure css3 solution?

div {
    resize: both;
    overflow: auto;
} 

MDN Web Docs

W3Schools example

Browser support

Handling InterruptedException in Java

I would say in some cases it's ok to do nothing. Probably not something you should be doing by default, but in case there should be no way for the interrupt to happen, I'm not sure what else to do (probably logging error, but that does not affect program flow).

One case would be in case you have a task (blocking) queue. In case you have a daemon Thread handling these tasks and you do not interrupt the Thread by yourself (to my knowledge the jvm does not interrupt daemon threads on jvm shutdown), I see no way for the interrupt to happen, and therefore it could be just ignored. (I do know that a daemon thread may be killed by the jvm at any time and therefore are unsuitable in some cases).

EDIT: Another case might be guarded blocks, at least based on Oracle's tutorial at: http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html

Using :focus to style outer div?

As per the spec:

The :focus pseudo-class applies while an element has the focus (accepts keyboard events or other forms of text input).

The <div> does not accept input, so it cannot have :focus. Furthermore, CSS does not allow you to set styles on an element based on targeting its descendants. So you can't really do this unless you are willing to use JavaScript.

Elegant Python function to convert CamelCase to snake_case?

Lightely adapted from https://stackoverflow.com/users/267781/matth who use generators.

def uncamelize(s):
    buff, l = '', []
    for ltr in s:
        if ltr.isupper():
            if buff:
                l.append(buff)
                buff = ''
        buff += ltr
    l.append(buff)
    return '_'.join(l).lower()

Importing JSON into an Eclipse project

Download the ZIP file from this URL and extract it to get the Jar. Add the Jar to your build path. To check the available classes in this Jar use this URL.

To Add this Jar to your build path Right click the Project > Build Path > Configure build path> Select Libraries tab > Click Add External Libraries > Select the Jar file Download

I hope this will solve your problem

Eclipse - Unable to install breakpoint due to missing line number attributes

I had the same error message in Eclipse 3.4.1, SUN JVM1.6.0_07 connected to Tomcat 6.0 (running in debug-mode on a different machine, Sun JVM1.6.0_16, the debug connection did work correctly).

Window --> Preferences --> Java --> Compiler --> Classfile Generation: "add line number attributes to generated class file" was checked. I did a clean, recompile. I did uncheck it, recompile, check it, recompile. I made sure the project did use the global settings. Still the same message.

I switched to ant build, using

<javac srcdir="./src/java" destdir="./bin" debug="true">

Still, same message.

I didn't find out what caused this message and why it wouldn't go away. Though it seemed to have something to do with the running Tomcat debug session: when disconnected, recompiling solves the issue. But on connecting the debugger to Tomcat or on setting new breakpoints during a connected debug session, it appeared again.

However, it turned out the message was wrong: I was indeed able to debug and set breakpoints, both before and during debugging (javap -l did show line numbers, too). So just ignore it :)

connect local repo with remote repo

git remote add origin <remote_repo_url>
git push --all origin

If you want to set all of your branches to automatically use this remote repo when you use git pull, add --set-upstream to the push:

git push --all --set-upstream origin

How to export all data from table to an insertable sql format?

Quick and Easy way:

  1. Right click database
  2. Point to tasks In SSMS 2017 you need to ignore step 2 - the generate scripts options is at the top level of the context menu Thanks to Daniel for the comment to update.
  3. Select generate scripts
  4. Click next
  5. Choose tables
  6. Click next
  7. Click advanced
  8. Scroll to Types of data to script - Called types of data to script in SMSS 2014 Thanks to Ellesedil for commenting
  9. Select data only
  10. Click on 'Ok' to close the advanced script options window
  11. Click next and generate your script

I usually in cases like this generate to a new query editor window and then just do any modifications where needed.

Laravel 4: how to run a raw SQL?

Actually, Laravel 4 does have a table rename function in Illuminate/Database/Schema/Builder.php, it's just undocumented at the moment: Schema::rename($from, $to);.

Getting files by creation date in .NET

You can use Linq

var files = Directory.GetFiles(@"C:\", "*").OrderByDescending(d => new FileInfo(d).CreationTime);

What does "int 0x80" mean in assembly code?

As mentioned, it causes control to jump to interrupt vector 0x80. In practice what this means (at least under Linux) is that a system call is invoked; the exact system call and arguments are defined by the contents of the registers. For example, exit() can be invoked by setting %eax to 1 followed by 'int 0x80'.

How do I create a local database inside of Microsoft SQL Server 2014?

As per comments, First you need to install an instance of SQL Server if you don't already have one - https://msdn.microsoft.com/en-us/library/ms143219.aspx

Once this is installed you must connect to this instance (server) and then you can create a database here - https://msdn.microsoft.com/en-US/library/ms186312.aspx

What does "implements" do on a class?

An interface can be thought of as just a list of method definitions (without any body). If a class wants to implement and interface, it is entering into a contract, saying that it will provide an implementation for all of the methods listed in the interface. For more information, see http://download.oracle.com/javase/tutorial/java/concepts/

update to python 3.7 using anaconda

conda create -n py37 -c anaconda anaconda=5.3

seems to be working.

.gitignore is ignored by Git

I just ran into this issue. The content within my .gitignore file continued to appear in the list of untracked files.

I was using this to create the ignore file:

echo "node_modules" > .gitignore

It turns out that the double quotations were causing the issue for me. I deleted the ignore file and then used the command again without quotes, and it worked as expected. I did not need to mess with the file encoding. I'm on a Windows 10 machine using Cmder.

Example:

echo node_modules > .gitignore

Setting up JUnit with IntelliJ IDEA

  1. Create and setup a "tests" folder
    • In the Project sidebar on the left, right-click your project and do New > Directory. Name it "test" or whatever you like.
    • Right-click the folder and choose "Mark Directory As > Test Source Root".
  2. Adding JUnit library
    • Right-click your project and choose "Open Module Settings" or hit F4. (Alternatively, File > Project Structure, Ctrl-Alt-Shift-S is probably the "right" way to do this)
    • Go to the "Libraries" group, click the little green plus (look up), and choose "From Maven...".
    • Search for "junit" -- you're looking for something like "junit:junit:4.11".
    • Check whichever boxes you want (Sources, JavaDocs) then hit OK.
    • Keep hitting OK until you're back to the code.
  3. Write your first unit test

    • Right-click on your test folder, "New > Java Class", call it whatever, e.g. MyFirstTest.
    • Write a JUnit test -- here's mine:

      import org.junit.Assert;
      import org.junit.Test;
      
      public class MyFirstTest {
          @Test
          public void firstTest() {
              Assert.assertTrue(true);
          }
      }
      
  4. Run your tests
    • Right-click on your test folder and choose "Run 'All Tests'". Presto, testo.
    • To run again, you can either hit the green "Play"-style button that appeared in the new section that popped on the bottom of your window, or you can hit the green "Play"-style button in the top bar.

Get filename and path from URI from mediastore

This solution works for every case:

It is too hard in some cases get the path from the URL. Then why do you need the path? To copy the file in other place? You don't need the path.

public void SavePhotoUri (Uri imageuri, String Filename){

    File FilePath = context.getDir(Environment.DIRECTORY_PICTURES,Context.MODE_PRIVATE);
    try {
        Bitmap selectedImage = MediaStore.Images.Media.getBitmap(context.getContentResolver(), imageuri);
        String destinationImagePath = FilePath + "/" + Filename;
        FileOutputStream destination = new FileOutputStream(destinationImagePath);
        selectedImage.compress(Bitmap.CompressFormat.JPEG, 100, destination);
        destination.close();
    }
    catch (Exception e) {
        Log.e("error", e.toString());
    }
}

VB.Net .Clear() or txtbox.Text = "" textbox clear methods

The two methods are 100% equivalent.

I’m not sure why Microsoft felt the need to include this extra Clear method but since it’s there, I recommend using it, as it clearly expresses its purpose.

typedef struct vs struct definitions

The following code creates an anonymous struct with the alias myStruct:

typedef struct{
    int one;
    int two;
} myStruct;

You can't refer it without the alias because you don't specify an identifier for the structure.

Setting the selected attribute on a select list using jQuery

Something along the lines of...

$('select option:nth(1)').attr("selected","selected"); 

Anybody knows any knowledge base open source?

Based on my personal experience with this knowledge base software, I would also like to join 'Julien H.' in suggesting PHPKB from http://www.knowledgebase-script.com

Personally I believe its one of the best. Many features, continously developed, excellent support & the GUI is just simple & great.

Strange PostgreSQL "value too long for type character varying(500)"

Character varying is different than text. Try running

ALTER TABLE product_product ALTER COLUMN code TYPE text;

That will change the column type to text, which is limited to some very large amount of data (you would probably never actually hit it.)

click() event is calling twice in jquery

When I use this method on load page with jquery, I write $('#obj').off('click'); before set the click function, so the bubble not occurs. Works for me.

Angular 2 Cannot find control with unspecified name attribute on formArrays

So, I had this code:

<div class="dropdown-select-wrapper" *ngIf="contentData">
    <button mat-stroked-button [disableRipple]="true" class="mat-button" (click)="openSelect()" [ngClass]="{'only-icon': !contentData?.buttonText?.length}">
      <i *ngIf="contentData.iconClassInfo" class="dropdown-icon {{contentData.iconClassInfo.name}}"></i>
      <span class="button-text" *ngIf="contentData.buttonText">{{contentData.buttonText}}</span>
    </button>
    <mat-select class="small-dropdown-select" [formControl]="theFormControl" #buttonSelect (selectionChange)="onSelect(buttonSelect.selected)" (click)="$event.stopPropagation();">
      <mat-option *ngFor="let option of options" [ngClass]="{'selected-option': buttonSelect.selected?.value === option[contentData.optionsStructure.valName]}" [disabled]="buttonSelect.selected?.value === option[contentData.optionsStructure.valName] && contentData.optionSelectedWillDisable" [value]="option[contentData.optionsStructure.valName]">
        {{option[contentData.optionsStructure.keyName]}}
      </mat-option>
    </mat-select>
  </div>

Here I was using standalone formControl, and I was getting the error we are talking about, which made no sense for me, since I wasn't working with formgroups or formarrays... it only disappeared when I added the *ngIf to the select it self, so is not being used before it actually exists. That's what solved the issue in my case.

<mat-select class="small-dropdown-select" [formControl]="theFormControl" #buttonSelect (selectionChange)="onSelect(buttonSelect.selected)" (click)="$event.stopPropagation();" *ngIf="theFormControl">
          <mat-option *ngFor="let option of options" [ngClass]="{'selected-option': buttonSelect.selected?.value === option[contentData.optionsStructure.valName]}" [disabled]="buttonSelect.selected?.value === option[contentData.optionsStructure.valName] && contentData.optionSelectedWillDisable" [value]="option[contentData.optionsStructure.valName]">
            {{option[contentData.optionsStructure.keyName]}}
          </mat-option>
        </mat-select>

Python read-only property

While I like the class decorator from Oz123, you could also do the following, which uses an explicit class wrapper and __new__ with a class Factory method returning the class within a closure:

class B(object):
    def __new__(cls, val):
        return cls.factory(val)

@classmethod
def factory(cls, val):
    private = {'var': 'test'}

    class InnerB(object):
        def __init__(self):
            self.variable = val
            pass

        @property
        def var(self):
            return private['var']

    return InnerB()

Breaking out of a for loop in Java

How about

for (int k = 0; k < 10; k = k + 2) {
    if (k == 2) {
        break;
    }

    System.out.println(k);
}

The other way is a labelled loop

myloop:  for (int i=0; i < 5; i++) {

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

                if (i * j > 6) {
                  System.out.println("Breaking");
                  break myloop;
                }

                System.out.println(i + " " + j);
              }
          }

For an even better explanation you can check here

How do I format a date in Jinja2?

There are two ways to do it. The direct approach would be to simply call (and print) the strftime() method in your template, for example

{{ car.date_of_manufacture.strftime('%Y-%m-%d') }}

Another, sightly better approach would be to define your own filter, e.g.:

from flask import Flask
import babel

app = Flask(__name__)

@app.template_filter()
def format_datetime(value, format='medium'):
    if format == 'full':
        format="EEEE, d. MMMM y 'at' HH:mm"
    elif format == 'medium':
        format="EE dd.MM.y HH:mm"
    return babel.dates.format_datetime(value, format)

(This filter is based on babel for reasons regarding i18n, but you can use strftime too). The advantage of the filter is, that you can write

{{ car.date_of_manufacture|datetime }}
{{ car.date_of_manufacture|datetime('full') }}

which looks nicer and is more maintainable. Another common filter is also the "timedelta" filter, which evaluates to something like "written 8 minutes ago". You can use babel.dates.format_timedelta for that, and register it as filter similar to the datetime example given here.

How do I get a HttpServletRequest in my spring beans?

this should do it

((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest().getRequestURI();

Printing everything except the first field with awk

If you're open to another Perl solution:

perl -ple 's/^(\S+)\s+(.*)/$2 $1/' file

What is “assert” in JavaScript?

Java has a assert statement, the JVM disables assertion validation by default. They must be explicitly enabled using command line argument -enableassertions (or its shorthand -ea),

while JavaScript supports console.assert(), it's just a logging method and won't interrupt current procedure if assertion failed.

To bring things together and satisfy various needs, here is a tiny js assertion lib.

_x000D_
_x000D_
globalThis.assert = (()=> {
  class AssertionError extends Error {
    constructor(message) {
      super(message);
      this.name = 'AssertionError';
    }
  }
  let config = {
    async: true,
    silent: false
  };
  function assert(condition, message = undefined) {
    if (!condition) {
      if (config.silent) {
        //NOOP
      } else if (config.async) {
        console.assert(condition, message || 'assert');
      } else {
        throw new AssertionError(message || 'assertion failed');
      }
    }
  }
  assert.config = config;
  return assert;
})();


/* global assert */
Object.assign(assert.config, {
  // silent: true, // to disable assertion validation
  async: false, // to validate assertion synchronously (will interrupt if assertion failed, like Java's)
});

let items = [
  {id: 1},
  {id: 2},
  {id: 3}
];
function deleteItem(item) {
  let index = items.findIndex((e)=> e.id === item.id);
  assert(index > -1, `index should be >=0, the item(id=${item.id}) to be deleted doesn't exist, or was already deleted`);
  items.splice(index, 1);
}

console.log('begin');
deleteItem({id: 1});
deleteItem({id: 1});
console.log('end');
_x000D_
_x000D_
_x000D_

filter out multiple criteria using excel vba

I don't have found any solution on Internet, so I have implemented one.

The Autofilter code with criteria is then

iColNumber = 1
Dim aFilterValueArray() As Variant
Call ConstructFilterValueArray(aFilterValueArray, iColNumber, Array("A", "B", "C"))

ActiveSheet.range(sRange).AutoFilter Field:=iColNumber _
    , Criteria1:=aFilterValueArray _
    , Operator:=xlFilterValues

In fact, the ConstructFilterValueArray() method (not function) get all distinct values that it found in a specific column and remove all values present in last argument.

The VBA code of this method is

'************************************************************
'* ConstructFilterValueArray()
'************************************************************

Sub ConstructFilterValueArray(a() As Variant, iCol As Integer, aRemoveArray As Variant)

    Dim aValue As New Collection
    Call GetDistinctColumnValue(aValue, iCol)
    Call RemoveValueList(aValue, aRemoveArray)
    Call CollectionToArray(a, aValue)

End Sub

'************************************************************
'* GetDistinctColumnValue()
'************************************************************

Sub GetDistinctColumnValue(ByRef aValue As Collection, iCol As Integer)

    Dim sValue As String

    iEmptyValueCount = 0
    iLastRow = ActiveSheet.UsedRange.Rows.Count

    Dim oSheet: Set oSheet = Sheets("X")

    Sheets("Data")
        .range(Cells(1, iCol), Cells(iLastRow, iCol)) _
            .AdvancedFilter Action:=xlFilterCopy _
                          , CopyToRange:=oSheet.range("A1") _
                          , Unique:=True

    iRow = 2
    Do While True
        sValue = Trim(oSheet.Cells(iRow, 1))
        If sValue = "" Then
            If iEmptyValueCount > 0 Then
                Exit Do
            End If
            iEmptyValueCount = iEmptyValueCount + 1
        End If

        aValue.Add sValue
        iRow = iRow + 1
    Loop

End Sub

'************************************************************
'* RemoveValueList()
'************************************************************

Sub RemoveValueList(ByRef aValue As Collection, aRemoveArray As Variant)

    For i = LBound(aRemoveArray) To UBound(aRemoveArray)
        sValue = aRemoveArray(i)
        iMax = aValue.Count
        For j = iMax To 0 Step -1
            If aValue(j) = sValue Then
                aValue.Remove (j)
                Exit For
            End If
        Next j
     Next i

End Sub

'************************************************************
'* CollectionToArray()
'************************************************************

Sub CollectionToArray(a() As Variant, c As Collection)

    iSize = c.Count - 1
    ReDim a(iSize)

    For i = 0 To iSize
        a(i) = c.Item(i + 1)
    Next

End Sub

This code can certainly be improved in returning an Array of String but working with Array in VBA is not easy.

CAUTION: this code work only if you define a sheet named X because CopyToRange parameter used in AdvancedFilter() need an Excel Range !

It's a shame that Microfsoft doesn't have implemented this solution in adding simply a new enum as xlNotFilterValues ! ... or xlRegexMatch !

What is the default value for Guid?

To extend answers above, you cannot use Guid default value with Guid.Empty as an optional argument in method, indexer or delegate definition, because it will give you compile time error. Use default(Guid) or new Guid() instead.

When to use Comparable and Comparator

Comparable:
Whenever we want to store only homogeneous elements and default natural sorting order required, we can go for class implementing comparable interface.

Comparator:
Whenever we want to store homogeneous and heterogeneous elements and we want to sort in default customized sorting order, we can go for comparator interface.

What is the difference between Html.Hidden and Html.HiddenFor

Most of the MVC helper methods have a XXXFor variant. They are intended to be used in conjunction with a concrete model class. The idea is to allow the helper to derive the appropriate "name" attribute for the form-input control based on the property you specify in the lambda. This means that you get to eliminate "magic strings" that you would otherwise have to employ to correlate the model properties with your views. For example:

Html.Hidden("Name", "Value")

Will result in:

<input id="Name" name="Name" type="hidden" value="Value">

In your controller, you might have an action like:

[HttpPost]
public ActionResult MyAction(MyModel model) 
{
}

And a model like:

public class MyModel 
{
    public string Name { get; set; }
}

The raw Html.Hidden we used above will get correlated to the Name property in the model. However, it's somewhat distasteful that the value "Name" for the property must be specified using a string ("Name"). If you rename the Name property on the Model, your code will break and the error will be somewhat difficult to figure out. On the other hand, if you use HiddenFor, you get protected from that:

Html.HiddenFor(x => x.Name, "Value");

Now, if you rename the Name property, you will get an explicit runtime error indicating that the property can't be found. In addition, you get other benefits of static analysis, such as getting a drop-down of the members after typing x..

Setting cursor at the end of any text of a textbox

There are multiple options:

txtBox.Focus();
txtBox.SelectionStart = txtBox.Text.Length;

OR

txtBox.Focus();
txtBox.CaretIndex = txtBox.Text.Length;

OR

txtBox.Focus();
txtBox.Select(txtBox.Text.Length, 0);

Test for array of string type in TypeScript

You cannot test for string[] in the general case but you can test for Array quite easily the same as in JavaScript https://stackoverflow.com/a/767492/390330

If you specifically want for string array you can do something like:

if (Array.isArray(value)) {
   var somethingIsNotString = false;
   value.forEach(function(item){
      if(typeof item !== 'string'){
         somethingIsNotString = true;
      }
   })
   if(!somethingIsNotString && value.length > 0){
      console.log('string[]!');
   }
}

Should functions return null or an empty object?

More meat to grind: let's say my DAL returns a NULL for GetPersonByID as advised by some. What should my (rather thin) BLL do if it receives a NULL? Pass that NULL on up and let the end consumer worry about it (in this case, an ASP.Net page)? How about having the BLL throw an exception?

The BLL may be being used by ASP.Net and Win App, or another class library - I think it is unfair to expect the end consumer to intrinsically "know" that the method GetPersonByID returns a null (unless null types are used, I guess).

My take (for what it's worth) is that my DAL returns NULL if nothing is found. FOR SOME OBJECTS, that's ok - it could be a 0:many list of things, so not having any things is fine (e.g. a list of favourite books). In this case, my BLL returns an empty list. For most single entity things (e.g. user, account, invoice) if I don't have one, then that's definitely a problem and a throw a costly exception. However, seeing as retrieving a user by a unique identifier that's been previously given by the application should always return a user, the exception is a "proper" exception, as in it's exceptional. The end consumer of the BLL (ASP.Net, f'rinstance) only ever expects things to be hunky-dory, so an Unhandled Exception Handler will be used instead of wrapping every single call to GetPersonByID in a try - catch block.

If there is a glaring problem in my approach, please let me know as I am always keen to learn. As other posters have said, exceptions are costly things, and the "checking first" approach is good, but exceptions should be just that - exceptional.

I'm enjoying this post, lot's of good suggestions for "it depends" scenarios :-)

How do I compare two Integers?

Minor note: since Java 1.7 the Integer class has a static compare(Integer, Integer) method, so you can just call Integer.compare(x, y) and be done with it (questions about optimization aside).

Of course that code is incompatible with versions of Java before 1.7, so I would recommend using x.compareTo(y) instead, which is compatible back to 1.2.

How I can check whether a page is loaded completely or not in web driver?

I know this post is old. But after gathering all code from above I made a nice method (solution) to handle ajax running and regular pages. The code is made for C# only (since Selenium is definitely a best fit for C# Visual Studio after a year of messing around).

The method is used as an extension method, which means to put it simple; that you can add more functionality (methods) in this case, to the object IWebDriver. Important is that you have to define: 'this' in the parameters to make use of it.

The timeout variable is the amount of seconds for the webdriver to wait, if the page is not responding. Using 'Selenium' and 'Selenium.Support.UI' namespaces it is possible to execute a piece of javascript that returns a boolean, whether the document is ready (complete) and if jQuery is loaded. If the page does not have jQuery then the method will throw an exception. This exception is 'catched' by error handling. In the catch state the document will only be checked for it's ready state, without checking for jQuery.

public static void WaitUntilDocumentIsReady(this IWebDriver driver, int timeoutInSeconds) {
    var javaScriptExecutor = driver as IJavaScriptExecutor;
    var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));

    try {
        Func<IWebDriver, bool> readyCondition = webDriver => (bool)javaScriptExecutor.ExecuteScript("return (document.readyState == 'complete' && jQuery.active == 0)");
        wait.Until(readyCondition);
    } catch(InvalidOperationException) {
        wait.Until(wd => javaScriptExecutor.ExecuteScript("return document.readyState").ToString() == "complete");
    }
}

Show a div as a modal pop up

A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:

  • 1. Create a div with semi transparent background & show it on top of your content page on click.
  • 2. Show your pop up div or alert div on top of the semi transparent dimming/hiding div.
  • So we need three divs:

  • content(main content of the site).
  • hider(To dim the content).
  • popup_box(the modal div to display).

    First let us define the CSS:

        #hider
        {
            position:absolute;
            top: 0%;
            left: 0%;
            width:1600px;
            height:2000px;
            margin-top: -800px; /*set to a negative number 1/2 of your height*/
            margin-left: -500px; /*set to a negative number 1/2 of your width*/
            /*
            z- index must be lower than pop up box
           */
            z-index: 99;
           background-color:Black;
           //for transparency
           opacity:0.6;
        }
    
        #popup_box  
        {
    
        position:absolute;
            top: 50%;
            left: 50%;
            width:10em;
            height:10em;
            margin-top: -5em; /*set to a negative number 1/2 of your height*/
            margin-left: -5em; /*set to a negative number 1/2 of your width*/
            border: 1px solid #ccc;
            border:  2px solid black;
            z-index:100; 
    
        }
    

    It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
    Here comes the java Script:

            $(document).ready(function () {
            //hide hider and popup_box
            $("#hider").hide();
            $("#popup_box").hide();
    
            //on click show the hider div and the message
            $("#showpopup").click(function () {
                $("#hider").fadeIn("slow");
                $('#popup_box').fadeIn("slow");
            });
            //on click hide the message and the
            $("#buttonClose").click(function () {
    
                $("#hider").fadeOut("slow");
                $('#popup_box').fadeOut("slow");
            });
    
            });
    

    And finally the HTML:

    <div id="hider"></div>
    <div id="popup_box">
        Message<br />
        <a id="buttonClose">Close</a>
    </div>    
    <div id="content">
        Page's main content.<br />
        <a id="showpopup">ClickMe</a>
    </div>
    

    I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.

  • Is Task.Result the same as .GetAwaiter.GetResult()?

    https://github.com/aspnet/Security/issues/59

    "One last remark: you should avoid using Task.Result and Task.Wait as much as possible as they always encapsulate the inner exception in an AggregateException and replace the message by a generic one (One or more errors occurred), which makes debugging harder. Even if the synchronous version shouldn't be used that often, you should strongly consider using Task.GetAwaiter().GetResult() instead."

    Why do I get "MismatchSenderId" from GCM server side?

    This happens when the Server key and Sender ID parameters HTTP request do not match each other. Basically both server ID and Server key must belong to the same firebase project. Please refer to the below image. In case of mixing these parameters from deferent Firebase projects will cause error MismatchSenderId enter image description here

    Link to reload current page

    If you are using php/smarty templates, u could do something like this:

    <a href="{{$smarty.server.REQUEST_URI}}{if $smarty.server.REQUEST_URI|strstr:"?"}&{else}?{/if}newItem=1">Add New Item</a>
    

    Convert Pandas Column to DateTime

    You can use the DataFrame method .apply() to operate on the values in Mycol:

    >>> df = pd.DataFrame(['05SEP2014:00:00:00.000'],columns=['Mycol'])
    >>> df
                        Mycol
    0  05SEP2014:00:00:00.000
    >>> import datetime as dt
    >>> df['Mycol'] = df['Mycol'].apply(lambda x: 
                                        dt.datetime.strptime(x,'%d%b%Y:%H:%M:%S.%f'))
    >>> df
           Mycol
    0 2014-09-05
    

    What does the "map" method do in Ruby?

    map, along with select and each is one of Ruby's workhorses in my code.

    It allows you to run an operation on each of your array's objects and return them all in the same place. An example would be to increment an array of numbers by one:

    [1,2,3].map {|x| x + 1 }
    #=> [2,3,4]
    

    If you can run a single method on your array's elements you can do it in a shorthand-style like so:

    1. To do this with the above example you'd have to do something like this

      class Numeric
        def plusone
          self + 1
        end
      end
      [1,2,3].map(&:plusone)
      #=> [2,3,4]
      
    2. To more simply use the ampersand shortcut technique, let's use a different example:

      ["vanessa", "david", "thomas"].map(&:upcase)
      #=> ["VANESSA", "DAVID", "THOMAS"]
      

    Transforming data in Ruby often involves a cascade of map operations. Study map & select, they are some of the most useful Ruby methods in the primary library. They're just as important as each.

    (map is also an alias for collect. Use whatever works best for you conceptually.)

    More helpful information:

    If the Enumerable object you're running each or map on contains a set of Enumerable elements (hashes, arrays), you can declare each of those elements inside your block pipes like so:

    [["audi", "black", 2008], ["bmw", "red", 2014]].each do |make, color, year|
      puts "make: #{make}, color: #{color}, year: #{year}"
    end
    # Output:
    # make: audi, color: black, year: 2008
    # make: bmw, color: red, year: 2014
    

    In the case of a Hash (also an Enumerable object, a Hash is simply an array of tuples with special instructions for the interpreter). The first "pipe parameter" is the key, the second is the value.

    {:make => "audi", :color => "black", :year => 2008}.each do |k,v|
        puts "#{k} is #{v}"
    end
    #make is audi
    #color is black
    #year is 2008
    

    To answer the actual question:

    Assuming that params is a hash, this would be the best way to map through it: Use two block parameters instead of one to capture the key & value pair for each interpreted tuple in the hash.

    params = {"one" => 1, "two" => 2, "three" => 3}
    params.each do |k,v|
      puts "#{k}=#{v}"
    end
    # one=1
    # two=2
    # three=3
    

    I want to truncate a text or line with ellipsis using JavaScript

    Try this

    function shorten(text, maxLength, delimiter, overflow) {
      delimiter = delimiter || "&hellip;";
      overflow = overflow || false;
      var ret = text;
      if (ret.length > maxLength) {
        var breakpoint = overflow ? maxLength + ret.substr(maxLength).indexOf(" ") : ret.substr(0, maxLength).lastIndexOf(" ");
        ret = ret.substr(0, breakpoint) + delimiter;
      }
      return ret;
    }
    
    $(document).ready(function() {
      var $editedText = $("#edited_text");
      var text = $editedText.text();
      $editedText.text(shorten(text, 33, "...", false));
    });
    

    Checkout a working sample on Codepen http://codepen.io/Izaias/pen/QbBwwE

    Javascript switch vs. if...else if...else

    Sometimes it's better to use neither. For example, in a "dispatch" situation, Javascript lets you do things in a completely different way:

    function dispatch(funCode) {
      var map = {
        'explode': function() {
          prepExplosive();
          if (flammable()) issueWarning();
          doExplode();
        },
    
        'hibernate': function() {
          if (status() == 'sleeping') return;
          // ... I can't keep making this stuff up
        },
        // ...
      };
    
      var thisFun = map[funCode];
      if (thisFun) thisFun();
    }
    

    Setting up multi-way branching by creating an object has a lot of advantages. You can add and remove functionality dynamically. You can create the dispatch table from data. You can examine it programmatically. You can build the handlers with other functions.

    There's the added overhead of a function call to get to the equivalent of a "case", but the advantage (when there are lots of cases) of a hash lookup to find the function for a particular key.

    How to pass html string to webview on android

    Passing null would be better. The full codes is like:

    WebView wv = (WebView)this.findViewById(R.id.myWebView);
    wv.getSettings().setJavaScriptEnabled(true);
    wv.loadDataWithBaseURL(null, "<html>...</html>", "text/html", "utf-8", null);
    

    How to print Boolean flag in NSLog?

    While this is not a direct answer to Devang's question I believe that the below macro can be very helpful to people looking to log BOOLs. This will log out the value of the bool as well as automatically labeling it with the name of the variable.

    #define LogBool(BOOLVARIABLE) NSLog(@"%s: %@",#BOOLVARIABLE, BOOLVARIABLE ? @"YES" : @"NO" )
    
    BOOL success = NO;
    LogBool(success); // Prints out 'success: NO' to the console
    
    success = YES;
    LogBool(success); // Prints out 'success: YES' to the console
    

    Android: how to get the current day of the week (Monday, etc...) in the user's language?

    Sorry for late reply.But this would work properly.

    daytext=(textview)findviewById(R.id.day);
    
    Calender c=Calender.getInstance();
    SimpleDateFormat sd=new SimpleDateFormat("EEEE");
    String dayofweek=sd.format(c.getTime());
    
    
    daytext.setText(dayofweek);
    

    Which maven dependencies to include for spring 3.0?

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>3.0.0.RELEASE</version>
    </dependency>
    

    Count number of rows within each group

    If your trying the aggregate solutions above and you get the error:

    invalid type (list) for variable

    Because you're using date or datetime stamps, try using as.character on the variables:

    aggregate(x ~ as.character(Year) + Month, data = df, FUN = length)
    

    On one or both of the variables.

    Adding delay between execution of two following lines

    You can use gcd to do this without having to create another method

    double delayInSeconds = 2.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
      NSLog(@"Do some work");
    });
    

    You should still ask yourself "do I really need to add a delay" as it can often complicate code and cause race conditions

    Java getHours(), getMinutes() and getSeconds()

    Try this:

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(yourdate);
    int hours = calendar.get(Calendar.HOUR_OF_DAY);
    int minutes = calendar.get(Calendar.MINUTE);
    int seconds = calendar.get(Calendar.SECOND);
    

    Edit:

    hours, minutes, seconds
    

    above will be the hours, minutes and seconds after converting yourdate to System Timezone!

    Is there an easy way to reload css without reloading the page?

    simple if u are using php Just append the current time at the end of the css like

    <link href="css/name.css?<?php echo 
    time(); ?>" rel="stylesheet">
    

    So now everytime u reload whatever it is , the time changes and browser thinks its a different file since the last bit keeps changing.... U can do this for any file u force the browser to always refresh using whatever scripting language u want

    How to read an external local JSON file in JavaScript?

    You can use d3.js to import JSON files. Just call d3 on your html body:

    <script src="https://d3js.org/d3.v5.min.js"></script>
    

    Then put this on your js scripts:

      d3.json("test.json").then(function(data_json) {
             //do your stuff
      })
    

    How to make the script wait/sleep in a simple way in unity

    You were correct to use WaitForSeconds. But I suspect that you tried using it without coroutines. That's how it should work:

    public void SomeMethod()
    {
        StartCoroutine(SomeCoroutine());
    }
    
    private IEnumerator SomeCoroutine()
    {
        TextUI.text = "Welcome to Number Wizard!";
        yield return new WaitForSeconds (3);
        TextUI.text = ("The highest number you can pick is " + max);
        yield return new WaitForSeconds (3);
        TextUI.text = ("The lowest number you can pick is " + min);
    }
    

    How to flush output after each `echo` call?

    Flushing seemingly failing to work is a side effect of automatic character set detection.

    The browser will not display anything until it knows the character set to display it in, and if you don't specify the character set, it need tries to guess it. The problem being that it can't make a good guess without enough data, which is why browsers seem to have this 1024 byte (or similar) buffer they need filled before displaying anything.

    The solution is therefore to make sure the browser doesn't have to guess the character set.

    If you're sending text, add a '; charset=utf-8' to its content type, and if it's HTML, add the character set to the appropriate meta tag.

    What does "var" mean in C#?

    var is a "contextual keyword" in C# meaning you can only use it as a local variable implicitly in the context of the same class that you are using the variable. If you try to use it in a class that you call from "Main" or some other exterior class, or an interface for example you will get the error CS0825 < https://docs.microsoft.com/en-us/dotnet/csharp/misc/cs0825 >

    See the remarks about when you can and can't use it in the documentation here: < https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/implicitly-typed-local-variables#remarks >

    Basically, you should only use this when you are declaring a variable with an implicit value such as "var myValue = "This is the value"; This saves a little time in comparison to saying "string" for example but IMHO not much time is saved and places a constraint on the scalability of your project.

    CSS: Creating textured backgrounds

    If you search for an image base-64 converter, you can embed some small image texture files as code into your @import url('') section of code. It will look like a lot of code; but at least all your data is now stored locally - rather than having to call a separate resource to load the image.

    Example link: http://www.base64-image.de/

    When I take a file from my own inventory of a simple icon in PNG format, and convert it to base-64, it looks like this in my CSS:

    url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAm0SURBVHjaRFdLrF1lFf72++xzzj33nMPt7QuhxNJCY4smGomKCQlWxMSJgQ4dyEATE3FCSDRxjnHiwMTUAdHowIGJOqBEg0RDCCESKIgCWtqCfd33eeyz39vvW/vcctvz2nv/61/rW9/61vqd7CIewMT5VlnChf059t40QBwB7io+vjx3kczb++D9Tof3x1xWNu39hP9nHhxH62t0u7zWb9rFtl73G1veXamrs98rf+5Pbjnnnv5p+IPNiQvXreF7AZ914bgOv/PBOIDH767HH/DgO4F9d7hLHPkYrIRw+d1x2/sufBRViboCgkCvBmmWcw2v5zWStABv4+iBOe49enXqb2x4a79+wYfidx2XRgP4vm8QBLTgBx4CLva4QRjyO+9FUUjndD1ATJjkgNaEoW/R6ZmyqgxFvU3nCTzaqLhzURSoGWJ82cN9d3r3+Z5TV6srni30fAdNXSP0a3ToiCHvVuh1mQsua+gl98Zqz0PNEIOAv4OidZToNU1OG8TAbUC7qGirdV6bV0SGa3gvISKrPUcoFj5xt/S4xDtktFVZMRrXItDiKAxRFiVh9HH2y+s05OHVizvod+mJ4yEnebSOROCzAfJ5ZgRxGHmXzwQ+U+aKFJ5oQ8fllGfp0XM+f0OsaaoaHnPq8U4YtFAqz0rL+riDR7+4guPrGaK4i8+dWMdotYdBf8CIPaatgzCKEHdi7hPRTg9uvIoLL76DC39+DcN+F4s8ZaAOCkYfEOmCQenPl3ftho4xmxcYfcmcCZGAMALjUYBvf2WM3//pDcwZoVKSzyNUowHGa2Pc0R9iOFjFcMSHhwxtQHNjDye+8Bht1Hj+wpsCy3i0N19gY3sPZ+5ty8uXVyFh8jyXm7EW+RkwZ47jmjNFJXKEGJ06g8ebDi5vptjYnWJvj68iR87vO2R3b0bHtmck4jYOjVYQuR8gHr2L73z3NN68eBm3NqbGo7gTMoAu6qatbV8wi70iiCL2/ZaQIfPZYf59eiBYcfdXMbj7NJ55+Cf4x1sfYkUiYSZ3jbie267LyKFPfXKI809/BjsfXMPpPMPjZ4/g2fNvg5mywEaDFa5JSNpGDihSMZU64Dlkr2uElCqVJFhJV4UEsMLXacTdIY4cSCwNYrdSKEOeZ1Q2Qv7n6iZ+99IlPHCwwot/3cDxU/dynWdk3v9ToJVs101lP1zWrgzJjGwpFULBzWs0t6WwINNd3HnwgPHGZbUIpZIIqFpqcqcbx2R4jJcv3sLdD6Z4+587JG6Fg+MAl6+1xAZajShLiR/Z4Wszwh9zw7gTWemYoFgZtvxgUsyJcOl5oOtcW0uwpHKMTrbmSYLVfoyk6OLUqZM4uNbF1asf4cBKTkHKuGll61MqYl0JXXrU68ao5RjRUNk5vpQtMkmuyQ1Yrb7H15qRJwj2hUvpkxPUfTpeSX+ZljTNMZmXOHLsJJ48t4KbWzso329w4ZUNOuuaGrpMiVBw95uPR0csWhrsdTv2aSXK+vYIPfK/86m/8VpDKe7cblAtOjClExpCQtfSJMVOcBL+I9/A0bMP4cFP32NaoHQrCD2vunddzwTbUqA8Rp2gLUEJDKOS5ktmceMScP1dNpQCi6Tk3gGBabBIMxmhdtS2eV21FRGFEa5f36Ht+4HRw7jnzEOMlmsXKbI8NxQkAf5w6FD3QyNU20Rqay5Mj5GwMS9ZDTf/S+MhTnyiD9w1RK/XwTvv7xqRxKG8rFoSEzUJmch2a3PXCtVY3+tzuwZ50d7LGYhs+8qnOlrJHRtGpM3F8IqkUDRMLzepceNGQjHZxFPfHGJ1MKMTx/DMDz1c/rCy3NdNc1u+hYQSu8gFc2R9Qn8qaVF5v71rhV+r+ZA46myN8iiPJcl+YAQTS8TByZ6Dm9cb7O7usgNu4+T2BJvbazQxREG9EHo5YVUqFWmWMx3FhPc3IG3O0tIqQMaLggZj64aQ5toEo1w7hDLJarBCrBv2SUb1gpSOTCYNtjYqE5QgcrC7UxtitfX/wHIqIs+ThTnuqP8vrvPu83wdxtbNErMkp050DLGcPNCw4jtUuR7FQ4YWWYlzjw5wZJSwZoXEzEpuPkvRFBk0FtQFiZext6eOkdV1GBFTFAStFoiA83RBljfoRZzR/vdvDhA7eOftGerSMfbnRMcjlWwCExOlhjVFZJIU+PqXYqyevAJc2cJ8K8KlzRDFSoXd6RCDO2GbiS83FyusdTJewxP7ha7LeJoVbU/gJr6zg/zyFYRHZnj9YorabTki5CRGxgFYvgoSMVBxYpYGWB0dZ+ncg9d/VeKRJ1/FGtuxmF4pHyp7Qd9McezoHTh8IG51QE6oFMtWB+KY82J3gX+9N8MJ9xZeeSNDh2gusgwpn8mLZXUIxsDGk8aYmU83We8sn/EYvf4Yp08cZvPpGbzyuVr2CxMvEyENpLCB0+Y93q8KDbcVIke8qXGpW+Kt9xc2U+oZIZCXRTsRzea+abgm2YybTKc587YH8LNOGoyHKrvISrGNHuaIUNPoXTF9FYlbL0tRk9WMLD60RpImFCmOYn95rcH2XoW1VXc5Z/LVOK0QZWllRhSWCDWdpsg/ShAOK+xMBtie5lailSlcKzgWad1+qnekWWojuSon10heB3jqCYpYlmD98AjPPbdLojsMsK0UNSH9k5KqB1tX23dCjeTGjRzhdoED4QTff2Idh8YhK8CxuVgGoDLT6KZzAk8navN1vocimZCYKdaHCe5f2+AGfTz7h5zzAW2NQrKfaRJqFZYtXkLEN83tIcdwTbJXthwMj64jM/hdPPZZ1rWXstY9SjbTxTyio5ZI/uocEPF3OCIAh0kEcifZQbO7wT4Q4Jd/3MbPfnuNLbnHlFXYP1KpAjTsiEu+8uiYmHh2FPvx+Q8NSqFScEaUUtoMQQLoWXmuKbu2SmjssKH7MqrkNstzXcnjWsXX0YN944/WFrJlnbO2IWY5lMIOEMkiMxk9cdchu6nGUi6xUr4ko4I9YxmpWozNS/0vjBeVafx+dNZofHdZ722FqOKKsp2GHBNspaCq/e0pdSByLRKeifhZW3cET0U6SIg03ZglqgEV7TGMMxQluzQnijLntdCMS2Z1DlyQS1nRmGhlWeu8KsRxWjscF3itcfz+ILv5tc9vYGui+a6FUP0ey8OymF812qD1WPOATkeSUxMgpklqaNMQS6soVSGu1Xpp3ZTNLsBSQ9oUSIPuO9aQsKj8H/2i+M14cIVV5UZZThrWikhQtOdEhxOqH1ZQI6PysyQdO93q/KdeHbC/hp2P+aG3PG1aiCVahDWIm49p77RHf/LHfeFlvPR/AQYAyMIq/fJRUogAAAAASUVORK5CYII=')
    

    With your texture images, you'll want to employ a similar process.

    How do I find the value of $CATALINA_HOME?

    Tomcat can tell you in several ways. Here's the easiest:

     $ /path/to/catalina.sh version
    Using CATALINA_BASE:   /usr/local/apache-tomcat-7.0.29
    Using CATALINA_HOME:   /usr/local/apache-tomcat-7.0.29
    Using CATALINA_TMPDIR: /usr/local/apache-tomcat-7.0.29/temp
    Using JRE_HOME:        /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
    Using CLASSPATH:       /usr/local/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/local/apache-tomcat-7.0.29/bin/tomcat-juli.jar
    Server version: Apache Tomcat/7.0.29
    Server built:   Jul 3 2012 11:31:52
    Server number:  7.0.29.0
    OS Name:        Mac OS X
    OS Version:     10.7.4
    Architecture:   x86_64
    JVM Version:    1.6.0_33-b03-424-11M3720
    JVM Vendor:     Apple Inc.
    

    If you don't know where catalina.sh is (or it never gets called), you can usually find it via ps:

    $ ps aux | grep catalina
    chris            930   0.0  3.1  2987336 258328 s000  S    Wed01PM   2:29.43 /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java -Dnop -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.library.path=/usr/local/apache-tomcat-7.0.29/lib -Djava.endorsed.dirs=/usr/local/apache-tomcat-7.0.29/endorsed -classpath /usr/local/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/local/apache-tomcat-7.0.29/bin/tomcat-juli.jar -Dcatalina.base=/Users/chris/blah/blah -Dcatalina.home=/usr/local/apache-tomcat-7.0.29 -Djava.io.tmpdir=/Users/chris/blah/blah/temp org.apache.catalina.startup.Bootstrap start
    

    From the ps output, you can see both catalina.home and catalina.base. catalina.home is where the Tomcat base files are installed, and catalina.base is where the running configuration of Tomcat exists. These are often set to the same value unless you have configured your Tomcat for multiple (configuration) instances to be launched from a single Tomcat base install.

    You can also interrogate the JVM directly if you can't find it in a ps listing:

    $ jinfo -sysprops 930 | grep catalina
    Attaching to process ID 930, please wait...
    Debugger attached successfully.
    Server compiler detected.
    JVM version is 20.8-b03-424
    catalina.base = /Users/chris/blah/blah
    [...]
    catalina.home = /usr/local/apache-tomcat-7.0.29
    

    If you can't manage that, you can always try to write a JSP that dumps the values of the two system properties catalina.home and catalina.base.

    How to write a JSON file in C#?

    var responseData = //Fetch Data
    string jsonData = JsonConvert.SerializeObject(responseData, Formatting.None);
    System.IO.File.WriteAllText(Server.MapPath("~/JsonData/jsondata.txt"), jsonData);
    

    align 3 images in same row with equal spaces?

    I assumed the first DIV is #content :

    <div id="content">
       <img src="@Url.Content("~/images/image1.bmp")" alt="" />
       <img src="@Url.Content("~/images/image2.bmp")" alt="" />
       <img src="@Url.Content("~/images/image3.bmp")" alt="" />
    </div>
    

    And CSS :

    #content{
             width: 700px;
             display: block;
             height: auto;
         }
         #content > img{
            float: left; width: 200px;
            height: 200px;
            margin: 5px 8px;
         }
    

    Single Form Hide on Startup

    Why do it like that at all?

    Why not just start like a console app and show the form when necessary? There's nothing but a few references separating a console app from a forms app.

    No need in being greedy and taking the memory needed for the form when you may not even need it.

    What is the theoretical maximum number of open TCP connections that a modern Linux box can have

    If you are thinking of running a server and trying to decide how many connections can be served from one machine, you may want to read about the C10k problem and the potential problems involved in serving lots of clients simultaneously.

    Node Multer unexpected field

    In my scenario this was happening because I renamed a parameter in swagger.yaml but did not reload the docs page.

    Hence I was trying the API with an unexpected input parameter.
    Long story short, F5 is my friend.

    Passing argument to alias in bash

    In csh (as opposed to bash) you can do exactly what you want.

    alias print 'lpr \!^ -Pps5'
    print memo.txt
    

    The notation \!^ causes the argument to be inserted in the command at this point.

    The ! character is preceeded by a \ to prevent it being interpreted as a history command.

    You can also pass multiple arguments:

    alias print 'lpr \!* -Pps5'
    print part1.ps glossary.ps figure.ps
    

    (Examples taken from http://unixhelp.ed.ac.uk/shell/alias_csh2.1.html .)

    Create iOS Home Screen Shortcuts on Chrome for iOS

    Can't change the default browser, but try this (found online a while ago). Add a bookmark in Safari called "Open in Chrome" with the following.

    javascript:location.href=%22googlechrome%22+location.href.substring(4);
    

    Will open the current page in Chrome. Not as convenient, but maybe someone will find it useful.

    Source

    Works for me.

    Linux cmd to search for a class file among jars irrespective of jar path

    I have used this small snippet. Might be slower but works every time.

    for i in 'find . -type f -name "*.jar"'; do
        jar tvf $i | grep "com.foo.bar.MyClass.clss";
        if [ $? -eq 0 ]; then echo $i; fi;
    done
    

    Build .so file from .c file using gcc command line

    To generate a shared library you need first to compile your C code with the -fPIC (position independent code) flag.

    gcc -c -fPIC hello.c -o hello.o
    

    This will generate an object file (.o), now you take it and create the .so file:

    gcc hello.o -shared -o libhello.so
    

    EDIT: Suggestions from the comments:

    You can use

    gcc -shared -o libhello.so -fPIC hello.c
    

    to do it in one step. – Jonathan Leffler

    I also suggest to add -Wall to get all warnings, and -g to get debugging information, to your gcc commands. – Basile Starynkevitch

    Node.js quick file server (static files over HTTP)

    First install node-static server via npm install node-static -g -g is to install it global on your system, then navigate to the directory where your files are located, start the server with static it listens on port 8080, naviaget to the browser and type localhost:8080/yourhtmlfilename.

    Nullable types: better way to check for null or zero in c#

    Don't forget, for strings, you can always use:

    String.IsNullOrEmpty(str)
    

    Instead of:

    str==null || str==""
    

    Get href attribute on jQuery

    Use $(this) for get the desire element.

    function openAll()
    {
         $("tr.b_row").each(function(){
            var a_href = $(this).find('.cpt h2 a').attr('href');
            alert ("Href is: "+a_href);
         });
    }
    

    Remove all special characters with RegExp

    why dont you do something like:

    re = /^[a-z0-9 ]$/i;
    var isValid = re.test(yourInput);
    

    to check if your input contain any special char

    Accessing nested JavaScript objects and arrays by string path

    Extension of Mohamad Hamouday' Answer will fill in missing keys

    function Object_Manager(obj, Path, value, Action, strict) 
    {
        try
        {
            if(Array.isArray(Path) == false)
            {
                Path = [Path];
            }
    
            let level = 0;
            var Return_Value;
            Path.reduce((a, b)=>{
                console.log(level,':',a, '|||',b)
                if (!strict){
                  if (!(b in a)) a[b] = {}
                }
    
    
                level++;
                if (level === Path.length)
                {
                    if(Action === 'Set')
                    {
                        a[b] = value;
                        return value;
                    }
                    else if(Action === 'Get')
                    {
                        Return_Value = a[b];
                    }
                    else if(Action === 'Unset')
                    {
                        delete a[b];
                    }
                } 
                else 
                {
                    return a[b];
                }
            }, obj);
            return Return_Value;
        }
    
        catch(err)
        {
            console.error(err);
            return obj;
        }
    }
    
    

    Example

    
    obja = {
      "a": {
        "b":"nom"
      }
    }
    
    // Set
    path = "c.b" // Path does not exist
    Object_Manager(obja,path.split('.'), 'test_new_val', 'Set', false);
    
    // Expected Output: Object { a: Object { b: "nom" }, c: Object { b: "test_new_value" } }
    
    

    Using android.support.v7.widget.CardView in my project (Eclipse)

    I have done following and it resolve an issue with recyclerview same you may use for other widget as well if it's not working in eclipse project.

    • Go to sdk\extras\android\m2repository\com\android\support\recyclerview-v7\21.0.0-rc1 directory

    • Copy recyclerview-v7-21.0.0-rc1.aar file and rename it as .zip

    • Unzip the file, you will get classes.jar (rename the jar file more meaningful name)

    • Use the following jar in your project build path or lib directory.

    and it resolve your error.

    happy coding :)

    How to "test" NoneType in python?

    So how can I question a variable that is a NoneType?

    Use is operator, like this

    if variable is None:
    

    Why this works?

    Since None is the sole singleton object of NoneType in Python, we can use is operator to check if a variable has None in it or not.

    Quoting from is docs,

    The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. x is not y yields the inverse truth value.

    Since there can be only one instance of None, is would be the preferred way to check None.


    Hear it from the horse's mouth

    Quoting Python's Coding Style Guidelines - PEP-008 (jointly defined by Guido himself),

    Comparisons to singletons like None should always be done with is or is not, never the equality operators.

    How to check if an element is in an array

    (Swift 3)

    Check if an element exists in an array (fulfilling some criteria), and if so, proceed working with the first such element

    If the intent is:

    1. To check whether an element exist in an array (/fulfils some boolean criteria, not necessarily equality testing),
    2. And if so, proceed and work with the first such element,

    Then an alternative to contains(_:) as blueprinted Sequence is to first(where:) of Sequence:

    let elements = [1, 2, 3, 4, 5]
    
    if let firstSuchElement = elements.first(where: { $0 == 4 }) {
        print(firstSuchElement) // 4
        // ...
    }
    

    In this contrived example, its usage might seem silly, but it's very useful if querying arrays of non-fundamental element types for existence of any elements fulfilling some condition. E.g.

    struct Person {
        let age: Int
        let name: String
        init(_ age: Int, _ name: String) {
            self.age = age
            self.name = name
        }
    }
    
    let persons = [Person(17, "Fred"),   Person(16, "Susan"),
                   Person(19, "Hannah"), Person(18, "Sarah"),
                   Person(23, "Sam"),    Person(18, "Jane")]
    
    if let eligableDriver = persons.first(where: { $0.age >= 18 }) {
        print("\(eligableDriver.name) can possibly drive the rental car in Sweden.")
        // ...
    } // Hannah can possibly drive the rental car in Sweden.
    
    let daniel = Person(18, "Daniel")
    if let sameAgeAsDaniel = persons.first(where: { $0.age == daniel.age }) {
        print("\(sameAgeAsDaniel.name) is the same age as \(daniel.name).")
        // ...
    } // Sarah is the same age as Daniel.
    

    Any chained operations using .filter { ... some condition }.first can favourably be replaced with first(where:). The latter shows intent better, and have performance advantages over possible non-lazy appliances of .filter, as these will pass the full array prior to extracting the (possible) first element passing the filter.


    Check if an element exists in an array (fulfilling some criteria), and if so, remove the first such element

    A comment below queries:

    How can I remove the firstSuchElement from the array?

    A similar use case to the one above is to remove the first element that fulfils a given predicate. To do so, the index(where:) method of Collection (which is readily available to array collection) may be used to find the index of the first element fulfilling the predicate, whereafter the index can be used with the remove(at:) method of Array to (possible; given that it exists) remove that element.

    var elements = ["a", "b", "c", "d", "e", "a", "b", "c"]
    
    if let indexOfFirstSuchElement = elements.index(where: { $0 == "c" }) {
        elements.remove(at: indexOfFirstSuchElement)
        print(elements) // ["a", "b", "d", "e", "a", "b", "c"]
    }
    

    Or, if you'd like to remove the element from the array and work with, apply Optional:s map(_:) method to conditionally (for .some(...) return from index(where:)) use the result from index(where:) to remove and capture the removed element from the array (within an optional binding clause).

    var elements = ["a", "b", "c", "d", "e", "a", "b", "c"]
    
    if let firstSuchElement = elements.index(where: { $0 == "c" })
        .map({ elements.remove(at: $0) }) {
    
        // if we enter here, the first such element have now been
        // remove from the array
        print(elements) // ["a", "b", "d", "e", "a", "b", "c"]
    
        // and we may work with it
        print(firstSuchElement) // c
    }
    

    Note that in the contrived example above the array members are simple value types (String instances), so using a predicate to find a given member is somewhat over-kill, as we might simply test for equality using the simpler index(of:) method as shown in @DogCoffee's answer. If applying the find-and-remove approach above to the Person example, however, using index(where:) with a predicate is appropriate (since we no longer test for equality but for fulfilling a supplied predicate).

    How to set caret(cursor) position in contenteditable element (div)?

    I'm writting a syntax highlighter (and basic code editor), and I needed to know how to auto-type a single quote char and move the caret back (like a lot of code editors nowadays).

    Heres a snippet of my solution, thanks to much help from this thread, the MDN docs, and a lot of moz console watching..

    //onKeyPress event
    
    if (evt.key === "\"") {
        let sel = window.getSelection();
        let offset = sel.focusOffset;
        let focus = sel.focusNode;
    
        focus.textContent += "\""; //setting div's innerText directly creates new
        //nodes, which invalidate our selections, so we modify the focusNode directly
    
        let range = document.createRange();
        range.selectNode(focus);
        range.setStart(focus, offset);
    
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
    }
    
    //end onKeyPress event
    

    This is in a contenteditable div element

    I leave this here as a thanks, realizing there is already an accepted answer.

    Undo a particular commit in Git that's been pushed to remote repos

    Identify the hash of the commit, using git log, then use git revert <commit> to create a new commit that removes these changes. In a way, git revert is the converse of git cherry-pick -- the latter applies the patch to a branch that's missing it, the former removes it from a branch that has it.

    Which programming languages can be used to develop in Android?

    Scala is supported. See example.

    Support for other languages is problematic:

    7) Something like the dx tool can be forced into the phone, so that Java code could in principle continue to generate bytecodes, yet have them be translated into a VM-runnable form. But, at present, Java code cannot be generated on the fly. This means Dalvik cannot run dynamic languages (JRuby, Jython, Groovy). Yet. (Perhaps the dex format needs a detuned variant which can be easily generated from bytecodes.)

    The name 'ViewBag' does not exist in the current context

    I updated webpages:Version under in ./Views/Web.Config folder but this setting was also present in web.config in root. Update both or remove from root web.config

    Convert HTML5 into standalone Android App

    Create an Android app using Eclipse.

    Create a layout that has a <WebView> control.

    Move your HTML code to /assets folder.

    Load webview with your file:///android_asset/ file.

    And you have an android app!

    Array copy values to keys in PHP

    $final_array = array_combine($a, $a);
    

    Reference: http://php.net/array-combine

    P.S. Be careful with source array containing duplicated keys like the following:

    $a = ['one','two','one'];
    

    Note the duplicated one element.

    iOS: Convert UTC NSDate to local Timezone

    The easiest method I've found is this:

    NSDate *someDateInUTC = …;
    NSTimeInterval timeZoneSeconds = [[NSTimeZone localTimeZone] secondsFromGMT];
    NSDate *dateInLocalTimezone = [someDateInUTC dateByAddingTimeInterval:timeZoneSeconds];
    

    How to add an extra row to a pandas dataframe

    A different approach that I found ugly compared to the classic dict+append, but that works:

    df = df.T
    
    df[0] = ['1/1/2013', 'Smith','test',123]
    
    df = df.T
    
    df
    Out[6]: 
           Date   Name Action   ID
    0  1/1/2013  Smith   test  123
    

    Powershell 2 copy-item which creates a folder if doesn't exist

    Here's an example that worked for me. I had a list of about 500 specific files in a text file, contained in about 100 different folders, that I was supposed to copy over to a backup location in case those files were needed later. The text file contained full path and file name, one per line. In my case, I wanted to strip off the Drive letter and first sub-folder name from each file name. I wanted to copy all these files to a similar folder structure under another root destination folder I specified. I hope other users find this helpful.

    # Copy list of files (full path + file name) in a txt file to a new destination, creating folder structure for each file before copy
    $rootDestFolder = "F:\DestinationFolderName"
    $sourceFiles = Get-Content C:\temp\filelist.txt
    foreach($sourceFile in $sourceFiles){
        $filesplit = $sourceFile.split("\")
        $splitcount = $filesplit.count
        # This example strips the drive letter & first folder ( ex: E:\Subfolder\ ) but appends the rest of the path to the rootDestFolder
        $destFile = $rootDestFolder + "\" + $($($sourceFile.split("\")[2..$splitcount]) -join "\")
        # Output List of source and dest 
        Write-Host ""
        Write-Host "===$sourceFile===" -ForegroundColor Green
        Write-Host "+++$destFile+++"
        # Create path and file, if they do not already exist
        $destPath = Split-Path $destFile
        If(!(Test-Path $destPath)) { New-Item $destPath -Type Directory }
        If(!(Test-Path $destFile)) { Copy-Item $sourceFile $destFile }
    }
    

    How to copy marked text in notepad++

    It's not possible with Notepad but HERE'S THE EASY SOLUTION:

    You will need the freeware Expresso v3.1 http://www.ultrapico.com/ExpressoDownload.htm

    I resorted to another piece of free software: Expresso by Ultrapico.

    1. Once installed go in the tab "Test Mode".
    2. Copy your REGEX into the "Regular expressions" pane.
    3. Paste your whole text to be searched into the "Sample text" pane of Expresso,

    4. Press the "Run match" button. Right click in the "Search results pane" and "Export to..." or "Copy matched text to clipboard".

    N.B.: The original author is @Andreas Jansson but it is hidden in a comment, so since this page is high ranked in Google Search I leave it here for others.

    Can I set enum start value in Java?

    @scottf

    An enum is like a Singleton. The JVM creates the instance.

    If you would create it by yourself with classes it could be look like that

    public static class MyEnum {
    
        final public static MyEnum ONE;
        final public static MyEnum TWO;
    
        static {
            ONE = new MyEnum("1");
            TWO = new MyEnum("2");
        }
    
        final String enumValue;
    
        private MyEnum(String value){
            enumValue = value;    
        }
    
        @Override
        public String toString(){
            return enumValue;
        }
    
    
    }
    

    And could be used like that:

    public class HelloWorld{
    
       public static class MyEnum {
    
           final public static MyEnum ONE;
           final public static MyEnum TWO;
    
           static {
              ONE = new MyEnum("1");
              TWO = new MyEnum("2");
           }
    
           final String enumValue;
    
           private MyEnum(String value){
               enumValue = value;    
           }
    
           @Override
           public String toString(){
               return enumValue;
           }
    
    
       }
    
        public static void main(String []args){
    
           System.out.println(MyEnum.ONE);
           System.out.println(MyEnum.TWO);
    
           System.out.println(MyEnum.ONE == MyEnum.ONE);
    
           System.out.println("Hello World");
        }
    }
    

    RecyclerView and java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder in Samsung devices

    I ran into the same problem when I have both removed and updated items in the list... After days of investigating I think I finally found a solution.

    What you need to do is first do all the notifyItemChanged of your list and only then do all the notifyItemRemoved in a descending order

    I hope this will help people that are running into the same issue...

    "Javac" doesn't work correctly on Windows 10

    The PATH is for current user, instead you can add a CLASSPATH and below link would help you more PATH and CLASSPATH

    How to fix: "HAX is not working and emulator runs in emulation mode"

    Yes it should be fixed, HAXM isn't working.

    HAXM sometimes works; experience with HAXM is currently sporadic across platforms.

    For instance, I've got late 2009 iMac running 10.8.5 and i7 processor @2.8Ghz, Android SDK 22.6 with all the goodies updated this morning (03/05/14). API17 will build emulators with HAXM acceleration on this iMac machine, API19 chokes out.

    I also have early 2013 MBP 15" Retina running 10.8.5 and i7 processor @2.7Ghz, Android SDK 22.6 with all the goodies updated this morning (03/05/14). API17 will build emulators with HAXM acceleration, API19 works great too.

    Ditto for my (personal) late 2013 MBP Retina 13" with dual-core i5 and Mavericks.

    There is something going on for virtualization at the chip level missing from older CPU's (even i7's) that the new API19 x86 images need for HAXM to work. If API19 is not working, give API17 or even 16 a try.

    How to check if a file exists in Documents folder?

    NSURL.h provided - (BOOL)checkResourceIsReachableAndReturnError:(NSError **)error to do so

    NSURL *fileURL = [NSURL fileURLWithPath:NSHomeDirectory()];
    NSError * __autoreleasing error = nil;
    if ([fileURL checkResourceIsReachableAndReturnError:&error]) {
        NSLog(@"%@ exists", fileURL);
    } else {
        NSLog(@"%@ existence checking error: %@", fileURL, error);
    }
    

    Or using Swift

    if let url = URL(fileURLWithPath: NSHomeDirectory()) {
        do {
            let result = try url.checkResourceIsReachable()
        } catch {
            print(error)
        }
    }
    

    How to convert text column to datetime in SQL

    In SQL Server , cast text as datetime

    select cast('5/21/2013 9:45:48' as datetime)
    

    Xcode 6.1 - How to uninstall command line tools?

    If you installed the command line tools separately, delete them using:

    sudo rm -rf /Library/Developer/CommandLineTools
    

    When maven says "resolution will not be reattempted until the update interval of MyRepo has elapsed", where is that interval specified?

    For Intellij users the following worked for me:

    Right click on your package

    Maven > Reimport 
    

    and

    Maven > Generate Sources and Update Folders
    

    Convert time span value to format "hh:mm Am/Pm" using C#

    Very simple by using the string format

    on .ToSTring("") :

    • if you use "hh" ->> The hour, using a 12-hour clock from 01 to 12.

    • if you use "HH" ->> The hour, using a 24-hour clock from 00 to 23.

    • if you add "tt" ->> The Am/Pm designator.

    exemple converting from 23:12 to 11:12 Pm :

    DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
    var res = d.ToString("hh:mm tt");   // this show  11:12 Pm
    var res2 = d.ToString("HH:mm");  // this show  23:12
    
    Console.WriteLine(res);
    Console.WriteLine(res2);
    
    Console.Read();
    

    wait a second that is not all you need to care about something else is the system Culture because the same code executed on windows with other langage especialy with difrent culture langage will generate difrent result with the same code

    exemple of windows set to Arabic langage culture will show like that :

    // 23:12 ?

    ? means Evening (first leter of ????) .

    in another system culture depend on what is set on the windows regional and language option, it will show // 23:12 du.

    you can change between different format on windows control panel under windows regional and language -> current format (combobox) and change... apply it do a rebuild (execute) of your app and watch what iam talking about.

    so who can I force showing Am and Pm Words in English event if the culture of the current system isn't set to English ?

    easy just by adding two lines : ->

    the first step add using System.Globalization; on top of your code

    and modifing the Previous code to be like this :

    DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
    var res = d.ToString("HH:mm tt", CultureInfo.InvariantCulture); // this show  11:12 Pm
    

    InvariantCulture => using default English Format.

    another question I want to have the pm to be in Arabic or specific language, even if I use windows set to English (or other language) regional format?

    Soution for Arabic Exemple :

    DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
    var res = d.ToString("HH:mm tt", CultureInfo.CreateSpecificCulture("ar-AE")); 
    

    this will show // 23:12 ?

    event if my system is set to an English region format. you can change "ar-AE" if you want to another language format. there is a list of each language and its format.

    exemples : ar ar-SA Arabic ar-BH ar-BH Arabic (Bahrain) ar-DZ ar-DZ Arabic (Algeria) ar-EG ar-EG Arabic (Egypt)

    Thymeleaf: how to use conditionals to dynamically add/remove a CSS class

    There is also th:classappend.

    <a href="" class="baseclass" th:classappend="${isAdmin} ? adminclass : userclass"></a>
    

    If isAdmin is true, then this will result in:

    <a href="" class="baseclass adminclass"></a>
    

    C++ Object Instantiation

    Though having things on the stack might be an advantage in terms of allocation and automatic freeing, it has some disadvantages.

    1. You might not want to allocate huge objects on the Stack.

    2. Dynamic dispatch! Consider this code:

    #include <iostream>
    
    class A {
    public:
      virtual void f();
      virtual ~A() {}
    };
    
    class B : public A {
    public:
      virtual void f();
    };
    
    void A::f() {cout << "A";}
    void B::f() {cout << "B";}
    
    int main(void) {
      A *a = new B();
      a->f();
      delete a;
      return 0;
    }
    

    This will print "B". Now lets see what happens when using Stack:

    int main(void) {
      A a = B();
      a.f();
      return 0;
    }
    

    This will print "A", which might not be intuitive to those who are familiar with Java or other object oriented languages. The reason is that you don't have a pointer to an instance of B any longer. Instead, an instance of B is created and copied to a variable of type A.

    Some things might happen unintuitively, especially when you are new to C++. In C you have your pointers and that's it. You know how to use them and they do ALWAYS the same. In C++ this is not the case. Just imagine what happens, when you use a in this example as an argument for a method - things get more complicated and it DOES make a huge difference if a is of type A or A* or even A& (call-by-reference). Many combinations are possible and they all behave differently.

    Tomcat Servlet: Error 404 - The requested resource is not available

    My problem was in web.xml file. In one <servlet-mapping> there was an error inside <url-pattern>: I forgot to add / before url.

    Call to getLayoutInflater() in places not in activity

    Using context object you can get LayoutInflater from following code

    LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    

    public static const in TypeScript

    If you did want something that behaved more like a static constant value in modern browsers (in that it can't be changed by other code), you could add a get only accessor to the Library class (this will only work for ES5+ browsers and NodeJS):

    export class Library {
        public static get BOOK_SHELF_NONE():string { return "None"; }
        public static get BOOK_SHELF_FULL():string { return "Full"; }   
    }
    
    var x = Library.BOOK_SHELF_NONE;
    console.log(x);
    Library.BOOK_SHELF_NONE = "Not Full";
    x = Library.BOOK_SHELF_NONE;
    console.log(x);
    

    If you run it, you'll see how the attempt to set the BOOK_SHELF_NONE property to a new value doesn't work.

    2.0

    In TypeScript 2.0, you can use readonly to achieve very similar results:

    export class Library {
        public static readonly BOOK_SHELF_NONE = "None";
        public static readonly BOOK_SHELF_FULL = "Full";
    }
    

    The syntax is a bit simpler and more obvious. However, the compiler prevents changes rather than the run time (unlike in the first example, where the change would not be allowed at all as demonstrated).

    ojdbc14.jar vs. ojdbc6.jar

    Also, from ojdbc14 to ojdbc6, several types (e.g., OracleResultSet, OracleStatement) moved from package oracle.jdbc.driver to oracle.jdbc.

    Qt jpg image display

    1. Add Label (a QLabel) to the dialog where you want to show the image. This QLabel will actually display the image. Resize it to the size you want the image to appear.

    2. Add the image to your resources in your project.

    3. Now go into QLabel properties and select the image you added to resources for pixmap property. Make sure to check the next property scaledContents to shrink the image in the size you want to see it.

    That's all, the image will now show up.

    How to launch jQuery Fancybox on page load?

    Window.load (as opposed to document.ready()) appears to the be the trick used in the JSFiddler onload demos of Fancybox 2.0:

    $(window).load(function()
    {
        $.fancybox("test");
    });
    

    Bare in mind you may be using document.ready() elsewhere, and IE9 gets upset with the load order of the two. This leaves you with two options: change everything to window.load or use a setTimer().

    How to configure Spring Security to allow Swagger URL to be accessed without authentication

    More or less this page has answers but all are not at one place. I was dealing with the same issue and spent quite a good time on it. Now i have a better understanding and i would like to share it here:

    I Enabling Swagger ui with Spring websecurity:

    If you have enabled Spring Websecurity by default it will block all the requests to your application and returns 401. However for the swagger ui to load in the browser swagger-ui.html makes several calls to collect data. The best way to debug is open swagger-ui.html in a browser(like google chrome) and use developer options('F12' key ). You can see several calls made when the page loads and if the swagger-ui is not loading completely probably some of them are failing.

    you may need to tell Spring websecurity to ignore authentication for several swagger path patterns. I am using swagger-ui 2.9.2 and in my case below are the patterns that i had to ignore:

    However if you are using a different version your's might change. you may have to figure out yours with developer option in your browser as i said before.

    @Configuration
    public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", 
                "/swagger-resources/**", "/configuration/**", "/swagger-ui.html"
                , "/webjars/**", "/csrf", "/");
    }
    }
    

    II Enabling swagger ui with interceptor

    Generally you may not want to intercept requests that are made by swagger-ui.html. To exclude several patterns of swagger below is the code:

    Most of the cases pattern for web security and interceptor will be same.

    @Configuration
    @EnableWebMvc
    public class RetrieveCiamInterceptorConfiguration implements WebMvcConfigurer {
    
    @Autowired
    RetrieveInterceptor validationInterceptor;
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    
        registry.addInterceptor(validationInterceptor).addPathPatterns("/**")
        .excludePathPatterns("/v2/api-docs", "/configuration/ui", 
                "/swagger-resources/**", "/configuration/**", "/swagger-ui.html"
                , "/webjars/**", "/csrf", "/");
    }
    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
          .addResourceLocations("classpath:/META-INF/resources/");
    
        registry.addResourceHandler("/webjars/**")
          .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
    
    }
    

    Since you may have to enable @EnableWebMvc to add interceptors you may also have to add resource handlers to swagger similar to i have done in the above code snippet.

    Lua String replace

    Try:

    name = "^aH^ai"
    name = name:gsub("%^a", "")
    

    See also: http://lua-users.org/wiki/StringLibraryTutorial

    conversion from infix to prefix

    here is an java implementation for convert infix to prefix and evaluate prefix expression (based on rajdip's algorithm)

    import java.util.*;
    
    public class Expression {
        private static int isp(char token){
            switch (token){
                case '*':
                case '/':
                    return 2;
                case '+':
                case '-':
                    return 1;
                default:
                    return -1;
            }
        }
        private static double calculate(double oprnd1,double oprnd2,char oprt){
            switch (oprt){
                case '+':
                    return oprnd1+oprnd2;
                case '*':
                    return oprnd1*oprnd2;
                case '/':
                    return oprnd1/oprnd2;
                case '-':
                    return oprnd1-oprnd2;
                default:
                    return 0;
            }
        }
        public static String infix2prefix(String infix) {
            Stack<String> OperandStack = new Stack<>();
            Stack<Character> OperatorStack = new Stack<>();
            for(char token:infix.toCharArray()){
                if ('a' <= token && token <= 'z')
                    OperandStack.push(String.valueOf(token));
                else if (token == '(' || OperatorStack.isEmpty() || isp(token) > isp(OperatorStack.peek()))
                    OperatorStack.push(token);
                else if(token == ')'){
                    while (OperatorStack.peek() != '(') {
                        Character operator = OperatorStack.pop();
                        String RightOperand = OperandStack.pop();
                        String LeftOperand = OperandStack.pop();
                        String operand = operator + LeftOperand + RightOperand;
                        OperandStack.push(operand);
                    }
                    OperatorStack.pop();
                }
                else if(isp(token) <= isp(OperatorStack.peek())){
                    while (!OperatorStack.isEmpty() && isp(token)<= isp(OperatorStack.peek())) {
                        Character operator = OperatorStack.pop();
                        String RightOperand = OperandStack.pop();
                        String LeftOperand = OperandStack.pop();
                        String operand = operator + LeftOperand + RightOperand;
                        OperandStack.push(operand);
                    }
                    OperatorStack.push(token);
                }
            }
            while (!OperatorStack.isEmpty()){
                Character operator = OperatorStack.pop();
                String RightOperand = OperandStack.pop();
                String LeftOperand = OperandStack.pop();
                String operand = operator + LeftOperand + RightOperand;
                OperandStack.push(operand);
            }
            return OperandStack.pop();
        }
        public static double evaluatePrefix(String prefix, Map values){
            Stack<Double> stack = new Stack<>();
            prefix = new StringBuffer(prefix).reverse().toString();
            for (char token:prefix.toCharArray()){
                if ('a'<=token && token <= 'z')
                    stack.push((double) values.get(token));
                else {
                    double oprnd1 = stack.pop();
                    double oprnd2 = stack.pop();
                    stack.push(calculate(oprnd1,oprnd2,token));
                }
            }
            return stack.pop();
        }
        public static void main(String[] args) {
            Map dictionary = new HashMap<>();
            dictionary.put('a',2.);
            dictionary.put('b',3.);
            dictionary.put('c',2.);
            dictionary.put('d',5.);
            dictionary.put('e',16.);
            dictionary.put('f',4.);
            dictionary.put('g',7.);
            String s = "((a+b)/(c-d)+e)*f-g";
            System.out.println(evaluatePrefix(infix2prefix(s),dictionary));
        }
    }
    

    How do I use .toLocaleTimeString() without displaying seconds?

    You can try this, which is working for my needs.

    var d = new Date();
    d.toLocaleTimeString().replace(/:\d{2}\s/,' ');
    

    or

    d.toLocaleString().replace(/:\d{2}\s/,' ');
    

    JavaScript: How do I print a message to the error console?

    If you are using Firebug and need to support IE, Safari or Opera as well, Firebug Lite adds console.log() support to these browsers.

    Difference between try-catch and throw in java

    try block contains set of statements where an exception can occur.

    catch block will be used to used to handle the exception that occur with in try block. A try block is always followed by a catch block and we can have multiple catch blocks.

    finally block is executed after catch block. We basically use it to put some common code when there are multiple catch blocks. Even if there is an exception or not finally block gets executed.

    throw keyword will allow you to throw an exception and it is used to transfer control from try block to catch block.

    throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself.

    // Java program to demonstrate working of throws, throw, try, catch and finally.

     public class MyExample { 
          
            static void myMethod() throws IllegalAccessException 
            { 
                System.out.println("Inside myMethod()."); 
                throw new IllegalAccessException("demo"); 
            } 
          
            // This is a caller function  
            public static void main(String args[]) 
            { 
                try { 
                    myMethod(); 
                } 
                catch (IllegalAccessException e) { 
                    System.out.println("exception caught in main method."); 
                }
                finally(){
                    System.out.println("I am in final block.");
                } 
            } 
        } 
    

    Output:

    Inside myMethod().
    exception caught in main method.
    I am in final block.
    

    height style property doesn't work in div elements

    You try to set the height property of an inline element, which is not possible. You can try to make it a block element, or perhaps you meant to alter the line-height property?

    Regex to remove all special characters from string?

    tmp = Regex.Replace(n, @"\W+", "");
    

    \w matches letters, digits, and underscores, \W is the negated version.

    How to sum a list of integers with java streams?

    From the docs

    Reduction operations A reduction operation (also called a fold) takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation, such as finding the sum or maximum of a set of numbers, or accumulating elements into a list. The streams classes have multiple forms of general reduction operations, called reduce() and collect(), as well as multiple specialized reduction forms such as sum(), max(), or count().

    Of course, such operations can be readily implemented as simple sequential loops, as in:

    int sum = 0;
    for (int x : numbers) {
       sum += x;
    }
    

    However, there are good reasons to prefer a reduce operation over a mutative accumulation such as the above. Not only is a reduction "more abstract" -- it operates on the stream as a whole rather than individual elements -- but a properly constructed reduce operation is inherently parallelizable, so long as the function(s) used to process the elements are associative and stateless. For example, given a stream of numbers for which we want to find the sum, we can write:

    int sum = numbers.stream().reduce(0, (x,y) -> x+y);
    

    or:

    int sum = numbers.stream().reduce(0, Integer::sum);
    

    These reduction operations can run safely in parallel with almost no modification:

    int sum = numbers.parallelStream().reduce(0, Integer::sum);
    

    So, for a map you would use:

    integers.values().stream().mapToInt(i -> i).reduce(0, (x,y) -> x+y);
    

    Or:

    integers.values().stream().reduce(0, Integer::sum);
    

    Unable to import a module that is definitely installed

    If the other answers mentioned do not work for you, try deleting your pip cache and reinstalling the package. My machine runs Ubuntu14.04 and it was located under ~/.cache/pip. Deleting this folder did the trick for me.

    Changing default startup directory for command prompt in Windows 7

    My default dir was system32 when starting CMD. I then created a batch file in that directory to change dir to the one I was after.

    This caused me to always call that bat when starting CMD every time. So I made a reg file & put this inside:

    Windows Registry Editor Version 5.00
    
    [HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
    "Autorun"="cd C:\\Users\\Me\\SomeFolder"
    
    

    After saving it, I opened the file, clicked ok to merge with registry, and since then every time I open CMD, I get my dir

    MySQL joins and COUNT(*) from another table

    Your groups_main table has a key column named id. I believe you can only use the USING syntax for the join if the groups_fans table has a key column with the same name, which it probably does not. So instead, try this:

    LEFT JOIN groups_fans AS m ON m.group_id = g.id

    Or replace group_id with whatever the appropriate column name is in the groups_fans table.

    How to pretty print XML from Java?

    Just for future reference, here's a solution that worked for me (thanks to a comment that @George Hawkins posted in one of the answers):

    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
    LSSerializer writer = impl.createLSSerializer();
    writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
    LSOutput output = impl.createLSOutput();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    output.setByteStream(out);
    writer.write(document, output);
    String xmlStr = new String(out.toByteArray());
    

    jquery $.each() for objects

    You are indeed passing the first data item to the each function.

    Pass data.programs to the each function instead. Change the code to as below:

    <script>     
        $(document).ready(function() {         
            var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };         
            $.each(data.programs, function(key,val) {             
                alert(key+val);         
            });     
        }); 
    </script> 
    

    How to make div go behind another div?

    You need to add z-index to the divs, with a positive number for the top div and negative for the div below

    example

    Routing for custom ASP.NET MVC 404 Error page

    Just add catch all route at the end of the routes table and display whatever page you want with it.

    See: How can i make a catch all route to handle '404 page not found' queries for ASP.NET MVC?

    How to access Session variables and set them in javascript?

    Javascript can not directly set session values. For setting session values from javascript I do ajax call as follows.

    Check Online

    At ASPx file or html,

     <script type="text/javascript">
     $(function(){
       //Getting values from session and saving in javascript variable.
       // But this will be executed only at document.ready.
       var firstName = '<%= Session["FirstName"] ?? "" %>';
       var lastName = '<%= Session["LastName"] ?? "" %>';
    
       $("#FirstName").val(firstName);
       $("#LastName").val(lastName);
    
       $('Button').click(function(){
         //Posting values to save in session
         $.post(document.URL+'?mode=ajax', 
         {'FirstName':$("#FirstName").val(),
         'LastName':$("#LastName").val()
         } );
       });
    
     });
    

    At Server side,

    protected void Page_Load(object sender, EventArgs e)
     {
          if(Request.QueryString["mode"] != null && Request.QueryString["mode"] == "ajax")
          {
            //Saving the variables in session. Variables are posted by ajax.
            Session["FirstName"] = Request.Form["FirstName"] ?? "";
            Session["LastName"] = Request.Form["LastName"] ?? "";
          }
     }
    

    For getting session values, as said by Shekhar and Rajeev

    var firstName = '<%= Session["FirstName"] ?? "" %>';
    

    Hope this helps.

    How to print out a variable in makefile

    from a "Mr. Make post" https://www.cmcrossroads.com/article/printing-value-makefile-variable

    Add the following rule to your Makefile:

    print-%  : ; @echo $* = $($*)
    

    Then, if you want to find out the value of a makefile variable, just:

    make print-VARIABLE
    

    and it will return:

    VARIABLE = the_value_of_the_variable
    

    Auto increment primary key in SQL Server Management Studio 2012

    You have to expand the Identity section to expose increment and seed.

    enter image description here

    Edit: I assumed that you'd have an integer datatype, not char(10). Which is reasonable I'd say and valid when I posted this answer

    How to replace string in Groovy

    You need to escape the backslash \:

    println yourString.replace("\\", "/")
    

    I get Access Forbidden (Error 403) when setting up new alias

    I just found the same issue with Aliases on a Windows install of Xampp.

    To solve the 403 error:

    <Directory "C:/Your/Directory/With/No/Trailing/Slash">
       Require all granted
    </Directory>
    
    Alias /dev "C:/Your/Directory/With/No/Trailing/Slash"
    

    The default Xampp set up should be fine with just this. Some people have experienced issues with a deny placed on the root directory so flipping out the directory tag to:

    <Directory "C:/Your/Directory/With/No/Trailing/Slash">
       Allow from all
       Require all granted
    </Directory>
    

    Would help with this but the current version of Xampp (v1.8.1 at the time of writing) doesn't require it.

    As for op's issue with port 80 Xampp includes a handy Netstat button to discover what's using your ports. Fire that off and fix the conflict, I imagine it could have been IIS but can't be sure.

    How to measure time elapsed on Javascript?

    var seconds = 0;
    setInterval(function () {
      seconds++;
    }, 1000);
    

    There you go, now you have a variable counting seconds elapsed. Since I don't know the context, you'll have to decide whether you want to attach that variable to an object or make it global.

    Set interval is simply a function that takes a function as it's first parameter and a number of milliseconds to repeat the function as it's second parameter.

    You could also solve this by saving and comparing times.

    EDIT: This answer will provide very inconsistent results due to things such as the event loop and the way browsers may choose to pause or delay processing when a page is in a background tab. I strongly recommend using the accepted answer.

    CSS ''background-color" attribute not working on checkbox inside <div>

    In addition to the currently accepted answer: You can set border and background of a checkbox/radiobutton, but how it is rendered in the end depends on the browser. For example, if you set a red background on a checkbox

    • IE will show a red border instead
    • Opera will show a red background as intended
    • Firefox, Safari and Chrome will do nothing

    This German language article compares a few browsers and explains at least the IE behavior. It maybe bit older (still including Netscape), but when you test around you'll notice that not much has changed. Another comparison can be found here.

    Typing Greek letters etc. in Python plots

    You need to make the strings raw and use latex:

    fig.gca().set_ylabel(r'$\lambda$')
    

    As of matplotlib 2.0 the default font supports most western alphabets and can simple do

    ax.set_xlabel('?')
    

    with unicode.

    How to check if element has any children in Javascript?

    As slashnick & bobince mention, hasChildNodes() will return true for whitespace (text nodes). However, I didn't want this behaviour, and this worked for me :)

    element.getElementsByTagName('*').length > 0
    

    Edit: for the same functionality, this is a better solution:

     element.children.length > 0
    

    children[] is a subset of childNodes[], containing elements only.

    Compatibility

    Notice: Undefined variable: _SESSION in "" on line 9

    Add

    session_start();
    

    at the beginning of your page before any HTML

    You will have something like :

    <?php session_start();
    include("inc/incfiles/header.inc.php")?>
    <html>
    <head>
    <meta http-equiv="Content-Type" conte...
    

    Don't forget to remove the space you have before

    Update Git submodule to latest commit on origin

    If you are looking to checkout master branch for each submodule -- you can use the following command for that purpose:

    git submodule foreach git checkout master
    

    What are Bearer Tokens and token_type in OAuth 2?

    From RFC 6750, Section 1.2:

    Bearer Token

    A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).

    The Bearer Token or Refresh token is created for you by the Authentication server. When a user authenticates your application (client) the authentication server then goes and generates for your a Bearer Token (refresh token) which you can then use to get an access token.

    The Bearer Token is normally some kind of cryptic value created by the authentication server, it isn't random it is created based upon the user giving you access and the client your application getting access.

    See also: Mozilla MDN Header Information.