Programs & Examples On #Obliterate

How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries

If you need to open XLS files rather than XLSX files, http://npoi.codeplex.com/ is a great choice. We've used it to good effect on our projects.

Unit test naming best practices

I recently came up with the following convention for naming my tests, their classes and containing projects in order to maximize their descriptivenes:

Lets say I am testing the Settings class in a project in the MyApp.Serialization namespace.

First I will create a test project with the MyApp.Serialization.Tests namespace.

Within this project and of course the namespace I will create a class called IfSettings (saved as IfSettings.cs).

Lets say I am testing the SaveStrings() method. -> I will name the test CanSaveStrings().

When I run this test it will show the following heading:

MyApp.Serialization.Tests.IfSettings.CanSaveStrings

I think this tells me very well, what it is testing.

Of course it is usefull that in English the noun "Tests" is the same as the verb "tests".

There is no limit to your creativity in naming the tests, so that we get full sentence headings for them.

Usually the Test names will have to start with a verb.

Examples include:

  • Detects (e.g. DetectsInvalidUserInput)
  • Throws (e.g. ThrowsOnNotFound)
  • Will (e.g. WillCloseTheDatabaseAfterTheTransaction)

etc.

Another option is to use "that" instead of "if".

The latter saves me keystrokes though and describes more exactly what I am doing, since I don't know, that the tested behavior is present, but am testing if it is.

[Edit]

After using above naming convention for a little longer now, I have found, that the If prefix can be confusing, when working with interfaces. It just so happens, that the testing class IfSerializer.cs looks very similar to the interface ISerializer.cs in the "Open Files Tab". This can get very annoying when switching back and forth between the tests, the class being tested and its interface. As a result I would now choose That over If as a prefix.

Additionally I now use - only for methods in my test classes as it is not considered best practice anywhere else - the "_" to separate words in my test method names as in:

[Test] public void detects_invalid_User_Input()

I find this to be easier to read.

[End Edit]

I hope this spawns some more ideas, since I consider naming tests of great importance as it can save you a lot of time that would otherwise have been spent trying to understand what the tests are doing (e.g. after resuming a project after an extended hiatus).

What's the difference between <mvc:annotation-driven /> and <context:annotation-config /> in servlet?

mvc:annotation-driven is a tag added in Spring 3.0 which does the following:

  1. Configures the Spring 3 Type ConversionService (alternative to PropertyEditors)
  2. Adds support for formatting Number fields with @NumberFormat
  3. Adds support for formatting Date, Calendar, and Joda Time fields with @DateTimeFormat, if Joda Time is on the classpath
  4. Adds support for validating @Controller inputs with @Valid, if a JSR-303 Provider is on the classpath
  5. Adds support for support for reading and writing XML, if JAXB is on the classpath (HTTP message conversion with @RequestBody/@ResponseBody)
  6. Adds support for reading and writing JSON, if Jackson is o n the classpath (along the same lines as #5)

context:annotation-config Looks for annotations on beans in the same application context it is defined and declares support for all the general annotations like @Autowired, @Resource, @Required, @PostConstruct etc etc.

Importing modules from parent folder

Relative imports (as in from .. import mymodule) only work in a package. To import 'mymodule' that is in the parent directory of your current module:

import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir) 

import mymodule

edit: the __file__ attribute is not always given. Instead of using os.path.abspath(__file__) I now suggested using the inspect module to retrieve the filename (and path) of the current file

Displaying a Table in Django from Database

If you want to table do following steps:-

views.py:

def view_info(request):
    objs=Model_name.objects.all()
    ............
    return render(request,'template_name',{'objs':obj})

.html page

 {% for item in objs %}
    <tr> 
         <td>{{ item.field1 }}</td>
         <td>{{ item.field2 }}</td>
         <td>{{ item.field3 }}</td>
         <td>{{ item.field4 }}</td>
    </tr>
       {% endfor %}

Javascript validation: Block special characters

Try this one, this function allows alphanumeric and spaces:

function alpha(e) {
    var k;
    document.all ? k = e.keyCode : k = e.which;
    return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57));
}

in your html:

<input type="text" name="name"  onkeypress="return alpha(event)"/>

Can you animate a height change on a UITableViewCell when selected?

Instead of beginUpdates()/endUpdates(), the recommended call is now:

tableView.performBatchUpdates(nil, completion: nil)

Apple says, regarding beginUpdates/endUpdates: "Use the performBatchUpdates(_:completion:) method instead of this one whenever possible."

See: https://developer.apple.com/documentation/uikit/uitableview/1614908-beginupdates

get current page from url

Path.GetFileName( Request.Url.AbsolutePath )

TypeError: tuple indices must be integers, not str

SQlite3 has a method named row_factory. This method would allow you to access the values by column name.

https://www.kite.com/python/examples/3884/sqlite3-use-a-row-factory-to-access-values-by-column-name

C#: Converting byte array to string and printing out to console

For some fun with linq and string interpolation:

public string ByteArrayToString(byte[] bytes)
{
    if ( bytes == null ) return "null";
    string joinedBytes = string.Join(", ", bytes.Select(b => b.ToString()));
    return $"new byte[] {{ {joinedBytes} }}";
}

Test cases:

byte[] bytes = { 1, 2, 3, 4 };
ByteArrayToString( bytes ) .Dump();
ByteArrayToString(null).Dump();
ByteArrayToString(new byte[] {} ) .Dump();

Output:

new byte[] { 1, 2, 3, 4 }
null
new byte[] {  }

Adding rows dynamically with jQuery

I have Tried something like this and its works fine;

enter image description here

this is the html part :

<table class="dd" width="100%" id="data">
<tr>
<td>Year</td>
<td>:</td>
<td><select name="year1" id="year1" >
<option value="2012">2012</option>
<option value="2011">2011</option>
</select></td>
<td>Month</td>
<td>:</td>
<td width="17%"><select name="month1" id="month1">
  <option value="1">January</option>
  <option value="2">February</option>
  <option value="3">March</option>
  <option value="4">April</option>
  <option value="5">May</option>
  <option value="6">June</option>
  <option value="7">July</option>
  <option value="8">August</option>
  <option value="9">September</option>
  <option value="10">October</option>
  <option value="11">November</option>
  <option value="12">December</option>
</select></td>
<td width="7%">Week</td>
<td width="3%">:</td>
<td width="17%"><select name="week1" id="week1" >
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select></td>
<td width="8%">&nbsp;</td>
<td colspan="2">&nbsp;</td>
</tr>
<tr>
<td>Actual</td>
<td>:</td>
<td width="17%"><input name="actual1" id="actual1" type="text" /></td>
<td width="7%">Max</td>
<td width="3%">:</td>
<td><input name="max1" id="max1" type="text" /></td>
<td>Target</td>
<td>:</td>
<td><input name="target1" id="target1" type="text" /></td>
</tr>

this is Javascript part;

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type='text/javascript'>
//<![CDATA[
$(document).ready(function() {
var currentItem = 1;
$('#addnew').click(function(){
currentItem++;
$('#items').val(currentItem);
var strToAdd = '<tr><td>Year</td><td>:</td><td><select name="year'+currentItem+'" id="year'+currentItem+'" ><option value="2012">2012</option><option value="2011">2011</option></select></td><td>Month</td><td>:</td><td width="17%"><select name="month'+currentItem+'" id="month'+currentItem+'"><option value="1">January</option><option value="2">February</option><option value="3">March</option><option value="4">April</option><option value="5">May</option><option value="6">June</option><option value="7">July</option><option value="8">August</option><option value="9">September</option><option value="10">October</option><option value="11">November</option><option value="12">December</option></select></td><td width="7%">Week</td><td width="3%">:</td><td width="17%"><select name="week'+currentItem+'" id="week'+currentItem+'" ><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option></select></td><td width="8%"></td><td colspan="2"></td></tr><tr><td>Actual</td><td>:</td><td width="17%"><input name="actual'+currentItem+'" id="actual'+currentItem+'" type="text" /></td><td width="7%">Max</td> <td width="3%">:</td><td><input name="max'+currentItem+'" id ="max'+currentItem+'"type="text" /></td><td>Target</td><td>:</td><td><input name="target'+currentItem+'" id="target'+currentItem+'" type="text" /></td></tr>';
  $('#data').append(strToAdd);

 });
 });

 //]]>
 </script>

Finaly PHP submit part:

    for( $i = 1; $i <= $count; $i++ )
{
    $year = $_POST['year'.$i];
    $month = $_POST['month'.$i];
    $week = $_POST['week'.$i];
    $actual = $_POST['actual'.$i];
    $max = $_POST['max'.$i];
    $target = $_POST['target'.$i];
    $extreme = $_POST['extreme'.$i];
    $que = "insert INTO table_name(id,year,month,week,actual,max,target) VALUES ('".$_POST['type']."','".$year."','".$month."','".$week."','".$actual."','".$max."','".$target."')";
    mysql_query($que);

}

you can find more details via Dynamic table row inserter

html/css buttons that scroll down to different div sections on a webpage

try this:

<input type="button" onClick="document.getElementById('middle').scrollIntoView();" />

<div style display="none" > inside a table not working

Semantically what you are trying is invalid html, table element cannot have a div element as a direct child. What you can do is, get your div element inside a td element and than try to hide it

Is there a way to get the XPath in Google Chrome?

For Chrome, for instance:

  1. Right-click "inspect" on the item you are trying to find the XPath.
  2. Right-click on the highlighted area on the HTML DOM.
  3. Go to Copy > select 'Copy XPath'.
  4. After the above step, you will get the absolute XPath of the element from DOM.
  5. You can make changes to make it relative XPath (because if the DOM changes, still your XPath would be able to find the element).

a. To do so, by opening the 'Elements' panel of the browser, press CTRL+F, paste the XPath.

b. Make changes as describes in the following example.

Absolute xpath = //*[@id="app"]/div[1]/header/nav/div[2]/ul/li[2]/div/button

Related xpath = //div//nav/div[2]/ul/li[2]/div/button

When you make changes:

  1. make sure the XPath is unique within the DOM.
  2. still the web element is selected on the DOM and on the webpage.

Understanding dict.copy() - shallow or deep?

It's not a matter of deep copy or shallow copy, none of what you're doing is deep copy.

Here:

>>> new = original 

you're creating a new reference to the the list/dict referenced by original.

while here:

>>> new = original.copy()
>>> # or
>>> new = list(original) # dict(original)

you're creating a new list/dict which is filled with a copy of the references of objects contained in the original container.

force css grid container to fill full screen of device

Two important CSS properties to set for full height pages are these:

  1. Allow the body to grow as high as the content in it requires.

    html { height: 100%; }
    
  2. Force the body not to get any smaller than then window height.

    body { min-height: 100%; }
    

What you do with your gird is irrelevant as long as you use fractions or percentages you should be safe in all cases.

Have a look at this common dashboard layout.

How to change the docker image installation directory?

On Fedora 26 and probably many other versions, you may encounter an error after moving your base folder location as described above. This is particularly true if you are moving it to somewhere under /home. This is because SeLinux kicks in and prevents the docker container from running many of its programs from under this location.

The short solution is to remove the --enable-selinux option when you add the -g parameter.

Angularjs $http.get().then and binding to a list

Actually you get promise on $http.get.

Try to use followed flow:

<li ng-repeat="document in documents" ng-class="IsFiltered(document.Filtered)">
    <span><input type="checkbox" name="docChecked" id="doc_{{document.Id}}" ng-model="document.Filtered" /></span>
    <span>{{document.Name}}</span>
</li>

Where documents is your array.

$scope.documents = [];

$http.get('/Documents/DocumentsList/' + caseId).then(function(result) {
    result.data.forEach(function(val, i) { 
        $scope.documents.push(/* put data here*/);
    });
}, function(error) {
    alert(error.message);
});                       

React.js inline style best practices

Some time we require to style some element from a component but if we have to display that component only ones or the style is so less then instead of using the CSS class we go for the inline style in react js. reactjs inline style is as same as HTML inline style just the property names are a little bit different

Write your style in any tag using style={{prop:"value"}}

import React, { Component } from "react";
    import { Redirect } from "react-router";

    class InlineStyle extends Component {
      constructor(props) {
        super(props);
        this.state = {};
      }

      render() {
        return (
          <div>
            <div>
              <div
                style={{
                  color: "red",
                  fontSize: 40,
                  background: "green"
                }}// this is inline style in reactjs
              >

              </div>
            </div>
          </div>
        );
      }
    }
    export default InlineStyle;

How do I determine the size of an object in Python?

This can be more complicated than it looks depending on how you want to count things. For instance, if you have a list of ints, do you want the size of the list containing the references to the ints? (ie. list only, not what is contained in it), or do you want to include the actual data pointed to, in which case you need to deal with duplicate references, and how to prevent double-counting when two objects contain references to the same object.

You may want to take a look at one of the python memory profilers, such as pysizer to see if they meet your needs.

Different CURRENT_TIMESTAMP and SYSDATE in oracle

Note: SYSDATE - returns only date, i.e., "yyyy-mm-dd" is not correct. SYSDATE returns the system date of the database server including hours, minutes, and seconds. For example:

SELECT SYSDATE FROM DUAL; will return output similar to the following: 12/15/2017 12:42:39 PM

HTML form do some "action" when hit submit button

index.html

<!DOCTYPE html>
<html>
   <body>
       <form action="submit.php" method="POST">
         First name: <input type="text" name="firstname" /><br /><br />
         Last name: <input type="text" name="lastname" /><br />
         <input type="submit" value="Submit" />
      </form> 
   </body>
</html>

After that one more file which page you want to display after pressing the submit button

submit.php

<html>
  <body>

    Your First Name is -  <?php echo $_POST["firstname"]; ?><br>
    Your Last Name is -   <?php echo $_POST["lastname"]; ?>

  </body>
</html>

Looping through list items with jquery

Try this:

listItems = $("#productList").find("li").each(function(){
   var product = $(this);
   // rest of code.
});

Format cell if cell contains date less than today

=$W$4<=TODAY()

Returns true for dates up to and including today, false otherwise.

How do I reference a local image in React?

You have two ways to do it.

First

Import the image on top of the class and then reference it in your <img/> element like this

_x000D_
_x000D_
import React, { Component } from 'react';
import myImg from '../path/myImg.svg';

export default class HelloImage extends Component {
  render() {
    return <img src={myImg} width="100" height="50" /> 
  }
} 
_x000D_
_x000D_
_x000D_

Second

You can directly specify the image path using require('../pathToImh/img') in <img/> element like this

_x000D_
_x000D_
import React, { Component } from 'react'; 

export default class HelloImage extends Component {
  render() {
    return <img src={require(../path/myImg.svg)} width="100" height="50" /> 
  }
}
_x000D_
_x000D_
_x000D_

Java TreeMap Comparator

The comparator should be only for the key, not for the whole entry. It sorts the entries based on the keys.

You should change it to something as follows

SortedMap<String, Double> myMap = 
    new TreeMap<String, Double>(new Comparator<String>()
    {
        public int compare(String o1, String o2)
        {
            return o1.compareTo(o2);
        } 
});

Update

You can do something as follows (create a list of entries in the map and sort the list base on value, but note this not going to sort the map itself) -

List<Map.Entry<String, Double>> entryList = new ArrayList<Map.Entry<String, Double>>(myMap.entrySet());
    Collections.sort(entryList, new Comparator<Map.Entry<String, Double>>() {
        @Override
        public int compare(Entry<String, Double> o1, Entry<String, Double> o2) {
            return o1.getValue().compareTo(o2.getValue());
        }
    });

Best way to create a simple python web service

The simplest way to get a Python script online is to use CGI:

#!/usr/bin/python

print "Content-type: text/html"
print

print "<p>Hello world.</p>"

Put that code in a script that lives in your web server CGI directory, make it executable, and run it. The cgi module has a number of useful utilities when you need to accept parameters from the user.

Html/PHP - Form - Input as array

If is ok for you to index the array you can do this:

<form>
    <input type="text" class="form-control" placeholder="Titel" name="levels[0][level]">
    <input type="text" class="form-control" placeholder="Titel" name="levels[0][build_time]">

    <input type="text" class="form-control" placeholder="Titel" name="levels[1][level]">
    <input type="text" class="form-control" placeholder="Titel" name="levels[1][build_time]">

    <input type="text" class="form-control" placeholder="Titel" name="levels[2][level]">
    <input type="text" class="form-control" placeholder="Titel" name="levels[2][build_time]">
</form>

... to achieve that:

[levels] => Array ( 
  [0] => Array ( 
    [level] => 1 
    [build_time] => 2 
  ) 
  [1] => Array ( 
    [level] => 234 
   [build_time] => 456 
  )
  [2] => Array ( 
    [level] => 111
    [build_time] => 222 
  )
) 

But if you remove one pair of inputs (dynamically, I suppose) from the middle of the form then you'll get holes in your array, unless you update the input names...

Django request.GET

Calling /search/ should result in "you submitted nothing", but calling /search/?q= on the other hand should result in "you submitted u''"

Browsers have to add the q= even when it's empty, because they have to include all fields which are part of the form. Only if you do some DOM manipulation in Javascript (or a custom javascript submit action), you might get such a behavior, but only if the user has javascript enabled. So you should probably simply test for non-empty strings, e.g:

if request.GET.get('q'):
    message = 'You submitted: %r' % request.GET['q']
else:
    message = 'You submitted nothing!'

How to Make Laravel Eloquent "IN" Query?

If you are using Query builder then you may use a blow

DB::table(Newsletter Subscription)
->select('*')
->whereIn('id', $send_users_list)
->get()

If you are working with Eloquent then you can use as below

$sendUsersList = Newsletter Subscription:: select ('*')
                ->whereIn('id', $send_users_list)
                ->get();

Which rows are returned when using LIMIT with OFFSET in MySQL?

It will return 18 results starting on record #9 and finishing on record #26.

Start by reading the query from offset. First you offset by 8, which means you skip the first 8 results of the query. Then you limit by 18. Which means you consider records 9, 10, 11, 12, 13, 14, 15, 16....24, 25, 26 which are a total of 18 records.

Check this out.

And also the official documentation.

Can I change the viewport meta tag in mobile safari on the fly?

This has been answered for the most part, but I will expand...

Step 1

My goal was to enable zoom at certain times, and disable it at others.

// enable pinch zoom
var $viewport = $('head meta[name="viewport"]');    
$viewport.attr('content', 'width=device-width, initial-scale=1, maximum-scale=4');

// ...later...

// disable pinch zoom
$viewport.attr('content', 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no');

Step 2

The viewport tag would update, but pinch zoom was still active!! I had to find a way to get the page to pick up the changes...

It's a hack solution, but toggling the opacity of body did the trick. I'm sure there are other ways to accomplish this, but here's what worked for me.

// after updating viewport tag, force the page to pick up changes           
document.body.style.opacity = .9999;
setTimeout(function(){
    document.body.style.opacity = 1;
}, 1);

Step 3

My problem was mostly solved at this point, but not quite. I needed to know the current zoom level of the page so I could resize some elements to fit on the page (think of map markers).

// check zoom level during user interaction, or on animation frame
var currentZoom = $document.width() / window.innerWidth;

I hope this helps somebody. I spent several hours banging my mouse before finding a solution.

How do I test a single file using Jest?

If you install VSCode plugin Jest Runner

enter image description here

You will have Debug/Run options above every describe and it.

enter image description here

You can open your test file in VSCode and click on one of those options.

How to install python developer package?

If you use yum search you can find the python dev package for your version of python.

For me I was using python 3.5. I ran the following

yum search python | grep devel

Which returned the following

enter image description here

I was then able to install the correct package for my version of python with the following cmd.

sudo yum install python35u-devel.x86_64

This works on centos for ubuntu or debian you would need to use apt-get

What does the shrink-to-fit viewport meta attribute do?

It is Safari specific, at least at time of writing, being introduced in Safari 9.0. From the "What's new in Safari?" documentation for Safari 9.0:

Viewport Changes

Viewport meta tags using "width=device-width" cause the page to scale down to fit content that overflows the viewport bounds. You can override this behavior by adding "shrink-to-fit=no" to your meta tag as shown below. The added value will prevent the page from scaling to fit the viewport.

<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">

In short, adding this to the viewport meta tag restores pre-Safari 9.0 behaviour.

Example

Here's a worked visual example which shows the difference upon loading the page in the two configurations.

The red section is the width of the viewport and the blue section is positioned outside the initial viewport (eg left: 100vw). Note how in the first example the page is zoomed to fit when shrink-to-fit=no is omitted (thus showing the out-of-viewport content) and the blue content remains off screen in the latter example.

The code for this example can be found at https://codepen.io/davidjb/pen/ENGqpv.

Without shrink-to-fit specified

Without shrink-to-fit=no

With shrink-to-fit=no

With shrink-to-fit=no

How to apply Hovering on html area tag?

for complete this script , the function for draw circle ,

    function drawCircle(coordon)
    {
        var coord = coordon.split(',');

        var c = document.getElementById("myCanvas");
        var hdc = c.getContext("2d");
        hdc.beginPath();

        hdc.arc(coord[0], coord[1], coord[2], 0, 2 * Math.PI);
        hdc.stroke();
    }

How do I profile memory usage in Python?

Since the accepted answer and also the next highest voted answer have, in my opinion, some problems, I'd like to offer one more answer that is based closely on Ihor B.'s answer with some small but important modifications.

This solution allows you to run profiling on either by wrapping a function call with the profile function and calling it, or by decorating your function/method with the @profile decorator.

The first technique is useful when you want to profile some third-party code without messing with its source, whereas the second technique is a bit "cleaner" and works better when you are don't mind modifying the source of the function/method you want to profile.

I've also modified the output, so that you get RSS, VMS, and shared memory. I don't care much about the "before" and "after" values, but only the delta, so I removed those (if you're comparing to Ihor B.'s answer).

Profiling code

# profile.py
import time
import os
import psutil
import inspect


def elapsed_since(start):
    #return time.strftime("%H:%M:%S", time.gmtime(time.time() - start))
    elapsed = time.time() - start
    if elapsed < 1:
        return str(round(elapsed*1000,2)) + "ms"
    if elapsed < 60:
        return str(round(elapsed, 2)) + "s"
    if elapsed < 3600:
        return str(round(elapsed/60, 2)) + "min"
    else:
        return str(round(elapsed / 3600, 2)) + "hrs"


def get_process_memory():
    process = psutil.Process(os.getpid())
    mi = process.memory_info()
    return mi.rss, mi.vms, mi.shared


def format_bytes(bytes):
    if abs(bytes) < 1000:
        return str(bytes)+"B"
    elif abs(bytes) < 1e6:
        return str(round(bytes/1e3,2)) + "kB"
    elif abs(bytes) < 1e9:
        return str(round(bytes / 1e6, 2)) + "MB"
    else:
        return str(round(bytes / 1e9, 2)) + "GB"


def profile(func, *args, **kwargs):
    def wrapper(*args, **kwargs):
        rss_before, vms_before, shared_before = get_process_memory()
        start = time.time()
        result = func(*args, **kwargs)
        elapsed_time = elapsed_since(start)
        rss_after, vms_after, shared_after = get_process_memory()
        print("Profiling: {:>20}  RSS: {:>8} | VMS: {:>8} | SHR {"
              ":>8} | time: {:>8}"
            .format("<" + func.__name__ + ">",
                    format_bytes(rss_after - rss_before),
                    format_bytes(vms_after - vms_before),
                    format_bytes(shared_after - shared_before),
                    elapsed_time))
        return result
    if inspect.isfunction(func):
        return wrapper
    elif inspect.ismethod(func):
        return wrapper(*args,**kwargs)

Example usage, assuming the above code is saved as profile.py:

from profile import profile
from time import sleep
from sklearn import datasets # Just an example of 3rd party function call


# Method 1
run_profiling = profile(datasets.load_digits)
data = run_profiling()

# Method 2
@profile
def my_function():
    # do some stuff
    a_list = []
    for i in range(1,100000):
        a_list.append(i)
    return a_list


res = my_function()

This should result in output similar to the below:

Profiling:        <load_digits>  RSS:   5.07MB | VMS:   4.91MB | SHR  73.73kB | time:  89.99ms
Profiling:        <my_function>  RSS:   1.06MB | VMS:   1.35MB | SHR       0B | time:   8.43ms

A couple of important final notes:

  1. Keep in mind, this method of profiling is only going to be approximate, since lots of other stuff might be happening on the machine. Due to garbage collection and other factors, the deltas might even be zero.
  2. For some unknown reason, very short function calls (e.g. 1 or 2 ms) show up with zero memory usage. I suspect this is some limitation of the hardware/OS (tested on basic laptop with Linux) on how often memory statistics are updated.
  3. To keep the examples simple, I didn't use any function arguments, but they should work as one would expect, i.e. profile(my_function, arg) to profile my_function(arg)

How to find EOF through fscanf?

fscanf - "On success, the function returns the number of items successfully read. This count can match the expected number of readings or be less -even zero- in the case of a matching failure. In the case of an input failure before any data could be successfully read, EOF is returned."

So, instead of doing nothing with the return value like you are right now, you can check to see if it is == EOF.

You should check for EOF when you call fscanf, not check the array slot for EOF.

How to trust a apt repository : Debian apt-get update error public key is not available: NO_PUBKEY <id>

I found several posts telling me to run several gpg commands, but they didn't solve the problem because of two things. First, I was missing the debian-keyring package on my system and second I was using an invalid keyserver. Try different keyservers if you're getting timeouts!

Thus, the way I fixed it was:

apt-get install debian-keyring
gpg --keyserver pgp.mit.edu --recv-keys 1F41B907
gpg --armor --export 1F41B907 | apt-key add -

Then running a new "apt-get update" worked flawlessly!

Laravel 5.1 - Checking a Database Connection

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

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

Illegal string offset Warning PHP

There are a lot of great answers here - but I found my issue was quite a bit more simple.

I was trying to run the following command:

$x['name']   = $j['name'];

and I was getting this illegal string error on $x['name'] because I hadn't defined the array first. So I put the following line of code in before trying to assign things to $x[]:

$x = array();

and it worked.

JPA: how do I persist a String into a database field, type MYSQL Text

Since you're using JPA, use the Lob annotation (and optionally the Column annotation). Here is what the JPA specification says about it:

9.1.19 Lob Annotation

A Lob annotation specifies that a persistent property or field should be persisted as a large object to a database-supported large object type. Portable applications should use the Lob annotation when mapping to a database Lob type. The Lob annotation may be used in conjunction with the Basic annotation. A Lob may be either a binary or character type. The Lob type is inferred from the type of the persistent field or property, and except for string and character-based types defaults to Blob.

So declare something like this:

@Lob 
@Column(name="CONTENT", length=512)
private String content;

References

  • JPA 1.0 specification:
    • Section 9.1.19 "Lob Annotation"

flutter remove back button on appbar

A simple way to remove the back button in the AppBar is to set automaticallyImplyLeading to false.

appBar: AppBar(
  title: Text("App Bar without Back Button"),
  automaticallyImplyLeading: false,
),

How does one set up the Visual Studio Code compiler/debugger to GCC?

Ctrl+P and Type "ext install cpptools" it will install everything you need to debug c and c++.

Debugging in VS code is very complete, but if you just need to compile and run: https://code.visualstudio.com/docs/languages/cpp

Look in the debugging section and it will explain everything

Concatenating variables in Bash

Try doing this, there's no special character to concatenate in bash :

mystring="${arg1}12${arg2}endoffile"

explanations

If you don't put brackets, you will ask to concatenate $arg112 + $argendoffile (I guess that's not what you asked) like in the following example :

mystring="$arg112$arg2endoffile"

The brackets are delimiters for the variables when needed. When not needed, you can use it or not.

another solution

(less portable : require bash > 3.1)

$ arg1=foo
$ arg2=bar
$ mystring="$arg1"
$ mystring+="12"
$ mystring+="$arg2"
$ mystring+="endoffile"
$ echo "$mystring"
foo12barendoffile

See http://mywiki.wooledge.org/BashFAQ/013

Which is the best Linux C/C++ debugger (or front-end to gdb) to help teaching programming?

Perhaps it is indirect to gdb (because it's an IDE), but my recommendations would be KDevelop. Being quite spoiled with Visual Studio's debugger (professionally at work for many years), I've so far felt the most comfortable debugging in KDevelop (as hobby at home, because I could not afford Visual Studio for personal use - until Express Edition came out). It does "look something similar to" Visual Studio compared to other IDE's I've experimented with (including Eclipse CDT) when it comes to debugging step-through, step-in, etc (placing break points is a bit awkward because I don't like to use mouse too much when coding, but it's not difficult).

CSS animation delay in repeating

This is what you should do. It should work in that you have a 1 second animation, then a 4 second delay between iterations:

@keyframes barshine {
  0% {
  background-image:linear-gradient(120deg,rgba(255,255,255,0) 0%,rgba(255,255,255,0.25) -5%,rgba(255,255,255,0) 0%);
  }
  20% {
    background-image:linear-gradient(120deg,rgba(255,255,255,0) 10%,rgba(255,255,255,0.25) 105%,rgba(255,255,255,0) 110%);
  }
}
.progbar {
  animation: barshine 5s 0s linear infinite;
}

So I've been messing around with this a lot and you can do it without being very hacky. This is the simplest way to put in a delay between animation iterations that's 1. SUPER EASY and 2. just takes a little logic. Check out this dance animation I've made:

.dance{
  animation-name: dance;
  -webkit-animation-name: dance;

  animation-iteration-count: infinite;
  -webkit-animation-iteration-count: infinite;
  animation-duration: 2.5s;
  -webkit-animation-duration: 2.5s;

  -webkit-animation-delay: 2.5s;
  animation-delay: 2.5s;
  animation-timing-function: ease-in;
  -webkit-animation-timing-function: ease-in;

}
@keyframes dance {
  0% {
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  25% {
    -webkit-transform: rotate(-120deg);
    -moz-transform: rotate(-120deg);
    -o-transform: rotate(-120deg);
    -ms-transform: rotate(-120deg);
    transform: rotate(-120deg);
  }
  50% {
    -webkit-transform: rotate(20deg);
    -moz-transform: rotate(20deg);
    -o-transform: rotate(20deg);
    -ms-transform: rotate(20deg);
    transform: rotate(20deg);
  }
  100% {
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    transform: rotate(0deg);
  }
}

@-webkit-keyframes dance {
  0% {
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  20% {
    -webkit-transform: rotate(20deg);
    -moz-transform: rotate(20deg);
    -o-transform: rotate(20deg);
    -ms-transform: rotate(20deg);
    transform: rotate(20deg);
  }
  40% {
    -webkit-transform: rotate(-120deg);
    -moz-transform: rotate(-120deg);
    -o-transform: rotate(-120deg);
    -ms-transform: rotate(-120deg);
    transform: rotate(-120deg);
  }
  60% {
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  80% {
    -webkit-transform: rotate(-120deg);
    -moz-transform: rotate(-120deg);
    -o-transform: rotate(-120deg);
    -ms-transform: rotate(-120deg);
    transform: rotate(-120deg);
  }
  95% {
    -webkit-transform: rotate(20deg);
    -moz-transform: rotate(20deg);
    -o-transform: rotate(20deg);
    -ms-transform: rotate(20deg);
    transform: rotate(20deg);
  }
}

I actually came here trying to figure out how to put a delay in the animation, when I realized that you just 1. extend the duration of the animation and shirt the proportion of time for each animation. Beore I had them each lasting .5 seconds for the total duration of 2.5 seconds. Now lets say i wanted to add a delay equal to the total duration, so a 2.5 second delay.

You animation time is 2.5 seconds and delay is 2.5, so you change duration to 5 seconds. However, because you doubled the total duration, you'll want to halve the animations proportion. Check the final below. This worked perfectly for me.

@-webkit-keyframes dance {
  0% {
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  10% {
    -webkit-transform: rotate(20deg);
    -moz-transform: rotate(20deg);
    -o-transform: rotate(20deg);
    -ms-transform: rotate(20deg);
    transform: rotate(20deg);
  }
  20% {
    -webkit-transform: rotate(-120deg);
    -moz-transform: rotate(-120deg);
    -o-transform: rotate(-120deg);
    -ms-transform: rotate(-120deg);
    transform: rotate(-120deg);
  }
  30% {
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  40% {
    -webkit-transform: rotate(-120deg);
    -moz-transform: rotate(-120deg);
    -o-transform: rotate(-120deg);
    -ms-transform: rotate(-120deg);
    transform: rotate(-120deg);
  }
  50% {
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    transform: rotate(0deg);
  }
}

In sum:

These are the calcultions you'd probably use to figure out how to change you animation's duration and the % of each part.

desired_duration = x

desired_duration = animation_part_duration1 + animation_part_duration2 + ... (and so on)

desired_delay = y

total duration = x + y

animation_part_duration1_actual = animation_part_duration1 * desired_duration / total_duration

Cannot execute script: Insufficient memory to continue the execution of the program

It might help you! Please see below steps.

sqlcmd -S server-name -d database-name -i script.sql

  • Open cmd.exe as Administrator.
  • Create Documents directory.
  • Put your SQL Script file(script.sql) in the documents folder.
  • Type query with sqlcmd, server-name, database-name and script-file-name as like above highlighted query or below command line screen.

enter image description here

C# Telnet Library

I doubt very much a telnet library will ever be part of the .Net BCL, although you do have almost full socket support so it wouldnt be too hard to emulate a telnet client, Telnet in its general implementation is a legacy and dying technology that where exists generally sits behind a nice new modern facade. In terms of Unix/Linux variants you'll find that out the box its SSH and enabling telnet is generally considered poor practice.

You could check out: http://granados.sourceforge.net/ - SSH Library for .Net http://www.tamirgal.com/home/dev.aspx?Item=SharpSsh

You'll still need to put in place your own wrapper to handle events for feeding in input in a scripted manner.

Call PHP function from Twig template

This worked for me (using Slim Twig-View):

$twig->getEnvironment()->addFilter(
   new \Twig_Filter('md5', function($arg){ return md5($arg); })
);

This creates a new filter named md5 which returns the MD5 checksum of the argument.

Why does viewWillAppear not get called when an app comes back from the background?

Just trying to make it as easy as possible see code below:

- (void)viewDidLoad
{
   [self appWillEnterForeground]; //register For Application Will enterForeground
}


- (id)appWillEnterForeground{ //Application will enter foreground.

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(allFunctions)
                                                 name:UIApplicationWillEnterForegroundNotification
                                               object:nil];
    return self;
}


-(void) allFunctions{ //call any functions that need to be run when application will enter foreground 
    NSLog(@"calling all functions...application just came back from foreground");


}

How to redirect user's browser URL to a different page in Nodejs?

For those who (unlike OP) are using the express lib:

http.get('*',function(req,res){  
    res.redirect('http://exmple.com'+req.url)
})

Matplotlib: Specify format of floats for tick labels

In matplotlib 3.1, you can also use ticklabel_format. To prevents scientific notation without offsets:

plt.gca().ticklabel_format(axis='both', style='plain', useOffset=False)

Use Font Awesome icon as CSS content

Update for FontAwesome 5 Thanks to Aurelien

You need to change the font-family to Font Awesome 5 Brands OR Font Awesome 5 Free, based on the type of icon you are trying to render. Also, do not forget to declare font-weight: 900;

a:before {
   font-family: "Font Awesome 5 Free";
   content: "\f095";
   display: inline-block;
   padding-right: 3px;
   vertical-align: middle;
   font-weight: 900;
}

Demo

You can read the rest of the answer below to understand how it works and to know some workarounds for spacing between icon and the text.


FontAwesome 4 and below

That's the wrong way to use it. Open the font awesome style sheet, go to the class of the font you want to use say fa-phone, copy the content property under that class with the entity, and use it like:

a:before {
    font-family: FontAwesome;
    content: "\f095";
}

Demo

Just make sure that if you are looking to target a specific a tag, then consider using a class instead to make it more specific like:

a.class_name:before {
    font-family: FontAwesome;
    content: "\f095";
}

Using the way above will stick the icon with the remaining text of yours, so if you want to have a bit of space between the two of them, make it display: inline-block; and use some padding-right:

a:before {
    font-family: FontAwesome;
    content: "\f095";
    display: inline-block;
    padding-right: 3px;
    vertical-align: middle;
}

Extending this answer further, since many might be having a requirement to change an icon on hover, so for that, we can write a separate selector and rules for :hover action:

a:hover:before {
    content: "\f099"; /* Code of the icon you want to change on hover */
}

Demo

Now in the above example, icon nudges because of the different size and you surely don't want that, so you can set a fixed width on the base declaration like

a:before {
    /* Other properties here, look in the above code snippets */
    width: 12px; /* add some desired width here to prevent nudge */
}

Demo

What is the Eclipse shortcut for "public static void main(String args[])"?

As bmargulies mentioned:

Preferences>Java>Editor>Templates>New...

enter image description here

enter image description here

Now, type psvm then Ctrl + Space on Mac or Windows.

Why does background-color have no effect on this DIV?

Change it to:

<div style="background-color:black; overflow:hidden;" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
</div>

Basically the outer div only contains floats. Floats are removed from the normal flow. As such the outer div really contains nothing and thus has no height. It really is black but you just can't see it.

The overflow:hidden property basically makes the outer div enclose the floats. The other way to do this is:

<div style="background-color:black" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
<div style="clear:both></div>
</div>

Oh and just for completeness, you should really prefer classes to direct CSS styles.

How do I provide a username and password when running "git clone [email protected]"?

This is an excellent Stack Overflow question, and the answers have been very instructive, such that I was able to resolve an annoying problem I ran into recently.

The organization that I work for uses Atlassian's BitBucket product (not Github), essentially their version of GitHub so that repositories can be secured completely on premise. I was running into a similar problem as @coordinate, in that my password was required for a new repository I checked out. My credentials had been saved globally for all BitBucket projects, so I'm not sure what prompted the loss of credentials.

In short, I was able to enter the following GIT command (supplying only my username), which then prompted Git's Credential Manager to prompt me for the password, which I was then able to save.

git clone https://[email protected]/git/[organization]/[team]/[repository.git]

NOTE: the bracketed directory sub-paths simply refer to internal references, and will vary for you!

How to convert list to string

L = ['L','O','L']
makeitastring = ''.join(map(str, L))

how to parse json using groovy

        def jsonFile = new File('File Path');
        JsonSlurper jsonSlurper = new JsonSlurper();
        def parseJson = jsonSlurper.parse(jsonFile)
        String json = JsonOutput.toJson(parseJson)
        def prettyJson = JsonOutput.prettyPrint(json)
        println(prettyJson)

How to create a floating action button (FAB) in android, using AppCompat v21?

I've generally used xml drawables to create shadow/elevation on a pre-lollipop widget. Here, for example, is an xml drawable that can be used on pre-lollipop devices to simulate the floating action button's elevation.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:top="8px">
    <layer-list>
        <item>
            <shape android:shape="oval">
                <solid android:color="#08000000"/>
                <padding
                    android:bottom="3px"
                    android:left="3px"
                    android:right="3px"
                    android:top="3px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#09000000"/>
                <padding
                    android:bottom="2px"
                    android:left="2px"
                    android:right="2px"
                    android:top="2px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#10000000"/>
                <padding
                    android:bottom="2px"
                    android:left="2px"
                    android:right="2px"
                    android:top="2px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#11000000"/>
                <padding
                    android:bottom="1px"
                    android:left="1px"
                    android:right="1px"
                    android:top="1px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#12000000"/>
                <padding
                    android:bottom="1px"
                    android:left="1px"
                    android:right="1px"
                    android:top="1px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#13000000"/>
                <padding
                    android:bottom="1px"
                    android:left="1px"
                    android:right="1px"
                    android:top="1px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#14000000"/>
                <padding
                    android:bottom="1px"
                    android:left="1px"
                    android:right="1px"
                    android:top="1px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#15000000"/>
                <padding
                    android:bottom="1px"
                    android:left="1px"
                    android:right="1px"
                    android:top="1px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#16000000"/>
                <padding
                    android:bottom="1px"
                    android:left="1px"
                    android:right="1px"
                    android:top="1px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#17000000"/>
                <padding
                    android:bottom="1px"
                    android:left="1px"
                    android:right="1px"
                    android:top="1px"
                    />
            </shape>
        </item>
    </layer-list>
</item>
<item>
    <shape android:shape="oval">
        <solid android:color="?attr/colorPrimary"/>
    </shape>
</item>
</layer-list>

In place of ?attr/colorPrimary you can choose any color. Here's a screenshot of the result:

enter image description here

What is a callback?

In computer programming, a callback is executable code that is passed as an argument to other code.

Wikipedia: Callback (computer science)

C# has delegates for that purpose. They are heavily used with events, as an event can automatically invoke a number of attached delegates (event handlers).

Instant run in Android Studio 2.0 (how to turn off)

Update August 2019

In Android Studio 3.5 Instant Run was replaced with Apply Changes. And it works in different way: APK is not modified on the fly anymore but instead runtime instrumentation is used to redefine classes on the fly (more info). So since Android Studio 3.5 instant run settings are replaced with Deployment (Settings -> Build, Execution, Deployment -> Deployment):enter image description here

Writing an Excel file in EPPlus

Have you looked at the samples provided with EPPlus?

This one shows you how to create a file http://epplus.codeplex.com/wikipage?title=ContentSheetExample

This one shows you how to use it to stream back a file http://epplus.codeplex.com/wikipage?title=WebapplicationExample

This is how we use the package to generate a file.

var newFile = new FileInfo(ExportFileName);
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{                       
    // do work here                            
    xlPackage.Save();
}

ALTER TABLE on dependent column

you can drop the Constraint which is restricting you. If the column has access to other table. suppose a view is accessing the column which you are altering then it wont let you alter the column unless you drop the view. and after making changes you can recreate the view.

enter image description here

CSS scrollbar style cross browser

Scrollbar CSS styles are an oddity invented by Microsoft developers. They are not part of the W3C standard for CSS and therefore most browsers just ignore them.

How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list?

I was able to get this to work thanks to this post utilizing VisualWGet. It worked great for me. The important part seems to be to check the -recursive flag (see image).

Also found that the -no-parent flag is important, othewise it will try to download everything.

enter image description here enter image description here

Show SOME invisible/whitespace characters in Eclipse

I would prefer to keep the "Show Whitespace" button on the toolbar, so that in one click you can toggle it.

Go to Window -> Perspective -> Customize Perspective and enable to show the button on toolbar.

enter image description here

Scala list concatenation, ::: vs ++

Always use :::. There are two reasons: efficiency and type safety.

Efficiency

x ::: y ::: z is faster than x ++ y ++ z, because ::: is right associative. x ::: y ::: z is parsed as x ::: (y ::: z), which is algorithmically faster than (x ::: y) ::: z (the latter requires O(|x|) more steps).

Type safety

With ::: you can only concatenate two Lists. With ++ you can append any collection to List, which is terrible:

scala> List(1, 2, 3) ++ "ab"
res0: List[AnyVal] = List(1, 2, 3, a, b)

++ is also easy to mix up with +:

scala> List(1, 2, 3) + "ab"
res1: String = List(1, 2, 3)ab

How to get jQuery to wait until an effect is finished?

You can specify a callback function:

$(selector).fadeOut('slow', function() {
    // will be called when the element finishes fading out
    // if selector matches multiple elements it will be called once for each
});

Documentation here.

Replace all non Alpha Numeric characters, New Lines, and multiple White Space with one Space

This is an old post of mine, the accepted answers are good for the most part. However i decided to benchmark each solution and another obvious one (just for fun). I wondered if there was a difference between the regex patterns on different browsers with different sized strings.

So basically i used jsPerf on

  • Testing in Chrome 65.0.3325 / Windows 10 0.0.0
  • Testing in Edge 16.16299.0 / Windows 10 0.0.0

The regex patterns i tested were

  • /[\W_]+/g
  • /[^a-z0-9]+/gi
  • /[^a-zA-Z0-9]+/g

I loaded them up with a string length of random characters

  • length 5000
  • length 1000
  • length 200

Example javascript i used var newstr = str.replace(/[\W_]+/g," ");

Each run consisted of 50 or more sample on each regex, and i run them 5 times on each browser.

Lets race our horses!

Results

                                Chrome                  Edge
Chars   Pattern                 Ops/Sec     Deviation   Op/Sec      Deviation
------------------------------------------------------------------------
5,000   /[\W_]+/g                19,977.80  1.09         10,820.40  1.32
5,000   /[^a-z0-9]+/gi           19,901.60  1.49         10,902.00  1.20
5,000   /[^a-zA-Z0-9]+/g         19,559.40  1.96         10,916.80  1.13
------------------------------------------------------------------------
1,000   /[\W_]+/g                96,239.00  1.65         52,358.80  1.41
1,000   /[^a-z0-9]+/gi           97,584.40  1.18         52,105.00  1.60
1,000   /[^a-zA-Z0-9]+/g         96,965.80  1.10         51,864.60  1.76
------------------------------------------------------------------------
  200   /[\W_]+/g               480,318.60  1.70        261,030.40  1.80
  200   /[^a-z0-9]+/gi          476,177.80  2.01        261,751.60  1.96
  200   /[^a-zA-Z0-9]+/g        486,423.00  0.80        258,774.20  2.15

Truth be known, Regex in both browsers (taking into consideration deviation) were nearly indistinguishable, however i think if it run this even more times the results would become a little more clearer (but not by much).

Theoretical scaling for 1 character

                            Chrome                        Edge
Chars   Pattern             Ops/Sec     Scaled            Op/Sec    Scaled
------------------------------------------------------------------------
5,000   /[\W_]+/g            19,977.80  99,889,000       10,820.40  54,102,000
5,000   /[^a-z0-9]+/gi       19,901.60  99,508,000       10,902.00  54,510,000
5,000   /[^a-zA-Z0-9]+/g     19,559.40  97,797,000       10,916.80  54,584,000
------------------------------------------------------------------------

1,000   /[\W_]+/g            96,239.00  96,239,000       52,358.80  52,358,800
1,000   /[^a-z0-9]+/gi       97,584.40  97,584,400       52,105.00  52,105,000
1,000   /[^a-zA-Z0-9]+/g     96,965.80  96,965,800       51,864.60  51,864,600
------------------------------------------------------------------------

  200   /[\W_]+/g           480,318.60  96,063,720      261,030.40  52,206,080
  200   /[^a-z0-9]+/gi      476,177.80  95,235,560      261,751.60  52,350,320
  200   /[^a-zA-Z0-9]+/g    486,423.00  97,284,600      258,774.20  51,754,840

I wouldn't take to much into these results as this is not really a significant differences, all we can really tell is edge is slower :o . Additionally that i was super bored.

Anyway you can run the benchmark for your self.

Jsperf Benchmark here

What are -moz- and -webkit-?

What are -moz- and -webkit-?

CSS properties starting with -webkit-, -moz-, -ms- or -o- are called vendor prefixes.


Why do different browsers add different prefixes for the same effect?

A good explanation of vendor prefixes comes from Peter-Paul Koch of QuirksMode:

Originally, the point of vendor prefixes was to allow browser makers to start supporting experimental CSS declarations.

Let's say a W3C working group is discussing a grid declaration (which, incidentally, wouldn't be such a bad idea). Let's furthermore say that some people create a draft specification, but others disagree with some of the details. As we know, this process may take ages.

Let's furthermore say that Microsoft as an experiment decides to implement the proposed grid. At this point in time, Microsoft cannot be certain that the specification will not change. Therefore, instead of adding the grid to its CSS, it adds -ms-grid.

The vendor prefix kind of says "this is the Microsoft interpretation of an ongoing proposal." Thus, if the final definition of the grid is different, Microsoft can add a new CSS property grid without breaking pages that depend on -ms-grid.


UPDATE AS OF THE YEAR 2016

As this post 3 years old, it's important to mention that now most vendors do understand that these prefixes are just creating un-necessary duplicate code and that the situation where you need to specify 3 different CSS rules to get one effect working in all browser is an unwanted one.

As mentioned in this glossary about Mozilla's view on Vendor Prefix on May 3, 2016,

Browser vendors are now trying to get rid of vendor prefix for experimental features. They noticed that Web developers were using them on production Web sites, polluting the global space and making it more difficult for underdogs to perform well.

For example, just a few years ago, to set a rounded corner on a box you had to write:

-moz-border-radius: 10px 5px;
-webkit-border-top-left-radius: 10px;
-webkit-border-top-right-radius: 5px;
-webkit-border-bottom-right-radius: 10px;
-webkit-border-bottom-left-radius: 5px;
border-radius: 10px 5px;

But now that browsers have come to fully support this feature, you really only need the standardized version:

border-radius: 10px 5px;

Finding the right rules for all browsers

As still there's no standard for common CSS rules that work on all browsers, you can use tools like caniuse.com to check support of a rule across all major browsers.

You can also use pleeease.io/play. Pleeease is a Node.js application that easily processes your CSS. It simplifies the use of preprocessors and combines them with best postprocessors. It helps create clean stylesheets, support older browsers and offers better maintainability.

Input:

a {
  column-count: 3;
  column-gap: 10px;
  column-fill: auto;
}

Output:

a {
  -webkit-column-count: 3;
     -moz-column-count: 3;
          column-count: 3;
  -webkit-column-gap: 10px;
     -moz-column-gap: 10px;
          column-gap: 10px;
  -webkit-column-fill: auto;
     -moz-column-fill: auto;
          column-fill: auto;
}

What does the @ symbol before a variable name mean in C#?

The @ symbol serves 2 purposes in C#:

Firstly, it allows you to use a reserved keyword as a variable like this:

int @int = 15;

The second option lets you specify a string without having to escape any characters. For instance the '\' character is an escape character so typically you would need to do this:

var myString = "c:\\myfolder\\myfile.txt"

alternatively you can do this:

var myString = @"c:\myFolder\myfile.txt"

.htaccess: Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

This comment from verybadbug under question helped me:

ln -s /etc/apache2/mods-available/rewrite.load /etc/apache2/mods-enabled/rewrite.load

After that we need restart Apache:

sudo service apache2 restart

Evaluate expression given as a string

The eval() function evaluates an expression, but "5+5" is a string, not an expression. Use parse() with text=<string> to change the string into an expression:

> eval(parse(text="5+5"))
[1] 10
> class("5+5")
[1] "character"
> class(parse(text="5+5"))
[1] "expression"

Calling eval() invokes many behaviours, some are not immediately obvious:

> class(eval(parse(text="5+5")))
[1] "numeric"
> class(eval(parse(text="gray")))
[1] "function"
> class(eval(parse(text="blue")))
Error in eval(expr, envir, enclos) : object 'blue' not found

See also tryCatch.

Reading serial data in realtime in Python

You need to set the timeout to "None" when you open the serial port:

ser = serial.Serial(**bco_port**, timeout=None, baudrate=115000, xonxoff=False, rtscts=False, dsrdtr=False) 

This is a blocking command, so you are waiting until you receive data that has newline (\n or \r\n) at the end: line = ser.readline()

Once you have the data, it will return ASAP.

How to remove html special chars?

It looks like what you really want is:

function xmlEntities($string) {
    $translationTable = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);

    foreach ($translationTable as $char => $entity) {
        $from[] = $entity;
        $to[] = '&#'.ord($char).';';
    }
    return str_replace($from, $to, $string);
}

It replaces the named-entities with their number-equivalent.

SQL Server command line backup statement

I am using SQL Server 2005 Express, and I had to enable Named Pipes connection to be able to backup from the Windows Command. My final script is this:

@echo off
set DB_NAME=Your_DB_Name
set BK_FILE=D:\DB_Backups\%DB_NAME%.bak
set DB_HOSTNAME=Your_DB_Hostname
echo.
echo.
echo Backing up %DB_NAME% to %BK_FILE%...
echo.
echo.
sqlcmd -E -S np:\\%DB_HOSTNAME%\pipe\MSSQL$SQLEXPRESS\sql\query -d master -Q "BACKUP DATABASE [%DB_NAME%] TO DISK = N'%BK_FILE%' WITH INIT , NOUNLOAD , NAME = N'%DB_NAME% backup', NOSKIP , STATS = 10, NOFORMAT"
echo.
echo Done!
echo.

It's working just fine here!!

How to make sure docker's time syncs with that of the host?

You can add your local files (/etc/timezone and /etc/localtime) as volume in your Docker container.

Update your docker-compose.yml with the following lines.

volumes:
    - "/etc/timezone:/etc/timezone:ro"
    - "/etc/localtime:/etc/localtime:ro"

Now the container time is the same as on your host.

SQL Query to fetch data from the last 30 days?

The easiest way would be to specify

SELECT productid FROM product where purchase_date > sysdate-30;

Remember this sysdate above has the time component, so it will be purchase orders newer than 03-06-2011 8:54 AM based on the time now.

If you want to remove the time conponent when comparing..

SELECT productid FROM product where purchase_date > trunc(sysdate-30);

And (based on your comments), if you want to specify a particular date, make sure you use to_date and not rely on the default session parameters.

SELECT productid FROM product where purchase_date > to_date('03/06/2011','mm/dd/yyyy')

And regardng the between (sysdate-30) - (sysdate) comment, for orders you should be ok with usin just the sysdate condition unless you can have orders with order_dates in the future.

ESLint Parsing error: Unexpected token

"parser": "babel-eslint" helped me to fix the issue

{
    "parser": "babel-eslint",
    "parserOptions": {
        "ecmaVersion": 6,
        "sourceType": "module",
        "ecmaFeatures": {
            "jsx": true,
            "modules": true,
            "experimentalObjectRestSpread": true
        }
    },
    "plugins": [
        "react"
    ],
    "extends": ["eslint:recommended", "plugin:react/recommended"],
    "rules": {
        "comma-dangle": 0,
        "react/jsx-uses-vars": 1,
        "react/display-name": 1,
        "no-unused-vars": "warn",
        "no-console": 1,
        "no-unexpected-multiline": "warn"
    },
    "settings": {
        "react": {
            "pragma": "React",
            "version": "15.6.1"
        }
    }
}

Reference

How to recursively find the latest modified file in a directory?

This gives a sorted list:

find . -type f -ls 2>/dev/null | sort -M -k8,10 | head -n5

Reverse the order by placing a '-r' in the sort command. If you only want filenames, insert "awk '{print $11}' |" before '| head'

don't fail jenkins build if execute shell fails

I was able to get this working using the answer found here:

How to git commit nothing without an error?

git diff --quiet --exit-code --cached || git commit -m 'bla'

Boolean checking in the 'if' condition

The former. The latter merely adds verbosity.

jQuery Scroll to Div

Could just use JQuery position function to get coordinates of your div, then use javascript scroll:

var position = $("div").position();
scroll(0,position.top);

HTML span align center not working?

Span is inline-block and adjusts to inline text size, with a tenacity that blocks most efforts to style out of inline context. To simplify layout style (limit conflicts), add div to 'p' tag with line break.

<p> some default stuff
<br>
<div style="text-align: center;"> your entered stuff </div>

How do I store an array in localStorage?

Just created this:

https://gist.github.com/3854049

//Setter
Storage.setObj('users.albums.sexPistols',"blah");
Storage.setObj('users.albums.sexPistols',{ sid : "My Way", nancy : "Bitch" });
Storage.setObj('users.albums.sexPistols.sid',"Other songs");

//Getters
Storage.getObj('users');
Storage.getObj('users.albums');
Storage.getObj('users.albums.sexPistols');
Storage.getObj('users.albums.sexPistols.sid');
Storage.getObj('users.albums.sexPistols.nancy');

Find oldest/youngest datetime object in a list

Given a list of dates dates:

Max date is max(dates)

Min date is min(dates)

How to copy a folder via cmd?

xcopy  e:\source_folder f:\destination_folder /e /i /h

The /h is just in case there are hidden files. The /i creates a destination folder if there are muliple source files.

How to set variables in HIVE scripts

There are multiple options to set variables in Hive.

If you're looking to set Hive variable from inside the Hive shell, you can set it using hivevar. You can set string or integer datatypes. There are no problems with them.

SET hivevar:which_date=20200808;
select ${which_date};

If you're planning to set variables from shell script and want to pass those variables into your Hive script (HQL) file, you can use --hivevar option while calling hive or beeline command.

# shell script will invoke script like this
beeline --hivevar tablename=testtable -f select.hql
-- select.hql file
select * from <dbname>.${tablename};

Dealing with timestamps in R

You want the (standard) POSIXt type from base R that can be had in 'compact form' as a POSIXct (which is essentially a double representing fractional seconds since the epoch) or as long form in POSIXlt (which contains sub-elements). The cool thing is that arithmetic etc are defined on this -- see help(DateTimeClasses)

Quick example:

R> now <- Sys.time()
R> now
[1] "2009-12-25 18:39:11 CST"
R> as.numeric(now)
[1] 1.262e+09
R> now + 10  # adds 10 seconds
[1] "2009-12-25 18:39:21 CST"
R> as.POSIXlt(now)
[1] "2009-12-25 18:39:11 CST"
R> str(as.POSIXlt(now))
 POSIXlt[1:9], format: "2009-12-25 18:39:11"
R> unclass(as.POSIXlt(now))
$sec
[1] 11.79

$min
[1] 39

$hour
[1] 18

$mday
[1] 25

$mon
[1] 11

$year
[1] 109

$wday
[1] 5

$yday
[1] 358

$isdst
[1] 0

attr(,"tzone")
[1] "America/Chicago" "CST"             "CDT"            
R> 

As for reading them in, see help(strptime)

As for difference, easy too:

R> Jan1 <- strptime("2009-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
R> difftime(now, Jan1, unit="week")
Time difference of 51.25 weeks
R> 

Lastly, the zoo package is an extremely versatile and well-documented container for matrix with associated date/time indices.

PHP array value passes to next row

Change the checkboxes so that the name includes the index inside the brackets:

<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>"> 

The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.

javascript Unable to get property 'value' of undefined or null reference

The issue is how you're attempting to get the value. Things like...

if ( document.frm_new_user_request.u_isid.value == '' )

won't work. You need to find the element you want to get the value of first. It's not quite like a server side language where you can type in an object's reference name and a period to get or assign values.

document.getElementById('[id goes here]').value;

will work. Note: JavaScript is case-sensitive

I would recommend using:

var variablename = document.getElementById('[id goes here]');

or

var variablename = document.getElementById('[id goes here]').value;

Linking dll in Visual Studio

On Windows you do not link with a .dll file directly – you must use the accompanying .lib file instead. To do that go to Project -> Properties -> Configuration Properties -> Linker -> Additional Dependencies and add path to your .lib as a next line.

You also must make sure that the .dll file is either in the directory contained by the %PATH% environment variable or that its copy is in Output Directory (by default, this is Debug\Release under your project's folder).

If you don't have access to the .lib file, one alternative is to load the .dll manually during runtime using WINAPI functions such as LoadLibrary and GetProcAddress.

Named colors in matplotlib

I constantly forget the names of the colors I want to use and keep coming back to this question =)

The previous answers are great, but I find it a bit difficult to get an overview of the available colors from the posted image. I prefer the colors to be grouped with similar colors, so I slightly tweaked the matplotlib answer that was mentioned in a comment above to get a color list sorted in columns. The order is not identical to how I would sort by eye, but I think it gives a good overview.

I updated the image and code to reflect that 'rebeccapurple' has been added and the three sage colors have been moved under the 'xkcd:' prefix since I posted this answer originally.

enter image description here

I really didn't change much from the matplotlib example, but here is the code for completeness.

import matplotlib.pyplot as plt
from matplotlib import colors as mcolors


colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)

# Sort colors by hue, saturation, value and name.
by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3])), name)
                for name, color in colors.items())
sorted_names = [name for hsv, name in by_hsv]

n = len(sorted_names)
ncols = 4
nrows = n // ncols

fig, ax = plt.subplots(figsize=(12, 10))

# Get height and width
X, Y = fig.get_dpi() * fig.get_size_inches()
h = Y / (nrows + 1)
w = X / ncols

for i, name in enumerate(sorted_names):
    row = i % nrows
    col = i // nrows
    y = Y - (row * h) - h

    xi_line = w * (col + 0.05)
    xf_line = w * (col + 0.25)
    xi_text = w * (col + 0.3)

    ax.text(xi_text, y, name, fontsize=(h * 0.8),
            horizontalalignment='left',
            verticalalignment='center')

    ax.hlines(y + h * 0.1, xi_line, xf_line,
              color=colors[name], linewidth=(h * 0.8))

ax.set_xlim(0, X)
ax.set_ylim(0, Y)
ax.set_axis_off()

fig.subplots_adjust(left=0, right=1,
                    top=1, bottom=0,
                    hspace=0, wspace=0)
plt.show()

Additional named colors

Updated 2017-10-25. I merged my previous updates into this section.

xkcd

If you would like to use additional named colors when plotting with matplotlib, you can use the xkcd crowdsourced color names, via the 'xkcd:' prefix:

plt.plot([1,2], lw=4, c='xkcd:baby poop green')

Now you have access to a plethora of named colors!

enter image description here

Tableau

The default Tableau colors are available in matplotlib via the 'tab:' prefix:

plt.plot([1,2], lw=4, c='tab:green')

There are ten distinct colors:

enter image description here

HTML

You can also plot colors by their HTML hex code:

plt.plot([1,2], lw=4, c='#8f9805')

This is more similar to specifying and RGB tuple rather than a named color (apart from the fact that the hex code is passed as a string), and I will not include an image of the 16 million colors you can choose from...


For more details, please refer to the matplotlib colors documentation and the source file specifying the available colors, _color_data.py.


Maven: How do I activate a profile from command line?

Activation by system properties can be done as follows

<activation>
    <property>
        <name>foo</name>
        <value>bar</value>
    </property>
</activation>

And run the mvn build with -D to set system property

mvn clean install -Dfoo=bar

This method also helps select profiles in transitive dependency of project artifacts.

When a 'blur' event occurs, how can I find out which element focus went *to*?

I see only hacks in the answers, but there's actually a builtin solution very easy to use : Basically you can capture the focus element like this:

const focusedElement = document.activeElement

https://developer.mozilla.org/en-US/docs/Web/API/DocumentOrShadowRoot/activeElement

Java Set retain order?

Iterator returned by Set is not suppose to return data in Ordered way. See this Two java.util.Iterators to the same collection: do they have to return elements in the same order?

How to remove border of drop down list : CSS

The most you can get is:

select#xyz {
   border:0px;
   outline:0px;
}

You cannot style it completely, but you can try something like

select#xyz {
  -webkit-appearance: button;
  -webkit-border-radius: 2px;
  -webkit-box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.1);
  -webkit-padding-end: 20px;
  -webkit-padding-start: 2px;
  -webkit-user-select: none;
  background-image: url(../images/select-arrow.png), 
    -webkit-linear-gradient(#FAFAFA, #F4F4F4 40%, #E5E5E5);
  background-position: center right;
  background-repeat: no-repeat;
  border: 1px solid #AAA;
  color: #555;
  font-size: inherit;
  margin: 0;
  overflow: hidden;
  padding-top: 2px;
  padding-bottom: 2px;
  text-overflow: ellipsis;
  white-space: nowrap;
}

How to write macro for Notepad++?

I recorded a macro and I found it in %APPDATA%\Notepad++\shortcuts.xml. It looks like posted in the first post of this thread.

I use NPP Ver. 5.9.6.2 with Win7.

The 'json' native gem requires installed build tools

My gem version 2.0.3 and I was getting the same issue. This command resolved it:

gem install json --platform=ruby --verbose

C# switch statement limitations - why?

It's important not to confuse the C# switch statement with the CIL switch instruction.

The CIL switch is a jump table, that requires an index into a set of jump addresses.

This is only useful if the C# switch's cases are adjacent:

case 3: blah; break;
case 4: blah; break;
case 5: blah; break;

But of little use if they aren't:

case 10: blah; break;
case 200: blah; break;
case 3000: blah; break;

(You'd need a table ~3000 entries in size, with only 3 slots used)

With non-adjacent expressions, the compiler may start to perform linear if-else-if-else checks.

With larger non- adjacent expression sets, the compiler may start with a binary tree search, and finally if-else-if-else the last few items.

With expression sets containing clumps of adjacent items, the compiler may binary tree search, and finally a CIL switch.

This is full of "mays" & "mights", and it is dependent on the compiler (may differ with Mono or Rotor).

I replicated your results on my machine using adjacent cases:

total time to execute a 10 way switch, 10000 iterations (ms) : 25.1383
approximate time per 10 way switch (ms) : 0.00251383

total time to execute a 50 way switch, 10000 iterations (ms) : 26.593
approximate time per 50 way switch (ms) : 0.0026593

total time to execute a 5000 way switch, 10000 iterations (ms) : 23.7094
approximate time per 5000 way switch (ms) : 0.00237094

total time to execute a 50000 way switch, 10000 iterations (ms) : 20.0933
approximate time per 50000 way switch (ms) : 0.00200933

Then I also did using non-adjacent case expressions:

total time to execute a 10 way switch, 10000 iterations (ms) : 19.6189
approximate time per 10 way switch (ms) : 0.00196189

total time to execute a 500 way switch, 10000 iterations (ms) : 19.1664
approximate time per 500 way switch (ms) : 0.00191664

total time to execute a 5000 way switch, 10000 iterations (ms) : 19.5871
approximate time per 5000 way switch (ms) : 0.00195871

A non-adjacent 50,000 case switch statement would not compile.
"An expression is too long or complex to compile near 'ConsoleApplication1.Program.Main(string[])'

What's funny here, is that the binary tree search appears a little (probably not statistically) quicker than the CIL switch instruction.

Brian, you've used the word "constant", which has a very definite meaning from a computational complexity theory perspective. While the simplistic adjacent integer example may produce CIL that is considered O(1) (constant), a sparse example is O(log n) (logarithmic), clustered examples lie somewhere in between, and small examples are O(n) (linear).

This doesn't even address the String situation, in which a static Generic.Dictionary<string,int32> may be created, and will suffer definite overhead on first use. Performance here will be dependent on the performance of Generic.Dictionary.

If you check the C# Language Specification (not the CIL spec) you'll find "15.7.2 The switch statement" makes no mention of "constant time" or that the underlying implementation even uses the CIL switch instruction (be very careful of assuming such things).

At the end of the day, a C# switch against an integer expression on a modern system is a sub-microsecond operation, and not normally worth worrying about.


Of course these times will depend on machines and conditions. I wouldn’t pay attention to these timing tests, the microsecond durations we’re talking about are dwarfed by any “real” code being run (and you must include some “real code” otherwise the compiler will optimise the branch away), or jitter in the system. My answers are based on using IL DASM to examine the CIL created by the C# compiler. Of course, this isn’t final, as the actual instructions the CPU runs are then created by the JIT.

I have checked the final CPU instructions actually executed on my x86 machine, and can confirm a simple adjacent set switch doing something like:

  jmp     ds:300025F0[eax*4]

Where a binary tree search is full of:

  cmp     ebx, 79Eh
  jg      3000352B
  cmp     ebx, 654h
  jg      300032BB
  …
  cmp     ebx, 0F82h
  jz      30005EEE

Error: Execution failed for task ':app:clean'. Unable to delete file

I had the same problem and this worked for me:

  1. close Android Studio.
  2. delete intermediates directory (as long as Android Studio is opened, this directory can't be deleted)
  3. open Android Studio again

Reading numbers from a text file into an array in C

Loop with %c to read the stream character by character instead of %d.

Remove quotes from a character vector in R

as.name(char[1]) will work, although I'm not sure why you'd ever really want to do this -- the quotes won't get carried over in a paste for example:

> paste("I am counting to", char[1], char[2], char[3])
[1] "I am counting to one two three"

Append text to file from command line without using io redirection

If you don't mind using sed then,

$ cat test 
this is line 1
$ sed -i '$ a\this is line 2 without redirection' test 
$ cat test 
this is line 1
this is line 2 without redirection

As the documentation may be a bit long to go through, some explanations :

  • -i means an inplace transformation, so all changes will occur in the file you specify
  • $ is used to specify the last line
  • a means append a line after
  • \ is simply used as a delimiter

Nullable property to entity field, Entity Framework through Code First

Just omit the [Required] attribute from the string somefield property. This will make it create a NULLable column in the db.

To make int types allow NULLs in the database, they must be declared as nullable ints in the model:

// an int can never be null, so it will be created as NOT NULL in db
public int someintfield { get; set; }

// to have a nullable int, you need to declare it as an int?
// or as a System.Nullable<int>
public int? somenullableintfield { get; set; }
public System.Nullable<int> someothernullableintfield { get; set; }

Storing Images in DB - Yea or Nay?

No, due to page splits. You're essentially defining rows that can be 1KB - n MB so your database will have a lot of empty spaces in its pages which is bad for performance.

Constantly print Subprocess output while process is running

There is actually a really simple way to do this when you just want to print the output:

import subprocess
import sys

def execute(command):
    subprocess.check_call(command, stdout=sys.stdout, stderr=subprocess.STDOUT)

Here we're simply pointing the subprocess to our own stdout, and using existing succeed or exception api.

What is resource-ref in web.xml used for?

You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.

<resource-ref> introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.

So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB name. The container finds that web.xml has a <resource-ref> element for jdbc/primaryDB, so it will look into the container-specific configuration, that contains something similar to the following:

<resource-ref>
  <res-ref-name>jdbc/primaryDB</res-ref-name>
  <jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>

Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer.

The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.

How do I run a single test using Jest?

In Visual Studio Code, this lets me run/debug only one Jest test, with breakpoints: Debugging tests in Visual Studio Code

My launch.json file has this inside:

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Jest All",
      "program": "${workspaceFolder}/node_modules/.bin/jest",
      "args": ["--runInBand"],
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen",
      "windows": {
        "program": "${workspaceFolder}/node_modules/jest/bin/jest",
      }
    },
    {
      "type": "node",
      "request": "launch",
      "name": "Jest Current File",
      "program": "${workspaceFolder}/node_modules/.bin/jest",
      "args": ["${relativeFile}"],
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen",
      "windows": {
        "program": "${workspaceFolder}/node_modules/jest/bin/jest",
      }
    }
  ]
}

And this in file package.json:

  "scripts": {
    "test": "jest"
  }
  • To run one test, in that test, change test (or it) to test.only (or it.only). To run one test suite (several tests), change describe to describe.only.
  • Set breakpoint(s) if you want.
  • In Visual Studio Code, go to Debug View (Shift + Cmd + D or Shift + Ctrl + D).
  • From the dropdown menu at top, pick Jest Current File.
  • Click the green arrow to run that test.

Passing properties by reference in C#

If you want to get and set the property both, you can use this in C#7:

GetString(
    inputString,
    (() => client.WorkPhone, x => client.WorkPhone = x))

void GetString(string inValue, (Func<string> get, Action<string> set) outValue)
{
    if (!string.IsNullOrEmpty(outValue))
    {
        outValue.set(inValue);
    }
}

target input by type and name (selector)

You want a multiple attribute selector

$("input[type='checkbox'][name='ProductCode']").each(function(){ ...

or

$("input:checkbox[name='ProductCode']").each(function(){ ...

It would be better to use a CSS class to identify those that you want to select however as a lot of the modern browsers implement the document.getElementsByClassName method which will be used to select elements and be much faster than selecting by the name attribute

PHP $_POST not working?

Dump the global variable to find out what you have in the page scope:

var_dump($GLOBALS);

This will tell you the "what" and "where" regarding the data on your page.

How to Initialize char array from a string

Here is obscure solution: define macro function:

#define Z(x) \
        (x==0 ? 'A' : \
        (x==1 ? 'B' : \
        (x==2 ? 'C' : '\0')))

char x[] = { Z(0), Z(1), Z(2) };

How to print full stack trace in exception?

1. Create Method: If you pass your exception to the following function, it will give you all methods and details which are reasons of the exception.

public string GetAllFootprints(Exception x)
{
        var st = new StackTrace(x, true);
        var frames = st.GetFrames();
        var traceString = new StringBuilder();

        foreach (var frame in frames)
        {
            if (frame.GetFileLineNumber() < 1)
                continue;

            traceString.Append("File: " + frame.GetFileName());
            traceString.Append(", Method:" + frame.GetMethod().Name);
            traceString.Append(", LineNumber: " + frame.GetFileLineNumber());
            traceString.Append("  -->  ");
        }

        return traceString.ToString();
}

2. Call Method: You can call the method like this.

try
{
    // code part which you want to catch exception on it
}
catch(Exception ex)
{
    Debug.Writeline(GetAllFootprints(ex));
}

3. Get the Result:

File: c:\MyProject\Program.cs, Method:MyFunction, LineNumber: 29  -->  
File: c:\MyProject\Program.cs, Method:Main, LineNumber: 16  --> 

How do I make my ArrayList Thread-Safe? Another approach to problem in Java?

Use Collections.synchronizedList().

Ex:

Collections.synchronizedList(new ArrayList<YourClassNameHere>())

Restart container within pod

The whole reason for having kubernetes is so it manages the containers for you so you don't have to care so much about the lifecyle of the containers in the pod.

Since you have a deployment setup that uses replica set. You can delete the pod using kubectl delete pod test-1495806908-xn5jn and kubernetes will manage the creation of a new pod with the 2 containers without any downtime. Trying to manually restart single containers in pods negates the whole benefits of kubernetes.

Loop through all the files with a specific extension

the correct answer is @chepner's

EXT=java
for i in *.${EXT}; do
    ...
done

however, here's a small trick to check whether a filename has a given extensions:

EXT=java
for i in *; do
    if [ "${i}" != "${i%.${EXT}}" ];then
        echo "I do something with the file $i"
    fi
done

Case statement with multiple values in each 'when' block

In a case statement, a , is the equivalent of || in an if statement.

case car
   when 'toyota', 'lexus'
      # code
end

Some other things you can do with a Ruby case statement

How to add a button to UINavigationBar?

swift 3

    let cancelBarButton = UIBarButtonItem(title: "Cancel", style: .done, target: self, action: #selector(cancelPressed(_:)))
    cancelBarButton.setTitleTextAttributes( [NSFontAttributeName : UIFont.cancelBarButtonFont(),
                                                          NSForegroundColorAttributeName : UIColor.white], for: .normal)
    self.navigationItem.leftBarButtonItem = cancelBarButton


    func cancelPressed(_ sender: UIBarButtonItem ) {
        self.dismiss(animated: true, completion: nil)
    }

Drop all tables whose names begin with a certain string

Here is my solution:

SELECT CONCAT('DROP TABLE `', TABLE_NAME,'`;') 
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_NAME LIKE 'TABLE_PREFIX_GOES_HERE%';

And of course you need to replace TABLE_PREFIX_GOES_HERE with your prefix.

How can I get Android Wifi Scan Results into a list?

Wrap an ArrayAdapter around your List<ScanResult>. Override getView() to populate your rows with the ScanResult data. Here is a free excerpt from one of my books that covers how to create custom ArrayAdapters like this.

Process to convert simple Python script into Windows executable

1) Get py2exe from here, according to your Python version.

2) Make a file called "setup.py" in the same folder as the script you want to convert, having the following code:

from distutils.core import setup
import py2exe
setup(console=['myscript.py']) #change 'myscript' to your script

3) Go to command prompt, navigate to that folder, and type:

python setup.py py2exe

4) It will generate a "dist" folder in the same folder as the script. This folder contains the .exe file.

Convert a string representation of a hex dump to a byte array using Java?

I know this is a very old thread, but still like to add my penny worth.

If I really need to code up a simple hex string to binary converter, I'd like to do it as follows.

public static byte[] hexToBinary(String s){

  /*
   * skipped any input validation code
   */

  byte[] data = new byte[s.length()/2];

  for( int i=0, j=0; 
       i<s.length() && j<data.length; 
       i+=2, j++)
  {
     data[j] = (byte)Integer.parseInt(s.substring(i, i+2), 16);
  }

  return data;
}

Using if(isset($_POST['submit'])) to not display echo when script is open is not working

What you're checking

if(isset($_POST['submit']))

but there's no variable name called "submit". well i want you to understand why it doesn't works. lets imagine if you give your submit button name delete <input type="submit" value="Submit" name="delete" /> and check if(isset($_POST['delete'])) then it works in this code you didn't give any name to submit button and checking its exist or not with isset(); function so php didn't find any variable like "submit" so its not working now try this :

<input type="submit" name="submit" value="Submit" />

Check if all values of array are equal

Another interesting way when you use ES6 arrow function syntax:

x = ['a', 'a', 'a', 'a']
!x.filter(e=>e!==x[0])[0]  // true

x = ['a', 'a', 'b', 'a']
!x.filter(e=>e!==x[0])[0] // false

x = []
!x.filter(e=>e!==x[0])[0]  // true

And when you don't want to reuse the variable for array (x):

!['a', 'a', 'a', 'a'].filter((e,i,a)=>e!==a[0])[0]    // true

IMO previous poster who used array.every(...) has the cleanest solution.

Powershell's Get-date: How to get Yesterday at 22:00 in a variable?

Use DateTime.Today as opposed to DateTime.Now (which is what Get-Date returns) because Today is just the date with 00:00 as the time, and now is the moment in time down to the millisecond. (from masenkablast)

> [DateTime]::Today.AddDays(-1).AddHours(22)
Thursday, March 11, 2010 10:00:00 PM

How to run .APK file on emulator

You need to install the APK on the emulator. You can do this with the adb command line tool that is included in the Android SDK.

adb -e install -r yourapp.apk

Once you've done that you should be able to run the app.

The -e and -r flags might not be necessary. They just specify that you are using an emulator (if you also have a device connected) and that you want to replace the app if it already exists.

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

Find the number of employees in each department - SQL Oracle

select  d.dname
       ,count(e.empno) as count 
from dept d 
left outer join emp e 
  on e.deptno=d.deptno 
group by d.dname;

java.lang.UnsupportedClassVersionError Unsupported major.minor version 51.0

Use Maven and use the maven-compiler-plugin to explicitly call the actual correct version JDK javac.exe command, because Maven could be running any version; this also catches the really stupid long standing bug in javac that does not spot runtime breaking class version jars and missing classes/methods/properties when compiling for earlier java versions! This later part could have easily been fixed in Java 1.5+ by adding versioning attributes to new classes, methods, and properties, or separate compiler versioning data, so is a quite stupid oversight by Sun and Oracle.

Django: Model Form "object has no attribute 'cleaned_data'"

For some reason, you're re-instantiating the form after you check is_valid(). Forms only get a cleaned_data attribute when is_valid() has been called, and you haven't called it on this new, second instance.

Just get rid of the second form = SearchForm(request.POST) and all should be well.

Get ALL User Friends Using Facebook Graph API - Android

In v2.0 of the Graph API, calling /me/friends returns the person's friends who also use the app.

In addition, in v2.0, you must request the user_friends permission from each user. user_friends is no longer included by default in every login. Each user must grant the user_friends permission in order to appear in the response to /me/friends. See the Facebook upgrade guide for more detailed information, or review the summary below.

The /me/friendlists endpoint and user_friendlists permission are not what you're after. This endpoint does not return the users friends - its lets you access the lists a person has made to organize their friends. It does not return the friends in each of these lists. This API and permission is useful to allow you to render a custom privacy selector when giving people the opportunity to publish back to Facebook.

If you want to access a list of non-app-using friends, there are two options:

  1. If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.

  2. If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.

In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends permission).

For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.

How to select an element by classname using jqLite?

angualr uses the lighter version of jquery called as jqlite which means it doesnt have all the features of jQuery. here is a reference in angularjs docs about what you can use from jquery. Angular Element docs

In your case you need to find a div with ID or class name. for class name you can use

var elems =$element.find('div') //returns all the div's in the $elements
    angular.forEach(elems,function(v,k)){
    if(angular.element(v).hasClass('class-name')){
     console.log(angular.element(v));
}}

or you can use much simpler way by query selector

angular.element(document.querySelector('#id'))

angular.element(elem.querySelector('.classname'))

it is not as flexible as jQuery but what

Datanode process not running in Hadoop

Delete the datanode under your hadoop folder then rerun start-all.sh

Change div height on button click

_x000D_
_x000D_
var ww1 = "";_x000D_
var ww2 = 0;_x000D_
var myVar1 ;_x000D_
var myVar2 ;_x000D_
function wm1(){_x000D_
  myVar1 =setInterval(w1, 15);_x000D_
}_x000D_
function wm2(){_x000D_
  myVar2 =setInterval(w2, 15);_x000D_
}_x000D_
function w1(){_x000D_
 ww1=document.getElementById('chartdiv').style.height;_x000D_
 ww2= ww1.replace("px", ""); _x000D_
    if(parseFloat(ww2) <= 200){_x000D_
document.getElementById('chartdiv').style.height = (parseFloat(ww2)+5) + 'px';_x000D_
    }else{_x000D_
      clearInterval(myVar1);_x000D_
    }_x000D_
}_x000D_
function w2(){_x000D_
 ww1=document.getElementById('chartdiv').style.height;_x000D_
 ww2= ww1.replace("px", ""); _x000D_
    if(parseFloat(ww2) >= 50){_x000D_
document.getElementById('chartdiv').style.height = (parseFloat(ww2)-5) + 'px';_x000D_
    }else{_x000D_
      clearInterval(myVar2);_x000D_
    }_x000D_
}
_x000D_
<html>_x000D_
  <head>    _x000D_
  </head>_x000D_
_x000D_
<body >_x000D_
    <button type="button" onClick = "wm1()">200px</button>_x000D_
    <button type="button" onClick = "wm2()">50px</button>_x000D_
    <div id="chartdiv" style="width: 100%; height: 50px; background-color:#ccc"></div>_x000D_
  _x000D_
  <div id="demo"></div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

Starting with MySQL 8.0.4, they have changed the default authentication plugin for MySQL server from mysql_native_password to caching_sha2_password.

You can run the below command to resolve the issue.

sample username / password => student / pass123

ALTER USER 'student'@'localhost' IDENTIFIED WITH mysql_native_password BY 'pass123';

Refer the official page for details: MySQL Reference Manual

Get a specific bit from byte

While it's good to read and understand Josh's answer, you'll probably be happier using the class Microsoft provided for this purpose: System.Collections.BitArray It's available in all versions of .NET Framework.

How can I emulate a get request exactly like a web browser?

i'll make an example, first decide what browser you want to emulate, in this case i chose Firefox 60.6.1esr (64-bit), and check what GET request it issues, this can be obtained with a simple netcat server (MacOS bundles netcat, most linux distributions bunles netcat, and Windows users can get netcat from.. Cygwin.org , among other places),

setting up the netcat server to listen on port 9999: nc -l 9999

now hitting http://127.0.0.1:9999 in firefox, i get:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

now let us compare that with this simple script:

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_exec($ch);

i get:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
Accept: */*

there are several missing headers here, they can all be added with the CURLOPT_HTTPHEADER option of curl_setopt, but the User-Agent specifically should be set with CURLOPT_USERAGENT instead (it will be persistent across multiple calls to curl_exec() and if you use CURLOPT_FOLLOWLOCATION then it will persist across http redirections as well), and the Accept-Encoding header should be set with CURLOPT_ENCODING instead (if they're set with CURLOPT_ENCODING then curl will automatically decompress the response if the server choose to compress it, but if you set it via CURLOPT_HTTPHEADER then you must manually detect and decompress the content yourself, which is a pain in the ass and completely unnecessary, generally speaking) so adding those we get:

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
        CURLOPT_ENCODING=>'gzip, deflate',
        CURLOPT_HTTPHEADER=>array(
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',
        ),
));
curl_exec($ch);

now running that code, our netcat server gets:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept-Encoding: gzip, deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Upgrade-Insecure-Requests: 1

and voila! our php-emulated browser GET request should now be indistinguishable from the real firefox GET request :)

this next part is just nitpicking, but if you look very closely, you'll see that the headers are stacked in the wrong order, firefox put the Accept-Encoding header in line 6, and our emulated GET request puts it in line 3.. to fix this, we can manually put the Accept-Encoding header in the right line,

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
        CURLOPT_ENCODING=>'gzip, deflate',
        CURLOPT_HTTPHEADER=>array(
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Accept-Encoding: gzip, deflate',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',
        ),
));
curl_exec($ch);

running that, our netcat server gets:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

problem solved, now the headers is even in the correct order, and the request seems to be COMPLETELY INDISTINGUISHABLE from the real firefox request :) (i don't actually recommend this last step, it's a maintenance burden to keep CURLOPT_ENCODING in sync with the custom Accept-Encoding header, and i've never experienced a situation where the order of the headers are significant)

@Autowired - No qualifying bean of type found for dependency at least 1 bean

@Service: It tells that particular class is a Service to the client. Service class contains mainly business Logic. If you have more Service classes in a package than provide @Qualifier otherwise it should not require @Qualifier.

Case 1:

@Service("employeeService")
public class EmployeeServiceImpl implements EmployeeService{
}

Case2:

@Service
public class EmployeeServiceImpl implements EmployeeService{
}

both cases are working...

Visual Studio Code: format is not using indent settings

The number of spaces to use for formatting is taken from a different location. I'm using version 1.0 and this is what I've done to fix it (I'm assuming your using spaces instead of tabs):

At the bottom of the editor on the right hand click "Spaces: #":

status bar on the right

Then a menu will appear up top. Select "Indent Using Spaces":

select indentation type

Finally you can select by how many spaces you want your files to be indented.

select tab size

The next time you format a file you should be able to get the spacing you configured.

Histogram with Logarithmic Scale and custom breaks

I've put together a function that behaves identically to hist in the default case, but accepts the log argument. It uses several tricks from other posters, but adds a few of its own. hist(x) and myhist(x) look identical.

The original problem would be solved with:

myhist(mydata$V3, breaks=c(0,1,2,3,4,5,25), log="xy")

The function:

myhist <- function(x, ..., breaks="Sturges",
                   main = paste("Histogram of", xname),
                   xlab = xname,
                   ylab = "Frequency") {
  xname = paste(deparse(substitute(x), 500), collapse="\n")
  h = hist(x, breaks=breaks, plot=FALSE)
  plot(h$breaks, c(NA,h$counts), type='S', main=main,
       xlab=xlab, ylab=ylab, axes=FALSE, ...)
  axis(1)
  axis(2)
  lines(h$breaks, c(h$counts,NA), type='s')
  lines(h$breaks, c(NA,h$counts), type='h')
  lines(h$breaks, c(h$counts,NA), type='h')
  lines(h$breaks, rep(0,length(h$breaks)), type='S')
  invisible(h)
}

Exercise for the reader: Unfortunately, not everything that works with hist works with myhist as it stands. That should be fixable with a bit more effort, though.

Adding background image to div using CSS

Specify a height and a width:

.header-shadow{
    background-image: url('../images/header-shade.jpg');
    height: 10px;
    width: 10px;
}

How do I format a string using a dictionary in python-3.x?

print("{latitude} {longitude}".format(**geopoint))

How do I do a case-insensitive string comparison?

Using Python 2, calling .lower() on each string or Unicode object...

string1.lower() == string2.lower()

...will work most of the time, but indeed doesn't work in the situations @tchrist has described.

Assume we have a file called unicode.txt containing the two strings S?s?f?? and S?S?F?S. With Python 2:

>>> utf8_bytes = open("unicode.txt", 'r').read()
>>> print repr(utf8_bytes)
'\xce\xa3\xce\xaf\xcf\x83\xcf\x85\xcf\x86\xce\xbf\xcf\x82\n\xce\xa3\xce\x8a\xce\xa3\xce\xa5\xce\xa6\xce\x9f\xce\xa3\n'
>>> u = utf8_bytes.decode('utf8')
>>> print u
S?s?f??
S?S?F?S

>>> first, second = u.splitlines()
>>> print first.lower()
s?s?f??
>>> print second.lower()
s?s?f?s
>>> first.lower() == second.lower()
False
>>> first.upper() == second.upper()
True

The S character has two lowercase forms, ? and s, and .lower() won't help compare them case-insensitively.

However, as of Python 3, all three forms will resolve to ?, and calling lower() on both strings will work correctly:

>>> s = open('unicode.txt', encoding='utf8').read()
>>> print(s)
S?s?f??
S?S?F?S

>>> first, second = s.splitlines()
>>> print(first.lower())
s?s?f??
>>> print(second.lower())
s?s?f??
>>> first.lower() == second.lower()
True
>>> first.upper() == second.upper()
True

So if you care about edge-cases like the three sigmas in Greek, use Python 3.

(For reference, Python 2.7.3 and Python 3.3.0b1 are shown in the interpreter printouts above.)

The equivalent of a GOTO in python

answer = None
while True:
    answer = raw_input("Do you like pie?")
    if answer in ("yes", "no"): break
    print "That is not a yes or a no"

Would give you what you want with no goto statement.

How can I INSERT data into two tables simultaneously in SQL Server?

You could write a stored procedure that iterates over the transaction that you have proposed. The iterator would be the cursor for the table that contains the source data.

AngularJS custom filter function

Here's an example of how you'd use filter within your AngularJS JavaScript (rather than in an HTML element).

In this example, we have an array of Country records, each containing a name and a 3-character ISO code.

We want to write a function which will search through this list for a record which matches a specific 3-character code.

Here's how we'd do it without using filter:

$scope.FindCountryByCode = function (CountryCode) {
    //  Search through an array of Country records for one containing a particular 3-character country-code.
    //  Returns either a record, or NULL, if the country couldn't be found.
    for (var i = 0; i < $scope.CountryList.length; i++) {
        if ($scope.CountryList[i].IsoAlpha3 == CountryCode) {
            return $scope.CountryList[i];
        };
    };
    return null;
};

Yup, nothing wrong with that.

But here's how the same function would look, using filter:

$scope.FindCountryByCode = function (CountryCode) {
    //  Search through an array of Country records for one containing a particular 3-character country-code.
    //  Returns either a record, or NULL, if the country couldn't be found.

    var matches = $scope.CountryList.filter(function (el) { return el.IsoAlpha3 == CountryCode; })

    //  If 'filter' didn't find any matching records, its result will be an array of 0 records.
    if (matches.length == 0)
        return null;

    //  Otherwise, it should've found just one matching record
    return matches[0];
};

Much neater.

Remember that filter returns an array as a result (a list of matching records), so in this example, we'll either want to return 1 record, or NULL.

Hope this helps.

How to process POST data in Node.js?

Limit POST size avoid flood your node app. There is a great raw-body module, suitable both for express and connect, that can help you limit request by size and length.

Why do you have to link the math library in C?

The functions in stdlib.h and stdio.h have implementations in libc.so (or libc.a for static linking), which is linked into your executable by default (as if -lc were specified). GCC can be instructed to avoid this automatic link with the -nostdlib or -nodefaultlibs options.

The math functions in math.h have implementations in libm.so (or libm.a for static linking), and libm is not linked in by default. There are historical reasons for this libm/libc split, none of them very convincing.

Interestingly, the C++ runtime libstdc++ requires libm, so if you compile a C++ program with GCC (g++), you will automatically get libm linked in.

How do I find out which process is locking a file using .NET?

One of the good things about handle.exe is that you can run it as a subprocess and parse the output.

We do this in our deployment script - works like a charm.

Pass values of checkBox to controller action in asp.net mvc4

You should be strongly typing your views. Then you can do this:

public class YourViewModel {
    public bool ConditionaValue { get; set; }
}

In your view, you can create a checkbox that will bind to this boolean value:

@Html.CheckBoxFor(x => x.ConditionalValue)

If it is checked, the model property will be true.

For your immediate problem though.. you need to name your checkbox to be the same name as your action method parameters.. and they should be bool..

SyntaxError: Use of const in strict mode?

If this is happening in nodejs, it is due to the older version of nodejs. Update node by using,

1) Clear NPM's cache:

sudo npm cache clean -f

2) Install a little helper called 'n'

sudo npm install -g n

3) Install latest stable NodeJS version

sudo n stable

Update nodejs instructions taken from, https://stackoverflow.com/a/19584407/698072

Reset MySQL root password using ALTER USER statement after install on Mac

Run these:

$ cd /usr/local/mysql/bin
$ ./mysqladmin -u root password 'password'

Then run

./mysql -u root

It should log in. Now run FLUSH privileges;

Then exit the MySQL console and try logging in. If that doesn't work run these:

$ mysql -u root
mysql> USE mysql;
mysql> UPDATE user SET authentication_string=PASSWORD("XXXXXXX") WHERE User='root';
mysql> FLUSH PRIVILEGES;
mysql> quit

Change xxxxxx to ur new password. Then try logging in again.

Update. See this http://dev.mysql.com/doc/refman/5.7/en/resetting-permissions.html

It should solve your problem.

If you are on oracle try this

ALTER USER username IDENTIFIED BY password

how to make UITextView height dynamic according to text length?

In Storyboard / Interface Builder simply disable scrolling in the Attribute inspector.

In code textField.scrollEnabled = false should do the trick.

XML Parsing - Read a Simple XML File and Retrieve Values

Are you familiar with the DataSet class?

The DataSet can also load XML documents and you may find it easier to iterate.

http://msdn.microsoft.com/en-us/library/system.data.dataset.readxml.aspx

DataSet dt = new DataSet();
dt.ReadXml(@"c:\test.xml");

How to JUnit test that two List<E> contain the same elements in the same order?

For excellent code-readability, Fest Assertions has nice support for asserting lists

So in this case, something like:

Assertions.assertThat(returnedComponents).containsExactly("One", "Two", "Three");

Or make the expected list to an array, but I prefer the above approach because it's more clear.

Assertions.assertThat(returnedComponents).containsExactly(argumentComponents.toArray());

Python/BeautifulSoup - how to remove all tags from an element?

You can use the decompose method in bs4:

soup = bs4.BeautifulSoup('<body><a href="http://example.com/">I linked to <i>example.com</i></a></body>')

for a in soup.find('a').children:
    if isinstance(a,bs4.element.Tag):
        a.decompose()

print soup

Out: <html><body><a href="http://example.com/">I linked to </a></body></html>

Creating a copy of a database in PostgreSQL

First, sudo as the database user:

sudo su postgres

Go to PostgreSQL command line:

psql

Create the new database, give the rights and exit:

CREATE DATABASE new_database_name;
GRANT ALL PRIVILEGES ON DATABASE new_database_name TO my_user;
\d

Copy structure and data from the old database to the new one:

pg_dump old_database_name | psql new_database_name

AngularJS does not send hidden field value

Just in case someone still struggles with this, I had similar problem when trying to keep track of user session/userid on multipage form

Ive fixed that by adding

.when("/q2/:uid" in the routing:

    .when("/q2/:uid", {
        templateUrl: "partials/q2.html",
        controller: 'formController',
        paramExample: uid
    })

And added this as a hidden field to pass params between webform pages

<< input type="hidden" required ng-model="formData.userid" ng-init="formData.userid=uid" />

Im new to Angular so not sure its the best possible solution but it seems to work ok for me now

Test a string for a substring

if "ABCD" in "xxxxABCDyyyy":
    # whatever

How do I mock a static method that returns void with PowerMock?

In simpler terms, Imagine if you want mock below line:

StaticClass.method();

then you write below lines of code to mock:

PowerMockito.mockStatic(StaticClass.class);
PowerMockito.doNothing().when(StaticClass.class);
StaticClass.method();

How to get the date 7 days earlier date from current date in Java

You can use this to continue using the type Date and a more legible code, if you preffer:

import org.apache.commons.lang.time.DateUtils;
...
Date yourDate = DateUtils.addDays(new Date(), *days here*);

Run on server option not appearing in Eclipse

Perhaps you lost some configuration, check jar dependencies in properties -> Deployment Assembly. If you miss something, try to add dependencies again.

in my case, fixing this, Run on Server appear again.

What does -1 mean in numpy reshape?

numpy.reshape(a,newshape,order{})

check the below link for more info. https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html

for the below example you mentioned the output explains the resultant vector to be a single row.(-1) indicates the number of rows to be 1. if the

a = numpy.matrix([[1, 2, 3, 4], [5, 6, 7, 8]])
b = numpy.reshape(a, -1)

output:

matrix([[1, 2, 3, 4, 5, 6, 7, 8]])

this can be explained more precisely with another example:

b = np.arange(10).reshape((-1,1))

output:(is a 1 dimensional columnar array)

array([[0],
       [1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7],
       [8],
       [9]])

or

b = np.arange(10).reshape((1,-1))

output:(is a 1 dimensional row array)

array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])

Apache Maven install "'mvn' not recognized as an internal or external command" after setting OS environmental variables?

I had similar issue on Windows 7. At first I setup M2, M2_HOME under User variable but when I echoed %PATH% , I did not see maven bin directory listed under PATH. Then I setup M2, M2_HOME under system variable and it worked.

Double precision - decimal places

It is because it's being converted from a binary representation. Just because it has printed all those decimal digits doesn't mean it can represent all decimal values to that precision. Take, for example, this in Python:

>>> 0.14285714285714285
0.14285714285714285
>>> 0.14285714285714286
0.14285714285714285

Notice how I changed the last digit, but it printed out the same number anyway.

ASP.NET MVC Razor: How to render a Razor Partial View's HTML inside the controller action

@Html.Partial("nameOfPartial", Model)

Update

protected string RenderPartialViewToString(string viewName, object model)
{
    if (string.IsNullOrEmpty(viewName))
        viewName = ControllerContext.RouteData.GetRequiredString("action");

    ViewData.Model = model;

    using (StringWriter sw = new StringWriter()) {
        ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
        ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
        viewResult.View.Render(viewContext, sw);

        return sw.GetStringBuilder().ToString();
    }
}

GitHub README.md center image

To extend the answer a little bit to support local images, just replace FILE_PATH_PLACEHOLDER to your image path and check it out.

<p align="center">
  <img src="FILE_PATH_PLACEHOLDER">
</p>

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

The Accept Ranges header (the bit in writeHead()) is required for the HTML5 video controls to work.

I think instead of just blindly send the full file, you should first check the Accept Ranges header in the REQUEST, then read in and send just that bit. fs.createReadStream support start, and end option for that.

So I tried an example and it works. The code is not pretty but it is easy to understand. First we process the range header to get the start/end position. Then we use fs.stat to get the size of the file without reading the whole file into memory. Finally, use fs.createReadStream to send the requested part to the client.

var fs = require("fs"),
    http = require("http"),
    url = require("url"),
    path = require("path");

http.createServer(function (req, res) {
  if (req.url != "/movie.mp4") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end('<video src="http://localhost:8888/movie.mp4" controls></video>');
  } else {
    var file = path.resolve(__dirname,"movie.mp4");
    fs.stat(file, function(err, stats) {
      if (err) {
        if (err.code === 'ENOENT') {
          // 404 Error if file not found
          return res.sendStatus(404);
        }
      res.end(err);
      }
      var range = req.headers.range;
      if (!range) {
       // 416 Wrong range
       return res.sendStatus(416);
      }
      var positions = range.replace(/bytes=/, "").split("-");
      var start = parseInt(positions[0], 10);
      var total = stats.size;
      var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
      var chunksize = (end - start) + 1;

      res.writeHead(206, {
        "Content-Range": "bytes " + start + "-" + end + "/" + total,
        "Accept-Ranges": "bytes",
        "Content-Length": chunksize,
        "Content-Type": "video/mp4"
      });

      var stream = fs.createReadStream(file, { start: start, end: end })
        .on("open", function() {
          stream.pipe(res);
        }).on("error", function(err) {
          res.end(err);
        });
    });
  }
}).listen(8888);

vagrant primary box defined but commands still run against all boxes

The primary flag seems to only work for vagrant ssh for me.

In the past I have used the following method to hack around the issue.

# stage box intended for configuration closely matching production if ARGV[1] == 'stage'     config.vm.define "stage" do |stage|         box_setup stage, \         "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml"     end end 

How to find when a web page was last updated

This is a Pythonic way to do it:

import httplib
import yaml
c = httplib.HTTPConnection(address)
c.request('GET', url_path)
r = c.getresponse()
# get the date into a datetime object
lmd = r.getheader('last-modified')
if lmd != None:
   cur_data = { url: datetime.strptime(lmd, '%a, %d %b %Y %H:%M:%S %Z') }
else:
   print "Hmmm, no last-modified data was returned from the URL."
   print "Returned header:"
   print yaml.dump(dict(r.getheaders()), default_flow_style=False)

The rest of the script includes an example of archiving a page and checking for changes against the new version, and alerting someone by email.

Convert a number to 2 decimal places in Java

DecimalFormat df=new DecimalFormat("0.00");

Use this code to get exact two decimal points. Even if the value is 0.0 it will give u 0.00 as output.

Instead if you use:

DecimalFormat df=new DecimalFormat("#.00");  

It wont convert 0.2659 into 0.27. You will get an answer like .27.

How to check if object has any properties in JavaScript?

Most recent browsers (and node.js) support Object.keys() which returns an array with all the keys in your object literal so you could do the following:

var ad = {}; 
Object.keys(ad).length;//this will be 0 in this case

Browser Support: Firefox 4, Chrome 5, Internet Explorer 9, Opera 12, Safari 5

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

logout and redirecting session in php

Only this is necessary

session_start();
unset($_SESSION["nome"]);  // where $_SESSION["nome"] is your own variable. if you do not have one use only this as follow **session_unset();**
header("Location: home.php");

How do I iterate through each element in an n-dimensional matrix in MATLAB?

You can use linear indexing to access each element.

for idx = 1:numel(array)
    element = array(idx)
    ....
end

This is useful if you don't need to know what i,j,k, you are at. However, if you don't need to know what index you are at, you are probably better off using arrayfun()

SQL RANK() over PARTITION on joined tables

As the rank doesn't depend at all from the contacts

RANKED_RSLTS

 QRY_ID  |  RES_ID  |  SCORE |  RANK
-------------------------------------
   A     |    1     |    15  |   3
   A     |    2     |    32  |   1
   A     |    3     |    29  |   2
   C     |    7     |    61  |   1
   C     |    9     |    30  |   2

Thus :

SELECT
    C.*
    ,R.SCORE
    ,MYRANK
FROM CONTACTS C LEFT JOIN
(SELECT  *,
 MYRANK = RANK() OVER (PARTITION BY QRY_ID ORDER BY SCORE DESC)
  FROM RSLTS)  R
ON C.RES_ID = R.RES_ID
AND C.QRY_ID = R.QRY_ID

How to get all the AD groups for a particular user?

Use tokenGroups:

DirectorySearcher ds = new DirectorySearcher();
ds.Filter = String.Format("(&(objectClass=user)(sAMAccountName={0}))", username);
SearchResult sr = ds.FindOne();

DirectoryEntry user = sr.GetDirectoryEntry();
user.RefreshCache(new string[] { "tokenGroups" });

for (int i = 0; i < user.Properties["tokenGroups"].Count; i++) {
    SecurityIdentifier sid = new SecurityIdentifier((byte[]) user.Properties["tokenGroups"][i], 0);
    NTAccount nt = (NTAccount)sid.Translate(typeof(NTAccount));
    //do something with the SID or name (nt.Value)
}

Note: this only gets security groups

Can I have an onclick effect in CSS?

I had a problem with an element which had to be colored RED on hover and be BLUE on click while being hovered. To achieve this with css you need for example:

h1:hover { color: red; } 
h1:active { color: blue; }

<h1>This is a heading.</h1>

I struggled for some time until I discovered that the order of CSS selectors was the problem I was having. The problem was that I switched the places and the active selector was not working. Then I found out that :hover to go first and then :active.

Session 'app': Error Launching activity

All answers did not work for me.This error raised when I was trying to rename the app package.I have ended up creating a new project with the new package name and move my files to the new one.

Single line sftp from terminal

Update Sep 2017 - tl;dr

Download a single file from a remote ftp server to your machine:

sftp {user}@{host}:{remoteFileName} {localFileName}

Upload a single file from your machine to a remote ftp server:

sftp {user}@{host}:{remote_dir} <<< $'put {local_file_path}'

Original answer:

Ok, so I feel a little dumb. But I figured it out. I almost had it at the top with:

sftp user@host remoteFile localFile

The only documentation shown in the terminal is this:

sftp [user@]host[:file ...]
sftp [user@]host[:dir[/]]

However, I came across this site which shows the following under the synopsis:

sftp [-vC1 ] [-b batchfile ] [-o ssh_option ] [-s subsystem | sftp_server ] [-B buffer_size ] [-F ssh_config ] [-P sftp_server path ] [-R num_requests ] [-S program ] host 
sftp [[user@]host[:file [file]]] 
sftp [[user@]host[:dir[/]]]

So the simple answer is you just do : after your user and host then the remote file and local filename. Incredibly simple!

Single line, sftp copy remote file:

sftp username@hostname:remoteFileName localFileName
sftp kyle@kylesserver:/tmp/myLogFile.log /tmp/fileNameToUseLocally.log

Update Feb 2016

In case anyone is looking for the command to do the reverse of this and push a file from your local computer to a remote server in one single line sftp command, user @Thariama below posted the solution to accomplish that. Hat tip to them for the extra code.

sftp {user}@{host}:{remote_dir} <<< $'put {local_file_path}'

How to create EditText with rounded corners?

Thanks for Norfeldt's answer. I slightly changed its gradient for a better inner shadow effect.

<item android:state_pressed="false" android:state_focused="false">
    <shape>
        <gradient
            android:centerY="0.2"
            android:startColor="#D3D3D3"
            android:centerColor="#65FFFFFF"
            android:endColor="#00FFFFFF"
            android:angle="270"
            />
        <stroke
            android:width="0.7dp"
            android:color="#BDBDBD" />
        <corners
            android:radius="15dp" />
    </shape>
</item>

Looks great in a light backgrounded layout..

enter image description here

Difference of keywords 'typename' and 'class' in templates?

This piece of snippet is from c++ primer book. Although I am sure this is wrong.

Each type parameter must be preceded by the keyword class or typename:

// error: must precede U with either typename or class
template <typename T, U> T calc(const T&, const U&);

These keywords have the same meaning and can be used interchangeably inside a template parameter list. A template parameter list can use both keywords:

// ok: no distinction between typename and class in a template parameter list
template <typename T, class U> calc (const T&, const U&);

It may seem more intuitive to use the keyword typename rather than class to designate a template type parameter. After all, we can use built-in (nonclass) types as a template type argument. Moreover, typename more clearly indicates that the name that follows is a type name. However, typename was added to C++ after templates were already in widespread use; some programmers continue to use class exclusively

disable past dates on datepicker

var dateToday = new Date();

$('#datepicker').datepicker({                                     
    'startDate': dateToday
});

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

I got this error after change a loop in my program, let`s see:

for ...
  for ... 
     x_batch.append(one_hot(int_word, vocab_size))
     y_batch.append(one_hot(int_nb, vocab_size, value))
  ...
  ...
  if ...
        x_batch = np.asarray(x_batch)
        y_batch = np.asarray(y_batch)
...

In fact, I was reusing the variable and forgot to reset them inside the external loop, like the comment of John Lyon:

for ...
  x_batch = []
  y_batch = []
  for ... 
     x_batch.append(one_hot(int_word, vocab_size))
     y_batch.append(one_hot(int_nb, vocab_size, value))
  ...
  ...
  if ...
        x_batch = np.asarray(x_batch)
        y_batch = np.asarray(y_batch)
...

Then, check if you are using np.asarray() or something like that.

How to copy a char array in C?

array2 = array1;

is not supported in c. You have to use functions like strcpy() to do it.

How to store printStackTrace into a string

You have to use getStackTrace () method instead of printStackTrace(). Here is a good example:

import java.io.*;

/**
* Simple utilities to return the stack trace of an
* exception as a String.
*/
public final class StackTraceUtil {

  public static String getStackTrace(Throwable aThrowable) {
    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);
    aThrowable.printStackTrace(printWriter);
    return result.toString();
  }

  /**
  * Defines a custom format for the stack trace as String.
  */
  public static String getCustomStackTrace(Throwable aThrowable) {
    //add the class name and any message passed to constructor
    final StringBuilder result = new StringBuilder( "BOO-BOO: " );
    result.append(aThrowable.toString());
    final String NEW_LINE = System.getProperty("line.separator");
    result.append(NEW_LINE);

    //add each element of the stack trace
    for (StackTraceElement element : aThrowable.getStackTrace() ){
      result.append( element );
      result.append( NEW_LINE );
    }
    return result.toString();
  }

  /** Demonstrate output.  */
  public static void main (String... aArguments){
    final Throwable throwable = new IllegalArgumentException("Blah");
    System.out.println( getStackTrace(throwable) );
    System.out.println( getCustomStackTrace(throwable) );
  }
} 

API vs. Webservice

another example: google map api vs google direction api web service, while the former serves (delivers) javascript file to the site (which can then be used as an api to make new functions) , the later is a Rest web service delivering data (in json or xml format), which can be processed (but not used in an api sense).

SQL MERGE statement to update data

Update energydata set energydata.kWh = temp.kWh 
where energydata.webmeterID = (select webmeterID from temp_energydata as temp) 

How to append something to an array?

concat(), of course, can be used with 2 dimensional arrays as well. No looping required.

var a = [ [1, 2], [3, 4] ];

var b = [ ["a", "b"], ["c", "d"] ];

b = b.concat(a);

alert(b[2][1]); // result 2

Git push error pre-receive hook declined

Please check if JIRA status in "In Development". For me , it was not , when i changed jira status to "In Development", it worked for me.

How to fix docker: Got permission denied issue

In Linux environment, after installing docker and docker-compose reboot is required for work docker better.

$ reboot

OR restart the docker

$ sudo systemctl restart docker

Laravel 5 - redirect to HTTPS

Alternatively, If you are using Apache then you can use .htaccess file to enforce your URLs to use https prefix. On Laravel 5.4, I added the following lines to my .htaccess file and it worked for me.

RewriteEngine On

RewriteCond %{HTTPS} !on
RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

How to show current time in JavaScript in the format HH:MM:SS?

You can use moment.js to do this.

var now = new moment();
console.log(now.format("HH:mm:ss"));

Outputs:

16:30:03