Programs & Examples On #Ipv4

IPv4 is the "old style" IP protocol currently used in most circumstances.

What is the total amount of public IPv4 addresses?

https://www.ripe.net/internet-coordination/press-centre/understanding-ip-addressing

For IPv4, this pool is 32-bits (2³²) in size and contains 4,294,967,296 IPv4 addresses.

In case of IPv6

The IPv6 address space is 128-bits (2¹²8) in size, containing 340,282,366,920,938,463,463,374,607,431,768,211,456 IPv6 addresses.

inclusive of RESERVED IP

 Reserved address blocks
 Range  Description Reference

 0.0.0.0/8  Current network (only valid as source address)  RFC 6890
 10.0.0.0/8 Private network RFC 1918
 100.64.0.0/10  Shared Address Space    RFC 6598
 127.0.0.0/8    Loopback    RFC 6890
 169.254.0.0/16 Link-local  RFC 3927
 172.16.0.0/12  Private network RFC 1918
 192.0.0.0/24   IETF Protocol Assignments   RFC 6890
 192.0.2.0/24   TEST-NET-1, documentation and examples  RFC 5737
 192.88.99.0/24 IPv6 to IPv4 relay (includes 2002::/16) RFC 3068
 192.168.0.0/16 Private network RFC 1918
 198.18.0.0/15  Network benchmark tests RFC 2544
 198.51.100.0/24    TEST-NET-2, documentation and examples  RFC 5737
 203.0.113.0/24 TEST-NET-3, documentation and examples  RFC 5737
 224.0.0.0/4    IP multicast (former Class D network)   RFC 5771
 240.0.0.0/4    Reserved (former Class E network)   RFC 1700
 255.255.255.255    Broadcast   RFC 919

wiki has full details and this has details of IPv6.

What is IPV6 for localhost and 0.0.0.0?

IPv6 localhost

::1 is the loopback address in IPv6.

Within URLs

Within a URL, use square brackets []:

  • http://[::1]/
    Defaults to port 80.
  • http://[::1]:80/
    Specify port.

Enclosing the IPv6 literal in square brackets for use in a URL is defined in RFC 2732 – Format for Literal IPv6 Addresses in URL's.

Validating IPv4 addresses with regexp

For number from 0 to 255 I use this regex:

(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))

Above regex will match integer number from 0 to 255, but not match 256.

So for IPv4 I use this regex:

^(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))((\.(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))){3})$

It is in this structure: ^(N)((\.(N)){3})$ where N is the regex used to match number from 0 to 255.
This regex will match IP like below:

0.0.0.0
192.168.1.2

but not those below:

10.1.0.256
1.2.3.
127.0.1-2.3

For IPv4 CIDR (Classless Inter-Domain Routing) I use this regex:

^(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))((\.(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))){3})\/(([0-9])|([12][0-9])|(3[0-2]))$

It is in this structure: ^(N)((\.(N)){3})\/M$ where N is the regex used to match number from 0 to 255, and M is the regex used to match number from 0 to 32.
This regex will match CIDR like below:

0.0.0.0/0
192.168.1.2/32

but not those below:

10.1.0.256/16
1.2.3./24
127.0.0.1/33

And for list of IPv4 CIDR like "10.0.0.0/16", "192.168.1.1/32" I use this regex:

^("(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))((\.(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))){3})\/(([0-9])|([12][0-9])|(3[0-2]))")((,([ ]*)("(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))((\.(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))){3})\/(([0-9])|([12][0-9])|(3[0-2]))"))*)$

It is in this structure: ^(“C”)((,([ ]*)(“C”))*)$ where C is the regex used to match CIDR (like 0.0.0.0/0).
This regex will match list of CIDR like below:

“10.0.0.0/16”,”192.168.1.2/32”, “1.2.3.4/32”

but not those below:

“10.0.0.0/16” 192.168.1.2/32 “1.2.3.4/32”

Maybe it might get shorter but for me it is easy to understand so fine by me.

Hope it helps!

How to set java.net.preferIPv4Stack=true at runtime?

Another approach, if you're desperate and don't have access to (a) the code or (b) the command line, then you can use environment variables:

http://docs.oracle.com/javase/7/docs/webnotes/tsg/TSG-Desktop/html/plugin.html.

Specifically for java web start set the environment variable:

JAVAWS_VM_ARGS

and for applets:

_JPI_VM_OPTIONS

e.g.

_JPI_VM_OPTIONS=-Djava.net.preferIPv4Stack=true

Additionally, under Windows global options (for general Java applications) can be set in the Java control plan page under the "Java" tab.

What is the largest Safe UDP Packet Size on the Internet

UDP is not "safe", so the question is not great - however -

  • if you are on a Mac the max size you can send by default is 9216 bytes.
  • if you are on Linux (CentOS/RedHat) or Windows 7 the max is 65507 bytes.

If you send 9217 or more (mac) or 65508+ (linux/windows), the socket send function returns with an error.

The above answers discussing fragmentation and MTU and so on are off topic - that all takes place at a lower level, is "invisible" to you, and does not affect "safety" on typical connections to a significant degree.

To answer the actual question meaning though - do not use UDP - use raw sockets so you get better control of everything; since you're writing a game, you need to delve into the flags to get priority into your traffic anyhow, so you may as well get rid of UDP issues at the same time.

How to convert an IPv4 address into a integer in C#?

Assembled several of the above answers into an extension method that handles the Endianness of the machine and handles IPv4 addresses that were mapped to IPv6.

public static class IPAddressExtensions
{
    /// <summary>
    /// Converts IPv4 and IPv4 mapped to IPv6 addresses to an unsigned integer.
    /// </summary>
    /// <param name="address">The address to conver</param>
    /// <returns>An unsigned integer that represents an IPv4 address.</returns>
    public static uint ToUint(this IPAddress address)
    {
        if (address.AddressFamily == AddressFamily.InterNetwork || address.IsIPv4MappedToIPv6)
        {
            var bytes = address.GetAddressBytes();
            if (BitConverter.IsLittleEndian)
                Array.Reverse(bytes);

            return BitConverter.ToUInt32(bytes, 0);
        }
        throw new ArgumentOutOfRangeException("address", "Address must be IPv4 or IPv4 mapped to IPv6");
    }
}

Unit tests:

[TestClass]
public class IPAddressExtensionsTests
{
    [TestMethod]
    public void SimpleIp1()
    {
        var ip = IPAddress.Parse("0.0.0.15");
        uint expected = GetExpected(0, 0, 0, 15);
        Assert.AreEqual(expected, ip.ToUint());
    }
    [TestMethod]
    public void SimpleIp2()
    {
        var ip = IPAddress.Parse("0.0.1.15");
        uint expected = GetExpected(0, 0, 1, 15);
        Assert.AreEqual(expected, ip.ToUint());
    }
    [TestMethod]
    public void SimpleIpSix1()
    {
        var ip = IPAddress.Parse("0.0.0.15").MapToIPv6();
        uint expected = GetExpected(0, 0, 0, 15);
        Assert.AreEqual(expected, ip.ToUint());
    }
    [TestMethod]
    public void SimpleIpSix2()
    {
        var ip = IPAddress.Parse("0.0.1.15").MapToIPv6();
        uint expected = GetExpected(0, 0, 1, 15);
        Assert.AreEqual(expected, ip.ToUint());
    }
    [TestMethod]
    public void HighBits()
    {
        var ip = IPAddress.Parse("200.12.1.15").MapToIPv6();
        uint expected = GetExpected(200, 12, 1, 15);
        Assert.AreEqual(expected, ip.ToUint());
    }
    uint GetExpected(uint a, uint b, uint c, uint d)
    {
        return
            (a * 256u * 256u * 256u) +
            (b * 256u * 256u) +
            (c * 256u) +
            (d);
    }
}

Get IPv4 addresses from Dns.GetHostEntry()

IPHostEntry ipHostInfo = Dns.GetHostEntry(serverName);
IPAddress ipAddress = ipHostInfo.AddressList
    .FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork);

How can I convert IPV6 address to IPV4 address?

Here is the code you are looking for in javascript. Well you know you can't convert all of the ipv6 addresses

<script>
function parseIp6(str)
{
  //init
  var ar=new Array;
  for(var i=0;i<8;i++)ar[i]=0;
  //check for trivial IPs
  if(str=="::")return ar;
  //parse
  var sar=str.split(':');
  var slen=sar.length;
  if(slen>8)slen=8;
  var j=0;
  for(var i=0;i<slen;i++){
    //this is a "::", switch to end-run mode
    if(i && sar[i]==""){j=9-slen+i;continue;}
    ar[j]=parseInt("0x0"+sar[i]);
    j++;
  }

  return ar;
}
function ipcnvfrom6(ip6)
{
  var ip6=parseIp6(ip6);
  var ip4=(ip6[6]>>8)+"."+(ip6[6]&0xff)+"."+(ip6[7]>>8)+"."+(ip6[7]&0xff);
  return ip4;
}
alert(ipcnvfrom6("::C0A8:4A07"));
</script>

HttpServletRequest - how to obtain the referring URL?

It's available in the HTTP referer header. You can get it in a servlet as follows:

String referrer = request.getHeader("referer"); // Yes, with the legendary misspelling.

You, however, need to realize that this is a client-controlled value and can thus be spoofed to something entirely different or even removed. Thus, whatever value it returns, you should not use it for any critical business processes in the backend, but only for presentation control (e.g. hiding/showing/changing certain pure layout parts) and/or statistics.

For the interested, background about the misspelling can be found in Wikipedia.

Service Reference Error: Failed to generate code for the service reference

Restarting Visual Studio did the trick for me. I am using VS 2015.

Disabling Chrome cache for website development

In addition to the disable cache option (which you get to via a button in the lower right corner of the developer tools window -- Tools | Developer Tools, or Ctrl + Shift + I), on the network pane of the developer tools you can now right click and choose "Clear Cache" from the popup menu.

What is the correct way to check for string equality in JavaScript?

Just one addition to answers: If all these methods return false, even if strings seem to be equal, it is possible that there is a whitespace to the left and or right of one string. So, just put a .trim() at the end of strings before comparing:

if(s1.trim() === s2.trim())
{
    // your code
}

I have lost hours trying to figure out what is wrong. Hope this will help to someone!

Alternative to google finance api

I'm way late, but check out Quandl. They have an API for stock prices and fundamentals.

Here's an example call, using Quandl-api download in csv

example:

https://www.quandl.com/api/v1/datasets/WIKI/AAPL.csv?column=4&sort_order=asc&collapse=quarterly&trim_start=2012-01-01&trim_end=2013-12-31

They support these languages. Their source data comes from Yahoo Finance, Google Finance, NSE, BSE, FSE, HKEX, LSE, SSE, TSE and more (see here).

Getting or changing CSS class property with Javascript using DOM style

You don't need to add '.' in your class name. This will do

document.getElementsByClassName('col1')

Additionally, since you haven't define the background color via javascript, you won't able to call it directly. You have to use window.getComputedStyle() or jquery to achieve what you are trying to do above.

Here is a working example

http://jsfiddle.net/J9LU8/

R data formats: RData, Rda, Rds etc

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

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

So, answering your questions:

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

Count the items from a IEnumerable<T> without iterating?

I use such code, if I have list of strings:

((IList<string>)Table).Count

How to set component default props on React component

use a static defaultProps like:

export default class AddAddressComponent extends Component {
    static defaultProps = {
        provinceList: [],
        cityList: []
    }

render() {
   let {provinceList,cityList} = this.props
    if(cityList === undefined || provinceList === undefined){
      console.log('undefined props')
    }
    ...
}

AddAddressComponent.contextTypes = {
  router: React.PropTypes.object.isRequired
}

AddAddressComponent.defaultProps = {
  cityList: [],
  provinceList: [],
}

AddAddressComponent.propTypes = {
  userInfo: React.PropTypes.object,
  cityList: PropTypes.array.isRequired,
  provinceList: PropTypes.array.isRequired,
}

Taken from: https://github.com/facebook/react-native/issues/1772

If you wish to check the types, see how to use PropTypes in treyhakanson's or Ilan Hasanov's answer, or review the many answers in the above link.

Renaming files using node.js

  1. fs.readdir(path, callback)
  2. fs.rename(old,new,callback)

Go through http://nodejs.org/api/fs.html

One important thing - you can use sync functions also. (It will work like C program)

package android.support.v4.app does not exist ; in Android studio 0.8

In my case the error was on a module of my project.I have resolved this with adding

dependencies {
    implementation 'com.android.support:support-v4:20.0.+'
}

this dependency in gradle of corresponding module

Importing a function from a class in another file?

You can use the below syntax -

from FolderName.FileName import Classname

What can cause a “Resource temporarily unavailable” on sock send() command

That's because you're using a non-blocking socket and the output buffer is full.

From the send() man page

   When the message does not fit into  the  send  buffer  of  the  socket,
   send() normally blocks, unless the socket has been placed in non-block-
   ing I/O mode.  In non-blocking mode it  would  return  EAGAIN  in  this
   case.  

EAGAIN is the error code tied to "Resource temporarily unavailable"

Consider using select() to get a better control of this behaviours

error code 1292 incorrect date value mysql

An update. Dates of the form '2019-08-00' will trigger the same error. Adding the lines:

[mysqld]

sql_mode="NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION" 

to mysql.cnf fixes this too. Inserting malformed dates now generates warnings for values out of range but does insert the data.

float:left; vs display:inline; vs display:inline-block; vs display:table-cell;

I prefer inline-block, but float are still useful way to put together HTML elemenets, specially when we have elements which one should stick to the left and one to the right, float working better with writing less lines, while inline-block working well in many other cases.

enter image description here

Initialize a long in Java

  1. You should add L: long i = 12345678910L;.
  2. Yes.

BTW: it doesn't have to be an upper case L, but lower case is confused with 1 many times :).

Do on-demand Mac OS X cloud services exist, comparable to Amazon's EC2 on-demand instances?

Here are some methods that may help others, though they aren't really services as much as they may be described as "methods that may, after some torture of effort or logic, lead to a claim of on-demand access to Mac OS X" (no doubt I should patent that phrase).

Fundamentally, I am inclined to believe that on-demand (per-hour) hosting does not exist, and @Erik has given information for the shortest feasible services, i.e. monthly hosting.


It seems that one may use EC2 itself, but install OS X on the instance through a lot of elbow grease.

  • This article on Lifehacker.com gives instructions for setting up OSX under Virtual Box and depends on hardware virtualization. It seems that the Cluster Compute instances (and Cluster GPU, but ignore these) are the only ones supporting hardware virtualization.
  • This article gives instructions for transferring a VirtualBox image to EC2.

Where this gets tricky is I'm not sure if this will work for a cluster compute instance. In fact, I think this is likely to be a royal pain. A similar approach may work for Rackspace or other cloud services.

I found only this site claiming on-demand Mac hosting, with a Mac Mini. It doesn't look particularly accurate: it offers free on-demand access to a Mini if one pays for a month of bandwidth. That's like free bandwidth if one rents a Mini for a month. That's not really how "on-demand" works.


Update 1: In the end, it seems that nobody offers a comparable service. An outfit called Media Temple claims they will offer the first virtual servers using Parallels, OS X Leopard, and some other stuff (in other words, I wonder if there is some caveat that makes them unique, but, without that caveat, someone else may have a usable offering).

After this search, I think that a counterpart to EC2 does not exist for the OS X operating system. It is extraordinarily unlikely that one would exist, offer a scalable solution, and yet be very difficult to find. One could set it up internally, but there's no reseller/vendor offering on-demand, hourly virtual servers. This may be disappointing, but not surprising - apparently iCloud is running on Amazon and Microsoft systems.

How to move or copy files listed by 'find' command in unix?

Actually, you can process the find command output in a copy command in two ways:

  1. If the find command's output doesn't contain any space, i.e if the filename doesn't contain a space in it, then you can use:

    Syntax:
        find <Path> <Conditions> | xargs cp -t <copy file path>
    Example:
        find -mtime -1 -type f | xargs cp -t inner/
    
  2. But our production data files might contain spaces, so most of time this command is effective:

    Syntax:
       find <path> <condition> -exec cp '{}' <copy path> \;
    
    Example 
       find -mtime -1 -type f -exec cp '{}' inner/ \;
    

In the second example, the last part, the semi-colon is also considered as part of the find command, and should be escaped before pressing Enter. Otherwise you will get an error something like:

find: missing argument to `-exec'

How can I open a .tex file?

I don't know what the .tex extension on your file means. If we are saying that it is any file with any extension you have several methods of reading it.

I have to assume you are using windows because you have mentioned notepad++.

  1. Use notepad++. Right click on the file and choose "edit with notepad++"

  2. Use notepad Change the filename extension to .txt and double click the file.

  3. Use command prompt. Open the folder that your file is in. Hold down shift and right click. (not on the file, but in the folder that the file is in.) Choose "open command window here" from the command prompt type: "type filename.tex"

If these don't work, I would need more detail as to how they are not working. Errors that you may be getting or what you may expect to be in the file might help.

How to get the difference between two dictionaries in Python?

def flatten_it(d):
    if isinstance(d, list) or isinstance(d, tuple):
        return tuple([flatten_it(item) for item in d])
    elif isinstance(d, dict):
        return tuple([(flatten_it(k), flatten_it(v)) for k, v in sorted(d.items())])
    else:
        return d

dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 1, 'b': 1}

print set(flatten_it(dict1)) - set(flatten_it(dict2)) # set([('b', 2), ('c', 3)])
# or 
print set(flatten_it(dict2)) - set(flatten_it(dict1)) # set([('b', 1)])

How to round up integer division and have int result in Java?

Use Math.ceil() and cast the result to int:

  • This is still faster than to avoid doubles by using abs().
  • The result is correct when working with negatives, because -0.999 will be rounded UP to 0

Example:

(int) Math.ceil((double)divident / divisor);

How can I compare two dates in PHP?

I had that problem too and I solve it by:

$today = date("Ymd");
$expire = str_replace('-', '', $row->expireDate); //from db

if(($today - $expire) > $NUMBER_OF_DAYS) 
{ 
    //do something; 
}

How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses?

It may be worth mentioning that running tomcat as a non root user (which you should be doing) will prevent you from using a port below 1024 on *nix. If you want to use TC as a standalone server -- as its performance no longer requires it to be fronted by Apache or the like -- you'll want to bind to port 80 along with whatever IP address you're specifying.

You can do this by using IPTABLES to redirect port 80 to 8080.

Why does printf not flush after the call unless a newline is in the format string?

stdout is buffered, so will only output after a newline is printed.

To get immediate output, either:

  1. Print to stderr.
  2. Make stdout unbuffered.

addClass and removeClass in jQuery - not removing class

The issue is caused because of event bubbling. The first part of your code to add .grown works fine.

The second part "removing grown class" on clicking the link doesn't work as expected as both the handler for .close_button and .clickable are executed. So it removes and readd the grown class to the div.

You can avoid this by using e.stopPropagation() inside .close_button click handler to avoid the event from bubbling.

DEMO: http://jsfiddle.net/vL8DP/

Full Code

$(document).on('click', '.clickable', function () {
   $(this).addClass('grown').removeClass('spot');
}).on('click', '.close_button', function (e) {
   e.stopPropagation();
   $(this).closest('.clickable').removeClass('grown').addClass('spot');
});

iPad browser WIDTH & HEIGHT standard

You can try this:

    /*iPad landscape oriented styles */

    @media only screen and (device-width:768px)and (orientation:landscape){
        .yourstyle{

        }

    }

    /*iPad Portrait oriented styles */

    @media only screen and (device-width:768px)and (orientation:portrait){
        .yourstyle{

        }
    }

PermissionError: [Errno 13] in python

For me, I was writing to a file that is opened in Excel.

Python def function: How do you specify the end of the function?

To be precise, a block ends when it encounter a non-empty line indented at most the same level with the start. This non empty line is not part of that block For example, the following print ends two blocks at the same time:

def foo():
    if bar:
        print "bar"

print "baz" # ends the if and foo at the same time

The indentation level is less-than-or-equal to both the def and the if, hence it ends them both.

Lines with no statement, no matter the indentation, does not matter

def foo():
    print "The line below has no indentation"

    print "Still part of foo"

But the statement that marks the end of the block must be indented at the same level as any existing indentation. The following, then, is an error:

def foo():
    print "Still correct"
   print "Error because there is no block at this indentation"

Generally, if you're used to curly braces language, just indent the code like them and you'll be fine.

BTW, the "standard" way of indenting is with spaces only, but of course tab only is possible, but please don't mix them both.

How to dynamically change header based on AngularJS partial view?

The better and dynamic solution I have found is to use $watch to trace the variable changes and then update the title.

How to use delimiter for csv in python

CSV Files with Custom Delimiters

By default, a comma is used as a delimiter in a CSV file. However, some CSV files can use delimiters other than a comma. Few popular ones are | and \t.

import csv
data_list = [["SN", "Name", "Contribution"],
             [1, "Linus Torvalds", "Linux Kernel"],
             [2, "Tim Berners-Lee", "World Wide Web"],
             [3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
    writer = csv.writer(file, delimiter='|')
    writer.writerows(data_list)

output:

SN|Name|Contribution
1|Linus Torvalds|Linux Kernel
2|Tim Berners-Lee|World Wide Web
3|Guido van Rossum|Python Programming

Write CSV files with quotes

import csv

row_list = [["SN", "Name", "Contribution"],
             [1, "Linus Torvalds", "Linux Kernel"],
             [2, "Tim Berners-Lee", "World Wide Web"],
             [3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
    writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC, delimiter=';')
    writer.writerows(row_list) 

output:

"SN";"Name";"Contribution"
1;"Linus Torvalds";"Linux Kernel"
2;"Tim Berners-Lee";"World Wide Web"
3;"Guido van Rossum";"Python Programming"

As you can see, we have passed csv.QUOTE_NONNUMERIC to the quoting parameter. It is a constant defined by the csv module.

csv.QUOTE_NONNUMERIC specifies the writer object that quotes should be added around the non-numeric entries.

There are 3 other predefined constants you can pass to the quoting parameter:

  • csv.QUOTE_ALL - Specifies the writer object to write CSV file with quotes around all the entries.
  • csv.QUOTE_MINIMAL - Specifies the writer object to only quote those fields which contain special characters (delimiter, quotechar or any characters in lineterminator)
  • csv.QUOTE_NONE - Specifies the writer object that none of the entries should be quoted. It is the default value.
import csv

row_list = [["SN", "Name", "Contribution"],
             [1, "Linus Torvalds", "Linux Kernel"],
             [2, "Tim Berners-Lee", "World Wide Web"],
             [3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
    writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC,
                        delimiter=';', quotechar='*')
    writer.writerows(row_list)

output:

*SN*;*Name*;*Contribution*
1;*Linus Torvalds*;*Linux Kernel*
2;*Tim Berners-Lee*;*World Wide Web*
3;*Guido van Rossum*;*Python Programming*

Here, we can see that quotechar='*' parameter instructs the writer object to use * as quote for all non-numeric values.

Divide a number by 3 without using *, /, +, -, % operators

I think the right answer is:

Why would I not use a basic operator to do a basic operation?

check if directory exists and delete in one command unix

Try:

bash -c '[ -d my_mystery_dirname ] && run_this_command'

This will work if you can run bash on the remote machine....

In bash, [ -d something ] checks if there is directory called 'something', returning a success code if it exists and is a directory. Chaining commands with && runs the second command only if the first one succeeded. So [ -d somedir ] && command runs the command only if the directory exists.

HTML for the Pause symbol in audio and video control

The ISO 7000 / IEC 60417 Symbol for Pause; Interruption is #5111B. See Media_Controls

PHP Adding 15 minutes to Time value

Current date and time

$current_date_time = date('Y-m-d H:i:s');

15 min ago Date and time

$newTime = date("Y-m-d H:i:s",strtotime("+15 minutes", strtotime($current_date)));

Write single CSV file using spark-csv

A solution that works for S3 modified from Minkymorgan.

Simply pass the temporary partitioned directory path (with different name than final path) as the srcPath and single final csv/txt as destPath Specify also deleteSource if you want to remove the original directory.

/**
* Merges multiple partitions of spark text file output into single file. 
* @param srcPath source directory of partitioned files
* @param dstPath output path of individual path
* @param deleteSource whether or not to delete source directory after merging
* @param spark sparkSession
*/
def mergeTextFiles(srcPath: String, dstPath: String, deleteSource: Boolean): Unit =  {
  import org.apache.hadoop.fs.FileUtil
  import java.net.URI
  val config = spark.sparkContext.hadoopConfiguration
  val fs: FileSystem = FileSystem.get(new URI(srcPath), config)
  FileUtil.copyMerge(
    fs, new Path(srcPath), fs, new Path(dstPath), deleteSource, config, null
  )
}

.includes() not working in Internet Explorer

includes() is not supported by most browsers. Your options are either to use

-polyfill from MDN https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes

or to use

-indexof()

var str = "abcde";
var n = str.indexOf("cd");

Which gives you n=2

This is widely supported.

Uri content://media/external/file doesn't exist for some devices

Most probably it has to do with caching on the device. Catching the exception and ignoring is not nice but my problem was fixed and it seems to work.

What's the best practice to "git clone" into an existing folder?

To clone a git repo into an empty existing directory do the following:

cd myfolder
git clone https://myrepo.com/git.git . 

Notice the . at the end of your git clone command. That will download the repo into the current working directory.

function to return a string in java

In Java, a String is a reference to heap-allocated storage. Returning "ans" only returns the reference so there is no need for stack-allocated storage. In fact, there is no way in Java to allocate objects in stack storage.

I would change to this, though. You don't need "ans" at all.

return String.format("%d:%d", mins, secs);

How to use `replace` of directive definition?

Replace [True | False (default)]

Effect

1.  Replace the directive element. 

Dependency:

1. When replace: true, the template or templateUrl must be required. 

How do I POST XML data with curl

I prefer the following command-line options:

cat req.xml | curl -X POST -H 'Content-type: text/xml' -d @- http://www.example.com

or

curl -X POST -H 'Content-type: text/xml' -d @req.xml http://www.example.com

or

curl -X POST -H 'Content-type: text/xml'  -d '<XML>data</XML>' http://www.example.com 

How to create an HTTPS server in Node.js?

The Express API doc spells this out pretty clearly.

Additionally this answer gives the steps to create a self-signed certificate.

I have added some comments and a snippet from the Node.js HTTPS documentation:

var express = require('express');
var https = require('https');
var http = require('http');
var fs = require('fs');

// This line is from the Node.js HTTPS documentation.
var options = {
  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.cert')
};

// Create a service (the app object is just a callback).
var app = express();

// Create an HTTP service.
http.createServer(app).listen(80);
// Create an HTTPS service identical to the HTTP service.
https.createServer(options, app).listen(443);

How do I change Eclipse to use spaces instead of tabs?

Eclipse IDE for C/C++ Developers, Version: Helios Service Release 2

You need to create new profile by pressing New button inside "Window->Preferences->Code Style"

Go to Indentation tab and select "Tab policy = Space only"


Eclipse IDE for C/C++ Developers, Version: Kepler Service Release 1

Follow the path below to create new profile: "Window > Preferences > C/C++ > Code Style > Formatter"

Go to Indentation tab and select "Tab policy = Space only"

Date to milliseconds and back to date in Swift

@Travis solution is right, but it loses milliseconds when a Date is generated. I have added a line to include the milliseconds into the date:

If you don't need this precision, use the Travis solution because it will be faster.

extension Date {

    func toMillis() -> Int64! {
        return Int64(self.timeIntervalSince1970 * 1000)
    }

    init(millis: Int64) {
        self = Date(timeIntervalSince1970: TimeInterval(millis / 1000))
        self.addTimeInterval(TimeInterval(Double(millis % 1000) / 1000 ))
    }

}

Maven compile with multiple src directories

You can add a new source directory with build-helper:

<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>build-helper-maven-plugin</artifactId>
            <version>3.2.0</version>
            <executions>
                <execution>
                    <phase>generate-sources</phase>
                    <goals>
                        <goal>add-source</goal>
                    </goals>
                    <configuration>
                        <sources>
                            <source>src/main/generated</source>
                        </sources>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

Printf long long int in C with GCC?

For portable code, the macros in inttypes.h may be used. They expand to the correct ones for the platform.

E.g. for 64 bit integer, the macro PRId64 can be used.

int64_t n = 7;
printf("n is %" PRId64 "\n", n);

Disable LESS-CSS Overwriting calc()

Apart from using an escaped value as described in my other answer, it is also possible to fix this issue by enabling the Strict Math setting.

With strict math on, only maths that are inside unnecessary parentheses will be processed, so your code:

width: calc(100% - 200px);

Would work as expected with the strict math option enabled.

However, note that Strict Math is applied globally, not only inside calc(). That means, if you have:

font-size: 12px + 2px;

The math will no longer be processed by Less -- it will output font-size: 12px + 2px which is, obviously, invalid CSS. You'd have to wrap all maths that should be processed by Less in (previously unnecessary) parentheses:

font-size: (12px + 2px);

Strict Math is a nice option to consider when starting a new project, otherwise you'd possibly have to rewrite a good part of the code base. For the most common use cases, the escaped string approach described in the other answer is more suitable.

How do I detect whether 32-bit Java is installed on x64 Windows, only looking at the filesystem and registry?

Do you have access to the command prompt ?

Method 1 : Command Prompt

The specifics of the Java installed on the system can be determined by executing the following command java -version

Method 2 : Folder Structure

In case you do not have access to command prompt then determining the folder where Java.

32 Bit : C:\Program Files (x86)\Java\jdk1.6.0_30

64 Bit : C:\Program Files\Java\jdk1.6.0_25

However during the installation it is possible that the user might change the installation folder.

Method 3 : Registry

You can also see the version installed in registry editor.

  1. Go to registry editor

  2. Edit -> Find

  3. Search for Java. You will get the registry entries for Java.

  4. In the entry with name : DisplayName & DisplayVersion, the installed java version is displayed

How to create multidimensional array

you can create array follow the code below:

var arraymultidimensional = []
    arraymultidimensional = [[value1,value2],[value3,value4],[value5,value6]];

Result:
[v1][v2] position 0
[v3][v4] position 1
[v5][v6] position 2

For add to array dinamically, use the method below:

//vectorvalue format = "[value,value,...]"
function addToArray(vectorvalue){
  arraymultidimensional[arraymultidimensional.length] = vectorvalue;
}

Hope this helps. :)

How does Facebook Sharer select Images and other metadata when sharing my URL?

When you share for Facebook, you have to add in your html into the head section next meta tags:

<meta property="og:title" content="title" />
<meta property="og:description" content="description" />
<meta property="og:image" content="thumbnail_image" />

And that's it!

Add the button as you should according to what FB tells you.

All the info you need is in www.facebook.com/share/

How to create a date object from string in javascript

The syntax is as follows:

new Date(year, month [, day, hour, minute, second, millisecond ])

so

Date d = new Date(2011,10,30);

is correct; day, hour, minute, second, millisecond are optional.

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date

When should I use nil and NULL in Objective-C?

nil is an object pointer to nothing. Although semantically distinct from NULL, they are technically equivalent to one another.

On the framework level, Foundation defines NSNull, which defines a class method, +null, which returns the singleton NSNull object. NSNull is different from nil or NULL, in that it is an actual object, rather than a zero value.

Additionally, in Foundation/NSObjCRuntime.h, Nil is defined as a class pointer to nothing.

Refer this for further info - nil / Nil / NULL / NSNull

jQuery check if <input> exists and has a value

Just for the heck of it, I tracked this down in the jQuery code. The .val() function currently starts at line 165 of attributes.js. Here's the relevant section, with my annotations:

val: function( value ) {
    var hooks, ret, isFunction,
        elem = this[0];

        /// NO ARGUMENTS, BECAUSE NOT SETTING VALUE
    if ( !arguments.length ) {

        /// IF NOT DEFINED, THIS BLOCK IS NOT ENTERED. HENCE 'UNDEFINED'
        if ( elem ) {
            hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];

            if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
                return ret;
            }

            ret = elem.value;

            /// IF IS DEFINED, JQUERY WILL CHECK TYPE AND RETURN APPROPRIATE 'EMPTY' VALUE
            return typeof ret === "string" ?
                // handle most common string cases
                ret.replace(rreturn, "") :
                // handle cases where value is null/undef or number
                ret == null ? "" : ret;
        }

        return;
    }

So, you'll either get undefined or "" or null -- all of which evaluate as false in if statements.

Why can't I have abstract static methods in C#?

The abstract methods are implicitly virtual. Abstract methods require an instance, but static methods do not have an instance. So, you can have a static method in an abstract class, it just cannot be static abstract (or abstract static).

Does Java have a complete enum for HTTP response codes?

If you are using Netty, you can use:

Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence?

You're getting the error message

ValueError: setting an array element with a sequence.

because you're trying to set an array element with a sequence. I'm not trying to be cute, there -- the error message is trying to tell you exactly what the problem is. Don't think of it as a cryptic error, it's simply a phrase. What line is giving the problem?

kOUT[i]=func(TempLake[i],Z)

This line tries to set the ith element of kOUT to whatever func(TempLAke[i], Z) returns. Looking at the i=0 case:

In [39]: kOUT[0]
Out[39]: 0.0

In [40]: func(TempLake[0], Z)
Out[40]: array([ 0.,  0.,  0.,  0.])

You're trying to load a 4-element array into kOUT[0] which only has a float. Hence, you're trying to set an array element (the left hand side, kOUT[i]) with a sequence (the right hand side, func(TempLake[i], Z)).

Probably func isn't doing what you want, but I'm not sure what you really wanted it to do (and don't forget you can usually use vectorized operations like A*B rather than looping in numpy.) That should explain the problem, anyway.

Changing plot scale by a factor in matplotlib

As you have noticed, xscale and yscale does not support a simple linear re-scaling (unfortunately). As an alternative to Hooked's answer, instead of messing with the data, you can trick the labels like so:

ticks = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x*scale))
ax.xaxis.set_major_formatter(ticks)

A complete example showing both x and y scaling:

import numpy as np
import pylab as plt
import matplotlib.ticker as ticker

# Generate data
x = np.linspace(0, 1e-9)
y = 1e3*np.sin(2*np.pi*x/1e-9) # one period, 1k amplitude

# setup figures
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
# plot two identical plots
ax1.plot(x, y)
ax2.plot(x, y)

# Change only ax2
scale_x = 1e-9
scale_y = 1e3
ticks_x = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_x))
ax2.xaxis.set_major_formatter(ticks_x)

ticks_y = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_y))
ax2.yaxis.set_major_formatter(ticks_y)

ax1.set_xlabel("meters")
ax1.set_ylabel('volt')
ax2.set_xlabel("nanometers")
ax2.set_ylabel('kilovolt')

plt.show() 

And finally I have the credits for a picture:

Left: ax1 no scaling, right: ax2 y axis scaled to kilo and x axis scaled to nano

Note that, if you have text.usetex: true as I have, you may want to enclose the labels in $, like so: '${0:g}$'.

How can I enable the MySQLi extension in PHP 7?

sudo phpenmod mysqli
sudo service apache2 restart

  • phpenmod moduleName enables a module to PHP 7 (restart Apache after that sudo service apache2 restart)
  • phpdismod moduleName disables a module to PHP 7 (restart Apache after that sudo service apache2 restart)
  • php -m lists the loaded modules

How to delete a folder and all contents using a bat file in windows?

  1. del /s /q c:\where ever the file is\*
  2. rmdir /s /q c:\where ever the file is\
  3. mkdir c:\where ever the file is\

ASP.NET MVC Custom Error Handling Application_Error Global.asax?

I have problem with this error handling approach: In case of web.config:

<customErrors mode="On"/>

The error handler is searching view Error.shtml and the control flow step in to Application_Error global.asax only after exception

System.InvalidOperationException: The view 'Error' or its master was not found or no view engine supports the searched locations. The following locations were searched: ~/Views/home/Error.aspx ~/Views/home/Error.ascx ~/Views/Shared/Error.aspx ~/Views/Shared/Error.ascx ~/Views/home/Error.cshtml ~/Views/home/Error.vbhtml ~/Views/Shared/Error.cshtml ~/Views/Shared/Error.vbhtml at System.Web.Mvc.ViewResult.FindView(ControllerContext context) ....................

So

 Exception exception = Server.GetLastError();
  Response.Clear();
  HttpException httpException = exception as HttpException;

httpException is always null then customErrors mode="On" :( It is misleading Then <customErrors mode="Off"/> or <customErrors mode="RemoteOnly"/> the users see customErrors html, Then customErrors mode="On" this code is wrong too


Another problem of this code that

Response.Redirect(String.Format("~/Error/{0}/?message={1}", action, exception.Message));

Return page with code 302 instead real error code(402,403 etc)

Steps to send a https request to a rest service in Node js

just use the core https module with the https.request function. Example for a POST request (GET would be similar):

var https = require('https');

var options = {
  host: 'www.google.com',
  port: 443,
  path: '/upload',
  method: 'POST'
};

var req = https.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

git diff file against its last change

This does exist, but it's actually a feature of git log:

git log -p [--follow] [-1] <path>

Note that -p can also be used to show the inline diff from a single commit:

git log -p -1 <commit>

Options used:

  • -p (also -u or --patch) is hidden deeeeeeeep in the git-log man page, and is actually a display option for git-diff. When used with log, it shows the patch that would be generated for each commit, along with the commit information—and hides commits that do not touch the specified <path>. (This behavior is described in the paragraph on --full-diff, which causes the full diff of each commit to be shown.)
  • -1 shows just the most recent change to the specified file (-n 1 can be used instead of -1); otherwise, all non-zero diffs of that file are shown.
  • --follow is required to see changes that occurred prior to a rename.

As far as I can tell, this is the only way to immediately see the last set of changes made to a file without using git log (or similar) to either count the number of intervening revisions or determine the hash of the commit.

To see older revisions changes, just scroll through the log, or specify a commit or tag from which to start the log. (Of course, specifying a commit or tag returns you to the original problem of figuring out what the correct commit or tag is.)

Credit where credit is due:

  • I discovered log -p thanks to this answer.
  • Credit to FranciscoPuga and this answer for showing me the --follow option.
  • Credit to ChrisBetti for mentioning the -n 1 option and atatko for mentioning the -1 variant.
  • Credit to sweaver2112 for getting me to actually read the documentation and figure out what -p "means" semantically.

Android - setOnClickListener vs OnClickListener vs View.OnClickListener

The logic is simple. setOnClickListener belongs to step 2.

  1. You create the button
  2. You create an instance of OnClickListener* like it's done in that example and override the onClick-method.
  3. You assign that OnClickListener to that button using btn.setOnClickListener(myOnClickListener); in your fragments/activities onCreate-method.
  4. When the user clicks the button, the onClick function of the assigned OnClickListener is called.

*If you import android.view.View; you use View.OnClickListener. If you import android.view.View.*; or import android.view.View.OnClickListener; you use OnClickListener as far as I get it.

Another way is to let you activity/fragment inherit from OnClickListener. This way you assign your fragment/activity as the listener for your button and implement onClick as a member-function.

How to set up file permissions for Laravel?

First of your answer is.

sudo chmod -R 777/775 /path/project_folder

Now You need to understand permissions and options in ubuntu.

  • chmod - You can set permissions.
  • chown - You can set the ownership of files and directories.
  • 777 - read/write/execute.
  • 775 - read/execute.

Spring RestTemplate timeout

I had a similar scenario, but was also required to set a Proxy. The simplest way I could see to do this was to extend the SimpleClientHttpRequestFactory for the ease of setting the proxy (different proxies for non-prod vs prod). This should still work even if you don't require the proxy though. Then in my extended class I override the openConnection(URL url, Proxy proxy) method, using the same as the source, but just setting the timeouts before returning.

@Override
protected HttpURLConnection openConnection(URL url, Proxy proxy) throws IOException {
    URLConnection urlConnection = proxy != null ? url.openConnection(proxy) : url.openConnection();
    Assert.isInstanceOf(HttpURLConnection.class, urlConnection);
    urlConnection.setConnectTimeout(5000);
    urlConnection.setReadTimeout(5000);
    return (HttpURLConnection) urlConnection;
}

How to open html file?

CODE:

import codecs

path="D:\\Users\\html\\abc.html" 
file=codecs.open(path,"rb")
file1=file.read()
file1=str(file1)

Isn't the size of character in Java 2 bytes?

Java stores all it's "chars" internally as two bytes. However, when they become strings etc, the number of bytes will depend on your encoding.

Some characters (ASCII) are single byte, but many others are multi-byte.

Java supports Unicode, thus according to:

Java Character Docs

The max value supported is "\uFFFF" (hex FFFF, dec 65535), or 11111111 11111111 binary (two bytes).

External resource not being loaded by AngularJs

If anybody is looking for a TypeScript solution:

.ts file (change variables where applicable):

module App.Filters {

    export class trustedResource {

        static $inject:string[] = ['$sce'];

        static filter($sce:ng.ISCEService) {
            return (value) => {
                return $sce.trustAsResourceUrl(value)
            };
        }
    }
}
filters.filter('trustedResource', App.Filters.trusted.filter);

Html:

<video controls ng-if="HeaderVideoUrl != null">
  <source ng-src="{{HeaderVideoUrl | trustedResource}}" type="video/mp4"/>
</video>

Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

Step 1:

cd /etc/postgresql/12/main/

open file named postgresql.conf

sudo nano postgresql.conf

add this line to that file

listen_addresses = '*'

then open file named pg_hba.conf

sudo nano pg_hba.conf

and add this line to that file

host  all  all 0.0.0.0/0 md5

It allows access to all databases for all users with an encrypted password

restart your server

sudo /etc/init.d/postgresql restart

How do I create a random alpha-numeric string in C++?

//C++ Simple Code
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<char> alphanum =
    {'0','1','2','3','4',
'5','6','7','8','9',
'A','B','C','D','E','F',
'G','H','I','J','K',
'L','M','N','O','P',
'Q','R','S','T','U',
'V','W','X','Y','Z',
'a','b','c','d','e','f',
'g','h','i','j','k',
'l','m','n','o','p',
'q','r','s','t','u',
'v','w','x','y','z'
};
string s="";
int len=5;
srand(time(0)); 
for (int i = 0; i <len; i++) {
    int t=alphanum.size()-1;
    int idx=rand()%t;
    s+= alphanum[idx];
}
cout<<s<<" ";
return 0;
}

Is there a way to run Python on Android?

You can run your Python code using sl4a. sl4a supports Python, Perl, JRuby, Lua, BeanShell, JavaScript, Tcl, and shell script.

You can learn sl4a Python Examples.

How to remove all duplicate items from a list

for unhashable lists. It is faster as it does not iterate about already checked entries.

def purge_dublicates(X):
    unique_X = []
    for i, row in enumerate(X):
        if row not in X[i + 1:]:
            unique_X.append(row)
    return unique_X

Should I size a textarea with CSS width / height or HTML cols / rows attributes?

_x000D_
_x000D_
textarea { height: auto; }
_x000D_
<textarea rows="10"></textarea>
_x000D_
_x000D_
_x000D_

This will trigger the browser to set the height of the textarea EXACTLY to the amount of rows plus the paddings around it. Setting the CSS height to an exact amount of pixels leaves arbitrary whitespaces.

Create Git branch with current changes

Follow these steps:

  1. Create a new branch:

    git branch newfeature
    
  2. Checkout new branch: (this will not reset your work.)

    git checkout newfeature
    
  3. Now commit your work on this new branch:

    git commit -s
    

Using above steps will keep your original branch clean and you dont have to do any 'git reset --hard'.

Need to navigate to a folder in command prompt

In MS-DOS COMMAND.COM shell, you have to use:

d:

cd \windows\movie

If by chance you actually meant "Windows command prompt" (which is not MS-DOS and not DOS at all), then you can use cd /d d:\windows\movie.

Rounding BigDecimal to *always* have two decimal places

value = value.setScale(2, RoundingMode.CEILING)

Retrieve Button value with jQuery

As a button value is an attribute you need to use the .attr() method in jquery. This should do it

<script type="text/javascript">
    $(document).ready(function() {
        $('.my_button').click(function() {
            alert($(this).attr("value"));
        });
    });
</script>

You can also use attr to set attributes, more info in the docs.

This only works in JQuery 1.6+. See postpostmodern's answer for older versions.

Stateless vs Stateful

We make Webapps statefull by overriding HTTP stateless behaviour by using session objects.When we use session objets state is carried but we still use HTTP only.

How to check for palindrome using Python logic

word = "<insert palindrome/string>"
reverse = word[::-1] 
is_palindrome = word.find(reverse)
print is_palindrome

This was a question in Udacity comp 101, chapter 1. Gives a 0 for palindrome gives a -1 for not. Its simple, and does not use loops.

Sending mail from Python using SMTP

The script I use is quite similar; I post it here as an example of how to use the email.* modules to generate MIME messages; so this script can be easily modified to attach pictures, etc.

I rely on my ISP to add the date time header.

My ISP requires me to use a secure smtp connection to send mail, I rely on the smtplib module (downloadable at http://www1.cs.columbia.edu/~db2501/ssmtplib.py)

As in your script, the username and password, (given dummy values below), used to authenticate on the SMTP server, are in plain text in the source. This is a security weakness; but the best alternative depends on how careful you need (want?) to be about protecting these.

=======================================

#! /usr/local/bin/python


SMTPserver = 'smtp.att.yahoo.com'
sender =     'me@my_email_domain.net'
destination = ['recipient@her_email_domain.com']

USERNAME = "USER_NAME_FOR_INTERNET_SERVICE_PROVIDER"
PASSWORD = "PASSWORD_INTERNET_SERVICE_PROVIDER"

# typical values for text_subtype are plain, html, xml
text_subtype = 'plain'


content="""\
Test message
"""

subject="Sent from Python"

import sys
import os
import re

from smtplib import SMTP_SSL as SMTP       # this invokes the secure SMTP protocol (port 465, uses SSL)
# from smtplib import SMTP                  # use this for standard SMTP protocol   (port 25, no encryption)

# old version
# from email.MIMEText import MIMEText
from email.mime.text import MIMEText

try:
    msg = MIMEText(content, text_subtype)
    msg['Subject']=       subject
    msg['From']   = sender # some SMTP servers will do this automatically, not all

    conn = SMTP(SMTPserver)
    conn.set_debuglevel(False)
    conn.login(USERNAME, PASSWORD)
    try:
        conn.sendmail(sender, destination, msg.as_string())
    finally:
        conn.quit()

except:
    sys.exit( "mail failed; %s" % "CUSTOM_ERROR" ) # give an error message

Detect application heap size in Android

Debug.getNativeHeapSize() will do the trick, I should think. It's been there since 1.0, though.

The Debug class has lots of great methods for tracking allocations and other performance concerns. Also, if you need to detect a low-memory situation, check out Activity.onLowMemory().

How to pass IEnumerable list to controller in MVC including checkbox state?

Use a list instead and replace your foreach loop with a for loop:

@model IList<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()

    @for (var i = 0; i < Model.Count; i++) 
    {
        <tr>
            <td>
                @Html.HiddenFor(x => x[i].IP)           
                @Html.CheckBoxFor(x => x[i].Checked)
            </td>
            <td>
                @Html.DisplayFor(x => x[i].IP)
            </td>
        </tr>
    }
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

Alternatively you could use an editor template:

@model IEnumerable<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()
    @Html.EditorForModel()   
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml which will automatically be rendered for each element of the collection:

@model BlockedIPViewModel
<tr>
    <td>
        @Html.HiddenFor(x => x.IP)
        @Html.CheckBoxFor(x => x.Checked)
    </td>
    <td>
        @Html.DisplayFor(x => x.IP)
    </td>
</tr>

The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article.

Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.

Where do you include the jQuery library from? Google JSAPI? CDN?

Pros: Host on Google has benefits

  • Probably faster (their servers are more optimised)
  • They handle the caching correctly - 1 year (we struggle to be allowed to make the changes to get the headers right on our servers)
  • Users who have already had a link to the Google-hosted version on another domain already have the file in their cache

Cons:

  • Some browsers may see it as XSS cross-domain and disallow the file.
  • Particularly users running the NoScript plugin for Firefox

I wonder if you can INCLUDE from Google, and then check the presence of some Global variable, or somesuch, and if absence load from your server?

Collision Detection between two images in Java

Here's the main class from my collision detection program.
You can see it run at: http://www.youtube.com/watch?v=JIXhCvXgjsQ

/**
 *
 * @author Tyler Griffin
 */
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.GraphicsDevice.*;
import java.util.ArrayList;
import java.awt.Graphics;
import java.awt.geom.Line2D;


public class collision extends JFrame implements KeyListener, MouseMotionListener, MouseListener
{
    ArrayList everything=new ArrayList<tile>();

    int time=0, x, y, width, height, up=0, down=0, left=0, right=0, mouse1=0, mouse2=0;
    int mouseX, mouseY;

    GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice screen = environment.getDefaultScreenDevice();
    DisplayMode displayMode = screen.getDisplayMode();

    //private BufferStrategy strategy;

    JLayeredPane pane = new JLayeredPane();

     tile Tile;
     circle Circle;
     rectangle Rectangle;

         textPane text;

    public collision()
    {
        setUndecorated(screen.isFullScreenSupported());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        setLayout(null);
        setResizable(false);
        screen.setFullScreenWindow(this);


        width=displayMode.getWidth();
        height=displayMode.getHeight();


          Circle=new circle(-(int)Math.round((double)height/7*2),-(int)Math.round((double)height/7*2),(int)Math.round((double)height/7*.85),this);
          Rectangle=new rectangle(-(int)Math.round((double)height/7*1.5),-(int)Math.round((double)height/7*1.5),(int)Math.round((double)height/7*1.5),(int)Math.round((double)height/7*1.5),this);
          Tile=Circle;
          Tile.move(mouseX-Tile.width/2, mouseY-Tile.height/2);
                  text=new textPane(0,0,width,height,this);

          everything.add(new circle((int)Math.round((double)width/100*75),(int)Math.round((double)height/100*15),(int)Math.round((double)width/100*10),this));
                  everything.add(new rectangle((int)Math.round((double)width/100*70),(int)Math.round((double)height/100*60),(int)Math.round((double)width/100*20),(int)Math.round((double)height/100*20),this));
                  //everything.add(new line(750,250,750,750,this));
                  /*everything.add(new line(width/700*419,height/700*68,width/700*495,height/700*345,this));
                  everything.add(new line(width/700*495,height/700*345,width/700*749,height/700*350,this));
                  everything.add(new line(width/700*749,height/700*350,width/700*549,height/700*519,this));
                  everything.add(new line(width/700*549,height/700*519,width/700*624,height/700*800,this));
                  everything.add(new line(width/700*624,height/700*800,width/700*419,height/700*638,this));
                  everything.add(new line(width/700*419,height/700*638,width/700*203,height/700*800,this));
                  everything.add(new line(width/700*203,height/700*800,width/700*279,height/700*519,this));
                  everything.add(new line(width/700*279,height/700*519,width/700*76,height/700*350,this));
                  everything.add(new line(width/700*76,height/700*350,width/700*333,height/700*345,this));
                  everything.add(new line(width/700*333,height/700*345,width/700*419,height/700*68,this));

                  everything.add(new line(width/950*419,height/700*68,width/950*624,height/700*800,this));
                  everything.add(new line(width/950*419,height/700*68,width/950*203,height/700*800,this));
                  everything.add(new line(width/950*76,height/700*350,width/950*624,height/700*800,this));
                  everything.add(new line(width/950*203,height/700*800,width/950*749,height/700*350,this));
                  everything.add(new rectangle(width/950*76,height/700*350,width/950*673,1,this));*/

                  everything.add(new line((int)Math.round((double)width/1350*419),(int)Math.round((double)height/1000*68),(int)Math.round((double)width/1350*624),(int)Math.round((double)height/1000*800),this));
                  everything.add(new line((int)Math.round((double)width/1350*419),(int)Math.round((double)height/1000*68),(int)Math.round((double)width/1350*203),(int)Math.round((double)height/1000*800),this));
                  everything.add(new line((int)Math.round((double)width/1350*76),(int)Math.round((double)height/1000*350),(int)Math.round((double)width/1350*624),(int)Math.round((double)height/1000*800),this));
                  everything.add(new line((int)Math.round((double)width/1350*203),(int)Math.round((double)height/1000*800),(int)Math.round((double)width/1350*749),(int)Math.round((double)height/1000*350),this));
                  everything.add(new rectangle((int)Math.round((double)width/1350*76),(int)Math.round((double)height/1000*350),(int)Math.round((double)width/1350*673),1,this));


        addKeyListener(this);
        addMouseMotionListener(this);
        addMouseListener(this);
    }

    public void keyReleased(KeyEvent e)
    {
        Object source=e.getSource();

        int released=e.getKeyCode();

        if (released==KeyEvent.VK_A){left=0;}
        if (released==KeyEvent.VK_W){up=0;}
        if (released==KeyEvent.VK_D){right=0;}
        if (released==KeyEvent.VK_S){down=0;}
    }//end keyReleased


    public void keyPressed(KeyEvent e)
    {
        Object source=e.getSource();

        int pressed=e.getKeyCode();

        if (pressed==KeyEvent.VK_A){left=1;}
        if (pressed==KeyEvent.VK_W){up=1;}
        if (pressed==KeyEvent.VK_D){right=1;}
        if (pressed==KeyEvent.VK_S){down=1;}

        if (pressed==KeyEvent.VK_PAUSE&&pressed==KeyEvent.VK_P)
        {
            //if (paused==0){paused=1;}
            //else paused=0;
        }
    }//end keyPressed

    public void keyTyped(KeyEvent e){}

//***********************************************************************************************

    public void mouseDragged(MouseEvent e)
    {
        mouseX=(e.getX());
        mouseY=(e.getY());

          //run();
    }

    public void mouseMoved(MouseEvent e)
    {
        mouseX=(e.getX());
        mouseY=(e.getY());

          //run();
    }

//***********************************************************************************************

    public void mousePressed(MouseEvent e)
    {
        if(e.getX()==0 && e.getY()==0){System.exit(0);}

    mouseX=(e.getX()+x);
        mouseY=(e.getY()+y);

        if(Tile instanceof circle)
        {
                Circle.move(0-Circle.width, 0-Circle.height);
                Circle.setBounds(Circle.x, Circle.y, Circle.width, Circle.height);
                Tile=Rectangle;
        }
        else
        {
                Rectangle.move(0-Rectangle.width, 0-Rectangle.height);
                Rectangle.setBounds(Rectangle.x, Rectangle.y, Rectangle.width, Rectangle.height);
                Tile=Circle;
        }

        Tile.move(mouseX-Tile.width/2, mouseY-Tile.height/2);
    }

    public void mouseReleased(MouseEvent e)
    {
         //run();
    }

    public void mouseEntered(MouseEvent e){}
    public void mouseExited(MouseEvent e){}

    public void mouseClicked(MouseEvent e){}

//***********************************************************************************************

    public void run()//run collision detection
    {
        while (this == this)
        {
            Tile.move(Tile.x + ((mouseX - (Tile.x + (Tile.width / 2))) / 10), Tile.y + ((mouseY - (Tile.y + (Tile.height / 2))) / 10));
            //Tile.move((mouseX - Tile.width / 2), mouseY - (Tile.height / 2));

            for (int i = 0; i < everything.size(); i++)
            {
                tile Temp = (tile) everything.get(i);

                if (Temp.x < (Tile.x + Tile.width) && (Temp.x + Temp.width) > Tile.x && Temp.y < (Tile.y + Tile.height) && (Temp.y + Temp.height) > Tile.y)//rectangles collided
                {
                    if (Temp instanceof rectangle)
                    {
                        if (Tile instanceof rectangle){rectangleRectangle(Temp);}
                        else {circleRectangle(Temp);}//Tile instanceof circle
                    }
                    else
                    {
                        if (Temp instanceof circle)
                        {
                            if (Tile instanceof rectangle) {rectangleCircle(Temp);}
                            else {circleCircle(Temp);}
                        }
                        else//line
                        {
                            if (Tile instanceof rectangle){rectangleLine(Temp);}
                            else{circleLine(Temp);}
                        }
                    }
                }//end if
            }//end for

            try {Thread.sleep(16L);}
            catch (Exception e) {}

            Tile.setBounds(Tile.x, Tile.y, Tile.width, Tile.height);
            //Rectangle.setBounds(x, y, width, height);
            //Circle.setBounds(x, y, width, height);
            repaint();

            text.out=" ";
        }//end while loop
    }//end run

//***************************************special collision detection/handling functions************************************************

    void rectangleRectangle(tile Temp)
    {
        int lapTop, lapBot, lapLeft, lapRight, small, scootX=0, scootY=0;

        lapTop=(Temp.y+Temp.height)-Tile.y;
        lapBot=(Tile.y+Tile.height)-Temp.y;
        lapLeft=(Temp.x+Temp.width)-Tile.x;
        lapRight=(Tile.x+Tile.width)-Temp.x;

        small=999999999;

        if (lapTop<small){small=lapTop; scootX=0; scootY=lapTop;}
        if (lapBot<small){small=lapBot; scootX=0; scootY=lapBot*-1;}
                if (lapLeft<small){small=lapLeft; scootX=lapLeft; scootY=0;}
                if (lapRight<small){small=lapRight; scootX=lapRight*-1; scootY=0;}

        Tile.move(Tile.x+scootX, Tile.y+scootY);text.out="collision detected!";
    }



    void circleRectangle(tile Temp)
    {
        if((Tile.x+Tile.width/2<=Temp.x+Temp.width && Tile.x+Tile.width/2>=Temp.x)||(Tile.y+Tile.height/2>=Temp.y && Tile.y+Tile.height/2<=Temp.y+Temp.height))
        {
            rectangleRectangle(Temp);
        }
        else//push from nearest corner
        {
            int x,y;
            if(Tile.x+Tile.width/2>Temp.x+Temp.width && Tile.y+Tile.height/2<Temp.y){x=Temp.x+Temp.width; y=Temp.y;}
            else if(Tile.x+Tile.width/2<Temp.x && Tile.y+Tile.height/2<Temp.y){x=Temp.x; y=Temp.y;}
            else if(Tile.x+Tile.width/2>Temp.x+Temp.width && Tile.y+Tile.height/2>Temp.y+Temp.height){x=Temp.x+Temp.width; y=Temp.y+Temp.height;}
            else {x=Temp.x; y=Temp.y+Temp.height;}

            double distance = Math.sqrt(Math.pow(Tile.x+(Tile.width/2) - x, 2) + Math.pow(Tile.y+(Tile.height/2) - y, 2));

            if((int)Math.round(distance)<Tile.height/2)
            {
                             double normY = ((Tile.y+(Tile.height/2) - y) / distance);
                             double normX = ((Tile.x+(Tile.width/2) - x) / distance);

                            Tile.move(x-Tile.width/2+(int)Math.round(normX*((Tile.width/2))) , y-Tile.height/2+(int)Math.round(normY*((Tile.height/2))));text.out="collision detected!";
            }
        }
    }



    void rectangleCircle(tile Temp)
    {
        if((Temp.x+Temp.width/2<=Tile.x+Tile.width && Temp.x+Temp.width/2>=Tile.x)||(Temp.y+Temp.height/2>=Tile.y && Temp.y+Temp.height/2<=Tile.y+Tile.height))
        {
            rectangleRectangle(Temp);
        }
        else//push from nearest corner
        {
            int x,y;
            if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2<Tile.y){x=Tile.x+Tile.width; y=Tile.y;}
            else if(Temp.x+Temp.width/2<Tile.x && Temp.y+Temp.height/2<Tile.y){x=Tile.x; y=Tile.y;}
            else if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2>Tile.y+Tile.height){x=Tile.x+Tile.width; y=Tile.y+Tile.height;}
            else {x=Tile.x; y=Tile.y+Tile.height;}

            double distance = Math.sqrt(Math.pow(Temp.x+(Temp.width/2) - x, 2) + Math.pow(Temp.y+(Temp.height/2) - y, 2));

            if((int)Math.round(distance)<Temp.height/2)
            {
             double normY = ((Temp.y+(Temp.height/2) - y) / distance);
             double normX = ((Temp.x+(Temp.width/2) - x) / distance);

             if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2<Tile.y){Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2)))-Tile.width,(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2))));text.out="collision detected!";}
                else if(Temp.x+Temp.width/2<Tile.x && Temp.y+Temp.height/2<Tile.y){Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2))),(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2))));text.out="collision detected!";}
                else if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2>Tile.y+Tile.height){Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2)))-Tile.width,(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2)))-Tile.height);text.out="collision detected!";}
                else {Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2))),(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2)))-Tile.height);text.out="collision detected!";}
            }
        }
    }




    void circleCircle(tile Temp)
    {
        double distance = Math.sqrt(Math.pow((Tile.x+(Tile.width/2)) - (Temp.x+(Temp.width/2)),2) + Math.pow((Tile.y+(Tile.height/2)) - (Temp.y+(Temp.height/2)), 2));

        if((int)distance<(Tile.width/2+Temp.width/2))
        {
                        double normX = ((Tile.x+(Tile.width/2)) - (Temp.x+(Temp.width/2))) / distance;
                        double normY = ((Tile.y+(Tile.height/2)) - (Temp.y+(Temp.height/2))) / distance;

            Tile.move((Temp.x+(Temp.width/2))+(int)Math.round(normX*(Tile.width/2+Temp.width/2))-(Tile.width/2) , (Temp.y+(Temp.height/2))+(int)Math.round(normY*(Tile.height/2+Temp.height/2))-(Tile.height/2));text.out="collision detected!";
        }
    }



    void circleLine(tile Temp)
    {
            line Line=(line)Temp;

            if (Line.x1 < (Tile.x + Tile.width) && (Line.x1) > Tile.x && Line.y1 < (Tile.y + Tile.height) && Line.y1 > Tile.y)//circle may be hitting one of the end points
            {
                rectangle rec=new rectangle(Line.x1, Line.y1, 1, 1, this);
                circleRectangle(rec);
                remove(rec);
            }

            if (Line.x2 < (Tile.x + Tile.width) && (Line.x2) > Tile.x && Line.y2 < (Tile.y + Tile.height) && Line.y2 > Tile.y)//circle may be hitting one of the end points
            {
                rectangle rec=new rectangle(Line.x2, Line.y2, 1, 1, this);
                circleRectangle(rec);
                remove(rec);
            }


            int x1=0, y1=0, x2=Tile.x+(Tile.width/2), y2=Tile.y+(Tile.height/2);

            x1=Tile.x+(Tile.width/2)-Line.height;//(int)Math.round(Line.xNorm*1000);
            x2=Tile.x+(Tile.width/2)+Line.height;
            if(Line.posSlope)
            {
                y1=Tile.y+(Tile.height/2)-Line.width;
                y2=Tile.y+(Tile.height/2)+Line.width;
            }
            else
            {
                y1=Tile.y+(Tile.height/2)+Line.width;
                y2=Tile.y+(Tile.height/2)-Line.width;
            }

            Point point=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection

            if (point.x < (Line.x + Line.width) && point.x > Line.x && point.y < (Line.y + Line.height) && point.y > Line.y)//line intersects within line segment
            {
                //if(point!=null){System.out.println(point.x+","+point.y);}
                double distance = Math.sqrt(Math.pow((Tile.x+(Tile.width/2)) - point.x,2) + Math.pow((Tile.y+(Tile.width/2)) - point.y, 2));

                if((int)distance<Tile.width/2)
                {
                    //System.out.println("hit");
                    double normX = ((Tile.x+(Tile.width/2)) - point.x) / distance;
                    double normY = ((Tile.y+(Tile.height/2)) - point.y) / distance;

                    Tile.move((point.x)+(int)Math.round(normX*(Tile.width/2))-(Tile.width/2) , (point.y)+(int)Math.round(normY*(Tile.height/2))-(Tile.height/2));text.out="collision detected!";
                    //System.out.println(point.x+","+point.y);
                }
            }

            //new bullet(this, (int)Math.round(tryX), (int)Math.round(tryY));
    }

        void rectangleLine(tile Temp)
    {
            line Line=(line)Temp;
            if(new Line2D.Double(Line.x1,Line.y1,Line.x2,Line.y2).intersects(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height)))
            {
                if (Line.x1 < (Tile.x + Tile.width) && (Line.x1) > Tile.x && Line.y1 < (Tile.y + Tile.height) && Line.y1 > Tile.y)//circle may be hitting one of the end points
                {
                    rectangle rec=new rectangle(Line.x1, Line.y1, 1, 1, this);
                    rectangleRectangle(rec);
                    remove(rec);
                }

                if (Line.x2 < (Tile.x + Tile.width) && (Line.x2) > Tile.x && Line.y2 < (Tile.y + Tile.height) && Line.y2 > Tile.y)//circle may be hitting one of the end points
                {
                    rectangle rec=new rectangle(Line.x2, Line.y2, 1, 1, this);
                    rectangleRectangle(rec);
                    remove(rec);
                }

                if(Line.posSlope)//positive sloped line
                {
                    //first we'll do the top left corner
                    int x1=Tile.x-Line.height;
                    int x2=Tile.x+Line.height;
                    int y1=Tile.y-Line.width;
                    int y2=Tile.y+Line.width;
                    Point topPoint=new Point(-99,-99), botPoint=new Point(-99,-99);
                    double topDistance=0, botDistance=0;

                    topPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection

                    topDistance = Math.sqrt(Math.pow(Tile.x - topPoint.x,2) + Math.pow(Tile.y - topPoint.y, 2));

                    //new let's do the bottom right corner
                    x1=Tile.x+Tile.width-Line.height;
                    x2=Tile.x+Tile.width+Line.height;
                    y1=Tile.y+Tile.height-Line.width;
                    y2=Tile.y+Tile.height+Line.width;

                    botPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection

                    botDistance = Math.sqrt(Math.pow((Tile.x+Tile.width) - botPoint.x,2) + Math.pow((Tile.y+Tile.height) - botPoint.y, 2));


                    if(topDistance<botDistance)
                    {
                        if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(topPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(topPoint))
                        {
                            Tile.move(topPoint.x,topPoint.y);text.out="collision detected!";
                        }
                    }
                    else
                    {
                        if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(botPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(botPoint))
                        {
                            Tile.move(botPoint.x-Tile.width,botPoint.y-Tile.height);text.out="collision detected!";
                        }
                    }
                }
                else//negative sloped lne
                {
                    //first we'll do the top right corner
                    int x1=Tile.x+Tile.width-Line.height;
                    int x2=Tile.x+Tile.width+Line.height;
                    int y1=Tile.y+Line.width;
                    int y2=Tile.y-Line.width;
                    Point topPoint=new Point(-99,-99), botPoint=new Point(-99,-99);
                    double topDistance=0, botDistance=0;

                    topPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection

                    topDistance = Math.sqrt(Math.pow(Tile.x + Tile.width - topPoint.x,2) + Math.pow(Tile.y - topPoint.y, 2));

                    //new let's do the bottom left corner
                    x1=Tile.x-Line.height;
                    x2=Tile.x+Line.height;
                    y1=Tile.y+Tile.height+Line.width;
                    y2=Tile.y+Tile.height-Line.width;

                    botPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection

                    botDistance = Math.sqrt(Math.pow(Tile.x - botPoint.x,2) + Math.pow((Tile.y+Tile.height) - botPoint.y, 2));


                    if(topDistance<botDistance)
                    {
                        if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(topPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(topPoint))
                        {
                            Tile.move(topPoint.x-Tile.width,topPoint.y);text.out="collision detected!";
                        }
                    }
                    else
                    {
                        if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(botPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(botPoint))
                        {
                            Tile.move(botPoint.x,botPoint.y-Tile.height);text.out="collision detected!";
                        }
                    }
                }
            }
    }

       public Point intersection(double x1, double y1, double x2, double y2,double x3, double y3, double x4, double y4)//I didn't write this. got it from http://www.ahristov.com/tutorial/geometry-games/intersection-lines.html (I altered it)
       {
            double d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);

            double xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d;
            double yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d;

            int x=(int)Math.round(xi);
            int y=(int)Math.round(yi);

            return new Point(x, y);
        }

//***************************************************************************************

    public static void main(String[] args)
    {
        final collision Collision=new collision();
          Collision.run();
    }//end main
}//end class

List<Map<String, String>> vs List<? extends Map<String, String>>

The difference is that, for example, a

List<HashMap<String,String>>

is a

List<? extends Map<String,String>>

but not a

List<Map<String,String>>

So:

void withWilds( List<? extends Map<String,String>> foo ){}
void noWilds( List<Map<String,String>> foo ){}

void main( String[] args ){
    List<HashMap<String,String>> myMap;

    withWilds( myMap ); // Works
    noWilds( myMap ); // Compiler error
}

You would think a List of HashMaps should be a List of Maps, but there's a good reason why it isn't:

Suppose you could do:

List<HashMap<String,String>> hashMaps = new ArrayList<HashMap<String,String>>();

List<Map<String,String>> maps = hashMaps; // Won't compile,
                                          // but imagine that it could

Map<String,String> aMap = Collections.singletonMap("foo","bar"); // Not a HashMap

maps.add( aMap ); // Perfectly legal (adding a Map to a List of Maps)

// But maps and hashMaps are the same object, so this should be the same as

hashMaps.add( aMap ); // Should be illegal (aMap is not a HashMap)

So this is why a List of HashMaps shouldn't be a List of Maps.

JavaScript check if variable exists (is defined/initialized)

In ReactJS, things are a bit more complicated! This is because it is a compiled environment, which follows ESLint's no-undef rule since [email protected] (released Oct. 1st, 2018). The documentation here is helpful to anyone interested in this problem...

In JavaScript, prior to ES6, variable and function declarations are hoisted to the top of a scope, so it's possible to use identifiers before their formal declarations in code....

This [new] rule [of ES6] will warn when it encounters a reference to an identifier that has not yet been declared.

So, while it's possible to have an undefined (or "uninitialized") variable, it is not possible to have an undeclared variable in ReactJS without turning off the eslint rules.

This can be very frustrating -- there are so many projects on GitHub that simply take advantage of the pre-ES6 standards; and directly compiling these without any adjustments is basically impossible.

But, for ReactJS, you can use eval(). If you have an undeclared variable like...

if(undeclaredvar) {...}

You can simply rewrite this part as...

if(eval('typeof undeclaredvar !== "undefined"')) {...}

For instance...

_x000D_
_x000D_
if(eval("false")) {
  console.log("NO!");
}
if(eval("true")) {
  console.log("YEAH!");
}
_x000D_
_x000D_
_x000D_

For those importing GitHub repositories into a ReactJS project, this is simply the only way to check if a variable is declared. Before closing, I'd like to remind you that there are security issues with eval() if use incorrectly.

jQuery class within class selector

is just going to look for a div with class="outer inner", is that correct?

No, '.outer .inner' will look for all elements with the .inner class that also have an element with the .outer class as an ancestor. '.outer.inner' (no space) would give the results you're thinking of.

'.outer > .inner' will look for immediate children of an element with the .outer class for elements with the .inner class.

Both '.outer .inner' and '.outer > .inner' should work for your example, although the selectors are fundamentally different and you should be wary of this.

did you register the component correctly? For recursive components, make sure to provide the "name" option

Adding my scenario. Just in case someone has similar problem and not able to identify ACTUAL issue.

I was using vue splitpanes.

Previously it required only "Splitpanes", in latest version, they made another "Pane" component (as children of splitpanes).

Now thing is, if you don't register "Pane" component in latest version of splitpanes, it was showing error for "Splitpanes". as below.

[Vue warn]: Unknown custom element: <splitpanes> - did you register the component correctly? For recursive components, make sure to provide the "name" option.

What's the difference between interface and @interface in java?

The interface keyword indicates that you are declaring a traditional interface class in Java.
The @interface keyword is used to declare a new annotation type.

See docs.oracle tutorial on annotations for a description of the syntax.
See the JLS if you really want to get into the details of what @interface means.

Get timezone from users browser using moment(timezone).js

When using moment.js, use:

var tz = moment.tz.guess();

It will return an IANA time zone identifier, such as America/Los_Angeles for the US Pacific time zone.

It is documented here.

Internally, it first tries to get the time zone from the browser using the following call:

Intl.DateTimeFormat().resolvedOptions().timeZone

If you are targeting only modern browsers that support this function, and you don't need Moment-Timezone for anything else, then you can just call that directly.

If Moment-Timezone doesn't get a valid result from that function, or if that function doesn't exist, then it will "guess" the time zone by testing several different dates and times against the Date object to see how it behaves. The guess is usually a good enough approximation, but not guaranteed to exactly match the time zone setting of the computer.

Convert array to JSON string in swift

You can try this.

func convertToJSONString(value: AnyObject) -> String? {
        if JSONSerialization.isValidJSONObject(value) {
            do{
                let data = try JSONSerialization.data(withJSONObject: value, options: [])
                if let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
                    return string as String
                }
            }catch{
            }
        }
        return nil
    }

MVC - Set selected value of SelectList

You can use below method, which is quite simple.

new SelectList(items, "ID", "Name",items.Select(x=> x.Id).FirstOrDefault());

This will auto-select the first item in your list. You can modify the above query by adding a where clause.

Recursively look for files with a specific extension

The syntax I use is a bit different than what @Matt suggested:

find $directory -type f -name \*.in

(it's one less keystroke).

How can I debug a Perl script?

If using an interactive debugger is OK for you, you can try perldebug.

How can I add reflection to a C++ application?

When I wanted reflection in C++ I read this article and improved upon what I saw there. Sorry, no can has. I don't own the result...but you can certainly get what I had and go from there.

I am currently researching, when I feel like it, methods to use inherit_linearly to make the definition of reflectable types much easier. I've gotten fairly far in it actually but I still have a ways to go. The changes in C++0x are very likely to be a lot of help in this area.

Right way to convert data.frame to a numeric matrix, when df also contains strings?

Edit 2: See @flodel's answer. Much better.

Try:

# assuming SFI is your data.frame
as.matrix(sapply(SFI, as.numeric))  

Edit: or as @ CarlWitthoft suggested in the comments:

matrix(as.numeric(unlist(SFI)),nrow=nrow(SFI))

How can I pipe stderr, and not stdout?

If you are using Bash, then use:

command >/dev/null |& grep "something"

http://www.gnu.org/software/bash/manual/bashref.html#Pipelines

Error: could not find function ... in R

I can usually resolve this problem when a computer is under my control, but it's more of a nuisance when working with a grid. When a grid is not homogenous, not all libraries may be installed, and my experience has often been that a package wasn't installed because a dependency wasn't installed. To address this, I check the following:

  1. Is Fortran installed? (Look for 'gfortran'.) This affects several major packages in R.
  2. Is Java installed? Are the Java class paths correct?
  3. Check that the package was installed by the admin and available for use by the appropriate user. Sometimes users will install packages in the wrong places or run without appropriate access to the right libraries. .libPaths() is a good check.
  4. Check ldd results for R, to be sure about shared libraries
  5. It's good to periodically run a script that just loads every package needed and does some little test. This catches the package issue as early as possible in the workflow. This is akin to build testing or unit testing, except it's more like a smoke test to make sure that the very basic stuff works.
  6. If packages can be stored in a network-accessible location, are they? If they cannot, is there a way to ensure consistent versions across the machines? (This may seem OT, but correct package installation includes availability of the right version.)
  7. Is the package available for the given OS? Unfortunately, not all packages are available across platforms. This goes back to step 5. If possible, try to find a way to handle a different OS by switching to an appropriate flavor of a package or switch off the dependency in certain cases.

Having encountered this quite a bit, some of these steps become fairly routine. Although #7 might seem like a good starting point, these are listed in approximate order of the frequency that I use them.

How do you clear Apache Maven's cache?

This works on the Spring Tool Suite v 3.1.0.RELEASE, but I'm guessing it's also available on Eclipse as well.

After deleting the artifacts by hand (as stated by palacsint above) in the /username/.m2 directory, re-index the files by doing the following:

Go to:

  • Windows->Preferences->Maven->User Settings menu.

Click the Reindex button next to the Local Repository text box. Click "Apply" then "OK" and you're done.

How to compress image size?

I think you are asking about Shrinking image size:

    public Bitmap ShrinkBitmap(String file, int width, int height)
{
    BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
    bmpFactoryOptions.inJustDecodeBounds = true;
    Bitmap bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);

    int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight / (float) height);
    int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth / (float) width);

    if(heightRatio > 1 || widthRatio > 1)
    {
        if(heightRatio > widthRatio)
        {
            bmpFactoryOptions.inSampleSize = heightRatio;
        }
        else
        {
            bmpFactoryOptions.inSampleSize = widthRatio;
        }
    }

    bmpFactoryOptions.inJustDecodeBounds = false;
    bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
    return bitmap;
}

How to Run a jQuery or JavaScript Before Page Start to Load

Hide the body with css then show it after the page is loaded:

CSS:

html { visibility:hidden; }

Javascript

$(document).ready(function() {
  document.getElementsByTagName("html")[0].style.visibility = "visible";
});

The page will go from blank to showing all content when the page is loaded, no flash of content, no watching images load etc.

Get the current date in java.sql.Date format

These are all too long.

Just use:

new Date(System.currentTimeMillis())

Spring 3 RequestMapping: Get path value

private final static String MAPPING = "/foo/*";

@RequestMapping(value = MAPPING, method = RequestMethod.GET)
public @ResponseBody void foo(HttpServletRequest request, HttpServletResponse response) {
    final String mapping = getMapping("foo").replace("*", ""); 
    final String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
    final String restOfPath = url.replace(mapping, "");
    System.out.println(restOfPath);
}

private String getMapping(String methodName) {
    Method methods[] = this.getClass().getMethods();
    for (int i = 0; i < methods.length; i++) {
        if (methods[i].getName() == methodName) {
            String mapping[] = methods[i].getAnnotation(RequestMapping.class).value();
            if (mapping.length > 0) {
                return mapping[mapping.length - 1];
            }
        }
    }
    return null;
}

How do I check out a remote Git branch?

to get all remote branches use this :

git fetch --all

then checkout to the branch :

git checkout test

python xlrd unsupported format, or corrupt file.

Try to open it with pandas:

import pandas as pd
data = pd.read_html('filename.xls')

Or try any other html python parser.

That's not a proper excel file, but an html readable with excel.

How do I print the content of httprequest request?

More details that help in logging

    String client = request.getRemoteAddr();
    logger.info("###### requested client: {} , Session ID : {} , URI :" + request.getMethod() + ":" + request.getRequestURI() + "", client, request.getSession().getId());

    Map params = request.getParameterMap();
    Iterator i = params.keySet().iterator();
    while (i.hasNext()) {
        String key = (String) i.next();
        String value = ((String[]) params.get(key))[0];
        logger.info("###### Request Param Name : {} , Value :  {} ", key, value);
    }

PHP Warning Permission denied (13) on session_start()

do a phpinfo(), and look for session.save_path. the directory there needs to have the correct permissions for the user and/or group that your webserver runs as

How to build x86 and/or x64 on Windows from command line with CMAKE?

Besides CMAKE_GENERATOR_PLATFORM variable, there is also the -A switch

cmake -G "Visual Studio 16 2019" -A Win32
cmake -G "Visual Studio 16 2019" -A x64

https://cmake.org/cmake/help/v3.16/generator/Visual%20Studio%2016%202019.html#platform-selection

  -A <platform-name>           = Specify platform name if supported by
                                 generator.

How to multiply duration by integer?

My turn:

https://play.golang.org/p/RifHKsX7Puh

package main

import (
    "fmt"
    "time"
)

func main() {
    var n int = 77
    v := time.Duration( 1.15 * float64(n) ) * time.Second

    fmt.Printf("%v %T", v, v)
}

It helps to remember the simple fact, that underlyingly the time.Duration is a mere int64, which holds nanoseconds value.

This way, conversion to/from time.Duration becomes a formality. Just remember:

  • int64
  • always nanosecs

In-memory size of a Python structure

One can also make use of the tracemalloc module from the Python standard library. It seems to work well for objects whose class is implemented in C (unlike Pympler, for instance).

Angular 4 HttpClient Query Parameters

A more concise solution:

this._Http.get(`${API_URL}/api/v1/data/logs`, { 
    params: {
      logNamespace: logNamespace
    } 
 })

Maximum call stack size exceeded on npm install

Try removing package-lock.json and the node_modules folder:

rm package-lock.json
rm -r node_modules

How to use foreach with a hash reference?

So, with Perl 5.20, the new answer is:

foreach my $key (keys $ad_grp_ref->%*) {

(which has the advantage of transparently working with more complicated expressions:

foreach my $key (keys $ad_grp_obj[3]->get_ref()->%*) {

etc.)

See perlref for the full documentation.

Note: in Perl version 5.20 and 5.22, this syntax is considered experimental, so you need

use feature 'postderef';
no warnings 'experimental::postderef';

at the top of any file that uses it. Perl 5.24 and later don't require any pragmas for this feature.

How can I set a DateTimePicker control to a specific date?

If you want to set a date, DateTimePicker.Value is a DateTime object.

DateTimePicker.Value = new DateTime(2012,05,28);

This is the constructor of DateTime:

new DateTime(int year,int month,int date);

My Visual is 2012

Find Locked Table in SQL Server

You can use sp_lock (and sp_lock2), but in SQL Server 2005 onwards this is being deprecated in favour of querying sys.dm_tran_locks:

select  
    object_name(p.object_id) as TableName, 
    resource_type, resource_description
from
    sys.dm_tran_locks l
    join sys.partitions p on l.resource_associated_entity_id = p.hobt_id

jQuery - selecting elements from inside a element

....but $('span', $('#foo')); doesn't work?

This method is called as providing selector context.

In this you provide a second argument to the jQuery selector. It can be any css object string just like you would pass for direct selecting or a jQuery element.

eg.

$("span",".cont1").css("background", '#F00');

The above line will select all spans within the container having the class named cont1.

DEMO

Formula px to dp, dp to px android

Use This function

private int dp2px(int dp) {
    return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
}

Open Source Alternatives to Reflector?

Well, Reflector itself is a .NET assembly so you can open Reflector.exe in Reflector to check out how it's built.

How do I create directory if it doesn't exist to create a file?

To Create

(new FileInfo(filePath)).Directory.Create() Before writing to the file.

....Or, If it exists, then create (else do nothing)

System.IO.FileInfo file = new System.IO.FileInfo(filePath);
file.Directory.Create(); // If the directory already exists, this method does nothing.
System.IO.File.WriteAllText(file.FullName, content);

.keyCode vs. .which

jQuery normalises event.which depending on whether event.which, event.keyCode or event.charCode is supported by the browser:

// Add which for key events
if ( event.which == null && (event.charCode != null || event.keyCode != null) ) {
   event.which = event.charCode != null ? event.charCode : event.keyCode;
}

An added benefit of .which is that jQuery does it for mouse clicks too:

// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && event.button !== undefined ) {
    event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
}

Python3: ImportError: No module named '_ctypes' when using Value from module multiprocessing

Detailed steps to install Python 3.7 in CentOS or any redhat linux machine:

  1. Download Python from https://www.python.org/ftp/python/3.7.0/Python-3.7.0.tar.xz
  2. Extract the content in new folder
  3. Open Terminal in the same directory
  4. Run below code step by step :
sudo yum -y install gcc gcc-c++ 
sudo yum -y install zlib zlib-devel
sudo yum -y install libffi-devel 
./configure
make
make install

pip install from git repo branch

Just to add an extra, if you want to install it in your pip file it can be added like this:

-e git+https://github.com/tangentlabs/django-oscar-paypal.git@issue/34/oscar-0.6#egg=django-oscar-paypal

It will be saved as an egg though.

How to extract a substring using regex

Because you also ticked Scala, a solution without regex which easily deals with multiple quoted strings:

val text = "some string with 'the data i want' inside 'and even more data'"
text.split("'").zipWithIndex.filter(_._2 % 2 != 0).map(_._1)

res: Array[java.lang.String] = Array(the data i want, and even more data)

Accessing nested JavaScript objects and arrays by string path

I haven't yet found a package to do all of the operations with a string path, so I ended up writing my own quick little package which supports insert(), get() (with default return), set() and remove() operations.

You can use dot notation, brackets, number indices, string number properties, and keys with non-word characters. Simple usage below:

> var jsocrud = require('jsocrud');

...

// Get (Read) ---
> var obj = {
>     foo: [
>         {
>             'key w/ non-word chars': 'bar'
>         }
>     ]
> };
undefined

> jsocrud.get(obj, '.foo[0]["key w/ non-word chars"]');
'bar'

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

https://github.com/vertical-knowledge/jsocrud

Excel VBA Automation Error: The object invoked has disconnected from its clients

I have had this problem on multiple projects converting Excel 2000 to 2010. Here is what I found which seems to be working. I made two changes, but not sure which caused the success:

1) I changed how I closed and saved the file (from close & save = true to save as the same file name and close the file:

...
    Dim oFile           As Object       ' File being processed
...
[Where the error happens - where aArray(i) is just the name of an Excel.xlsb file]
   Set oFile = GetObject(aArray(i))
...
'oFile.Close SaveChanges:=True    - OLD CODE WHICH ERROR'D
'New Code
oFile.SaveAs Filename:=oFile.Name
oFile.Close SaveChanges:=False

2) I went back and looked for all of the .range in the code and made sure it was the full construct..

Application.Workbooks("workbook name").Worksheets("worksheet name").Range("G19").Value

or (not 100% sure if this is correct syntax, but this is the 'effort' i made)

ActiveSheet.Range("A1").Select

Better way to get type of a Javascript variable?

typeof condition is used to check variable type, if you are check variable type in if-else condition e.g.

if(typeof Varaible_Name "undefined")
{

}

What is a quick way to force CRLF in C# / .NET?

input.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", "\r\n")

This will work if the input contains only one type of line breaks - either CR, or LF, or CR+LF.

How to specify a port number in SQL Server connection string?

Use a comma to specify a port number with SQL Server:

mycomputer.test.xxx.com,1234

It's not necessary to specify an instance name when specifying the port.

Lots more examples at http://www.connectionstrings.com/. It's saved me a few times.

How to enable CORS in AngularJs

I encountered a similar problem like this, problem was with the backend . I was using node server(Express). I had a get request from the frontend(angular) as shown below

   onGetUser(){
        return this.http.get("http://localhost:3000/user").pipe(map(
            (response:Response)=>{
                const user =response.json();
                return user;
            }
        )) 
    }

But it gave the following errorThe error

This is the backend code written using express without the headers

app.get('/user',async(req,res)=>{
     const user=await getuser();
     res.send(user);
 })

After adding a header to the method problem was solved

app.get('/user',async(req,res)=>{
    res.header("Access-Control-Allow-Origin", "*");
    const user=await getuser();
    res.send(user);
})

You can get more details about Enabling CORS on Node JS

Full-screen responsive background image

I personally dont recommend to apply style on HTML tag, it might have after effects somewhere later part of the development.

so i personally suggest to apply background-image property to the body tag.

body{
    width:100%;
    height: 100%;
    background-image: url("./images/bg.jpg");
    background-position: center;
    background-size: 100% 100%;
    background-repeat: no-repeat;
}

This simple trick solved my problem. this works for most of the screens larger/smaller ones.

there are so many ways to do it, i found this the simpler with minimum after effects

how to get value of selected item in autocomplete

To answer the question more generally, the answer is:

select: function( event , ui ) {
    alert( "You selected: " + ui.item.label );
}

Complete example :

_x000D_
_x000D_
$('#test').each(function(i, el) {_x000D_
    var that = $(el);_x000D_
    that.autocomplete({_x000D_
        source: ['apple','banana','orange'],_x000D_
        select: function( event , ui ) {_x000D_
            alert( "You selected: " + ui.item.label );_x000D_
        }_x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>_x000D_
_x000D_
Type a fruit here: <input type="text" id="test" />
_x000D_
_x000D_
_x000D_

Pass variables from servlet to jsp

If you are using Action, Actionforward way to process business logic and next page to show, check out if redirect is called. As many others pointed out, redirecting doesn't keep your original request since it is basically forcing you to make a new request to designated path. So the value set in original request will be vanished if you use redirection instead of requestdispatch.

What is the difference between "SMS Push" and "WAP Push"?

SMS Push uses SMS as a carrier, WAP uses download via WAP.

Remove spaces from std::string in C++

I created a function, that removes the white spaces from the either ends of string. Such as " Hello World ", will be converted into "Hello world".

This works similar to strip, lstrip and rstrip functions, which are frequently used in python.

string strip(string str) {
    while (str[str.length() - 1] == ' ') {
        str = str.substr(0, str.length() - 1);
    }
    while (str[0] == ' ') {
        str = str.substr(1, str.length() - 1);
    }
    return str;
}

string lstrip(string str) {
    while (str[0] == ' ') {
        str = str.substr(1, str.length() - 1);
    }
    return str;
}

string rstrip(string str) {
    while (str[str.length() - 1] == ' ') {
        str = str.substr(0, str.length() - 1);
    }
    return str;
}

Deserializing a JSON file with JavaScriptSerializer()

For .Net 4+:

string s = "{ \"user\" : {    \"id\" : 12345,    \"screen_name\" : \"twitpicuser\"}}";

var serializer = new JavaScriptSerializer();
dynamic usr = serializer.DeserializeObject(s);
var UserId = usr["user"]["id"];

For .Net 2/3.5: This code should work on JSON with 1 level

samplejson.aspx

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Globalization" %>
<%@ Import Namespace="System.Web.Script.Serialization" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%
string s = "{ \"id\" : 12345,    \"screen_name\" : \"twitpicuser\"}";
var serializer = new JavaScriptSerializer();
Dictionary<string, object> result = (serializer.DeserializeObject(s) as Dictionary<string, object>);
var UserId = result["id"];
 %>
 <%=UserId %>

And for a 2 level JSON:

sample2.aspx

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Globalization" %>
<%@ Import Namespace="System.Web.Script.Serialization" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%
string s = "{ \"user\" : {    \"id\" : 12345,    \"screen_name\" : \"twitpicuser\"}}";
var serializer = new JavaScriptSerializer();
Dictionary<string, object> result = (serializer.DeserializeObject(s) as Dictionary<string, object>);
Dictionary<string, object> usr = (result["user"] as Dictionary<string, object>);
var UserId = usr["id"];
 %>
 <%= UserId %>

insert password into database in md5 format?

use MD5,

$query="INSERT INTO ptb_users (id,
user_id,
first_name,
last_name,
email )
VALUES('NULL',
'NULL',
'".$firstname."',
'".$lastname."',
'".$email."',
MD5('".$password."')
)";

but MD5 is insecure. Use SHA2.

How do I insert non breaking space character &nbsp; in a JSF page?

The easiest way is:

<h:outputText value=" " />

How is the 'use strict' statement interpreted in Node.js?

"use strict";

Basically it enables the strict mode.

Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.

As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.

So, there will be no major difference how "use strict"; is interpreted by the Chrome browser and Node.js.

Please read what is strict mode in JavaScript.

For more information:

  1. Strict mode
  2. ECMAScript 5 Strict mode support in browsers
  3. Strict mode is coming to town
  4. Compatibility table for strict mode
  5. Stack Overflow questions: what does 'use strict' do in JavaScript & what is the reasoning behind it


ECMAScript 6:

ECMAScript 6 Code & strict mode. Following is brief from the specification:

10.2.1 Strict Mode Code

An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:

  • Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
  • Module code is always strict mode code.
  • All parts of a ClassDeclaration or a ClassExpression are strict mode code.
  • Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
  • Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
  • Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.

Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).

Warning: A non-numeric value encountered

You can solve the problem without any new logic by just casting the thing into the number, which prevents the warning and is equivalent to the behavior in PHP 7.0 and below:

$sub_total += ((int)$item['quantity'] * (int)$product['price']);

(The answer from Daniel Schroeder is not equivalent because $sub_total would remain unset if non-numeric values are encountered. For example, if you print out $sub_total, you would get an empty string, which is probably wrong in an invoice. - by casting you make sure that $sub_total is an integer.)

Is there an ignore command for git like there is for svn?

On Linux/Unix, you can append files to the .gitignore file with the echo command. For example if you want to ignore all .svn folders, run this from the root of the project:

echo .svn/ >> .gitignore

Select SQL results grouped by weeks

This should do it for you:

Declare @DatePeriod datetime

Set @DatePeriod = '2011-05-30'

Select  ProductName,
        IsNull([1],0) as 'Week 1',
        IsNull([2],0) as 'Week 2',
        IsNull([3],0) as 'Week 3',
        IsNull([4],0) as 'Week 4',
        IsNull([5], 0) as 'Week 5'

From 
(
Select  ProductName,
        DATEDIFF(week, DATEADD(MONTH, DATEDIFF(MONTH, 0, InputDate), 0), InputDate) +1 as [Weeks],
        Sale as 'Sale'

From dbo.YourTable
-- Only get rows where the date is the same as the DatePeriod
-- i.e DatePeriod is 30th May 2011 then only the weeks of May will be calculated
Where DatePart(Month, InputDate)= DatePart(Month, @DatePeriod)
)p 
Pivot (Sum(Sale) for Weeks in ([1],[2],[3],[4],[5])) as pv

It will calculate the week number relative to the month. So instead of week 20 for the year it will be week 2. The @DatePeriod variable is used to fetch only rows relative to the month (in this example only for the month of May)

Output using my sample data:

enter image description here

How do you change the value inside of a textfield flutter?

TextEditingController()..text = "new text"

Angularjs -> ng-click and ng-show to show a div

remove class hideByDefault. Div will remain hidden itself till value of myvalue is false.

Converting Go struct to JSON

You need to export the User.name field so that the json package can see it. Rename the name field to Name.

package main

import (
    "fmt"
    "encoding/json"
)

type User struct {
    Name string
}

func main() {
    user := &User{Name: "Frank"}
    b, err := json.Marshal(user)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(b))
}

Output:

{"Name":"Frank"}

TypeError: Can't convert 'int' object to str implicitly

def attributeSelection():
balance = 25
print("Your SP balance is currently 25.")
strength = input("How much SP do you want to put into strength?")
balanceAfterStrength = balance - int(strength)
if balanceAfterStrength == 0:
    print("Your SP balance is now 0.")
    attributeConfirmation()
elif strength < 0:
    print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
    attributeSelection()
elif strength > balance:
    print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
    attributeSelection()
elif balanceAfterStrength > 0 and balanceAfterStrength < 26:
    print("Ok. You're balance is now at " + str(balanceAfterStrength) + " skill points.")
else:
    print("That is an invalid input. Restarting attribute selection.")
    attributeSelection()

Spark - load CSV file as DataFrame?

spark-csv is part of core Spark functionality and doesn't require a separate library. So you could just do for example

df = spark.read.format("csv").option("header", "true").load("csvfile.csv")

In scala,(this works for any format-in delimiter mention "," for csv, "\t" for tsv etc)

val df = sqlContext.read.format("com.databricks.spark.csv") .option("delimiter", ",") .load("csvfile.csv")

JSON character encoding

If you're using StringEntity try this, using your choice of character encoding. It handles foreign characters as well.

Could not instantiate mail function. Why this error occurring

This a system error.

Check error of the system with:

tail /var/log/httpd/error_log

It can be any reason.

Viewing localhost website from mobile device

One of the easiest way to remotely access ASP.net local website, without messing with adding new rules to firewall, is to use this Visual Studio extension:

Conveyor by Keyoti (Visual Studio extension)

Just install it. Every time when you run your project, it will show you URL which can be used for remote access. No other configruration required.

enter image description here

How to turn off gcc compiler optimization to enable buffer overflow

On newer distros (as of 2016), it seems that PIE is enabled by default so you will need to disable it explicitly when compiling.

Here's a little summary of commands which can be helpful when playing locally with buffer overflow exercises in general:

Disable canary:

gcc vuln.c -o vuln_disable_canary -fno-stack-protector

Disable DEP:

gcc vuln.c -o vuln_disable_dep -z execstack

Disable PIE:

gcc vuln.c -o vuln_disable_pie -no-pie

Disable all of protection mechanisms listed above (warning: for local testing only):

gcc vuln.c -o vuln_disable_all -fno-stack-protector -z execstack -no-pie

For 32-bit machines, you'll need to add the -m32 parameter as well.

How to set -source 1.7 in Android Studio and Gradle

At current, Android doesn't support Java 7, only Java 6. New features in Java 7 such as the diamond syntax are therefore not currently supported. Finding sources to support this isn't easy, but I could find that the Dalvic engine is built upon a subset of Apache Harmony which only ever supported Java up to version 6. And if you check the system requirements for developing Android apps it also states that at least JDK 6 is needed (though this of course isn't real proof, just an indication). And this says pretty much the same as I have. If I find anything more substancial, I'll add it.

Edit: It seems Java 7 support has been added since I originally wrote this answer; check the answer by Sergii Pechenizkyi.

When should I use a List vs a LinkedList

Linked lists provide very fast insertion or deletion of a list member. Each member in a linked list contains a pointer to the next member in the list so to insert a member at position i:

  • update the pointer in member i-1 to point to the new member
  • set the pointer in the new member to point to member i

The disadvantage to a linked list is that random access is not possible. Accessing a member requires traversing the list until the desired member is found.

Validate phone number using angular js

An even cleaner and more professional look I have found is to use AngularUI Mask. Very simple to implement and the mask can be customized for other inputs as well. Then a simple required validation is all you need.

https://angular-ui.github.io/

How to get value by key from JObject?

Try this:

private string GetJArrayValue(JObject yourJArray, string key)
{
    foreach (KeyValuePair<string, JToken> keyValuePair in yourJArray)
    {
        if (key == keyValuePair.Key)
        {
            return keyValuePair.Value.ToString();
        }
    }
}

Public free web services for testing soap client

There is a bunch on here:

http://www.webservicex.net/WS/wscatlist.aspx

Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.

Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.

Is there a method that tells my program to quit?

Please note that the solutions based on sys.exit() or any Exception may not work in a multi-threaded environment.

Since exit() ultimately “only” raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted. (doc)

This answer from Alex Martelli for more details.

SQLAlchemy: What's the difference between flush() and commit()?

Why flush if you can commit?

As someone new to working with databases and sqlalchemy, the previous answers - that flush() sends SQL statements to the DB and commit() persists them - were not clear to me. The definitions make sense but it isn't immediately clear from the definitions why you would use a flush instead of just committing.

Since a commit always flushes (https://docs.sqlalchemy.org/en/13/orm/session_basics.html#committing) these sound really similar. I think the big issue to highlight is that a flush is not permanent and can be undone, whereas a commit is permanent, in the sense that you can't ask the database to undo the last commit (I think)

@snapshoe highlights that if you want to query the database and get results that include newly added objects, you need to have flushed first (or committed, which will flush for you). Perhaps this is useful for some people although I'm not sure why you would want to flush rather than commit (other than the trivial answer that it can be undone).

In another example I was syncing documents between a local DB and a remote server, and if the user decided to cancel, all adds/updates/deletes should be undone (i.e. no partial sync, only a full sync). When updating a single document I've decided to simply delete the old row and add the updated version from the remote server. It turns out that due to the way sqlalchemy is written, order of operations when committing is not guaranteed. This resulted in adding a duplicate version (before attempting to delete the old one), which resulted in the DB failing a unique constraint. To get around this I used flush() so that order was maintained, but I could still undo if later the sync process failed.

See my post on this at: Is there any order for add versus delete when committing in sqlalchemy

Similarly, someone wanted to know whether add order is maintained when committing, i.e. if I add object1 then add object2, does object1 get added to the database before object2 Does SQLAlchemy save order when adding objects to session?

Again, here presumably the use of a flush() would ensure the desired behavior. So in summary, one use for flush is to provide order guarantees (I think), again while still allowing yourself an "undo" option that commit does not provide.

Autoflush and Autocommit

Note, autoflush can be used to ensure queries act on an updated database as sqlalchemy will flush before executing the query. https://docs.sqlalchemy.org/en/13/orm/session_api.html#sqlalchemy.orm.session.Session.params.autoflush

Autocommit is something else that I don't completely understand but it sounds like its use is discouraged: https://docs.sqlalchemy.org/en/13/orm/session_api.html#sqlalchemy.orm.session.Session.params.autocommit

Memory Usage

Now the original question actually wanted to know about the impact of flush vs. commit for memory purposes. As the ability to persist or not is something the database offers (I think), simply flushing should be sufficient to offload to the database - although committing shouldn't hurt (actually probably helps - see below) if you don't care about undoing.

sqlalchemy uses weak referencing for objects that have been flushed: https://docs.sqlalchemy.org/en/13/orm/session_state_management.html#session-referencing-behavior

This means if you don't have an object explicitly held onto somewhere, like in a list or dict, sqlalchemy won't keep it in memory.

However, then you have the database side of things to worry about. Presumably flushing without committing comes with some memory penalty to maintain the transaction. Again, I'm new to this but here's a link that seems to suggest exactly this: https://stackoverflow.com/a/15305650/764365

In other words, commits should reduce memory usage, although presumably there is a trade-off between memory and performance here. In other words, you probably don't want to commit every single database change, one at a time (for performance reasons), but waiting too long will increase memory usage.

Can I force a page break in HTML printing?

_x000D_
_x000D_
First page (scroll down to see the second page)_x000D_
<div style="break-after:page"></div>_x000D_
Second page_x000D_
<br>_x000D_
<br>_x000D_
<button onclick="window.print();return false;" />Print (to see the result) </button>
_x000D_
_x000D_
_x000D_

Just add this where you need the page to go to the next one (the text "page 1" will be on page 1 and the text "page 2" will be on the second page).

Page 1
<div style='page-break-after:always'></div>
Page 2

This works too:

First page (there is a break after this)
<div style="break-after:page"></div>
Second page (This will be printed in the second page)

How to Install gcc 5.3 with yum on CentOS 7.2?

You can use the centos-sclo-rh-testing repo to install GCC v7 without having to compile it forever, also enable V7 by default and let you switch between different versions if required.

sudo yum install -y yum-utils centos-release-scl;
sudo yum -y --enablerepo=centos-sclo-rh-testing install devtoolset-7-gcc;
echo "source /opt/rh/devtoolset-7/enable" | sudo tee -a /etc/profile;
source /opt/rh/devtoolset-7/enable;
gcc --version;

Style jQuery autocomplete in a Bootstrap input field

I don't know if you fixed it, but I did had the same issue, finally it was a dumb thing, I had:

<script src="jquery-ui/jquery-ui.min.css" rel="stylesheet">

but it should be:

<link href="jquery-ui/jquery-ui.min.css" rel="stylesheet">

Just change <scrip> to <link> and src to href

Endless loop in C/C++

Is there a certain form which one should choose?

You can choose either. Its matter of choice. All are equivalent. while(1) {}/while(true){} is frequently used for infinite loop by programmers.

Git: How to remove proxy

git config --global --unset http.proxy
git config --unset http.proxy
http_proxy=""

C pointer to array/array of pointers disambiguation

In pointer to an integer if pointer is incremented then it goes next integer.

in array of pointer if pointer is incremented it jumps to next array

How to fill in proxy information in cntlm config file?

Without any configuration, you can simply issue the following command (modifying myusername and mydomain with your own information):

cntlm -u myusername -d mydomain -H

or

cntlm -u myusername@mydomain -H

It will ask you the password of myusername and will give you the following output:

PassLM          1AD35398BE6565DDB5C4EF70C0593492
PassNT          77B9081511704EE852F94227CF48A793
PassNTLMv2      A8FC9092D566461E6BEA971931EF1AEC    # Only for user 'myusername', domain 'mydomain'

Then create the file cntlm.ini (or cntlm.conf on Linux using default path) with the following content (replacing your myusername, mydomain and A8FC9092D566461E6BEA971931EF1AEC with your information and the result of the previous command):

Username    myusername
Domain      mydomain

Proxy       my_proxy_server.com:80
NoProxy     127.0.0.*, 192.168.*

Listen      127.0.0.1:5865
Gateway     yes

SOCKS5Proxy 5866

Auth        NTLMv2
PassNTLMv2  A8FC9092D566461E6BEA971931EF1AEC

Then you will have a local open proxy on local port 5865 and another one understanding SOCKS5 protocol at local port 5866.

Caesar Cipher Function in Python

Batteries included

while 1:
    phrase = raw_input("Could you please give me a phrase to encrypt?\n")
    if phrase == "" : break
    print "Here it is your phrase, encrypted:"
    print phrase.encode("rot_13")
print "Have a nice afternoon!"

https://docs.python.org/2/library/codecs.html#python-specific-encodings

Python 3 update

The fine docs say

[Now the rot_13] codec provides a text transform: a str to str mapping. It is not supported by str.encode() (which only produces bytes output).

Or, in other words, you have to import encode from the codecs module and use it with the string to be encoded as its first argument

from codecs import decode
...
    print(encode(phrase, 'rot13'))

How to read a CSV file into a .NET Datatable

Use this, one function solve all problems of comma and quote:

public static DataTable CsvToDataTable(string strFilePath)
    {

        if (File.Exists(strFilePath))
        {

            string[] Lines;
            string CSVFilePathName = strFilePath;

            Lines = File.ReadAllLines(CSVFilePathName);
            while (Lines[0].EndsWith(","))
            {
                Lines[0] = Lines[0].Remove(Lines[0].Length - 1);
            }
            string[] Fields;
            Fields = Lines[0].Split(new char[] { ',' });
            int Cols = Fields.GetLength(0);
            DataTable dt = new DataTable();
            //1st row must be column names; force lower case to ensure matching later on.
            for (int i = 0; i < Cols; i++)
                dt.Columns.Add(Fields[i], typeof(string));
            DataRow Row;
            int rowcount = 0;
            try
            {
                string[] ToBeContinued = new string[]{};
                bool lineToBeContinued = false;
                for (int i = 1; i < Lines.GetLength(0); i++)
                {
                    if (!Lines[i].Equals(""))
                    {
                        Fields = Lines[i].Split(new char[] { ',' });
                        string temp0 = string.Join("", Fields).Replace("\"\"", "");
                        int quaotCount0 = temp0.Count(c => c == '"');
                        if (Fields.GetLength(0) < Cols || lineToBeContinued || quaotCount0 % 2 != 0)
                        {
                            if (ToBeContinued.GetLength(0) > 0)
                            {
                                ToBeContinued[ToBeContinued.Length - 1] += "\n" + Fields[0];
                                Fields = Fields.Skip(1).ToArray();
                            }
                            string[] newArray = new string[ToBeContinued.Length + Fields.Length];
                            Array.Copy(ToBeContinued, newArray, ToBeContinued.Length);
                            Array.Copy(Fields, 0, newArray, ToBeContinued.Length, Fields.Length);
                            ToBeContinued = newArray;
                            string temp = string.Join("", ToBeContinued).Replace("\"\"", "");
                            int quaotCount = temp.Count(c => c == '"');
                            if (ToBeContinued.GetLength(0) >= Cols && quaotCount % 2 == 0 )
                            {
                                Fields = ToBeContinued;
                                ToBeContinued = new string[] { };
                                lineToBeContinued = false;
                            }
                            else
                            {
                                lineToBeContinued = true;
                                continue;
                            }
                        }

                        //modified by Teemo @2016 09 13
                        //handle ',' and '"'
                        //Deserialize CSV following Excel's rule:
                        // 1: If there is commas in a field, quote the field.
                        // 2: Two consecutive quotes indicate a user's quote.

                        List<int> singleLeftquota = new List<int>();
                        List<int> singleRightquota = new List<int>();

                        //combine fileds if number of commas match
                        if (Fields.GetLength(0) > Cols) 
                        {
                            bool lastSingleQuoteIsLeft = true;
                            for (int j = 0; j < Fields.GetLength(0); j++)
                            {
                                bool leftOddquota = false;
                                bool rightOddquota = false;
                                if (Fields[j].StartsWith("\"")) 
                                {
                                    int numberOfConsecutiveQuotes = 0;
                                    foreach (char c in Fields[j]) //start with how many "
                                    {
                                        if (c == '"')
                                        {
                                            numberOfConsecutiveQuotes++;
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }
                                    if (numberOfConsecutiveQuotes % 2 == 1)//start with odd number of quotes indicate system quote
                                    {
                                        leftOddquota = true;
                                    }
                                }

                                if (Fields[j].EndsWith("\""))
                                {
                                    int numberOfConsecutiveQuotes = 0;
                                    for (int jj = Fields[j].Length - 1; jj >= 0; jj--)
                                    {
                                        if (Fields[j].Substring(jj,1) == "\"") // end with how many "
                                        {
                                            numberOfConsecutiveQuotes++;
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }

                                    if (numberOfConsecutiveQuotes % 2 == 1)//end with odd number of quotes indicate system quote
                                    {
                                        rightOddquota = true;
                                    }
                                }
                                if (leftOddquota && !rightOddquota)
                                {
                                    singleLeftquota.Add(j);
                                    lastSingleQuoteIsLeft = true;
                                }
                                else if (!leftOddquota && rightOddquota)
                                {
                                    singleRightquota.Add(j);
                                    lastSingleQuoteIsLeft = false;
                                }
                                else if (Fields[j] == "\"") //only one quota in a field
                                {
                                    if (lastSingleQuoteIsLeft)
                                    {
                                        singleRightquota.Add(j);
                                    }
                                    else
                                    {
                                        singleLeftquota.Add(j);
                                    }
                                }
                            }
                            if (singleLeftquota.Count == singleRightquota.Count)
                            {
                                int insideCommas = 0;
                                for (int indexN = 0; indexN < singleLeftquota.Count; indexN++)
                                {
                                    insideCommas += singleRightquota[indexN] - singleLeftquota[indexN];
                                }
                                if (Fields.GetLength(0) - Cols >= insideCommas) //probabaly matched
                                {
                                    int validFildsCount = insideCommas + Cols; //(Fields.GetLength(0) - insideCommas) may be exceed the Cols
                                    String[] temp = new String[validFildsCount];
                                    int totalOffSet = 0;
                                    for (int iii = 0; iii < validFildsCount - totalOffSet; iii++)
                                    {
                                        bool combine = false;
                                        int storedIndex = 0;
                                        for (int iInLeft = 0; iInLeft < singleLeftquota.Count; iInLeft++)
                                        {
                                            if (iii + totalOffSet == singleLeftquota[iInLeft])
                                            {
                                                combine = true;
                                                storedIndex = iInLeft;
                                                break;
                                            }
                                        }
                                        if (combine)
                                        {
                                            int offset = singleRightquota[storedIndex] - singleLeftquota[storedIndex];
                                            for (int combineI = 0; combineI <= offset; combineI++)
                                            {
                                                temp[iii] += Fields[iii + totalOffSet + combineI] + ",";
                                            }
                                            temp[iii] = temp[iii].Remove(temp[iii].Length - 1, 1);
                                            totalOffSet += offset;
                                        }
                                        else
                                        {
                                            temp[iii] = Fields[iii + totalOffSet];
                                        }
                                    }
                                    Fields = temp;
                                }
                            }
                        }
                        Row = dt.NewRow();
                        for (int f = 0; f < Cols; f++)
                        {
                            Fields[f] = Fields[f].Replace("\"\"", "\""); //Two consecutive quotes indicate a user's quote
                            if (Fields[f].StartsWith("\""))
                            {
                                if (Fields[f].EndsWith("\""))
                                {
                                    Fields[f] = Fields[f].Remove(0, 1);
                                    if (Fields[f].Length > 0)
                                    {
                                        Fields[f] = Fields[f].Remove(Fields[f].Length - 1, 1);
                                    }
                                }
                            }
                            Row[f] = Fields[f];
                        }
                        dt.Rows.Add(Row);
                        rowcount++;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception( "row: " + (rowcount+2) + ", " + ex.Message);
            }
            //OleDbConnection connection = new OleDbConnection(string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}; Extended Properties=""text;HDR=Yes;FMT=Delimited"";", FilePath + FileName));
            //OleDbCommand command = new OleDbCommand("SELECT * FROM " + FileName, connection);
            //OleDbDataAdapter adapter = new OleDbDataAdapter(command);
            //DataTable dt = new DataTable();
            //adapter.Fill(dt);
            //adapter.Dispose();
            return dt;
        }
        else
            return null;

        //OleDbConnection connection = new OleDbConnection(string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}; Extended Properties=""text;HDR=Yes;FMT=Delimited"";", strFilePath));
        //OleDbCommand command = new OleDbCommand("SELECT * FROM " + strFileName, connection);
        //OleDbDataAdapter adapter = new OleDbDataAdapter(command);
        //DataTable dt = new DataTable();
        //adapter.Fill(dt);
        //return dt;
    }

What is an uber jar?

Über is the German word for above or over (it's actually cognate with the English over).

Hence, in this context, an uber-jar is an "over-jar", one level up from a simple JAR (a), defined as one that contains both your package and all its dependencies in one single JAR file. The name can be thought to come from the same stable as ultrageek, superman, hyperspace, and metadata, which all have similar meanings of "beyond the normal".

The advantage is that you can distribute your uber-jar and not care at all whether or not dependencies are installed at the destination, as your uber-jar actually has no dependencies.

All the dependencies of your own stuff within the uber-jar are also within that uber-jar. As are all dependencies of those dependencies. And so on.


(a) I probably shouldn't have to explain what a JAR is to a Java developer but I'll include it for completeness. It's a Java archive, basically a single file that typically contains a number of Java class files along with associated metadata and resources.

Jenkins / Hudson environment variables

I have Jenkins 1.639 installed on SLES 11 SP3 via zypper (the package manager). Installation configured jenkins as a service

 # service jenkins
 Usage: /etc/init.d/jenkins {start|stop|status|try-restart|restart|force-reload|reload|probe}

Although /etc/init.d/jenkins sources /etc/sysconfig/jenkins, any env variables set there are not inherited by the jenkins process because it is started in a separate login shell with a new environment like this:

startproc -n 0 -s -e -l /var/log/jenkins.rc -p /var/run/jenkins.pid -t 1 /bin/su -l -s /bin/bash -c '/usr/java/default/bin/java -Djava.awt.headless=true -DJENKINS_HOME=/var/lib/jenkins -jar /usr/lib/jenkins/jenkins.war --javaHome=/usr/java/default --logfile=/var/log/jenkins/jenkins.log --webroot=/var/cache/jenkins/war --httpPort=8080 --ajp13Port=8009 --debug=9 --handlerCountMax=100 --handlerCountMaxIdle=20 &' jenkins

The way I managed to set env vars for the jenkins process is via .bashrc in its home directory - /var/lib/jenkins. I had to create /var/lib/jenkins/.bashrc as it did not exist before.

Is a LINQ statement faster than a 'foreach' loop?

LINQ-to-Objects generally is going to add some marginal overheads (multiple iterators, etc). It still has to do the loops, and has delegate invokes, and will generally have to do some extra dereferencing to get at captured variables etc. In most code this will be virtually undetectable, and more than afforded by the simpler to understand code.

With other LINQ providers like LINQ-to-SQL, then since the query can filter at the server it should be much better than a flat foreach, but most likely you wouldn't have done a blanket "select * from foo" anyway, so that isn't necessarily a fair comparison.

Re PLINQ; parallelism may reduce the elapsed time, but the total CPU time will usually increase a little due to the overheads of thread management etc.

What is the difference between window, screen, and document in Javascript?

Window is the main JavaScript object root, aka the global object in a browser, also can be treated as the root of the document object model. You can access it as window

window.screen or just screen is a small information object about physical screen dimensions.

window.document or just document is the main object of the potentially visible (or better yet: rendered) document object model/DOM.

Since window is the global object you can reference any properties of it with just the property name - so you do not have to write down window. - it will be figured out by the runtime.

Maven: How to run a .java file from command line passing arguments

You could run: mvn exec:exec -Dexec.args="arg1".

This will pass the argument arg1 to your program.

You should specify the main class fully qualified, for example, a Main.java that is in a package test would need

mvn exec:java  -Dexec.mainClass=test.Main

By using the -f parameter, as decribed here, you can also run it from other directories.

mvn exec:java -Dexec.mainClass=test.Main -f folder/pom.xm

For multiple arguments, simply separate them with a space as you would at the command line.

mvn exec:java -Dexec.mainClass=test.Main -Dexec.args="arg1 arg2 arg3"

For arguments separated with a space, you can group using 'argument separated with space' inside the quotation marks.

mvn exec:java -Dexec.mainClass=test.Main -Dexec.args="'argument separated with space' 'another one'"

How to remove a newline from a string in Bash

Using bash:

echo "|${COMMAND/$'\n'}|"

(Note that the control character in this question is a 'newline' (\n), not a carriage return (\r); the latter would have output REBOOT| on a single line.)

Explanation

Uses the Bash Shell Parameter Expansion ${parameter/pattern/string}:

The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. [...] If string is null, matches of pattern are deleted and the / following pattern may be omitted.

Also uses the $'' ANSI-C quoting construct to specify a newline as $'\n'. Using a newline directly would work as well, though less pretty:

echo "|${COMMAND/
}|"

Full example

#!/bin/bash
COMMAND="$'\n'REBOOT"
echo "|${COMMAND/$'\n'}|"
# Outputs |REBOOT|

Or, using newlines:

#!/bin/bash
COMMAND="
REBOOT"
echo "|${COMMAND/
}|"
# Outputs |REBOOT|

Android "elevation" not showing a shadow

Ugh, just spent an hour trying to figure this out. In my case I had a background set, however it was set to a color. This is not enough, you need to have the background of the view set to a drawable.

e.g. This won't have a shadow:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="165dp"
    android:background="@color/ight_grey"
    android:elevation="20dp"
    android:orientation="vertical"
    />

but this will

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="165dp"
    android:background="@drawable/selector_grey"
    android:elevation="20dp"
    android:orientation="vertical"
    />

EDIT: Have also discovered that if you use a selector as a background, if you don't have the corner set then the shadow won't show up in the Preview window but it will show up on the device

e.g. This doesn't have a shadow in preview:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/white" />
            <stroke
                android:width="1dp"
                android:color="@color/grey"/>
        </shape>
    </item>
</selector>

but this does:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/white" />
            <corners android:radius="1dp" />
            <stroke
                android:width="1dp"
                android:color="@color/grey"/>
        </shape>
    </item>
</selector>

JavaScript unit test tools for TDD

You should have a look at env.js. See my blog for an example how to write unit tests with env.js.

How to avoid the "divide by zero" error in SQL?

This is how I fixed it:

IIF(ValueA != 0, Total / ValueA, 0)

It can be wrapped in an update:

SET Pct = IIF(ValueA != 0, Total / ValueA, 0)

Or in a select:

SELECT IIF(ValueA != 0, Total / ValueA, 0) AS Pct FROM Tablename;

Thoughts?

How do I connect to this localhost from another computer on the same network?

This tool saved me a lot, since I have no Admin permission on my machine and already had nodejs installed. For some reason the configuration on my network does not give me access to other machines just pointing the IP on the browser.

# Using a local.dev vhost
$ browser-sync start --proxy

# Using a local.dev vhost with PORT
$ browser-sync start --proxy local.dev:8001

# Using a localhost address
$ browser-sync start --proxy localhost:8001

# Using a localhost address in a sub-dir
$ browser-sync start --proxy localhost:8080/site1

http://www.browsersync.io/docs/command-line/

Where is the Global.asax.cs file?

That's because you created a Web Site instead of a Web Application. The cs/vb files can only be seen in a Web Application, but in a website you can't have a separate cs/vb file.

Edit: In the website you can add a cs file behavior like..

<%@ Application CodeFile="Global.asax.cs" Inherits="ApplicationName.MyApplication" Language="C#" %>

~/Global.asax.cs:

namespace ApplicationName
{
    public partial class MyApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
        }
    }
}

Printing hexadecimal characters in C

You are seeing the ffffff because char is signed on your system. In C, vararg functions such as printf will promote all integers smaller than int to int. Since char is an integer (8-bit signed integer in your case), your chars are being promoted to int via sign-extension.

Since c0 and 80 have a leading 1-bit (and are negative as an 8-bit integer), they are being sign-extended while the others in your sample don't.

char    int
c0 -> ffffffc0
80 -> ffffff80
61 -> 00000061

Here's a solution:

char ch = 0xC0;
printf("%x", ch & 0xff);

This will mask out the upper bits and keep only the lower 8 bits that you want.

OR is not supported with CASE Statement in SQL Server

CASE
  WHEN ebv.db_no = 22978 OR 
       ebv.db_no = 23218 OR
       ebv.db_no = 23219
  THEN 'WECS 9500' 
  ELSE 'WECS 9520' 
END as wecs_system 

How to access SOAP services from iPhone

My solution was to have a proxy server accept REST, issue the SOAP request, and return result, using PHP.

Time to implement: 15-30 minutes.

Not most elegant, but solid.

How do I combine two lists into a dictionary in Python?

dict(zip([1,2,3,4], [a,b,c,d]))

If the lists are big you should use itertools.izip.

If you have more keys than values, and you want to fill in values for the extra keys, you can use itertools.izip_longest.

Here, a, b, c, and d are variables -- it will work fine (so long as they are defined), but you probably meant ['a','b','c','d'] if you want them as strings.

zip takes the first item from each iterable and makes a tuple, then the second item from each, etc. etc.

dict can take an iterable of iterables, where each inner iterable has two items -- it then uses the first as the key and the second as the value for each item.

Generate insert script for selected records?

You could create a view with your criteria and then export the view?

Force sidebar height 100% using CSS (with a sticky bottom image)?

This worked for me

.container { 
  overflow: hidden; 
  .... 
} 

#sidebar { 
  margin-bottom: -5000px; /* any large number will do */
  padding-bottom: 5000px; 
  .... 
} 

Regex in JavaScript for validating decimal numbers

as compared from the answer gven by mic... it doesnt validate anything in some of the platforms which i work upon... to be precise it doesnt actually work out in Dream Viewer..

hereby.. i re-write it again..which will work on any platform.. "^[0-9]+(.[0-9]{1,2})?$".. thnkss..

Styling JQuery UI Autocomplete

Are you looking for this selector?:

.ui-menu .ui-menu-item a{
    background:red;
    height:10px;
    font-size:8px;
}

Ugly demo:

http://jsfiddle.net/zeSTc/

Just replace with your code:

.ui-menu .ui-menu-item a{
    color: #96f226;
    border-radius: 0px;
    border: 1px solid #454545;
}

demo: http://jsfiddle.net/w5Dt2/

Call js-function using JQuery timer

jQuery 1.4 also includes a .delay( duration, [ queueName ] ) method if you only need it to trigger once and have already started using that version.

$('#foo').slideUp(300).delay(800).fadeIn(400);

http://api.jquery.com/delay/

Ooops....my mistake you were looking for an event to continue triggering. I'll leave this here, someone may find it helpful.

RESTful API methods; HEAD & OPTIONS

OPTIONS tells you things such as "What methods are allowed for this resource".

HEAD gets the HTTP header you would get if you made a GET request, but without the body. This lets the client determine caching information, what content-type would be returned, what status code would be returned. The availability is only a small part of it.

How do I access properties of a javascript object if I don't know the names?

var attr, object_information='';

for(attr in object){

      //Get names and values of propertys with style (name : value)
      object_information += attr + ' : ' + object[attr] + '\n'; 

   }


alert(object_information); //Show all Object

javascript: pause setTimeout();

Typescript implementation based on top rated answer

/** Represents the `setTimeout` with an ability to perform pause/resume actions */
export class Timer {
    private _start: Date;
    private _remaining: number;
    private _durationTimeoutId?: NodeJS.Timeout;
    private _callback: (...args: any[]) => void;
    private _done = false;
    get done () {
        return this._done;
    }

    constructor(callback: (...args: any[]) => void, ms = 0) {
        this._callback = () => {
            callback();
            this._done = true;
        };
        this._remaining = ms;
        this.resume();
    }

    /** pauses the timer */
    pause(): Timer {
        if (this._durationTimeoutId && !this._done) {
            this._clearTimeoutRef();
            this._remaining -= new Date().getTime() - this._start.getTime();
        }
        return this;
    }

    /** resumes the timer */
    resume(): Timer {
        if (!this._durationTimeoutId && !this._done) {
            this._start = new Date;
            this._durationTimeoutId = setTimeout(this._callback, this._remaining);
        }
        return this;
    }

    /** 
     * clears the timeout and marks it as done. 
     * 
     * After called, the timeout will not resume
     */
    clearTimeout() {
        this._clearTimeoutRef();
        this._done = true;
    }

    private _clearTimeoutRef() {
        if (this._durationTimeoutId) {
            clearTimeout(this._durationTimeoutId);
            this._durationTimeoutId = undefined;
        }
    }

}

Actionbar notification count icon (badge) like Google has

I don't like ActionView based solutions, my idea is:

  1. create a layout with TextView, that TextView will be populated by application
  2. when you need to draw a MenuItem:

    2.1. inflate layout

    2.2. call measure() & layout() (otherwise view will be 0px x 0px, it's too small for most use cases)

    2.3. set the TextView's text

    2.4. make "screenshot" of the view

    2.6. set MenuItem's icon based on bitmap created on 2.4

  3. profit!

so, result should be something like enter image description here

  1. create layout here is a simple example
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/counterPanel"
    android:layout_width="32dp"
    android:layout_height="32dp"
    android:background="@drawable/ic_menu_gallery">
    <RelativeLayout
        android:id="@+id/counterValuePanel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <ImageView
            android:id="@+id/counterBackground"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/unread_background" />

        <TextView
            android:id="@+id/count"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="1"
            android:textSize="8sp"
            android:layout_centerInParent="true"
            android:textColor="#FFFFFF" />
    </RelativeLayout>
</FrameLayout>

@drawable/unread_background is that green TextView's background, @drawable/ic_menu_gallery is not really required here, it's just to preview layout's result in IDE.

  1. add code into onCreateOptionsMenu/onPrepareOptionsMenu

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
    
        MenuItem menuItem = menu.findItem(R.id.testAction);
        menuItem.setIcon(buildCounterDrawable(count, R.drawable.ic_menu_gallery));
    
        return true;
    }
    
  2. Implement build-the-icon method:

    private Drawable buildCounterDrawable(int count, int backgroundImageId) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.counter_menuitem_layout, null);
        view.setBackgroundResource(backgroundImageId);
    
        if (count == 0) {
            View counterTextPanel = view.findViewById(R.id.counterValuePanel);
            counterTextPanel.setVisibility(View.GONE);
        } else {
            TextView textView = (TextView) view.findViewById(R.id.count);
            textView.setText("" + count);
        }
    
        view.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
    
        view.setDrawingCacheEnabled(true);
        view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
        Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
        view.setDrawingCacheEnabled(false);
    
        return new BitmapDrawable(getResources(), bitmap);
    }
    

The complete code is here: https://github.com/cvoronin/ActionBarMenuItemCounter

ASP.NET Bundles how to disable minification

Search for EnableOptimizations keyword in your project

So if you find

BundleTable.EnableOptimizations = true;

turn it false.

This does disable minification, And it also disables bundling entirely

Convert int (number) to string with leading zeros? (4 digits)

Use the formatting options available to you, use the Decimal format string. It is far more flexible and requires little to no maintenance compared to direct string manipulation.

To get the string representation using at least 4 digits:

int length = 4;
int number = 50;
string asString = number.ToString("D" + length); //"0050"

LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1

Using domain Name may solve the problem (get domain name using powershell: $env:userdomain):

    Hashtable<String, Object> env = new Hashtable<String, Object>();
    String principalName = "domainName\\userName";
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://URL:389/OU=ou-xx,DC=fr,DC=XXXXXX,DC=com");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, principalName);
    env.put(Context.SECURITY_CREDENTIALS, "Your Password");

    try {
        DirContext authContext = new InitialDirContext(env);
        // user is authenticated
        System.out.println("USER IS AUTHETICATED");
    } catch (AuthenticationException ex) {
        // Authentication failed
        System.out.println("AUTH FAILED : " + ex);

    } catch (NamingException ex) {
        ex.printStackTrace();
    }

Add Favicon to Website

  1. This is not done in PHP. It's part of the <head> tags in a HTML page.
  2. That icon is called a favicon. According to Wikipedia:

    A favicon (short for favorites icon), also known as a shortcut icon, website icon, URL icon, or bookmark icon is a 16×16 or 32×32 pixel square icon associated with a particular website or webpage.

  3. Adding it is easy. Just add an .ico image file that is either 16x16 pixels or 32x32 pixels. Then, in the web pages, add <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"> to the <head> element.
  4. You can easily generate favicons here.

How do I adb pull ALL files of a folder present in SD Card

Single File/Folder using pull:

adb pull "/sdcard/Folder1"

Output:

adb pull "/sdcard/Folder1"
pull: building file list...
pull: /sdcard/Folder1/image1.jpg -> ./image1.jpg
pull: /sdcard/Folder1/image2.jpg -> ./image2.jpg
pull: /sdcard/Folder1/image3.jpg -> ./image3.jpg
3 files pulled. 0 files skipped.

Specific Files/Folders using find from BusyBox:

adb shell find "/sdcard/Folder1" -iname "*.jpg" | tr -d '\015' | while read line; do adb pull "$line"; done;

Here is an explanation:

adb shell find "/sdcard/Folder1" - use the find command, use the top folder
-iname "*.jpg"                   - filter the output to only *.jpg files
|                                - passes data(output) from one command to another
tr -d '\015'                     - explained here: http://stackoverflow.com/questions/9664086/bash-is-removing-commands-in-while
while read line;                 - while loop to read input of previous commands
do adb pull "$line"; done;         - pull the files into the current running directory, finish. The quotation marks around $line are required to work with filenames containing spaces.

The scripts will start in the top folder and recursively go down and find all the "*.jpg" files and pull them from your phone to the current directory.

What is the difference between Jupyter Notebook and JupyterLab?

If you are looking for features that notebooks in JupyterLab have that traditional Jupyter Notebooks do not, check out the JupyterLab notebooks documentation. There is a simple video showing how to use each of the features in the documentation link.

JupyterLab notebooks have the following features and more:

  • Drag and drop cells to rearrange your notebook
  • Drag cells between notebooks to quickly copy content (since you can
    have more than one open at a time)
  • Create multiple synchronized views of a single notebook
  • Themes and customizations: Dark theme and increase code font size

Visual Studio move project to a different folder

It's easy in VS2012; just use the change mapping feature:

  1. Create the folder where you want the solution to be moved to.
  2. Check-in all your project files (if you want to keep you changes), or rollback any checked out files.
  3. Close the solution.
  4. Open the Source Control Explorer.
  5. Right-click the solution, and select "Advanced -> Remove Mapping..."
  6. Change the "Local Folder" value to the one you created in step #1.
  7. Select "Change".
  8. Open the solution by double-clicking it in the source control explorer.