Programs & Examples On #N way

How to select a div element in the code-behind page?

you'll need to cast it to an HtmlControl in order to access the Style property.

HtmlControl control = (HtmlControl)Page.FindControl("portlet_tab1"); control.Style.Add("display","none");

Comparing two NumPy arrays for equality, element-wise

Let's measure the performance by using the following piece of code.

import numpy as np
import time

exec_time0 = []
exec_time1 = []
exec_time2 = []

sizeOfArray = 5000
numOfIterations = 200

for i in xrange(numOfIterations):

    A = np.random.randint(0,255,(sizeOfArray,sizeOfArray))
    B = np.random.randint(0,255,(sizeOfArray,sizeOfArray))

    a = time.clock() 
    res = (A==B).all()
    b = time.clock()
    exec_time0.append( b - a )

    a = time.clock() 
    res = np.array_equal(A,B)
    b = time.clock()
    exec_time1.append( b - a )

    a = time.clock() 
    res = np.array_equiv(A,B)
    b = time.clock()
    exec_time2.append( b - a )

print 'Method: (A==B).all(),       ', np.mean(exec_time0)
print 'Method: np.array_equal(A,B),', np.mean(exec_time1)
print 'Method: np.array_equiv(A,B),', np.mean(exec_time2)

Output

Method: (A==B).all(),        0.03031857
Method: np.array_equal(A,B), 0.030025185
Method: np.array_equiv(A,B), 0.030141515

According to the results above, the numpy methods seem to be faster than the combination of the == operator and the all() method and by comparing the numpy methods the fastest one seems to be the numpy.array_equal method.

Convert varchar to uniqueidentifier in SQL Server

It would make for a handy function. Also, note I'm using STUFF instead of SUBSTRING.

create function str2uniq(@s varchar(50)) returns uniqueidentifier as begin
    -- just in case it came in with 0x prefix or dashes...
    set @s = replace(replace(@s,'0x',''),'-','')
    -- inject dashes in the right places
    set @s = stuff(stuff(stuff(stuff(@s,21,0,'-'),17,0,'-'),13,0,'-'),9,0,'-')
    return cast(@s as uniqueidentifier)
end

Java : Convert formatted xml file to one line string

//filename is filepath string
BufferedReader br = new BufferedReader(new FileReader(new File(filename)));
String line;
StringBuilder sb = new StringBuilder();

while((line=br.readLine())!= null){
    sb.append(line.trim());
}

using StringBuilder is more efficient then concat http://kaioa.com/node/59

Stash just a single file

You can interactively stash single lines with git stash -p (analogous to git add -p).

It doesn't take a filename, but you could just skip other files with d until you reached the file you want stashed and the stash all changes in there with a.

error: command 'gcc' failed with exit status 1 while installing eventlet

If it is still not working, you can try this

sudo apt-get install build-essential

in my case, it solved the problem.

How to continue a Docker container which has exited

by name

sudo docker start bob_the_container

or by Id

sudo docker start aa3f365f0f4e

this restarts stopped container, use -i to attach container's STDIN or instead of -i you can attach to container session (if you run with -it)

sudo docker attach bob_the_container

Oracle DB : java.sql.SQLException: Closed Connection

It means the connection was successfully established at some point, but when you tried to commit right there, the connection was no longer open. The parameters you mentioned sound like connection pool settings. If so, they're unrelated to this problem. The most likely cause is a firewall between you and the database that is killing connections after a certain amount of idle time. The most common fix is to make your connection pool run a validation query when a connection is checked out from it. This will immediately identify and evict dead connnections, ensuring that you only get good connections out of the pool.

How do I see which version of Swift I'm using?

if you want to check the run code for a particular version of swift you can use

#if compiler(>=5.1) //4.2, 3.0, 2.0 replace whatever swft version you wants to check
#endif

What's the difference between a Python module and a Python package?

Any Python file is a module, its name being the file's base name without the .py extension. A package is a collection of Python modules: while a module is a single Python file, a package is a directory of Python modules containing an additional __init__.py file, to distinguish a package from a directory that just happens to contain a bunch of Python scripts. Packages can be nested to any depth, provided that the corresponding directories contain their own __init__.py file.

The distinction between module and package seems to hold just at the file system level. When you import a module or a package, the corresponding object created by Python is always of type module. Note, however, when you import a package, only variables/functions/classes in the __init__.py file of that package are directly visible, not sub-packages or modules. As an example, consider the xml package in the Python standard library: its xml directory contains an __init__.py file and four sub-directories; the sub-directory etree contains an __init__.py file and, among others, an ElementTree.py file. See what happens when you try to interactively import package/modules:

>>> import xml
>>> type(xml)
<type 'module'>
>>> xml.etree.ElementTree
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'etree'
>>> import xml.etree
>>> type(xml.etree)
<type 'module'>
>>> xml.etree.ElementTree
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'ElementTree'
>>> import xml.etree.ElementTree
>>> type(xml.etree.ElementTree)
<type 'module'>
>>> xml.etree.ElementTree.parse
<function parse at 0x00B135B0>

In Python there also are built-in modules, such as sys, that are written in C, but I don't think you meant to consider those in your question.

Auto reloading python Flask app upon code changes

If you're running using uwsgi look at the python auto reload option:

uwsgi --py-autoreload 1

Example uwsgi-dev-example.ini:

[uwsgi]
socket = 127.0.0.1:5000
master = true
virtualenv = /Users/xxxx/.virtualenvs/sites_env
chdir = /Users/xxx/site_root
module = site_module:register_debug_server()
callable = app
uid = myuser
chmod-socket = 660
log-date = true
workers = 1
py-autoreload = 1

site_root/__init__.py

def register_debug_server():
    from werkzeug.debug import DebuggedApplication

    app = Flask(__name__)
    app.debug = True
    app = DebuggedApplication(app, evalex=True)
    return app

Then run:

uwsgi --ini uwsgi-dev-example.ini

Note: This example also enables the debugger.

I went this route to mimic production as close as possible with my nginx setup. Simply running the flask app with it's built in web server behind nginx it would result in a bad gateway error.

Current time formatting with Javascript

function formatTime(date){

  d = new Date(date);
  var h=d.getHours(),m=d.getMinutes(),l="AM";
  if(h > 12){
    h = h - 12;
  }
  if(h < 10){
    h = '0'+h;
  }
  if(m < 10){
    m = '0'+m;
  }
  if(d.getHours() >= 12){
    l="PM"
  }else{
    l="AM"
  }

  return h+':'+m+' '+l;

}

Usage & result:

var formattedTime=formatTime(new Date('2020 15:00'));
// Output: "03:00 PM"

Select <a> which href ends with some string

$('a[href$="ABC"]:first').attr('title');

This will return the title of the first link that has a URL which ends with "ABC".

Access-Control-Allow-Origin error sending a jQuery Post to Google API's

try my code In JavaScript

 var settings = {
              "url": "https://myinboxhub.co.in/example",
              "method": "GET",
              "timeout": 0,
              "headers": {},
            };
        $.ajax(settings).done(function (response) {
          console.log(response);
            if (response.auth) { 
                console.log('on success');
            } 
        }).fail(function (jqXHR, exception) { 
                var msg = '';
                if (jqXHR.status === '(failed)net::ERR_INTERNET_DISCONNECTED') {
                    
                        msg = 'Uncaught Error.\n' + jqXHR.responseText; 
                }
                if (jqXHR.status === 0) {
                        msg = 'Not connect.\n Verify Network.';
                } else if (jqXHR.status == 413) {
                        msg = 'Image size is too large.'; 
                }  else if (jqXHR.status == 404) {
                        msg = 'Requested page not found. [404]'; 
                } else if (jqXHR.status == 405) {
                        msg = 'Image size is too large.'; 
                } else if (jqXHR.status == 500) {
                        msg = 'Internal Server Error [500].'; 
                } else if (exception === 'parsererror') {
                        msg = 'Requested JSON parse failed.'; 
                } else if (exception === 'timeout') {
                        msg = 'Time out error.'; 
                } else if (exception === 'abort') {
                        msg = 'Ajax request aborted.'; 
                } else {
                        msg = 'Uncaught Error.\n' + jqXHR.responseText; 
                }
                console.log(msg);
        });;

In PHP

header('Content-type: application/json');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding");

print arraylist element?

Do you want to print the entire list or you want to iterate through each element of the list? Either way to print anything meaningful your Dog class need to override the toString() method (as mentioned in other answers) from the Object class to return a valid result.

public class Print {
    public static void main(final String[] args) {
        List<Dog> list = new ArrayList<Dog>();
        Dog e = new Dog("Tommy");
        list.add(e);
        list.add(new Dog("tiger"));
        System.out.println(list);
        for(Dog d:list) {
            System.out.println(d);
            // prints [Tommy, tiger]
        }
    }

    private static class Dog {
        private final String name;
        public Dog(final String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return name;
        }
    }
}

The output of this code is:

[Tommy, tiger]  
Tommy  
tiger

How to change the style of alert box?

_x000D_
_x000D_
<head>_x000D_
  _x000D_
_x000D_
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">_x000D_
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>_x000D_
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>_x000D_
  _x000D_
    <script type="text/javascript">_x000D_
  _x000D_
_x000D_
$(function() {_x000D_
    $( "#dialog" ).dialog({_x000D_
      autoOpen: false,_x000D_
      show: {_x000D_
        effect: "blind",_x000D_
        duration: 1000_x000D_
      },_x000D_
      hide: {_x000D_
        effect: "explode",_x000D_
        duration: 1000_x000D_
      }_x000D_
    });_x000D_
 _x000D_
    $( "#opener" ).click(function() {_x000D_
      $( "#dialog" ).dialog( "open" );_x000D_
    });_x000D_
  });_x000D_
    </script>_x000D_
</head>_x000D_
<body>_x000D_
   <div id="dialog" title="Basic dialog">_x000D_
   <p>This is an animated dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>_x000D_
  </div>_x000D_
 _x000D_
  <button id="opener">Open Dialog</button>_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_

Using if elif fi in shell scripts

I have a sample from your code. Try this:

echo "*Select Option:*"
echo "1 - script1"
echo "2 - script2"
echo "3 - script3 "
read option
echo "You have selected" $option"."
if [ $option="1" ]
then
    echo "1"
elif [ $option="2" ]
then
    echo "2"
    exit 0
elif [ $option="3" ]
then
    echo "3"
    exit 0
else
    echo "Please try again from given options only."
fi

This should work. :)

How to change the color of a CheckBox?

Programmatic version:

int states[][] = {{android.R.attr.state_checked}, {}};
int colors[] = {color_for_state_checked, color_for_state_normal}
CompoundButtonCompat.setButtonTintList(checkbox, new ColorStateList(states, colors));

Deprecated Java HttpClient - How hard can it be?

IMHO the accepted answer is correct but misses some 'teaching' as it does not explain how to come up with the answer. For all deprecated classes look at the JavaDoc (if you do not have it either download it or go online), it will hint at which class to use to replace the old code. Of course it will not tell you everything, but this is a start. Example:

...
 *
 * @deprecated (4.3) use {@link HttpClientBuilder}.  <----- THE HINT IS HERE !
 */
@ThreadSafe
@Deprecated
public class DefaultHttpClient extends AbstractHttpClient {

Now you have the class to use, HttpClientBuilder, as there is no constructor to get a builder instance you may guess that there must be a static method instead: create. Once you have the builder you can also guess that as for most builders there is a build method, thus:

org.apache.http.impl.client.HttpClientBuilder.create().build();

AutoClosable:

As Jules hinted in the comments, the returned class implements java.io.Closable, so if you use Java 7 or above you can now do:

    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {...}

The advantage is that you do not have to deal with finally and nulls.

Other relevant info

Also make sure to read about connection pooling and set the timeouts.

Rails params explained?

As others have pointed out, params values can come from the query string of a GET request, or the form data of a POST request, but there's also a third place they can come from: The path of the URL.

As you might know, Rails uses something called routes to direct requests to their corresponding controller actions. These routes may contain segments that are extracted from the URL and put into params. For example, if you have a route like this:

match 'products/:id', ...

Then a request to a URL like http://example.com/products/42 will set params[:id] to 42.

What are all the different ways to create an object in Java?

There are five different ways to create an object in Java,

1. Using new keyword ? constructor get called

Employee emp1 = new Employee();

2. Using newInstance() method of Class ? constructor get called

Employee emp2 = (Employee) Class.forName("org.programming.mitra.exercises.Employee")
                                .newInstance();

It can also be written as

Employee emp2 = Employee.class.newInstance();

3. Using newInstance() method of Constructor ? constructor get called

Constructor<Employee> constructor = Employee.class.getConstructor();
Employee emp3 = constructor.newInstance();

4. Using clone() method ? no constructor call

Employee emp4 = (Employee) emp3.clone();

5. Using deserialization ? no constructor call

ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj"));
Employee emp5 = (Employee) in.readObject();

First three methods new keyword and both newInstance() include a constructor call but later two clone and deserialization methods create objects without calling the constructor.

All above methods have different bytecode associated with them, Read Different ways to create objects in Java with Example for examples and more detailed description e.g. bytecode conversion of all these methods.

However one can argue that creating an array or string object is also a way of creating the object but these things are more specific to some classes only and handled directly by JVM, while we can create an object of any class by using these 5 ways.

How do you get the selected value of a Spinner?

mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()) works based on Rich's description.

Add a summary row with totals

If you want to display more column values without an aggregation function use GROUPING SETS instead of ROLLUP:

SELECT
  Type = ISNULL(Type, 'Total'),
  SomeIntColumn = ISNULL(SomeIntColumn, 0),
  TotalSales = SUM(TotalSales)
FROM atable
GROUP BY GROUPING SETS ((Type, SomeIntColumn ), ())
ORDER BY SomeIntColumn --Displays summary row as the first row in query result

Iterate over elements of List and Map using JSTL <c:forEach> tag

Mark, this is already answered in your previous topic. But OK, here it is again:

Suppose ${list} points to a List<Object>, then the following

<c:forEach items="${list}" var="item">
    ${item}<br>
</c:forEach>

does basically the same as as following in "normal Java":

for (Object item : list) {
    System.out.println(item);
}

If you have a List<Map<K, V>> instead, then the following

<c:forEach items="${list}" var="map">
    <c:forEach items="${map}" var="entry">
        ${entry.key}<br>
        ${entry.value}<br>
    </c:forEach>
</c:forEach>

does basically the same as as following in "normal Java":

for (Map<K, V> map : list) {
    for (Entry<K, V> entry : map.entrySet()) {
        System.out.println(entry.getKey());
        System.out.println(entry.getValue());
    }
}

The key and value are here not special methods or so. They are actually getter methods of Map.Entry object (click at the blue Map.Entry link to see the API doc). In EL (Expression Language) you can use the . dot operator to access getter methods using "property name" (the getter method name without the get prefix), all just according the Javabean specification.

That said, you really need to cleanup the "answers" in your previous topic as they adds noise to the question. Also read the comments I posted in your "answers".

Is there a way to check if a file is in use?

Just use the exception as intended. Accept that the file is in use and try again, repeatedly until your action is completed. This is also the most efficient because you do not waste any cycles checking the state before acting.

Use the function below, for example

TimeoutFileAction(() => { System.IO.File.etc...; return null; } );

Reusable method that times out after 2 seconds

private T TimeoutFileAction<T>(Func<T> func)
{
    var started = DateTime.UtcNow;
    while ((DateTime.UtcNow - started).TotalMilliseconds < 2000)
    {
        try
        {
            return func();                    
        }
        catch (System.IO.IOException exception)
        {
            //ignore, or log somewhere if you want to
        }
    }
    return default(T);
}

Pass arguments into C program from command line

Take a look at the getopt library; it's pretty much the gold standard for this sort of thing.

How to create friendly URL in php?

I try to explain this problem step by step in following example.

0) Question

I try to ask you like this :

i want to open page like facebook profile www.facebook.com/kaila.piyush

it get id from url and parse it to profile.php file and return featch data from database and show user to his profile

normally when we develope any website its link look like www.website.com/profile.php?id=username example.com/weblog/index.php?y=2000&m=11&d=23&id=5678

now we update with new style not rewrite we use www.website.com/username or example.com/weblog/2000/11/23/5678 as permalink

http://example.com/profile/userid (get a profile by the ID) 
http://example.com/profile/username (get a profile by the username) 
http://example.com/myprofile (get the profile of the currently logged-in user)

1) .htaccess

Create a .htaccess file in the root folder or update the existing one :

Options +FollowSymLinks
# Turn on the RewriteEngine
RewriteEngine On
#  Rules
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php

What does that do ?

If the request is for a real directory or file (one that exists on the server), index.php isn't served, else every url is redirected to index.php.

2) index.php

Now, we want to know what action to trigger, so we need to read the URL :

In index.php :

// index.php    

// This is necessary when index.php is not in the root folder, but in some subfolder...
// We compare $requestURL and $scriptName to remove the inappropriate values
$requestURI = explode(‘/’, $_SERVER[‘REQUEST_URI’]);
$scriptName = explode(‘/’,$_SERVER[‘SCRIPT_NAME’]);

for ($i= 0; $i < sizeof($scriptName); $i++)
{
    if ($requestURI[$i] == $scriptName[$i])
    {
        unset($requestURI[$i]);
    }
}

$command = array_values($requestURI);
With the url http://example.com/profile/19837, $command would contain :

$command = array(
    [0] => 'profile',
    [1] => 19837,
    [2] => ,
)
Now, we have to dispatch the URLs. We add this in the index.php :

// index.php

require_once("profile.php"); // We need this file
switch($command[0])
{
    case ‘profile’ :
        // We run the profile function from the profile.php file.
        profile($command([1]);
        break;
    case ‘myprofile’ :
        // We run the myProfile function from the profile.php file.
        myProfile();
        break;
    default:
        // Wrong page ! You could also redirect to your custom 404 page.
        echo "404 Error : wrong page.";
        break;
}

2) profile.php

Now in the profile.php file, we should have something like this :

// profile.php

function profile($chars)
{
    // We check if $chars is an Integer (ie. an ID) or a String (ie. a potential username)

    if (is_int($chars)) {
        $id = $chars;
        // Do the SQL to get the $user from his ID
        // ........
    } else {
        $username = mysqli_real_escape_string($char);
        // Do the SQL to get the $user from his username
        // ...........
    }

    // Render your view with the $user variable
    // .........
}

function myProfile()
{
    // Get the currently logged-in user ID from the session :
    $id = ....

    // Run the above function :
    profile($id);
}

Adding a new array element to a JSON object

JSON is just a notation; to make the change you want parse it so you can apply the changes to a native JavaScript Object, then stringify back to JSON

var jsonStr = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';

var obj = JSON.parse(jsonStr);
obj['theTeam'].push({"teamId":"4","status":"pending"});
jsonStr = JSON.stringify(obj);
// "{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"

css transform, jagged edges in chrome

I've been having an issue with a CSS3 gradient with -45deg. The background slanted, was badly jagged similar to but worse than the original post. So I started playing with both the background-size. This would stretch out the jaggedness, but it was still there. Then in addition I read that other people are having issues too at 45deg increments so I adjusted from -45deg to -45.0001deg and my problem was solved.

In my CSS below, background-size was initially 30px and the deg for the background gradient was exactly -45deg, and all keyframes were 30px 0.

    @-webkit-keyframes progressStripeLTR {
        to {
            background-position: 60px 0;
        };
    }

    @-moz-keyframes progressStripeLTR {
        to {
            background-position: 60px 0;
        };
    }

    @-ms-keyframes progressStripeLTR {
        to {
            background-position: 60px 0;
        };
    }

    @-o-keyframes progressStripeLTR {
        to {
            background-position: 60px 0;
        };
    }

    @keyframes progressStripeLTR {
        to {
            background-position: 60px 0;
        };
    }

    @-webkit-keyframes progressStripeRTL {
        to {
            background-position: -60px 0;
        };
    }

    @-moz-keyframes progressStripeRTL {
        to {
            background-position: -60px 0;
        };
    }

    @-ms-keyframes progressStripeRTL {
        to {
            background-position: -60px 0;
        };
    }

    @-o-keyframes progressStripeRTL {
        to {
            background-position: -60px 0;
        };
    }

    @keyframes progressStripeRTL {
        to {
            background-position: -60px 0;
        };
    }

    .pro-bar-candy {
        width: 100%;
        height: 15px;

        -webkit-border-radius:  3px;
        -moz-border-radius:     3px;
        border-radius:          3px;

        background: rgb(187, 187, 187);
        background: -moz-linear-gradient(
                        -45.0001deg,
                        rgba(187, 187, 187, 1.00) 25%,
                        transparent 25%,
                        transparent 50%,
                        rgba(187, 187, 187, 1.00) 50%,
                        rgba(187, 187, 187, 1.00) 75%,
                        transparent 75%,
                        transparent
                    );
        background: -webkit-linear-gradient(
                        -45.0001deg,
                        rgba(187, 187, 187, 1.00) 25%,
                        transparent 25%,
                        transparent 50%,
                        rgba(187, 187, 187, 1.00) 50%,
                        rgba(187, 187, 187, 1.00) 75%,
                        transparent 75%,
                        transparent
                    );
        background: -o-linear-gradient(
                        -45.0001deg,
                        rgba(187, 187, 187, 1.00) 25%,
                        transparent 25%,
                        transparent 50%,
                        rgba(187, 187, 187, 1.00) 50%,
                        rgba(187, 187, 187, 1.00) 75%,
                        transparent 75%,
                        transparent
                    );
        background: -ms-linear-gradient(
                        -45.0001deg,
                        rgba(187, 187, 187, 1.00) 25%,
                        transparent 25%,
                        transparent 50%,
                        rgba(187, 187, 187, 1.00) 50%,
                        rgba(187, 187, 187, 1.00) 75%,
                        transparent 75%,
                        transparent
                    );
        background: linear-gradient(
                        -45.0001deg,
                        rgba(187, 187, 187, 1.00) 25%,
                        transparent 25%,
                        transparent 50%,
                        rgba(187, 187, 187, 1.00) 50%,
                        rgba(187, 187, 187, 1.00) 75%,
                        transparent 75%,
                        transparent
                    );
        background: -webkit-gradient(
                        linear,
                        right bottom,
                        right top,
                        color-stop(
                            25%,
                            rgba(187, 187, 187, 1.00)
                        ),
                        color-stop(
                            25%,
                            rgba(0, 0, 0, 0.00)
                        ),
                        color-stop(
                            50%,
                            rgba(0, 0, 0, 0.00)
                        ),
                        color-stop(
                            50%,
                            rgba(187, 187, 187, 1.00)
                        ),
                        color-stop(
                            75%,
                            rgba(187, 187, 187, 1.00)
                        ),
                        color-stop(
                            75%,
                            rgba(0, 0, 0, 0.00)
                        ),
                        color-stop(
                            rgba(0, 0, 0, 0.00)
                        )
                    );

        background-repeat: repeat-x;
        -webkit-background-size:    60px 60px;
        -moz-background-size:       60px 60px;
        -o-background-size:         60px 60px;
        background-size:            60px 60px;
        }

    .pro-bar-candy.candy-ltr {
        -webkit-animation:  progressStripeLTR .6s linear infinite;
        -moz-animation:     progressStripeLTR .6s linear infinite;
        -ms-animation:      progressStripeLTR .6s linear infinite;
        -o-animation:       progressStripeLTR .6s linear infinite;
        animation:          progressStripeLTR .6s linear infinite;
        }

    .pro-bar-candy.candy-rtl {
        -webkit-animation:  progressStripeRTL .6s linear infinite;
        -moz-animation:     progressStripeRTL .6s linear infinite;
        -ms-animation:      progressStripeRTL .6s linear infinite;
        -o-animation:       progressStripeRTL .6s linear infinite;
        animation:          progressStripeRTL .6s linear infinite;
        }

How can I dynamically add a directive in AngularJS?

Dynamically adding directives on angularjs has two styles:

Add an angularjs directive into another directive

  • inserting a new element(directive)
  • inserting a new attribute(directive) to element

inserting a new element(directive)

it's simple. And u can use in "link" or "compile".

var newElement = $compile( "<div my-diretive='n'></div>" )( $scope );
$element.parent().append( newElement );

inserting a new attribute to element

It's hard, and make me headache within two days.

Using "$compile" will raise critical recursive error!! Maybe it should ignore the current directive when re-compiling element.

$element.$set("myDirective", "expression");
var newElement = $compile( $element )( $scope ); // critical recursive error.
var newElement = angular.copy(element);          // the same error too.
$element.replaceWith( newElement );

So, I have to find a way to call the directive "link" function. It's very hard to get the useful methods which are hidden deeply inside closures.

compile: (tElement, tAttrs, transclude) ->
   links = []
   myDirectiveLink = $injector.get('myDirective'+'Directive')[0] #this is the way
   links.push myDirectiveLink
   myAnotherDirectiveLink = ($scope, $element, attrs) ->
       #....
   links.push myAnotherDirectiveLink
   return (scope, elm, attrs, ctrl) ->
       for link in links
           link(scope, elm, attrs, ctrl)       

Now, It's work well.

Calculate the execution time of a method

If you are interested in understand performance, the best answer is to use a profiler.

Otherwise, System.Diagnostics.StopWatch provides a high resolution timer.

How to get MAC address of client using PHP?

The MAC address (the low-level local network interface address) does not survive hops through IP routers. You can't find the client MAC address from a remote server.

In a local subnet, the MAC addresses are mapped to IP addresses through the ARP system. Interfaces on the local net know how to map IP addresses to MAC addresses. However, when your packets have been routed on the local subnet to (and through) the gateway out to the "real" Internet, the originating MAC address is lost. Simplistically, each subnet-to-subnet hop of your packets involve the same sort of IP-to-MAC mapping for local routing in each subnet.

What is the difference between atomic / volatile / synchronized?

Declaring a variable as volatile means that modifying its value immediately affects the actual memory storage for the variable. The compiler cannot optimize away any references made to the variable. This guarantees that when one thread modifies the variable, all other threads see the new value immediately. (This is not guaranteed for non-volatile variables.)

Declaring an atomic variable guarantees that operations made on the variable occur in an atomic fashion, i.e., that all of the substeps of the operation are completed within the thread they are executed and are not interrupted by other threads. For example, an increment-and-test operation requires the variable to be incremented and then compared to another value; an atomic operation guarantees that both of these steps will be completed as if they were a single indivisible/uninterruptible operation.

Synchronizing all accesses to a variable allows only a single thread at a time to access the variable, and forces all other threads to wait for that accessing thread to release its access to the variable.

Synchronized access is similar to atomic access, but the atomic operations are generally implemented at a lower level of programming. Also, it is entirely possible to synchronize only some accesses to a variable and allow other accesses to be unsynchronized (e.g., synchronize all writes to a variable but none of the reads from it).

Atomicity, synchronization, and volatility are independent attributes, but are typically used in combination to enforce proper thread cooperation for accessing variables.

Addendum (April 2016)

Synchronized access to a variable is usually implemented using a monitor or semaphore. These are low-level mutex (mutual exclusion) mechanisms that allow a thread to acquire control of a variable or block of code exclusively, forcing all other threads to wait if they also attempt to acquire the same mutex. Once the owning thread releases the mutex, another thread can acquire the mutex in turn.

Addendum (July 2016)

Synchronization occurs on an object. This means that calling a synchronized method of a class will lock the this object of the call. Static synchronized methods will lock the Class object itself.

Likewise, entering a synchronized block requires locking the this object of the method.

This means that a synchronized method (or block) can be executing in multiple threads at the same time if they are locking on different objects, but only one thread can execute a synchronized method (or block) at a time for any given single object.

CSS I want a div to be on top of everything

For z-index:1000 to have an effect you need a non-static positioning scheme.

Add position:relative; to a rule selecting the element you want to be on top

How do I do redo (i.e. "undo undo") in Vim?

Also check out :undolist, which offers multiple paths through the undo history. This is useful if you accidentally type something after undoing too much.

Python 'If not' syntax

Yes, if bar is not None is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar: will execute if bar is any kind of zero or empty container, or False. Many people do use not bar where they really do mean bar is not None.

difference between @size(max = value ) and @min(value) @max(value)

@Min and @Max are used for validating numeric fields which could be String(representing number), int, short, byte etc and their respective primitive wrappers.

@Size is used to check the length constraints on the fields.

As per documentation @Size supports String, Collection, Map and arrays while @Min and @Max supports primitives and their wrappers. See the documentation.

PHP/MySQL Insert null values

I think you need quotes around your {$row['null_field']}, so '{$row['null_field']}'

If you don't have the quotes, you'll occasionally end up with an insert statement that looks like this: insert into table2 (f1, f2) values ('val1',) which is a syntax error.

If that is a numeric field, you will have to do some testing above it, and if there is no value in null_field, explicitly set it to null..

Working Soap client example

To implement simple SOAP clients in Java, you can use the SAAJ framework (it is shipped with JSE 1.6 and above):

SOAP with Attachments API for Java (SAAJ) is mainly used for dealing directly with SOAP Request/Response messages which happens behind the scenes in any Web Service API. It allows the developers to directly send and receive soap messages instead of using JAX-WS.

See below a working example (run it!) of a SOAP web service call using SAAJ. It calls this web service.

import javax.xml.soap.*;

public class SOAPClientSAAJ {

    // SAAJ - SOAP Client Testing
    public static void main(String args[]) {
        /*
            The example below requests from the Web Service at:
             http://www.webservicex.net/uszip.asmx?op=GetInfoByCity


            To call other WS, change the parameters below, which are:
             - the SOAP Endpoint URL (that is, where the service is responding from)
             - the SOAP Action

            Also change the contents of the method createSoapEnvelope() in this class. It constructs
             the inner part of the SOAP envelope that is actually sent.
         */
        String soapEndpointUrl = "http://www.webservicex.net/uszip.asmx";
        String soapAction = "http://www.webserviceX.NET/GetInfoByCity";

        callSoapWebService(soapEndpointUrl, soapAction);
    }

    private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
        SOAPPart soapPart = soapMessage.getSOAPPart();

        String myNamespace = "myNamespace";
        String myNamespaceURI = "http://www.webserviceX.NET";

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);

            /*
            Constructed SOAP Request Message:
            <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:myNamespace="http://www.webserviceX.NET">
                <SOAP-ENV:Header/>
                <SOAP-ENV:Body>
                    <myNamespace:GetInfoByCity>
                        <myNamespace:USCity>New York</myNamespace:USCity>
                    </myNamespace:GetInfoByCity>
                </SOAP-ENV:Body>
            </SOAP-ENV:Envelope>
            */

        // SOAP Body
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyElem = soapBody.addChildElement("GetInfoByCity", myNamespace);
        SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("USCity", myNamespace);
        soapBodyElem1.addTextNode("New York");
    }

    private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
        try {
            // Create SOAP Connection
            SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection soapConnection = soapConnectionFactory.createConnection();

            // Send SOAP Message to SOAP Server
            SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl);

            // Print the SOAP Response
            System.out.println("Response SOAP Message:");
            soapResponse.writeTo(System.out);
            System.out.println();

            soapConnection.close();
        } catch (Exception e) {
            System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n");
            e.printStackTrace();
        }
    }

    private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();

        createSoapEnvelope(soapMessage);

        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", soapAction);

        soapMessage.saveChanges();

        /* Print the request message, just for debugging purposes */
        System.out.println("Request SOAP Message:");
        soapMessage.writeTo(System.out);
        System.out.println("\n");

        return soapMessage;
    }

}

FFMPEG mp4 from http live streaming m3u8 file?

Aergistal's answer works, but I found that converting to mp4 can make some m3u8 videos broken. If you are stuck with this problem, try to convert them to mkv, and convert them to mp4 later.

Get week of year in JavaScript like in PHP

Here is my implementation for calculating the week number in JavaScript. corrected for summer and winter time offsets as well. I used the definition of the week from this article: ISO 8601

Weeks are from mondays to sunday, and january 4th is always in the first week of the year.

// add get week prototype functions
// weeks always start from monday to sunday
// january 4th is always in the first week of the year
Date.prototype.getWeek = function () {
    year = this.getFullYear();
    var currentDotw = this.getWeekDay();
    if (this.getMonth() == 11 && this.getDate() - currentDotw > 28) {
        // if true, the week is part of next year 
        return this.getWeekForYear(year + 1);
    }
    if (this.getMonth() == 0 && this.getDate() + 6 - currentDotw < 4) {
        // if true, the week is part of previous year
        return this.getWeekForYear(year - 1);
    }
    return this.getWeekForYear(year);
}

// returns a zero based day, where monday = 0
// all weeks start with monday
Date.prototype.getWeekDay = function () {
    return  (this.getDay() + 6) % 7;
}

// corrected for summer/winter time
Date.prototype.getWeekForYear = function (year) {
    var currentDotw = this.getWeekDay();
    var fourjan = new Date(year, 0, 4);
    var firstDotw = fourjan.getWeekDay();
    var dayTotal = this.getDaysDifferenceCorrected(fourjan) // the difference in days between the two dates.
    // correct for the days of the week
    dayTotal += firstDotw; // the difference between the current date and the first monday of the first week, 
    dayTotal -= currentDotw; // the difference between the first monday and the current week's monday
    // day total should be a multiple of 7 now
    var weeknumber = dayTotal / 7 + 1; // add one since it gives a zero based week number.
    return weeknumber;
}

// corrected for timezones and offset
Date.prototype.getDaysDifferenceCorrected = function (other) {
    var millisecondsDifference = (this - other);
    // correct for offset difference. offsets are in minutes, the difference is in milliseconds
    millisecondsDifference += (other.getTimezoneOffset()- this.getTimezoneOffset()) * 60000;
    // return day total. 1 day is 86400000 milliseconds, floor the value to return only full days
    return Math.floor(millisecondsDifference / 86400000);
}

for testing i used the following JavaScript tests in Qunit

var runweekcompare = function(result, expected) {
    equal(result, expected,'Week nr expected value: ' + expected + ' Actual value: ' + result);
}

test('first week number test', function () {
    expect(5);
    var temp = new Date(2016, 0, 4); // is the monday of the first week of the year
    runweekcompare(temp.getWeek(), 1);
    var temp = new Date(2016, 0, 4, 23, 50); // is the monday of the first week of the year
    runweekcompare(temp.getWeek(), 1);
    var temp = new Date(2016, 0, 10, 23, 50); // is the sunday of the first week of the year
    runweekcompare(temp.getWeek(), 1);
    var temp = new Date(2016, 0, 11, 23, 50); // is the second week of the year
    runweekcompare(temp.getWeek(), 2);
    var temp = new Date(2016, 1, 29, 23, 50); // is the 9th week of the year
    runweekcompare(temp.getWeek(), 9);
});

test('first day is part of last years last week', function () {
    expect(2);
    var temp = new Date(2016, 0, 1, 23, 50); // is the first last week of the previous year
    runweekcompare(temp.getWeek(), 53);
    var temp = new Date(2011, 0, 2, 23, 50); // is the first last week of the previous year
    runweekcompare(temp.getWeek(), 52);
});

test('last  day is part of next years first week', function () {
    var temp = new Date(2013, 11, 30); // is part of the first week of 2014
    runweekcompare(temp.getWeek(), 1);
});

test('summer winter time change', function () {
    expect(2);
    var temp = new Date(2000, 2, 26); 
    runweekcompare(temp.getWeek(), 12);
    var temp = new Date(2000, 2, 27); 
    runweekcompare(temp.getWeek(), 13);
});

test('full 20 year test', function () {
    //expect(20 * 12 * 28 * 2);
    for (i = 2000; i < 2020; i++) {
        for (month = 0; month < 12; month++) {
            for (day = 1; day < 29 ; day++) {
                var temp = new Date(i, month, day);
                var expectedweek = temp.getWeek();
                var temp2 = new Date(i, month, day, 23, 50);
                var resultweek = temp.getWeek();
                equal(expectedweek, Math.round(expectedweek), 'week number whole number expected ' + Math.round(expectedweek) + ' resulted week nr ' + expectedweek);
                equal(resultweek, expectedweek, 'Week nr expected value: ' + expectedweek + ' Actual value: ' + resultweek + ' for year ' + i + ' month ' + month + ' day ' + day);
            }
        }
    }
});

How to switch databases in psql?

If you want to switch to a specific database on startup, try

/Applications/Postgres.app/Contents/Versions/9.5/bin/psql vigneshdb;

By default, Postgres runs on the port 5432. If it runs on another, make sure to pass the port in the command line.

/Applications/Postgres.app/Contents/Versions/9.5/bin/psql -p2345 vigneshdb;

By a simple alias, we can make it handy.

Create an alias in your .bashrc or .bash_profile

function psql()
{
    db=vigneshdb
    if [ "$1" != ""]; then
            db=$1
    fi
    /Applications/Postgres.app/Contents/Versions/9.5/bin/psql -p5432 $1
}

Run psql in command line, it will switch to default database; psql anotherdb, it will switch to the db with the name in argument, on startup.

How can I give access to a private GitHub repository?

It's working in 2021,

Though the Repo has to be made private first then the click on
settings => Manage access => Invite Collaborator

The user who gets the repo access has to navigate to the repo and can make changes to the main branch.

Capturing image from webcam in java?

You can try Marvin Framework. It provides an interface to work with cameras. Moreover, it also provides a set of real-time video processing features, like object tracking and filtering.

Take a look!

Real-time Video Processing Demo:
http://www.youtube.com/watch?v=D5mBt0kRYvk

You can use the source below. Just save a frame using MarvinImageIO.saveImage() every 5 second.

Webcam video demo:

public class SimpleVideoTest extends JFrame implements Runnable{

    private MarvinVideoInterface    videoAdapter;
    private MarvinImage             image;
    private MarvinImagePanel        videoPanel;

    public SimpleVideoTest(){
        super("Simple Video Test");
        videoAdapter = new MarvinJavaCVAdapter();
        videoAdapter.connect(0);
        videoPanel = new MarvinImagePanel();
        add(videoPanel);
        new Thread(this).start();
        setSize(800,600);
        setVisible(true);
    }
    @Override
    public void run() {
        while(true){
            // Request a video frame and set into the VideoPanel
            image = videoAdapter.getFrame();
            videoPanel.setImage(image);
        }
    }
    public static void main(String[] args) {
        SimpleVideoTest t = new SimpleVideoTest();
        t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

For those who just want to take a single picture:

WebcamPicture.java

public class WebcamPicture {
    public static void main(String[] args) {
        try{
            MarvinVideoInterface videoAdapter = new MarvinJavaCVAdapter();
            videoAdapter.connect(0);
            MarvinImage image = videoAdapter.getFrame();
            MarvinImageIO.saveImage(image, "./res/webcam_picture.jpg");
        } catch(MarvinVideoInterfaceException e){
            e.printStackTrace();
        }
    }
}

How can I replace a newline (\n) using sed?

Using Awk:

awk "BEGIN { o=\"\" }  { o=o \" \" \$0 }  END { print o; }"

When should an Excel VBA variable be killed or set to Nothing?

VBA uses a garbage collector which is implemented by reference counting.

There can be multiple references to a given object (for example, Dim aw = ActiveWorkbook creates a new reference to Active Workbook), so the garbage collector only cleans up an object when it is clear that there are no other references. Setting to Nothing is an explicit way of decrementing the reference count. The count is implicitly decremented when you exit scope.

Strictly speaking, in modern Excel versions (2010+) setting to Nothing isn't necessary, but there were issues with older versions of Excel (for which the workaround was to explicitly set)

What's the difference between REST & RESTful

REST based Services/Architecture vs. RESTFUL Services/Architecture

To differentiate or compare these 2, you should know what REST is.

REST (REpresentational State Transfer) is basically an architectural style of development having some principles:

  • It should be stateless

  • It should access all the resources from the server using only URI

  • It does not have inbuilt encryption

  • It does not have session

  • It uses one and only one protocol - HTTP

  • For performing CRUD operations, it should use HTTP verbs such as get, post, put and delete

  • It should return the result only in the form of JSON or XML, atom, OData etc. (lightweight data )

REST based services follow some of the above principles and not all

RESTFUL services means it follows all the above principles.

It is similar to the concept of:

Object oriented languages support all the OOP concepts, examples: C++, C#

Object-based languages support some of the OOP features, examples: JavaScript, VB


Example:

ASP Dot NET MVC 4 is REST-Based while Microsoft WEB API is RESTFul.

MVC supports only some of the above REST principles whereas WEB API supports all the above REST Principles.

MVC only supports the following from the REST API

  • We can access the resource using URI

  • It supports the HTTP verb to access the resource from server

  • It can return the results in the form of JSON, XML, that is the HTTPResponse.

However, at the same time in MVC

  • We can use the session

  • We can make it stateful

  • We can return video or image from the controller action method which basically violates the REST principles

That is why MVC is REST-Based whereas WEB API supports all the above principles and is RESTFul.

Unable to open project... cannot be opened because the project file cannot be parsed

This is because project names are not suppose to have blank spaces in between them

How to force file download with PHP

Display your file first and set its value into url.

index.php

<a href="download.php?download='.$row['file'].'" title="Download File">

download.php

<?php
/*db connectors*/
include('dbconfig.php');

/*function to set your files*/
function output_file($file, $name, $mime_type='')
{
    if(!is_readable($file)) die('File not found or inaccessible!');
    $size = filesize($file);
    $name = rawurldecode($name);
    $known_mime_types=array(
        "htm" => "text/html",
        "exe" => "application/octet-stream",
        "zip" => "application/zip",
        "doc" => "application/msword",
        "jpg" => "image/jpg",
        "php" => "text/plain",
        "xls" => "application/vnd.ms-excel",
        "ppt" => "application/vnd.ms-powerpoint",
        "gif" => "image/gif",
        "pdf" => "application/pdf",
        "txt" => "text/plain",
        "html"=> "text/html",
        "png" => "image/png",
        "jpeg"=> "image/jpg"
    );

    if($mime_type==''){
        $file_extension = strtolower(substr(strrchr($file,"."),1));
        if(array_key_exists($file_extension, $known_mime_types)){
            $mime_type=$known_mime_types[$file_extension];
        } else {
            $mime_type="application/force-download";
        };
    };
    @ob_end_clean();
    if(ini_get('zlib.output_compression'))
    ini_set('zlib.output_compression', 'Off');
    header('Content-Type: ' . $mime_type);
    header('Content-Disposition: attachment; filename="'.$name.'"');
    header("Content-Transfer-Encoding: binary");
    header('Accept-Ranges: bytes');

    if(isset($_SERVER['HTTP_RANGE']))
    {
        list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
        list($range) = explode(",",$range,2);
        list($range, $range_end) = explode("-", $range);
        $range=intval($range);
        if(!$range_end) {
            $range_end=$size-1;
        } else {
            $range_end=intval($range_end);
        }

        $new_length = $range_end-$range+1;
        header("HTTP/1.1 206 Partial Content");
        header("Content-Length: $new_length");
        header("Content-Range: bytes $range-$range_end/$size");
    } else {
        $new_length=$size;
        header("Content-Length: ".$size);
    }

    $chunksize = 1*(1024*1024);
    $bytes_send = 0;
    if ($file = fopen($file, 'r'))
    {
        if(isset($_SERVER['HTTP_RANGE']))
        fseek($file, $range);

        while(!feof($file) &&
            (!connection_aborted()) &&
            ($bytes_send<$new_length)
        )
        {
            $buffer = fread($file, $chunksize);
            echo($buffer);
            flush();
            $bytes_send += strlen($buffer);
        }
        fclose($file);
    } else
        die('Error - can not open file.');
    die();
}
set_time_limit(0);

/*set your folder*/
$file_path='uploads/'."your file";

/*output must be folder/yourfile*/

output_file($file_path, ''."your file".'', $row['type']);

/*back to index.php while downloading*/
header('Location:index.php');
?>

bash: pip: command not found

Most of the methods to install PIP are deprecated. Here is the latest (2019) solution. Please download get-pip script

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

Run the script

sudo python get-pip.py

Reading Data From Database and storing in Array List object

 while (rs.next()) {

            customer.setId(rs.getInt("id"));
            customer.setName(rs.getString("name"));

            customer.setAddress(rs.getString("address"));
            customer.setPhone(rs.getString("phone"));
            customer.setEmail(rs.getString("email"));
            customer.setBountPoints(rs.getInt("bonuspoint"));
            customer.setTotalsale(rs.getInt("totalsale"));

            customers.add(customer);
             customer = null;
        }

Try replacing your while loop code with above mentioned code. Here what we have done is after doing customers.add(customer) we are doing customer = null;`

Can one do a for each loop in java in reverse order?

AFAIK there isn't a standard "reverse_iterator" sort of thing in the standard library that supports the for-each syntax which is already a syntactic sugar they brought late into the language.

You could do something like for(Item element: myList.clone().reverse()) and pay the associated price.

This also seems fairly consistent with the apparent phenomenon of not giving you convenient ways to do expensive operations - since a list, by definition, could have O(N) random access complexity (you could implement the interface with a single-link), reverse iteration could end up being O(N^2). Of course, if you have an ArrayList, you don't pay that price.

Composer update memory limit

This error can occur especially when you are updating large libraries or libraries with a lot of dependencies. Composer can be quite memory hungry.

Be sure that your composer itself is updated to the latest version:

php composer.phar --self-update

You can increase the memory limit for composer temporarily by adding the composer memory limit environment variable:

COMPOSER_MEMORY_LIMIT=128MB php composer.phar update

Use the format “128M” for megabyte or “2G” for gigabyte. You can use the value “-1” to ignore the memory limit completely.

Another way would be to increase the PHP memory limit:

php -d memory_limit=512M composer.phar update ...

String in function parameter

char *arr; above statement implies that arr is a character pointer and it can point to either one character or strings of character

& char arr[]; above statement implies that arr is strings of character and can store as many characters as possible or even one but will always count on '\0' character hence making it a string ( e.g. char arr[]= "a" is similar to char arr[]={'a','\0'} )

But when used as parameters in called function, the string passed is stored character by character in formal arguments making no difference.

Why is visible="false" not working for a plain html table?

The reason that visible="false" does not work is because HTML is defined as a standard by a consortium group. The standard for the Table element does not have a visibility property defined.

You can see all the valid properties for a table by going to the standards web page for tables.

That page can be a bit hard to read, so here is a link to another page that makes it easier to read.

How to send a POST request using volley with string body?

I created a function for a Volley Request. You just need to pass the arguments :

public void callvolly(final String username, final String password){
    RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
    String url = "http://your_url.com/abc.php"; // <----enter your post url here
    StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            //This code is executed if the server responds, whether or not the response contains data.
            //The String 'response' contains the server's response.
        }
    }, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
        @Override
        public void onErrorResponse(VolleyError error) {
            //This code is executed if there is an error.
        }
    }) {
        protected Map<String, String> getParams() {
            Map<String, String> MyData = new HashMap<String, String>();
            MyData.put("username", username);             
            MyData.put("password", password);                
            return MyData;
        }
    };


    MyRequestQueue.add(MyStringRequest);
}

What does `set -x` do?

-u: disabled by default. When activated, an error message is displayed when using an unconfigured variable.

-v: inactive by default. After activation, the original content of the information will be displayed (without variable resolution) before the information is output.

-x: inactive by default. If activated, the command content will be displayed before the command is run (after variable resolution, there is a ++ symbol).

Compare the following differences:

/ # set -v && echo $HOME
/root
/ # set +v && echo $HOME
set +v && echo $HOME
/root

/ # set -x && echo $HOME
+ echo /root
/root
/ # set +x && echo $HOME
+ set +x
/root

/ # set -u && echo $NOSET
/bin/sh: NOSET: parameter not set
/ # set +u && echo $NOSET

Making heatmap from pandas DataFrame

You want matplotlib.pcolor:

import numpy as np 
from pandas import DataFrame
import matplotlib.pyplot as plt

index = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
columns = ['A', 'B', 'C', 'D']
df = DataFrame(abs(np.random.randn(5, 4)), index=index, columns=columns)

plt.pcolor(df)
plt.yticks(np.arange(0.5, len(df.index), 1), df.index)
plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns)
plt.show()

This gives:

Output sample

How to see JavaDoc in IntelliJ IDEA?

To best mirror Eclipses functionality, enable the following settings:

  • IDE Settings/Editor -> Other.Show quick doc on mouse move
  • IDE Settings/Editor/Code Completion -> Autopopup Documentation

To see the javadoc in the autocomplete menu, hit '.' to get the popup, then hover over the object you are working with, once you get the javadoc popup, you can select an item in the popup to switch the javadoc over. Not ideal... But its something.

As another note. The search functionality of the options menu is very useful. Just type in 'doc' and you will see all the options for doc.

Also, searching for "autopopup doc" will not only find each of the options, but it will also highlight them in the menu. Pretty awesome!


Edit: Going beyond the initial question, this might be useful for people who just want quick and easy access to the docs.

After using this for a few more days, it seems just getting used to using the hotkey is the most efficient way. It will pop up the documentation for anything at the spot of where your text input marker is so you never have to touch the mouse. This works in the intellisense popup as well and will stay up while navigating up and down.

Personally, Ctrl+Q on windows was not ideal so I remapped it to Alt+D. Remaping can be done under IDE Settings/Keymap. Once in the keymap menu, just search for Quick Documentation.

C# Connecting Through Proxy

Foole's code worked perfectly for me, but in .NET 4.0, don't forget to check if Proxy is NULL, which means no proxy configured (outside corporate environment)

So here's the code that solved my problem with our corporate proxy

WebClient web = new WebClient();
if (web.Proxy != null)
    web.Proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

How do you merge two Git repositories?

If you're trying to simply glue two repositories together, submodules and subtree merges are the wrong tool to use because they don't preserve all of the file history (as people have noted on other answers). See this answer here for the simple and correct way to do this.

How do I get the full path to a Perl script that is executing?

use strict ; use warnings ; use Cwd 'abs_path';
    sub ResolveMyProductBaseDir { 

        # Start - Resolve the ProductBaseDir
        #resolve the run dir where this scripts is placed
        my $ScriptAbsolutPath = abs_path($0) ; 
        #debug print "\$ScriptAbsolutPath is $ScriptAbsolutPath \n" ;
        $ScriptAbsolutPath =~ m/^(.*)(\\|\/)(.*)\.([a-z]*)/; 
        $RunDir = $1 ; 
        #debug print "\$1 is $1 \n" ;
        #change the \'s to /'s if we are on Windows
        $RunDir =~s/\\/\//gi ; 
        my @DirParts = split ('/' , $RunDir) ; 
        for (my $count=0; $count < 4; $count++) {   pop @DirParts ;     }
        my $ProductBaseDir = join ( '/' , @DirParts ) ; 
        # Stop - Resolve the ProductBaseDir
        #debug print "ResolveMyProductBaseDir $ProductBaseDir is $ProductBaseDir \n" ; 
        return $ProductBaseDir ; 
    } #eof sub 

How to exit if a command failed?

If you want that behavior for all commands in your script, just add

  set -e 
  set -o pipefail

at the beginning of the script. This pair of options tell the bash interpreter to exit whenever a command returns with a non-zero exit code.

This does not allow you to print an exit message, though.

Using Cygwin to Compile a C program; Execution error

If you just do gcc program.c -o program -mno-cygwin it will compile just fine and you won't need to add cygwin1.dll to your path and you can just go ahead and distribute your executable to a computer which doesn't have cygwin installed and it will still run. Hope this helps

"[notice] child pid XXXX exit signal Segmentation fault (11)" in apache error.log

Attach gdb to one of the httpd child processes and reload or continue working and wait for a crash and then look at the backtrace. Do something like this:

$ ps -ef|grep httpd
0     681     1   0 10:38pm ??         0:00.45 /Applications/MAMP/Library/bin/httpd -k start
501   690   681   0 10:38pm ??         0:00.02 /Applications/MAMP/Library/bin/httpd -k start

...

Now attach gdb to one of the child processes, in this case PID 690 (columns are UID, PID, PPID, ...)

$ sudo gdb
(gdb) attach 690
Attaching to process 690.
Reading symbols for shared libraries . done
Reading symbols for shared libraries ....................... done
0x9568ce29 in accept$NOCANCEL$UNIX2003 ()
(gdb) c
Continuing.

Wait for crash... then:

(gdb) backtrace

Or

(gdb) backtrace full

Should give you some clue what's going on. If you file a bug report you should include the backtrace.

If the crash is hard to reproduce it may be a good idea to configure Apache to only use one child processes for handling requests. The config is something like this:

StartServers 1
MinSpareServers 1
MaxSpareServers 1

How to do URL decoding in Java?

This has been answered before (although this question was first!):

"You should use java.net.URI to do this, as the URLDecoder class does x-www-form-urlencoded decoding which is wrong (despite the name, it's for form data)."

As URL class documentation states:

The recommended way to manage the encoding and decoding of URLs is to use URI, and to convert between these two classes using toURI() and URI.toURL().

The URLEncoder and URLDecoder classes can also be used, but only for HTML form encoding, which is not the same as the encoding scheme defined in RFC2396.

Basically:

String url = "https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type";
System.out.println(new java.net.URI(url).getPath());

will give you:

https://mywebsite/docs/english/site/mybook.do?request_type

Google Apps Script to open a URL

This function opens a URL without requiring additional user interaction.

/**
 * Open a URL in a new tab.
 */
function openUrl( url ){
  var html = HtmlService.createHtmlOutput('<html><script>'
  +'window.close = function(){window.setTimeout(function(){google.script.host.close()},9)};'
  +'var a = document.createElement("a"); a.href="'+url+'"; a.target="_blank";'
  +'if(document.createEvent){'
  +'  var event=document.createEvent("MouseEvents");'
  +'  if(navigator.userAgent.toLowerCase().indexOf("firefox")>-1){window.document.body.append(a)}'                          
  +'  event.initEvent("click",true,true); a.dispatchEvent(event);'
  +'}else{ a.click() }'
  +'close();'
  +'</script>'
  // Offer URL as clickable link in case above code fails.
  +'<body style="word-break:break-word;font-family:sans-serif;">Failed to open automatically. <a href="'+url+'" target="_blank" onclick="window.close()">Click here to proceed</a>.</body>'
  +'<script>google.script.host.setHeight(40);google.script.host.setWidth(410)</script>'
  +'</html>')
  .setWidth( 90 ).setHeight( 1 );
  SpreadsheetApp.getUi().showModalDialog( html, "Opening ..." );
}

This method works by creating a temporary dialog box, so it will not work in contexts where the UI service is not accessible, such as the script editor or a custom G Sheets formula.

HTML Best Practices: Should I use &rsquo; or the special keyboard shortcut?

I don't think that one is better than the other in general; it depends on how you intend to use it.

  • If you want to store it in a DB column that has a charset/collation that does not support the right single quote character, you may run into storing it as the multi-byte character instead of 7-bit ASCII (&rsquo;).
  • If you are displaying it on an html element that specifies a charset that does not support it, it may not display in either case.
  • If many developers are going to be editing/viewing this file with editors/keyboards that do not support properly typing or displaying the character, you may want to use the entity
  • If you need to convert the file between various character encodings or formats, you may want to use the entity
  • If your HTML code may escape entities improperly, you may want to use the character.

In general I would lean more towards using the character because as you point out it is easier to read and type.

using .join method to convert array to string without commas

The .join() method has a parameter for the separator string. If you want it to be empty instead of the default comma, use

arr.join("");

In ASP.NET MVC: All possible ways to call Controller Action Method from a Razor View

Method 1 : Using jQuery Ajax Get call (partial page update).

Suitable for when you need to retrieve jSon data from database.

Controller's Action Method

[HttpGet]
public ActionResult Foo(string id)
{
    var person = Something.GetPersonByID(id);
    return Json(person, JsonRequestBehavior.AllowGet);
}

Jquery GET

function getPerson(id) {
    $.ajax({
        url: '@Url.Action("Foo", "SomeController")',
        type: 'GET',
        dataType: 'json',
        // we set cache: false because GET requests are often cached by browsers
        // IE is particularly aggressive in that respect
        cache: false,
        data: { id: id },
        success: function(person) {
            $('#FirstName').val(person.FirstName);
            $('#LastName').val(person.LastName);
        }
    });
}

Person class

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Method 2 : Using jQuery Ajax Post call (partial page update).

Suitable for when you need to do partial page post data into database.

Post method is also same like above just replace [HttpPost] on Action method and type as post for jquery method.

For more information check Posting JSON Data to MVC Controllers Here

Method 3 : As a Form post scenario (full page update).

Suitable for when you need to save or update data into database.

View

@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{        
    @Html.TextBoxFor(model => m.Text)
    
    <input type="submit" value="Save" />
}

Action Method

[HttpPost]
public ActionResult SaveData(FormCollection form)
    {
        // Get movie to update
        return View();
   }

Method 4 : As a Form Get scenario (full page update).

Suitable for when you need to Get data from database

Get method also same like above just replace [HttpGet] on Action method and FormMethod.Get for View's form method.

I hope this will help to you.

How to stop an app on Heroku?

http://devcenter.heroku.com/articles/maintenance-mode

If you’re deploying a large migration or need to disable access to your application for some length of time, you can use Heroku’s built in maintenance mode. It will serve a static page to all visitors, while still allowing you to run rake tasks or console commands.

$ heroku maintenance:on
Maintenance mode enabled.

and later

$ heroku maintenance:off
Maintenance mode disabled.

scrollbars in JTextArea

            txtarea = new JTextArea(); 
    txtarea.setRows(25);
    txtarea.setColumns(25);
    txtarea.setWrapStyleWord(true);
    JScrollPane scroll = new JScrollPane (txtarea);
    panel2.add(scroll); //Object of Jpanel

Above given lines automatically shows you both horizontal & vertical Scrollbars..

How to force child div to be 100% of parent div's height without specifying parent's height?

[Referring to Dmity's Less code in another answer] I'm guessing that this is some kind of "pseudo-code"?

From what I understand try using the faux-columns technique that should do the trick.

http://www.alistapart.com/articles/fauxcolumns/

Hope this helps :)

How to hide Bootstrap previous modal when you opening new one?

Toggle both modals

$('#modalOne').modal('toggle');
$('#modalTwo').modal('toggle');

How does one add keyboard languages and switch between them in Linux Mint 16?

For Linux Mate 17.1 Go to Menu/All applications/Keyboard/Layouts tab/Click Add/Pick out your layout by country or by language/Click Add and a language icon (US, PT and so on) will show at Panel/Close Keyboard Preferences and just click over it at Panel to switch the input language.

C# catch a stack overflow exception

Yes from CLR 2.0 stack overflow is considered a non-recoverable situation. So the runtime still shut down the process.

For details please see the documentation http://msdn.microsoft.com/en-us/library/system.stackoverflowexception.aspx

Checking if date is weekend PHP

For guys like me, who aren't minimalistic, there is a PECL extension called "intl". I use it for idn conversion since it works way better than the "idn" extension and some other n1 classes like "IntlDateFormatter".

Well, what I want to say is, the "intl" extension has a class called "IntlCalendar" which can handle many international countries (e.g. in Saudi Arabia, sunday is not a weekend day). The IntlCalendar has a method IntlCalendar::isWeekend for that. Maybe you guys give it a shot, I like that "it works for almost every country" fact on these intl-classes.

EDIT: Not quite sure but since PHP 5.5.0, the intl extension is bundled with PHP (--enable-intl).

Move an array element from one array position to another

    Array.prototype.moveUp = function (value, by) {
        var index = this.indexOf(value),
            newPos = index - (by || 1);

        if (index === -1)
            throw new Error("Element not found in array");

        if (newPos < 0)
            newPos = 0;

        this.splice(index, 1);
        this.splice(newPos, 0, value);
    };

    Array.prototype.moveDown = function (value, by) {
        var index = this.indexOf(value),
            newPos = index + (by || 1);

        if (index === -1)
            throw new Error("Element not found in array");

        if (newPos >= this.length)
            newPos = this.length;

        this.splice(index, 1);
        this.splice(newPos, 0, value);
    };



    var arr = ['banana', 'curyWurst', 'pc', 'remembaHaruMembaru'];

    alert('withiout changes= '+arr[0]+' ||| '+arr[1]+' ||| '+arr[2]+' ||| '+arr[3]);
    arr.moveDown(arr[2]);


    alert('third word moved down= '+arr[0] + ' ||| ' + arr[1] + ' ||| ' + arr[2] + ' ||| ' + arr[3]);
    arr.moveUp(arr[2]);
    alert('third word moved up= '+arr[0] + ' ||| ' + arr[1] + ' ||| ' + arr[2] + ' ||| ' + arr[3]);

http://plnkr.co/edit/JaiAaO7FQcdPGPY6G337?p=preview

How do I undo 'git add' before commit?

Run

git gui

and remove all the files manually or by selecting all of them and clicking on the unstage from commit button.

Python Hexadecimal

I think this is what you want:

>>> def twoDigitHex( number ):
...     return '%02x' % number
... 
>>> twoDigitHex( 2 )
'02'
>>> twoDigitHex( 255 )
'ff'

How do I detect if software keyboard is visible on Android Device or not?

With the new feature WindowInsetsCompat in androidx core release 1.5.0-alpha02 you could check the visibility of the soft keyboard easily as below

Quoting from reddit comment

val View.keyboardIsVisible: Boolean
    get() = WindowInsetsCompat
        .toWindowInsetsCompat(rootWindowInsets)
        .isVisible(WindowInsetsCompat.Type.ime())

Some note about backward compatibility, quoting from release notes

New Features

The WindowInsetsCompat APIs have been updated to those in the platform in Android 11. This includes the new ime() inset type, which allows checking the visibility and size of the on-screen keyboard.

Some caveats about the ime() type, it works very reliably on API 23+ when your Activity is using the adjustResize window soft input mode. If you’re instead using the adjustPan mode, it should work reliably back to API 14.

References

How to change the URI (URL) for a remote Git repository?

In the Git Bash, enter the command:

git remote set-url origin https://NewRepoLink.git

Enter the Credentials

Done

The way to check a HDFS directory's size?

To get the size of the directory hdfs dfs -du -s -h /$yourDirectoryName can be used. hdfs dfsadmin -report can be used to see a quick cluster level storage report.

Assign result of dynamic sql to variable

You should try this while getting SEQUENCE value in a variable from the dynamic table.

DECLARE @temp table (#temp varchar (MAX));
DECLARE @SeqID nvarchar(150);
DECLARE @Name varchar(150); 

SET @Name = (Select Name from table)
SET @SeqID = 'SELECT NEXT VALUE FOR '+ @Name + '_Sequence'
insert @temp exec (@SeqID)

SET @SeqID = (select * from @temp )
PRINT @SeqID

Result:

(1 row(s) affected)
 1

awk partly string match (if column/word partly matches)

GNU sed

sed '/\s*\(\S\+\s\+\)\{2\}\bsnow\(man\)\?\b/!d' file

Input:

C1    C2    C3    
1     a     snow   
2     b     snowman 
snow     c     sowman
      snow     snow     snowmanx

..output:

1     a     snow
2     b     snowman

String to object in JS

You need use JSON.parse() for convert String into a Object:

var obj = JSON.parse('{ "firstName":"name1", "lastName": "last1" }');

How does an SSL certificate chain bundle work?

You need to use the openssl pkcs12 -export -chain -in server.crt -CAfile ...

See https://www.openssl.org/docs/apps/pkcs12.html

How to push objects in AngularJS between ngRepeat arrays

change your method to:

$scope.toggleChecked = function (index) {
    $scope.checked.push($scope.items[index]);
    $scope.items.splice(index, 1);
};

Working Demo

How can I join multiple SQL tables using the IDs?

Simple INNER JOIN VIEW code....

CREATE VIEW room_view
AS SELECT a.*,b.*
FROM j4_booking a INNER JOIN j4_scheduling b
on a.room_id = b.room_id;

How do I test if a variable does not equal either of two values?

In general it would be something like this:

if(test != "A" && test != "B")

You should probably read up on JavaScript logical operators.

Class JavaLaunchHelper is implemented in both. One of the two will be used. Which one is undefined

  1. Install Java 7u21 from here: http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html#jdk-7u21-oth-JPR

  2. set these variables:

    export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home"
    export PATH=$JAVA_HOME/bin:$PATH
    
  3. Run your app and fun :)

(Minor update: put variable value in quote)

How to get thread id from a thread pool?

If your class inherits from Thread, you can use methods getName and setName to name each thread. Otherwise you could just add a name field to MyTask, and initialize it in your constructor.

Getting the docstring from a function

Interactively, you can display it with

help(my_func)

Or from code you can retrieve it with

my_func.__doc__

Android Studio: Module won't show up in "Edit Configuration"

Well, nothing worked for me from all the answers. Finally, I clicked Run > Edit Configuration. On the left, u can choose a new main module and remove to deleted ones.

Comment out HTML and PHP together

I agree that Pascal's solution is the way to go, but for those saying that it adds an extra task to remove the comments, you can use the following comment style trick to simplify your life:

<?php /* ?>
<tr>
      <td><?php echo $entry_keyword; ?></td>
      <td><input type="text" name="keyword" value="<?php echo $keyword; ?>" /></td>
    </tr>
    <tr>
      <td><?php echo $entry_sort_order; ?></td>
      <td><input name="sort_order" value="<?php echo $sort_order; ?>" size="1" /></td>
    </tr>
<?php // */ ?>

In order to stop the code block being commented out, simply change the opening comment to:

<?php //* ?>

How do I disable right click on my web page?

If your aim is to prevent people being able to download your images, as most people have said, disabling right click is pretty much ineffective.

Assuming you are trying to protect images the alternative methods are -

Using a flash player, users can't download them as such, but they could easily do a screen capture.

If you want to be more akward, make the image the background of a div, containing a transparent image, à la -

<div style="background-image: url(YourImage.jpg);">
   <img src="transparent.gif"/>
</div>

will be enough to deter the casual theft of your images (see below for a sample), but as with all these techniques, is trivial to defeat with a basic understanding of html.

Find an object in SQL Server (cross-database)

SELECT NAME AS ObjectName
    ,schema_name(o.schema_id) AS SchemaName, OBJECT_NAME(o.parent_object_id) as TableName
    ,type
    ,o.type_desc
FROM sys.objects o
WHERE o.is_ms_shipped = 0
    AND o.NAME LIKE '%UniqueID%'
ORDER BY o.NAME

Selected value for JSP drop down using JSTL

You can try one even more simple:

<option value="1" ${item.quantity == 1 ? "selected" : ""}>1</option>

Scanner vs. BufferedReader

  1. BufferedReader has significantly larger buffer memory than Scanner. Use BufferedReader if you want to get long strings from a stream, and use Scanner if you want to parse specific type of token from a stream.

  2. Scanner can use tokenize using custom delimiter and parse the stream into primitive types of data, while BufferedReader can only read and store String.

  3. BufferedReader is synchronous while Scanner is not. Use BufferedReader if you're working with multiple threads.

  4. Scanner hides IOException while BufferedReader throws it immediately.

Android: textview hyperlink

TextView t2 = (TextView) findViewById(R.id.textviewidname);
t2.setMovementMethod(LinkMovementMethod.getInstance());

and

<string name="google_stackoverflow"><a href="https://stackoverflow.com/questions/9852184/android-textview-hyperlink?rq=1">google stack overflow</a></string>

The link is, "Android: textview hyperlink"

and the tag is, "google stack overflow"

Define the first code block in your java and the second code block in your strings.xml file. Also, be sure to reference the id of the textView from your page layout in your java.

Capturing a single image from my webcam in Java or Python

I wrote a tool to capture images from a webcam entirely in Python, based on DirectShow. You can find it here: https://github.com/andreaschiavinato/python_grabber.

You can use the whole application or just the class FilterGraph in dshow_graph.py in the following way:

from pygrabber.dshow_graph import FilterGraph
import numpy as np
from matplotlib.image import imsave

graph = FilterGraph()
print(graph.get_input_devices())
device_index = input("Enter device number: ")
graph.add_input_device(int(device_index))
graph.display_format_dialog()
filename = r"c:\temp\imm.png"
# np.flip(image, axis=2) required to convert image from BGR to RGB
graph.add_sample_grabber(lambda image : imsave(filename, np.flip(image, axis=2)))
graph.add_null_render()
graph.prepare()
graph.run()
x = input("Press key to grab photo")
graph.grab_frame()
x = input(f"File {filename} saved. Press key to end")
graph.stop()

What is IPV6 for localhost and 0.0.0.0?

For use in a /etc/hosts file as a simple ad blocking technique to cause a domain to fail to resolve, the 0.0.0.0 address has been widely used because it causes the request to immediately fail without even trying, because it's not a valid or routable address. This is in comparison to using 127.0.0.1 in that place, where it will at least check to see if your own computer is listening on the requested port 80 before failing with 'connection refused.' Either of those addresses being used in the hosts file for the domain will stop any requests from being attempted over the actual network, but 0.0.0.0 has gained favor because it's more 'optimal' for the above reason. "127" IPs will attempt to hit your own computer, and any other IP will cause a request to be sent to the router to try to route it, but for 0.0.0.0 there's nowhere to even send a request to.

All that being said, having any IP listed in your hosts file for the domain to be blocked is sufficient, and you wouldn't need or want to also put an ipv6 address in your hosts file unless -- possibly -- you don't have ipv4 enabled at all. I'd be really surprised if that was the case, though. And still though, I think having the host appear in /etc/hosts with a bad ipv4 address when you don't have ipv4 enabled would still give you the result you are looking for which is for it to fail, instead of looking up the real DNS of say, adserver-example.com and getting back either a v4 or v6 IP.

Git: Could not resolve host github.com error while cloning remote repository in git

Different from all these solutions, in my case, I solved the issue when I restarted my terminal (or open another window).

How to create a zip file in Java

public static void zipFromTxt(String zipFilePath, String txtFilePath) {
    Assert.notNull(zipFilePath, "Zip file path is required");
    Assert.notNull(txtFilePath, "Txt file path is required");
    zipFromTxt(new File(zipFilePath), new File(txtFilePath));
}

public static void zipFromTxt(File zipFile, File txtFile) {
    ZipOutputStream out = null;
    FileInputStream in = null;
    try {
        Assert.notNull(zipFile, "Zip file is required");
        Assert.notNull(txtFile, "Txt file is required");
        out = new ZipOutputStream(new FileOutputStream(zipFile));
        in = new FileInputStream(txtFile);
        out.putNextEntry(new ZipEntry(txtFile.getName()));
        int len;
        byte[] buffer = new byte[1024];
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
            out.flush();
        }
    } catch (Exception e) {
        log.info("Zip from txt occur error,Detail message:{}", e.toString());
    } finally {
        try {
            if (in != null) in.close();
            if (out != null) {
                out.closeEntry();
                out.close();
            }
        } catch (Exception e) {
            log.info("Zip from txt close error,Detail message:{}", e.toString());
        }
    }
}

Why use argparse rather than optparse?

At first I was as reluctant as @fmark to switch from optparse to argparse, because:

  1. I thought the difference was not that huge.
  2. Quite some VPS still provides Python 2.6 by default.

Then I saw this doc, argparse outperforms optparse, especially when talking about generating meaningful help message: http://argparse.googlecode.com/svn/trunk/doc/argparse-vs-optparse.html

And then I saw "argparse vs. optparse" by @Nicholas, saying we can have argparse available in python <2.7 (Yep, I didn't know that before.)

Now my two concerns are well addressed. I wrote this hoping it will help others with a similar mindset.

How do you set the startup page for debugging in an ASP.NET MVC application?

If you want to start at the "application root" as you describe right click on the top level Default.aspx page and choose set as start page. Hit F5 and you're done.

If you want to start at a different controller action see Mark's answer.

Should I use Vagrant or Docker for creating an isolated environment?

I preface my reply by admitting I have no experience with Docker, other than as an avid observer of what looks to be a really neat solution that's gaining a lot of traction.

I do have a decent amount of experience with Vagrant and can highly recommend it. It's certainly a more heavyweight solution in terms of it being VM based instead of LXC based. However, I've found a decent laptop (8 GB RAM, i5/i7 CPU) has no trouble running a VM using Vagrant/VirtualBox alongside development tooling.

One of the really great things with Vagrant is the integration with Puppet/Chef/shell scripts for automating configuration. If you're using one of these options to configure your production environment, you can create a development environment which is as close to identical as you're going to get, and this is exactly what you want.

The other great thing with Vagrant is that you can version your Vagrantfile along with your application code. This means that everyone else on your team can share this file and you're guaranteed that everyone is working with the same environment configuration.

Interestingly, Vagrant and Docker may actually be complimentary. Vagrant can be extended to support different virtualization providers, and it may be possible that Docker is one such provider which gets support in the near future. See https://github.com/dotcloud/docker/issues/404 for recent discussion on the topic.

Resize background image in div using css

Answer

You have multiple options:

  1. background-size: 100% 100%; - image gets stretched (aspect ratio may be preserved, depending on browser)
  2. background-size: contain; - image is stretched without cutting it while preserving aspect ratio
  3. background-size: cover; - image is completely covering the element while preserving aspect ratio (image can be cut off)

/edit: And now, there is even more: https://alligator.io/css/cropping-images-object-fit

Demo on Codepen

Update 2017: Preview

Here are screenshots for some browsers to show their differences.

Chrome

preview background types chrome


Firefox

preview background types firefox


Edge

preview background types edge


IE11

preview background types ie11

Takeaway Message

background-size: 100% 100%; produces the least predictable result.

Resources

How does delete[] know it's an array?

Agree that the compiler doesn't know if it is an array or not. It is up to the programmer.

The compiler sometimes keep track of how many objects need to be deleted by over-allocating enough to store the array size, but not always necessary.

For a complete specification when extra storage is allocated, please refer to C++ ABI (how compilers are implemented): Itanium C++ ABI: Array Operator new Cookies

How does C compute sin() and other math functions?

Chebyshev polynomials, as mentioned in another answer, are the polynomials where the largest difference between the function and the polynomial is as small as possible. That is an excellent start.

In some cases, the maximum error is not what you are interested in, but the maximum relative error. For example for the sine function, the error near x = 0 should be much smaller than for larger values; you want a small relative error. So you would calculate the Chebyshev polynomial for sin x / x, and multiply that polynomial by x.

Next you have to figure out how to evaluate the polynomial. You want to evaluate it in such a way that the intermediate values are small and therefore rounding errors are small. Otherwise the rounding errors might become a lot larger than errors in the polynomial. And with functions like the sine function, if you are careless then it may be possible that the result that you calculate for sin x is greater than the result for sin y even when x < y. So careful choice of the calculation order and calculation of upper bounds for the rounding error are needed.

For example, sin x = x - x^3/6 + x^5 / 120 - x^7 / 5040... If you calculate naively sin x = x * (1 - x^2/6 + x^4/120 - x^6/5040...), then that function in parentheses is decreasing, and it will happen that if y is the next larger number to x, then sometimes sin y will be smaller than sin x. Instead, calculate sin x = x - x^3 * (1/6 - x^2 / 120 + x^4/5040...) where this cannot happen.

When calculating Chebyshev polynomials, you usually need to round the coefficients to double precision, for example. But while a Chebyshev polynomial is optimal, the Chebyshev polynomial with coefficients rounded to double precision is not the optimal polynomial with double precision coefficients!

For example for sin (x), where you need coefficients for x, x^3, x^5, x^7 etc. you do the following: Calculate the best approximation of sin x with a polynomial (ax + bx^3 + cx^5 + dx^7) with higher than double precision, then round a to double precision, giving A. The difference between a and A would be quite large. Now calculate the best approximation of (sin x - Ax) with a polynomial (b x^3 + cx^5 + dx^7). You get different coefficients, because they adapt to the difference between a and A. Round b to double precision B. Then approximate (sin x - Ax - Bx^3) with a polynomial cx^5 + dx^7 and so on. You will get a polynomial that is almost as good as the original Chebyshev polynomial, but much better than Chebyshev rounded to double precision.

Next you should take into account the rounding errors in the choice of polynomial. You found a polynomial with minimum error in the polynomial ignoring rounding error, but you want to optimise polynomial plus rounding error. Once you have the Chebyshev polynomial, you can calculate bounds for the rounding error. Say f (x) is your function, P (x) is the polynomial, and E (x) is the rounding error. You don't want to optimise | f (x) - P (x) |, you want to optimise | f (x) - P (x) +/- E (x) |. You will get a slightly different polynomial that tries to keep the polynomial errors down where the rounding error is large, and relaxes the polynomial errors a bit where the rounding error is small.

All this will get you easily rounding errors of at most 0.55 times the last bit, where +,-,*,/ have rounding errors of at most 0.50 times the last bit.

Carriage Return\Line feed in Java

Encapsulate your writer to provide char replacement, like this:

public class WindowsFileWriter extends Writer {

    private Writer writer;

    public WindowsFileWriter(File file) throws IOException {
        try {
            writer = new OutputStreamWriter(new FileOutputStream(file), "ISO-8859-15");
        } catch (UnsupportedEncodingException e) {
            writer = new FileWriter(logfile);
        }
    }

    @Override
    public void write(char[] cbuf, int off, int len) throws IOException {
        writer.write(new String(cbuf, off, len).replace("\n", "\r\n"));
    }

    @Override
    public void flush() throws IOException {
        writer.flush();
    }

    @Override
    public void close() throws IOException {
        writer.close();
    }

}

Postman: How to make multiple requests at the same time

Run all Collection in a folder in parallel:

'use strict';

global.Promise = require('bluebird');
const path = require('path');
const newman =  Promise.promisifyAll(require('newman'));
const fs = Promise.promisifyAll(require('fs'));
const environment = 'postman_environment.json';
const FOLDER = path.join(__dirname, 'Collections_Folder');


let files = fs.readdirSync(FOLDER);
files = files.map(file=> path.join(FOLDER, file))
console.log(files);

Promise.map(files, file => {

    return newman.runAsync({
    collection: file, // your collection
    environment: path.join(__dirname, environment), //your env
    reporters: ['cli']
    });

}, {
   concurrency: 2
});

What does java.lang.Thread.interrupt() do?

Thread.interrupt() sets the interrupted status/flag of the target thread. Then code running in that target thread MAY poll the interrupted status and handle it appropriately. Some methods that block such as Object.wait() may consume the interrupted status immediately and throw an appropriate exception (usually InterruptedException)

Interruption in Java is not pre-emptive. Put another way both threads have to cooperate in order to process the interrupt properly. If the target thread does not poll the interrupted status the interrupt is effectively ignored.

Polling occurs via the Thread.interrupted() method which returns the current thread's interrupted status AND clears that interrupt flag. Usually the thread might then do something such as throw InterruptedException.

EDIT (from Thilo comments): Some API methods have built in interrupt handling. Of the top of my head this includes.

  • Object.wait(), Thread.sleep(), and Thread.join()
  • Most java.util.concurrent structures
  • Java NIO (but not java.io) and it does NOT use InterruptedException, instead using ClosedByInterruptException.

EDIT (from @thomas-pornin's answer to exactly same question for completeness)

Thread interruption is a gentle way to nudge a thread. It is used to give threads a chance to exit cleanly, as opposed to Thread.stop() that is more like shooting the thread with an assault rifle.

Do HTTP POST methods send data as a QueryString?

Post uses the message body to send the information back to the server, as opposed to Get, which uses the query string (everything after the question mark). It is possible to send both a Get query string and a Post message body in the same request, but that can get a bit confusing so is best avoided.

Generally, best practice dictates that you use Get when you want to retrieve data, and Post when you want to alter it. (These rules aren't set in stone, the specs don't forbid altering data with Get, but it's generally avoided on the grounds that you don't want people making changes just by clicking a link or typing a URL)

Conversely, you can use Post to retrieve data without changing it, but using Get means you can bookmark the page, or share the URL with other people, things you couldn't do if you'd used Post.

As for the actual format of the data sent in the message body, that's entirely up to the sender and is specified with the Content-Type header. If not specified, the default content-type for HTML forms is application/x-www-form-urlencoded, which means the server will expect the post body to be a string encoded in a similar manner to a GET query string. However this can't be depended on in all cases. RFC2616 says the following on the Content-Type header:

Any HTTP/1.1 message containing an entity-body SHOULD include a
Content-Type header field defining the media type of that body. If
and only if the media type is not given by a Content-Type field, the
recipient MAY attempt to guess the media type via inspection of its
content and/or the name extension(s) of the URI used to identify the
resource. If the media type remains unknown, the recipient SHOULD
treat it as type "application/octet-stream".

Insert Multiple Rows Into Temp Table With SQL Server 2012

When using SQLFiddle, make sure that the separator is set to GO. Also the schema build script is executed in a different connection from the run script, so a temp table created in the one is not visible in the other. This fiddle shows that your code is valid and working in SQL 2012:

SQL Fiddle

MS SQL Server 2012 Schema Setup:

Query 1:

CREATE TABLE #Names
  ( 
    Name1 VARCHAR(100),
    Name2 VARCHAR(100)
  ) 

INSERT INTO #Names
  (Name1, Name2)
VALUES
  ('Matt', 'Matthew'),
  ('Matt', 'Marshal'),
  ('Matt', 'Mattison')

SELECT * FROM #NAMES

Results:

| NAME1 |    NAME2 |
--------------------
|  Matt |  Matthew |
|  Matt |  Marshal |
|  Matt | Mattison |

Here a SSMS 2012 screenshot: enter image description here

Starting a node.js server

Run cmd and then run node server.js. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)

How to find list intersection?

Using list comprehensions is a pretty obvious one for me. Not sure about performance, but at least things stay lists.

[x for x in a if x in b]

Or "all the x values that are in A, if the X value is in B".

Why in C++ do we use DWORD rather than unsigned int?

For myself, I would assume unsigned int is platform specific. Integer could be 8 bits, 16 bits, 32 bits or even 64 bits.

DWORD in the other hand, specifies its own size, which is Double Word. Word are 16 bits so DWORD will be known as 32 bit across all platform

`require': no such file to load -- mkmf (LoadError)

I think is a little late but

sudo yum install -y gcc ruby-devel libxml2 libxml2-devel libxslt libxslt-devel

worked for me on fedora.

http://nokogiri.org/tutorials/installing_nokogiri.html

Make div fill remaining space along the main axis in flexbox

Use the flex-grow property to make a flex item consume free space on the main axis.

This property will expand the item as much as possible, adjusting the length to dynamic environments, such as screen re-sizing or the addition / removal of other items.

A common example is flex-grow: 1 or, using the shorthand property, flex: 1.

Hence, instead of width: 96% on your div, use flex: 1.


You wrote:

So at the moment, it's set to 96% which looks OK until you really squash the screen - then the right hand div gets a bit starved of the space it needs.

The squashing of the fixed-width div is related to another flex property: flex-shrink

By default, flex items are set to flex-shrink: 1 which enables them to shrink in order to prevent overflow of the container.

To disable this feature use flex-shrink: 0.

For more details see The flex-shrink factor section in the answer here:


Learn more about flex alignment along the main axis here:

Learn more about flex alignment along the cross axis here:

What is the difference between char array and char pointer in C?

As far as I can remember, an array is actually a group of pointers. For example

p[1]== *(&p+1)

is a true statement

Excel VBA: Copying multiple sheets into new workbook

This worked for me (I added an "if sheet visible" because in my case I wanted to skip hidden sheets)

   Sub Create_new_file()

Application.DisplayAlerts = False

Dim wb As Workbook
Dim wbNew As Workbook
Dim sh As Worksheet
Dim shNew As Worksheet
Dim pname, parea As String


Set wb = ThisWorkbook
Workbooks.Add
Set wbNew = ActiveWorkbook

For Each sh In wb.Worksheets

    pname = sh.Name


    If sh.Visible = True Then

    sh.Copy After:=wbNew.Sheets(Sheets.Count)

    wbNew.Sheets(Sheets.Count).Cells.ClearContents
    wbNew.Sheets(Sheets.Count).Cells.ClearFormats
    wb.Sheets(sh.Name).Activate
    Range(sh.PageSetup.PrintArea).Select
    Selection.Copy

    wbNew.Sheets(pname).Activate
    Range("A1").Select

    With Selection

        .PasteSpecial (xlValues)
        .PasteSpecial (xlFormats)
        .PasteSpecial (xlPasteColumnWidths)

    End With

    ActiveSheet.Name = pname

    End If


Next

wbNew.Sheets("Hoja1").Delete

Application.DisplayAlerts = True

End Sub

For..In loops in JavaScript - key value pairs

var global = (function() {
   return this;
})();

// Pair object, similar to Python

function Pair(key, value) {
    this.key = key;
    this.value = value;

    this.toString = function() {
       return "(" + key + ", " + value + ")";
    };
}

/**
 * as function
 * @param {String} dataName A String holding the name of your pairs list.
 * @return {Array:Pair} The data list filled
 *    with all pair objects.
 */
Object.prototype.as = function(dataName) {
    var value, key, data;
    global[dataName] = data = [];

    for (key in this) {
       if (this.hasOwnProperty(key)) {
          value = this[key];

          (function() {
             var k = key,
                 v = value;

            data.push(new Pair(k, v));
          })();
       }
    }

    return data;
};

var d = {
   'one': 1,
   'two': 2
};

// Loop on your (key, list) pairs in this way
for (var i = 0, max = d.as("data").length; i < max; i += 1) {
   key = data[i].key;
   value = data[i].value;

   console.log("key: " + key + ", value: " + value);
}

// delete data when u've finished with it.
delete data;

SSRS - Checking whether the data is null

Or in your SQL query wrap that field with IsNull or Coalesce (SQL Server).

Either way works, I like to put that logic in the query so the report has to do less.

Make a table fill the entire window

Below line helped me to fix the issue of scroll bar for a table; the issue was awkward 2 scroll bars in a page. Below style when applied to table worked fine for me.
<table Style="position: absolute; height: 100%; width: 100%";/>

How to convert text column to datetime in SQL

Use convert with style 101.

select convert(datetime, Remarks, 101)

If your column is really text you need to convert to varchar before converting to datetime

select convert(datetime, convert(varchar(30), Remarks), 101)

Back button and refreshing previous activity

 @Override
protected void onRestart() {
    super.onRestart();
    finish();
    overridePendingTransition(0, 0);
    startActivity(getIntent());
    overridePendingTransition(0, 0);
}

In previous activity use this code. This will do a smooth transition and reload the activity when you come back by pressing back button.

MySQL Trigger after update only if row has changed

Use the following query to see which rows have changes:

(select * from inserted) except (select * from deleted)

The results of this query should consist of all the new records that are different from the old ones.

How to get a parent element to appear above child

Some of these answers do work, but setting position: absolute; and z-index: 10; seemed pretty strong just to achieve the required effect. I found the following was all that was required, though unfortunately, I've not been able to reduce it any further.

HTML:

<div class="wrapper">
    <div class="parent">
        <div class="child">
            ...
        </div>
    </div>
</div>

CSS:

.wrapper {
    position: relative;
    z-index: 0;
}

.child {
    position: relative;
    z-index: -1;
}

I used this technique to achieve a bordered hover effect for image links. There's a bit more code here but it uses the concept above to show the border over the top of the image.

http://jsfiddle.net/g7nP5/

linq query to return distinct field values from a list of objects

Sure, use Enumerable.Distinct.

Given a collection of obj (e.g. foo), you'd do something like this:

var distinctTypeIDs = foo.Select(x => x.typeID).Distinct();

Is there a portable way to get the current username in Python?

Look at getpass module

import getpass
getpass.getuser()
'kostya'

Availability: Unix, Windows


p.s. Per comment below "this function looks at the values of various environment variables to determine the user name. Therefore, this function should not be relied on for access control purposes (or possibly any other purpose, since it allows any user to impersonate any other)."

Get a file name from a path

A slow but straight forward regex solution:

    std::string file = std::regex_replace(path, std::regex("(.*\\/)|(\\..*)"), "");

Xcode 7 error: "Missing iOS Distribution signing identity for ..."

I also faced the same issue today. The following steps fixed my issue.

  1. Download https://developer.apple.com/certificationauthority/AppleWWDRCA.cer
  2. Double-click to install to Keychain.
  3. Then in Keychain, Select View -> "Show Expired Certificates" in Keychain app.
  4. It will list all the expired certifcates.
  5. Delete "Apple Worldwide Developer Relations Certificate Authority certificates" from "login" tab
  6. And also delete it from "System" tab.

Now you are ready go.

Print a div content using Jquery

Without using any plugin you can opt this logic.

$("#btn").click(function () {
    //Hide all other elements other than printarea.
    $("#printarea").show();
    window.print();
});

Invalid hook call. Hooks can only be called inside of the body of a function component

React linter assumes every method starting with use as hooks and hooks doesn't work inside classes. by renaming const useStyles into anything else that doesn't starts with use like const myStyles you are good to go.

Update:

makeStyles is hook api and you can't use that inside classes. you can use styled components API. see here

Pretty-Printing JSON with PHP

Use <pre> in combination with json_encode() and the JSON_PRETTY_PRINT option:

<pre>
    <?php
    echo json_encode($dataArray, JSON_PRETTY_PRINT);
    ?>
</pre>

Batch file to copy files from one folder to another folder

Look at rsync based Windows tool NASBackup. It will be a bonus if you are acquainted with rsync commands.

I want to calculate the distance between two points in Java

Unlike maths-on-paper notation, most programming languages (Java included) need a * sign to do multiplication. Your distance calculation should therefore read:

distance = Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));

Or alternatively:

distance = Math.sqrt(Math.pow((x1-x2), 2) + Math.pow((y1-y2), 2));

Python name 'os' is not defined

Just add:

import os

in the beginning, before:

from settings import PROJECT_ROOT

This will import the python's module os, which apparently is used later in the code of your module without being imported.

How to terminate a thread when main program ends?

Try with enabling the sub-thread as daemon-thread.

For Instance:

Recommended:

from threading import Thread

t = Thread(target=<your-method>)
t.daemon = True  # This thread dies when main thread (only non-daemon thread) exits.
t.start()

Inline:

t = Thread(target=<your-method>, daemon=True).start()

Old API:

t.setDaemon(True)
t.start()

When your main thread terminates ("i.e. when I press Ctrl+C"), other threads will also be killed by the instructions above.

Proper indentation for Python multiline strings

The textwrap.dedent function allows one to start with correct indentation in the source, and then strip it from the text before use.

The trade-off, as noted by some others, is that this is an extra function call on the literal; take this into account when deciding where to place these literals in your code.

import textwrap

def frobnicate(param):
    """ Frobnicate the scrognate param.

        The Weebly-Ruckford algorithm is employed to frobnicate
        the scrognate to within an inch of its life.

        """
    prepare_the_comfy_chair(param)
    log_message = textwrap.dedent("""\
            Prepare to frobnicate:
            Here it comes...
                Any moment now.
            And: Frobnicate!""")
    weebly(param, log_message)
    ruckford(param)

The trailing \ in the log message literal is to ensure that line break isn't in the literal; that way, the literal doesn't start with a blank line, and instead starts with the next full line.

The return value from textwrap.dedent is the input string with all common leading whitespace indentation removed on each line of the string. So the above log_message value will be:

Prepare to frobnicate:
Here it comes...
    Any moment now.
And: Frobnicate!

Tomcat - maxThreads vs maxConnections

Tomcat can work in 2 modes:

  • BIO – blocking I/O (one thread per connection)
  • NIOnon-blocking I/O (many more connections than threads)

Tomcat 7 is BIO by default, although consensus seems to be "don't use Bio because Nio is better in every way". You set this using the protocol parameter in the server.xml file.

  • BIO will be HTTP/1.1 or org.apache.coyote.http11.Http11Protocol
  • NIO will be org.apache.coyote.http11.Http11NioProtocol

If you're using BIO then I believe they should be more or less the same.

If you're using NIO then actually "maxConnections=1000" and "maxThreads=10" might even be reasonable. The defaults are maxConnections=10,000 and maxThreads=200. With NIO, each thread can serve any number of connections, switching back and forth but retaining the connection so you don't need to do all the usual handshaking which is especially time-consuming with HTTPS but even an issue with HTTP. You can adjust the "keepAlive" parameter to keep connections around for longer and this should speed everything up.

Count all duplicates of each value

SELECT   col,
         COUNT(dupe_col) AS dupe_cnt
FROM     TABLE
GROUP BY col
HAVING   COUNT(dupe_col) > 1
ORDER BY COUNT(dupe_col) DESC

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

Why do I need 'b' to encode a string with Base64?

There is all you need:

expected bytes, not str

The leading b makes your string binary.

What version of Python do you use? 2.x or 3.x?

Edit: See http://docs.python.org/release/3.0.1/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit for the gory details of strings in Python 3.x

Deleting all files in a directory with Python

I realize this is old; however, here would be how to do so using just the os module...

def purgedir(parent):
    for root, dirs, files in os.walk(parent):                                      
        for item in files:
            # Delete subordinate files                                                 
            filespec = os.path.join(root, item)
            if filespec.endswith('.bak'):
                os.unlink(filespec)
        for item in dirs:
            # Recursively perform this operation for subordinate directories   
            purgedir(os.path.join(root, item))

What is a Python equivalent of PHP's var_dump()?

I don't have PHP experience, but I have an understanding of the Python standard library.

For your purposes, Python has several methods:

logging module;

Object serialization module which is called pickle. You may write your own wrapper of the pickle module.

If your using var_dump for testing, Python has its own doctest and unittest modules. It's very simple and fast for design.

Open file in a relative location in Python

If the file is in your parent folder, eg. follower.txt, you can simply use open('../follower.txt', 'r').read()

How to find the unclosed div tag

1- Count the number of <div in notepad++ (Ctrl + F)
2- Count the number of </div

Compare the two numbers!

SQL Query - SUM(CASE WHEN x THEN 1 ELSE 0) for multiple columns

I would change the query in the following ways:

  1. Do the aggregation in subqueries. This can take advantage of more information about the table for optimizing the group by.
  2. Combine the second and third subqueries. They are aggregating on the same column. This requires using a left outer join to ensure that all data is available.
  3. By using count(<fieldname>) you can eliminate the comparisons to is null. This is important for the second and third calculated values.
  4. To combine the second and third queries, it needs to count an id from the mde table. These use mde.mdeid.

The following version follows your example by using union all:

SELECT CAST(Detail.ReceiptDate AS DATE) AS "Date",
       SUM(TOTALMAILED) as TotalMailed,
       SUM(TOTALUNDELINOTICESRECEIVED) as TOTALUNDELINOTICESRECEIVED,
       SUM(TRACEUNDELNOTICESRECEIVED) as TRACEUNDELNOTICESRECEIVED
FROM ((select SentDate AS "ReceiptDate", COUNT(*) as TotalMailed,
              NULL as TOTALUNDELINOTICESRECEIVED, NULL as TRACEUNDELNOTICESRECEIVED
       from MailDataExtract
       where SentDate is not null
       group by SentDate
      ) union all
      (select MDE.ReturnMailDate AS ReceiptDate, 0,
              COUNT(distinct mde.mdeid) as TOTALUNDELINOTICESRECEIVED,
              SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
       from MailDataExtract MDE left outer join
            DTSharedData.dbo.ScanData SD
            ON SD.ScanDataID = MDE.ReturnScanDataID
       group by MDE.ReturnMailDate;
      )
     ) detail
GROUP BY CAST(Detail.ReceiptDate AS DATE)
ORDER BY 1;

The following does something similar using full outer join:

SELECT coalesce(sd.ReceiptDate, mde.ReceiptDate) AS "Date",
       sd.TotalMailed, mde.TOTALUNDELINOTICESRECEIVED,
       mde.TRACEUNDELNOTICESRECEIVED
FROM (select cast(SentDate as date) AS "ReceiptDate", COUNT(*) as TotalMailed
      from MailDataExtract
      where SentDate is not null
      group by cast(SentDate as date)
     ) sd full outer join
    (select cast(MDE.ReturnMailDate as date) AS ReceiptDate,
            COUNT(distinct mde.mdeID) as TOTALUNDELINOTICESRECEIVED,
            SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
     from MailDataExtract MDE left outer join
          DTSharedData.dbo.ScanData SD
          ON SD.ScanDataID = MDE.ReturnScanDataID
     group by cast(MDE.ReturnMailDate as date)
    ) mde
    on sd.ReceiptDate = mde.ReceiptDate
ORDER BY 1;

Stacked bar chart

You need to transform your data to long format and shouldn't use $ inside aes:

DF <- read.table(text="Rank F1     F2     F3
1    500    250    50
2    400    100    30
3    300    155    100
4    200    90     10", header=TRUE)

library(reshape2)
DF1 <- melt(DF, id.var="Rank")

library(ggplot2)
ggplot(DF1, aes(x = Rank, y = value, fill = variable)) + 
  geom_bar(stat = "identity")

enter image description here

Find Process Name by its Process ID

Using only "native" Windows utilities, try the following, where "516" is the process ID that you want the image name for:

for /f "delims=," %a in ( 'tasklist /fi "PID eq 516" /nh /fo:csv' ) do ( echo %~a )
for /f %a in ( 'tasklist /fi "PID eq 516" ^| findstr "516"' ) do ( echo %a )

Or you could use wmic (the Windows Management Instrumentation Command-line tool) and get the full path to the executable:

wmic process where processId=516 get name
wmic process where processId=516 get ExecutablePath

Or you could download Microsoft PsTools, or specifically download just the pslist utility, and use PsList:

for /f %a in ( 'pslist 516 ^| findstr "516"' ) do ( echo %a )

How to display two digits after decimal point in SQL Server

You can also Make use of the Following if you want to Cast and Round as well. That may help you or someone else.

SELECT CAST(ROUND(Column_Name, 2) AS DECIMAL(10,2), Name FROM Table_Name

Fastest method to escape HTML tags as HTML entities?

I'm not entirely sure about speed, but if you are looking for simplicity I would suggest using the lodash/underscore escape function.

Alternative to google finance api

I'd suggest using TradeKing's developer API. It is very good and free to use. All that is required is that you have an account with them and to my knowledge you don't have to carry a balance ... only to be registered.

Why would anybody use C over C++?

Because they're writing a plugin and C++ has no standard ABI.

Why does this AttributeError in python occur?

The default namespace in Python is "__main__". When you use import scipy, Python creates a separate namespace as your module name. The rule in Pyhton is: when you want to call an attribute from another namespaces you have to use the fully qualified attribute name.

How do I write to a Python subprocess' stdin?

You can provide a file-like object to the stdin argument of subprocess.call().

The documentation for the Popen object applies here.

To capture the output, you should instead use subprocess.check_output(), which takes similar arguments. From the documentation:

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'

How to check if a textbox is empty using javascript

Canonical without using frameworks with added trim prototype for older browsers

<html>
<head>
<script type="text/javascript">
// add trim to older IEs
if (!String.trim) {
  String.prototype.trim = function() {return this.replace(/^\s+|\s+$/g, "");};
}

window.onload=function() { // onobtrusively adding the submit handler
  document.getElementById("form1").onsubmit=function() { // needs an ID
    var val = this.textField1.value; // 'this' is the form 
    if (val==null || val.trim()=="") { 
      alert('Please enter something');
      this.textField1.focus();
      return false; // cancel submission
    }
    return true; // allow submit
  }
}
</script>
</head>
<body>
<form id="form1">
  <input type="text" name="textField1" value="" /><br/>
  <input type="submit" />
</form>
</body>
</html>

Here is the inline version, although not recommended I show it here in case you need to add validation without being able to refactor the code

function validate(theForm) { // passing the form object
  var val = theForm.textField1.value;
  if (val==null || val.trim()=="") { 
    alert('Please enter something');
    theForm.textField1.focus();
    return false; // cancel submission
  }
  return true; // allow submit
}

passing the form object in (this)

<form onsubmit="return validate(this)">
  <input type="text" name="textField1" value="" /><br/>
  <input type="submit" />
</form>

Type definition in object literal in TypeScript

I'm surprised that no-one's mentioned this but you could just create an interface called ObjectLiteral, that accepts key: value pairs of type string: any:

interface ObjectLiteral {
  [key: string]: any;
}

Then you'd use it, like this:

let data: ObjectLiteral = {
  hello: "world",
  goodbye: 1,
  // ...
};

An added bonus is that you can re-use this interface many times as you need, on as many objects you'd like.

Good luck.

Unstaged changes left after git reset --hard

For some reason

git add .

didn't work, but

$ git add -A

worked out!

Insert HTML with React Variable Statements (JSX)

You can also include this HTML in ReactDOM like this:

var thisIsMyCopy = (<p>copy copy copy <strong>strong copy</strong></p>);

ReactDOM.render(<div className="content">{thisIsMyCopy}</div>, document.getElementById('app'));

Here are two links link and link2 from React documentation which could be helpful.

Java - Get a list of all Classes loaded in the JVM

You might be able to get a list of classes that are loaded through the classloader but this would not include classes you haven't loaded yet but are on your classpath.

To get ALL classes on your classpath you have to do something like your second solution. If you really want classes that are currently "Loaded" (in other words, classes you have already referenced, accessed or instantiated) then you should refine your question to indicate this.

Find specific string in a text file with VBS script

I'd recommend using a regular expressions instead of string operations for this:

Set fso = CreateObject("Scripting.FileSystemObject")

filename = "C:\VBS\filediprova.txt"

newtext = vbLf & "<tr><td><a href=""..."">Beginning_of_DD_TC5</a></td></tr>"

Set re = New RegExp
re.Pattern = "(\n.*?Test Case \d)"
re.Global  = False
re.IgnoreCase = True

text = f.OpenTextFile(filename).ReadAll
f.OpenTextFile(filename, 2).Write re.Replace(text, newText & "$1")

The regular expression will match a line feed (\n) followed by a line containing the string Test Case followed by a number (\d), and the replacement will prepend that with the text you want to insert (variable newtext). Setting re.Global = False makes the replacement stop after the first match.

If the line breaks in your text file are encoded as CR-LF (carriage return + line feed) you'll have to change \n into \r\n and vbLf into vbCrLf.

If you have to modify several text files, you could do it in a loop like this:

For Each f In fso.GetFolder("C:\VBS").Files
  If LCase(fso.GetExtensionName(f.Name)) = "txt" Then
    text = f.OpenAsTextStream.ReadAll
    f.OpenAsTextStream(2).Write re.Replace(text, newText & "$1")
  End If
Next

Can't compare naive and aware datetime.now() <= challenge.datetime_end

By default, the datetime object is naive in Python, so you need to make both of them either naive or aware datetime objects. This can be done using:

import datetime
import pytz

utc=pytz.UTC

challenge.datetime_start = utc.localize(challenge.datetime_start) 
challenge.datetime_end = utc.localize(challenge.datetime_end) 
# now both the datetime objects are aware, and you can compare them

Note: This would raise a ValueError if tzinfo is already set. If you are not sure about that, just use

start_time = challenge.datetime_start.replace(tzinfo=utc)
end_time = challenge.datetime_end.replace(tzinfo=utc)

BTW, you could format a UNIX timestamp in datetime.datetime object with timezone info as following

d = datetime.datetime.utcfromtimestamp(int(unix_timestamp))
d_with_tz = datetime.datetime(
    year=d.year,
    month=d.month,
    day=d.day,
    hour=d.hour,
    minute=d.minute,
    second=d.second,
    tzinfo=pytz.UTC)

ASP.NET Core return JSON with status code

Please refer below code, You can manage multiple status code with different type JSON

public async Task<HttpResponseMessage> GetAsync()
{
    try
    {
        using (var entities = new DbEntities())
        {
            var resourceModelList = entities.Resources.Select(r=> new ResourceModel{Build Your Resource Model}).ToList();

            if (resourceModelList.Count == 0)
            {
                return this.Request.CreateResponse<string>(HttpStatusCode.NotFound, "No resources found.");
            }

            return this.Request.CreateResponse<List<ResourceModel>>(HttpStatusCode.OK, resourceModelList, "application/json");
        }
    }
    catch (Exception ex)
    {
        return this.Request.CreateResponse<string>(HttpStatusCode.InternalServerError, "Something went wrong.");
    }
}

Correct mime type for .mp4

According to RFC 4337 § 2, video/mp4 is indeed the correct Content-Type for MPEG-4 video.

Generally, you can find official MIME definitions by searching for the file extension and "IETF" or "RFC". The RFC (Request for Comments) articles published by the IETF (Internet Engineering Taskforce) define many Internet standards, including MIME types.

What is a void pointer in C++?

A void* does not mean anything. It is a pointer, but the type that it points to is not known.

It's not that it can return "anything". A function that returns a void* generally is doing one of the following:

  • It is dealing in unformatted memory. This is what operator new and malloc return: a pointer to a block of memory of a certain size. Since the memory does not have a type (because it does not have a properly constructed object in it yet), it is typeless. IE: void.
  • It is an opaque handle; it references a created object without naming a specific type. Code that does this is generally poorly formed, since this is better done by forward declaring a struct/class and simply not providing a public definition for it. Because then, at least it has a real type.
  • It returns a pointer to storage that contains an object of a known type. However, that API is used to deal with objects of a wide variety of types, so the exact type that a particular call returns cannot be known at compile time. Therefore, there will be some documentation explaining when it stores which kinds of objects, and therefore which type you can safely cast it to.

This construct is nothing like dynamic or object in C#. Those tools actually know what the original type is; void* does not. This makes it far more dangerous than any of those, because it is very easy to get it wrong, and there's no way to ask if a particular usage is the right one.

And on a personal note, if you see code that uses void*'s "often", you should rethink what code you're looking at. void* usage, especially in C++, should be rare, used primary for dealing in raw memory.

How to set JAVA_HOME for multiple Tomcat instances?

You can add setenv.sh in the the bin directory with:

export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")

and it will dynamically change when you update your packages.

sql query distinct with Row_Number

Question is too old and my answer might not add much but here are my two cents for making query a little useful:

;WITH DistinctRecords AS (
    SELECT  DISTINCT [col1,col2,col3,..] 
    FROM    tableName 
    where   [my condition]
), 
serialize AS (
   SELECT
    ROW_NUMBER() OVER (PARTITION BY [colNameAsNeeded] ORDER BY  [colNameNeeded]) AS Sr,*
    FROM    DistinctRecords 
)
SELECT * FROM serialize 

Usefulness of using two cte's lies in the fact that now you can use serialized record much easily in your query and do count(*) etc very easily.

DistinctRecords will select all distinct records and serialize apply serial numbers to distinct records. after wards you can use final serialized result for your purposes without clutter.

Partition By might not be needed in most cases

Bootstrap Carousel Full Screen

This is how I did it. This makes the images in the slideshow take up the full screen if it´s aspect ratio allows it, othervice it scales down.

.carousel {
    height: 100vh;
    width: 100%;
    overflow:hidden;
}
.carousel .carousel-inner {
    height:100%;    
}

To allways get a full screen slideshow, no matter screen aspect ratio, you can also use object-fit: (doesn´t work in IE or Edge)

.carousel .carousel-inner img {
    display:block;
    object-fit: cover;
}

Moment.js transform to date object

moment has updated the js lib as of 06/2018.

var newYork    = moment.tz("2014-06-01 12:00", "America/New_York");
var losAngeles = newYork.clone().tz("America/Los_Angeles");
var london     = newYork.clone().tz("Europe/London");

newYork.format();    // 2014-06-01T12:00:00-04:00
losAngeles.format(); // 2014-06-01T09:00:00-07:00
london.format();     // 2014-06-01T17:00:00+01:00

if you have freedom to use Angular5+, then better use datePipe feature there than the timezone function here. I have to use moment.js because my project limits to Angular2 only.

Multi-line strings in PHP

$xml="l\rn";
$xml.="vv";

echo $xml;

But you should really look into http://us3.php.net/simplexml

How to change button text or link text in JavaScript?

You can simply use:

document.getElementById(button_id).innerText = 'Your text here';

If you want to use HTML formatting, use the innerHTML property instead.

HTML inside Twitter Bootstrap popover

You can use the popover event, and control the width by attribute 'data-width'

_x000D_
_x000D_
$('[data-toggle="popover-huongdan"]').popover({ html: true });_x000D_
$('[data-toggle="popover-huongdan"]').on("shown.bs.popover", function () {_x000D_
    var width = $(this).attr("data-width") == undefined ? 276 : parseInt($(this).attr("data-width"));_x000D_
    $("div[id^=popover]").css("max-width", width);_x000D_
});
_x000D_
 <a class="position-absolute" href="javascript:void(0);" data-toggle="popover-huongdan" data-trigger="hover" data-width="500" title="title-popover" data-content="html-content-code">_x000D_
 <i class="far fa-question-circle"></i>_x000D_
 </a>
_x000D_
_x000D_
_x000D_

How do you stretch an image to fill a <div> while keeping the image's aspect-ratio?

If you can, use background images and set background-size: cover. This will make the background cover the whole element.

CSS

div {
  background-image: url(path/to/your/image.png);
  background-repeat: no-repeat;
  background-position: 50% 50%;
  background-size: cover;
}

If you're stuck with using inline images there are a few options. First, there is

object-fit

This property acts on images, videos and other objects similar to background-size: cover.

CSS

img {
  object-fit: cover;
}

Sadly, browser support is not that great with IE up to version 11 not supporting it at all. The next option uses jQuery

CSS + jQuery

HTML

<div>
  <img src="image.png" class="cover-image">
</div>

CSS

div {
  height: 8em;
  width: 15em;
}

Custom jQuery plugin

(function ($) {
  $.fn.coverImage = function(contain) {
    this.each(function() {
      var $this = $(this),
        src = $this.get(0).src,
        $wrapper = $this.parent();

      if (contain) {
        $wrapper.css({
          'background': 'url(' + src + ') 50% 50%/contain no-repeat'
        });
      } else {
        $wrapper.css({
          'background': 'url(' + src + ') 50% 50%/cover no-repeat'
        });
      }

      $this.remove();
    });

    return this;
  };
})(jQuery);

Use the plugin like this

jQuery('.cover-image').coverImage();

It will take an image, set it as a background image on the image's wrapper element and remove the img tag from the document. Lastly you could use

Pure CSS

You might use this as a fallback. The image will scale up to cover it's container but it won't scale down.

CSS

div {
  height: 8em;
  width: 15em;
  overflow: hidden;
}

div img {
  min-height: 100%;
  min-width: 100%;
  width: auto;
  height: auto;
  max-width: none;
  max-height: none;
  display: block;
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Hope this might help somebody, happy coding!

Disabled href tag

try this one

  <a href="javascript:void(0)">Click Hare</a>

Changing background color of text box input not working when empty

You didn't call the function and you have other errors, should be:

function checkFilled() {
    var inputVal = document.getElementById("subEmail");
    if (inputVal.value == "") {
        inputVal.style.backgroundColor = "yellow";
    }
}
checkFilled();

Fiddle

You were setting inputVal to the string value of the input, but then you tried to set style.backgroundColor on it, which won't work because it's a string, not the element. I changed your variable to store the element object instead of its value.

Failed to read artifact descriptor for org.apache.maven.plugins:maven-source-plugin:jar:2.4

I am using JDK 7 for maven project and I used -Dhttps.protocols=TLSv1.2 as argument in JRE. It has allowed to download all maven repository which were failing earlier.

Global Events in Angular

There is no equivalent to $scope.emit() or $scope.broadcast() from AngularJS. EventEmitter inside of a component comes close, but as you mentioned, it will only emit an event to the immediate parent component.

In Angular, there are other alternatives which I'll try to explain below.

@Input() bindings allows the application model to be connected in a directed object graph (root to leaves). The default behavior of a component's change detector strategy is to propagate all changes to an application model for all bindings from any connected component.

Aside: There are two types of models: View Models and Application Models. An application model is connected through @Input() bindings. A view model is a just a component property (not decorated with @Input()) which is bound in the component's template.

To answer your questions:

What if I need to communicate between sibling components?

  1. Shared Application Model: Siblings can communicate through a shared application model (just like angular 1). For example, when one sibling makes a change to a model, the other sibling that has bindings to the same model is automatically updated.

  2. Component Events: Child components can emit an event to the parent component using @Output() bindings. The parent component can handle the event, and manipulate the application model or it's own view model. Changes to the Application Model are automatically propagated to all components that directly or indirectly bind to the same model.

  3. Service Events: Components can subscribe to service events. For example, two sibling components can subscribe to the same service event and respond by modifying their respective models. More on this below.

How can I communicate between a Root component and a component nested several levels deep?

  1. Shared Application Model: The application model can be passed from the Root component down to deeply nested sub-components through @Input() bindings. Changes to a model from any component will automatically propagate to all components that share the same model.
  2. Service Events: You can also move the EventEmitter to a shared service, which allows any component to inject the service and subscribe to the event. That way, a Root component can call a service method (typically mutating the model), which in turn emits an event. Several layers down, a grand-child component which has also injected the service and subscribed to the same event, can handle it. Any event handler that changes a shared Application Model, will automatically propagate to all components that depend on it. This is probably the closest equivalent to $scope.broadcast() from Angular 1. The next section describes this idea in more detail.

Example of an Observable Service that uses Service Events to Propagate Changes

Here is an example of an observable service that uses service events to propagate changes. When a TodoItem is added, the service emits an event notifying its component subscribers.

export class TodoItem {
    constructor(public name: string, public done: boolean) {
    }
}
export class TodoService {
    public itemAdded$: EventEmitter<TodoItem>;
    private todoList: TodoItem[] = [];

    constructor() {
        this.itemAdded$ = new EventEmitter();
    }

    public list(): TodoItem[] {
        return this.todoList;
    }

    public add(item: TodoItem): void {
        this.todoList.push(item);
        this.itemAdded$.emit(item);
    }
}

Here is how a root component would subscribe to the event:

export class RootComponent {
    private addedItem: TodoItem;
    constructor(todoService: TodoService) {
        todoService.itemAdded$.subscribe(item => this.onItemAdded(item));
    }

    private onItemAdded(item: TodoItem): void {
        // do something with added item
        this.addedItem = item;
    }
}

A child component nested several levels deep would subscribe to the event in the same way:

export class GrandChildComponent {
    private addedItem: TodoItem;
    constructor(todoService: TodoService) {
        todoService.itemAdded$.subscribe(item => this.onItemAdded(item));
    }

    private onItemAdded(item: TodoItem): void {
        // do something with added item
        this.addedItem = item;
    }
}

Here is the component that calls the service to trigger the event (it can reside anywhere in the component tree):

@Component({
    selector: 'todo-list',
    template: `
         <ul>
            <li *ngFor="#item of model"> {{ item.name }}
            </li>
         </ul>
        <br />
        Add Item <input type="text" #txt /> <button (click)="add(txt.value); txt.value='';">Add</button>
    `
})
export class TriggeringComponent{
    private model: TodoItem[];

    constructor(private todoService: TodoService) {
        this.model = todoService.list();
    }

    add(value: string) {
        this.todoService.add(new TodoItem(value, false));
    }
}

Reference: Change Detection in Angular

How to know if two arrays have the same values

Simple solution for shallow equality using ES6:

const arr1test = arr1.slice().sort()
const arr2test = arr2.slice().sort()
const equal = !arr1test.some((val, idx) => val !== arr2test[idx])

Creates shallow copies of each array and sorts them. Then uses some() to loop through arr1test values, checking each value against the value in arr2test with the same index. If all values are equal, some() returns false, and in turn equal evaluates to true.

Could also use every(), but it would have to cycle through every element in the array to satisfy a true result, whereas some() will bail as soon as it finds a value that is not equal:

const equal = arr1test.every((val, idx) => val === arr2test[idx])

Spring Boot yaml configuration for a list of strings

@Value("#{'${your.elements}'.split(',')}")  
private Set<String> stringSet;

yml file:

your:
 elements: element1, element2, element3

There is lot more you can play with spring spEL.

Java Long primitive type maximum limit

Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.

It will start from -9,223,372,036,854,775,808

Long.MIN_VALUE.

How to share my Docker-Image without using the Docker-Hub?

Based on this blog, one could share a docker image without a docker registry by executing:

docker save --output latestversion-1.0.0.tar dockerregistry/latestversion:1.0.0

Once this command has been completed, one could copy the image to a server and import it as follows:

docker load --input latestversion-1.0.0.tar

Converting a byte array to PNG/JPG

There are two problems with this question:

Assuming you have a gray scale bitmap, you have two factors to consider:

  1. For JPGS... what loss of quality is tolerable?
  2. For pngs... what level of compression is tolerable? (Although for most things I've seen, you don't have that much of a choice, so this choice might be negligible.) For anybody thinking this question doesn't make sense: yes, you can change the amount of compression/number of passes attempted to compress; check out either Ifranview or some of it's plugins.

Answer those questions, and then you might be able to find your original answer.

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

Use the deployment Toolkit's deployJava.js (though this ensures a minimum version, rather than a specific version)

How do I copy an object in Java?

You can try to implement Cloneable and use the clone() method; however, if you use the clone method you should - by standard - ALWAYS override Object's public Object clone() method.

How to do a SUM() inside a case statement in SQL server

If you're using SQL Server 2005 or above, you can use the windowing function SUM() OVER ().

case 
when test1.TotalType = 'Average' then Test2.avgscore
when test1.TotalType = 'PercentOfTot' then (cnt/SUM(test1.qrank) over ())
else cnt
end as displayscore

But it'll be better if you show your full query to get context of what you actually need.

When to use Common Table Expression (CTE)

Today we are going to learn about Common table expression that is a new feature which was introduced in SQL server 2005 and available in later versions as well.

Common table Expression :- Common table expression can be defined as a temporary result set or in other words its a substitute of views in SQL Server. Common table expression is only valid in the batch of statement where it was defined and cannot be used in other sessions.

Syntax of declaring CTE(Common table expression) :-

with [Name of CTE]
as
(
Body of common table expression
)

Lets take an example :-

CREATE TABLE Employee([EID] [int] IDENTITY(10,5) NOT NULL,[Name] [varchar](50) NULL)

insert into Employee(Name) values('Neeraj')
insert into Employee(Name) values('dheeraj')
insert into Employee(Name) values('shayam')
insert into Employee(Name) values('vikas')
insert into Employee(Name) values('raj')

CREATE TABLE DEPT(EID INT,DEPTNAME VARCHAR(100))
insert into dept values(10,'IT')
insert into dept values(15,'Finance')
insert into dept values(20,'Admin')
insert into dept values(25,'HR')
insert into dept values(10,'Payroll')

I have created two tables employee and Dept and inserted 5 rows in each table. Now I would like to join these tables and create a temporary result set to use it further.

With CTE_Example(EID,Name,DeptName)
as
(
select Employee.EID,Name,DeptName from Employee 
inner join DEPT on Employee.EID =DEPT.EID
)
select * from CTE_Example

Lets take each line of the statement one by one and understand.

To define CTE we write "with" clause, then we give a name to the table expression, here I have given name as "CTE_Example"

Then we write "As" and enclose our code in two brackets (---), we can join multiple tables in the enclosed brackets.

In the last line, I have used "Select * from CTE_Example" , we are referring the Common table expression in the last line of code, So we can say that Its like a view, where we are defining and using the view in a single batch and CTE is not stored in the database as an permanent object. But it behaves like a view. we can perform delete and update statement on CTE and that will have direct impact on the referenced table those are being used in CTE. Lets take an example to understand this fact.

With CTE_Example(EID,DeptName)
as
(
select EID,DeptName from DEPT 
)
delete from CTE_Example where EID=10 and DeptName ='Payroll'

In the above statement we are deleting a row from CTE_Example and it will delete the data from the referenced table "DEPT" that is being used in the CTE.

Getting an "ambiguous redirect" error

This might be the case too.

you have not specified the file in a variable and redirecting output to it, then bash will throw this error.

files=`ls`
out_file = /path/to/output_file.t
for i in `echo "$files"`;
do
    content=`cat $i` 
    echo "${content}  ${i}" >> ${out_file}
done

out_file variable is not set up correctly so keep an eye on this too. BTW this code is printing all the content and its filename on the console.

What is the syntax for Typescript arrow functions with generics?

The full example explaining the syntax referenced by Robin... brought it home for me:

Generic functions

Something like the following works fine:

function foo<T>(x: T): T { return x; }

However using an arrow generic function will not:

const foo = <T>(x: T) => x; // ERROR : unclosed `T` tag

Workaround: Use extends on the generic parameter to hint the compiler that it's a generic, e.g.:

const foo = <T extends unknown>(x: T) => x;

AngularJS event on window innerWidth size change

If Khanh TO's solution caused UI issues for you (like it did for me) try using $timeout to not update the attribute until it has been unchanged for 500ms.

var oldWidth = window.innerWidth;
$(window).on('resize.doResize', function () {
    var newWidth = window.innerWidth,
        updateStuffTimer;

    if (newWidth !== oldWidth) {
        $timeout.cancel(updateStuffTimer);
    }

    updateStuffTimer = $timeout(function() {
         updateStuff(newWidth); // Update the attribute based on window.innerWidth
    }, 500);
});

$scope.$on('$destroy',function (){
    $(window).off('resize.doResize'); // remove the handler added earlier
});

Reference: https://gist.github.com/tommaitland/7579618

spring autowiring with unique beans: Spring expected single matching bean but found 2

If I'm not mistaken, the default bean name of a bean declared with @Component is the name of its class its first letter in lower-case. This means that

@Component
public class SuggestionService {

declares a bean of type SuggestionService, and of name suggestionService. It's equivalent to

@Component("suggestionService")
public class SuggestionService {

or to

<bean id="suggestionService" .../>

You're redefining another bean of the same type, but with a different name, in the XML:

<bean id="SuggestionService" class="com.hp.it.km.search.web.suggestion.SuggestionService">
    ...
</bean>

So, either specify the name of the bean in the annotation to be SuggestionService, or use the ID suggestionService in the XML (don't forget to also modify the <ref> element, or to remove it, since it isn't needed). In this case, the XML definition will override the annotation definition.

How do I read and parse an XML file in C#?

There are different ways, depending on where you want to get. XmlDocument is lighter than XDocument, but if you wish to verify minimalistically that a string contains XML, then regular expression is possibly the fastest and lightest choice you can make. For example, I have implemented Smoke Tests with SpecFlow for my API and I wish to test if one of the results in any valid XML - then I would use a regular expression. But if I need to extract values from this XML, then I would parse it with XDocument to do it faster and with less code. Or I would use XmlDocument if I have to work with a big XML (and sometimes I work with XML's that are around 1M lines, even more); then I could even read it line by line. Why? Try opening more than 800MB in private bytes in Visual Studio; even on production you should not have objects bigger than 2GB. You can with a twerk, but you should not. If you would have to parse a document, which contains A LOT of lines, then this documents would probably be CSV.

I have written this comment, because I see a lof of examples with XDocument. XDocument is not good for big documents, or when you only want to verify if there the content is XML valid. If you wish to check if the XML itself makes sense, then you need Schema.

I also downvoted the suggested answer, because I believe it needs the above information inside itself. Imagine I need to verify if 200M of XML, 10 times an hour, is valid XML. XDocument will waste a lof of resources.

prasanna venkatesh also states you could try filling the string to a dataset, it will indicate valid XML as well.

How to drop all tables from a database with one SQL query?

As a follow-up to Dave.Gugg's answer, this would be the code someone would need to get all the DROP TABLE lines in MySQL:

SELECT CONCAT('DROP TABLE ', TABLE_NAME, ';')
FROM INFORMATION_SCHEMA.tables
WHERE TABLE_SCHEMA = 'your_database_name'