SyntaxFix.com - Programming Questions & Answers Hub For Beginners


Some Of The Best Answers From Latest Asked Questions

Does a VPN Hide my Location on Android?

Your question can be conveniently divided into several parts:

Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.

How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.

You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):

  1. Download and install a trusted VPN.

  2. Install the VPN on your Android device.

  3. Open the application and connect to a server in a different country.

  4. Your Android location will now be successfully changed!

Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.

Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.

How do I get the find command to print out the file size with the file name?

I struggled with this on Mac OS X where the find command doesn't support -printf.

A solution that I found, that admittedly relies on the 'group' for all files being 'staff' was...

ls -l -R | sed 's/\(.*\)staff *\([0-9]*\)..............\(.*\)/\2 \3/'

This splits the ls long output into three tokens

  1. the stuff before the text 'staff'
  2. the file size
  3. the file name

And then outputs tokens 2 and 3, i.e. output is number of bytes and then filename

8071 sections.php
54681 services.php
37961 style.css
13260 thumb.php
70951 workshops.php

What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

It's worth noting some other things:

  1. As shown in Windows Explorer Properties dialog for the generated assembly file, there are two places called "File version". The one seen in the header of the dialog shows the AssemblyVersion, not the AssemblyFileVersion.

    In the Other version information section, there is another element called "File Version". This is where you can see what was entered as the AssemblyFileVersion.

  2. AssemblyFileVersion is just plain text. It doesn't have to conform to the numbering scheme restrictions that AssemblyVersion does (<build> < 65K, e.g.). It can be 3.2.<release tag text>.<datetime>, if you like. Your build system will have to fill in the tokens.

    Moreover, it is not subject to the wildcard replacement that AssemblyVersion is. If you just have a value of "3.0.1.*" in the AssemblyInfo.cs, that is exactly what will show in the Other version information->File Version element.

  3. I don't know the impact upon an installer of using something other than numeric file version numbers, though.

Sending mail from Python using SMTP

Here's a working example for Python 3.x

#!/usr/bin/env python3

from email.message import EmailMessage
from getpass import getpass
from smtplib import SMTP_SSL
from sys import exit

smtp_server = 'smtp.gmail.com'
username = '[email protected]'
password = getpass('Enter Gmail password: ')

sender = '[email protected]'
destination = '[email protected]'
subject = 'Sent from Python 3.x'
content = 'Hello! This was sent to you via Python 3.x!'

# Create a text/plain message
msg = EmailMessage()
msg.set_content(content)

msg['Subject'] = subject
msg['From'] = sender
msg['To'] = destination

try:
    s = SMTP_SSL(smtp_server)
    s.login(username, password)
    try:
        s.send_message(msg)
    finally:
        s.quit()

except Exception as E:
    exit('Mail failed: {}'.format(str(E)))

WinForms DataGridView font size

    private void UpdateFont()
    {
        //Change cell font
        foreach(DataGridViewColumn c in dgAssets.Columns)
        {
            c.DefaultCellStyle.Font = new Font("Arial", 8.5F, GraphicsUnit.Pixel);
        }
    }

Setting java locale settings

With the user.language, user.country and user.variant properties.

Example:

java -Duser.language=th -Duser.country=TH -Duser.variant=TH SomeClass

How do you make a deep copy of an object?

For complicated objects and when performance is not significant i use a json library, like gson to serialize the object to json text, then deserialize the text to get new object.

gson which based on reflection will works in most cases, except that transient fields will not be copied and objects with circular reference with cause StackOverflowError.

public static <T> T copy(T anObject, Class<T> classInfo) {
    Gson gson = new GsonBuilder().create();
    String text = gson.toJson(anObject);
    T newObject = gson.fromJson(text, classInfo);
    return newObject;
}
public static void main(String[] args) {
    String originalObject = "hello";
    String copiedObject = copy(originalObject, String.class);
}

How do I use PHP to get the current year?

use a PHP function which is just called date().

It takes the current date and then you provide a format to it

and the format is just going to be Y. Capital Y is going to be a four digit year.

<?php echo date("Y"); ?>

Equivalent of *Nix 'which' command in PowerShell?

I like Get-Command | Format-List, or shorter, using aliases for the two and only for powershell.exe:

gcm powershell | fl

You can find aliases like this:

alias -definition Format-List

Tab completion works with gcm.

WPF Data Binding and Validation Rules Best Practices

I think the new preferred way might be to use IDataErrorInfo

Read more here

How do I perform an IF...THEN in an SQL SELECT?

The case statement is your friend in this situation, and takes one of two forms:

The simple case:

SELECT CASE <variable> WHEN <value>      THEN <returnvalue>
                       WHEN <othervalue> THEN <returnthis>
                                         ELSE <returndefaultcase>
       END AS <newcolumnname>
FROM <table>

The extended case:

SELECT CASE WHEN <test>      THEN <returnvalue>
            WHEN <othertest> THEN <returnthis>
                             ELSE <returndefaultcase>
       END AS <newcolumnname>
FROM <table>

You can even put case statements in an order by clause for really fancy ordering.

SQL: Select columns with NULL values only

An updated version of 'user2466387' version, with an additional small test which can improve performance, because it's useless to test non nullable columns:

AND IS_NULLABLE = 'YES'

The full code:

SET NOCOUNT ON;

DECLARE
 @ColumnName sysname
,@DataType nvarchar(128)
,@cmd nvarchar(max)
,@TableSchema nvarchar(128) = 'dbo'
,@TableName sysname = 'TableName';

DECLARE getinfo CURSOR FOR
SELECT
     c.COLUMN_NAME
    ,c.DATA_TYPE
FROM
    INFORMATION_SCHEMA.COLUMNS AS c
WHERE
    c.TABLE_SCHEMA = @TableSchema
    AND c.TABLE_NAME = @TableName
    AND IS_NULLABLE = 'YES';

OPEN getinfo;

FETCH NEXT FROM getinfo INTO @ColumnName, @DataType;

WHILE @@FETCH_STATUS = 0
BEGIN
    SET @cmd = N'IF NOT EXISTS (SELECT * FROM ' + @TableSchema + N'.' + @TableName + N' WHERE [' + @ColumnName + N'] IS NOT NULL) RAISERROR(''' + @ColumnName + N' (' + @DataType + N')'', 0, 0) WITH NOWAIT;';
    EXECUTE (@cmd);

    FETCH NEXT FROM getinfo INTO @ColumnName, @DataType;
END;

CLOSE getinfo;
DEALLOCATE getinfo;

How to determine CPU and memory consumption from inside a process?

For Linux You can also use /proc/self/statm to get a single line of numbers containing key process memory information which is a faster thing to process than going through a long list of reported information as you get from proc/self/status

See http://man7.org/linux/man-pages/man5/proc.5.html

   /proc/[pid]/statm
          Provides information about memory usage, measured in pages.
          The columns are:

              size       (1) total program size
                         (same as VmSize in /proc/[pid]/status)
              resident   (2) resident set size
                         (same as VmRSS in /proc/[pid]/status)
              shared     (3) number of resident shared pages (i.e., backed by a file)
                         (same as RssFile+RssShmem in /proc/[pid]/status)
              text       (4) text (code)
              lib        (5) library (unused since Linux 2.6; always 0)
              data       (6) data + stack
              dt         (7) dirty pages (unused since Linux 2.6; always 0)

What's the best way to build a string of delimited items in Java?

In Java 8 you can use String.join():

List<String> list = Arrays.asList("foo", "bar", "baz");
String joined = String.join(" and ", list); // "foo and bar and baz"

Also have a look at this answer for a Stream API example.

Microsoft SQL Server 2005 service fails to start

I have seen something similar before when the account the SQL Server is set to run under does not have the required permission.

Tangentially, once it is installed, a common mistake is to change the login credentials from Windows Services, not from SQL Server Configuration Manager. Although they look the same, the SQL Server tool grants access to some registry keys that the Windows tool does not, which can cause a problem on service startup.

You can run Sysinternals RegMon/Sysinternals ProcessMon while the install is running, filtering by sqlsevr.exe and Failure messages to see if the account credentials are a problem.

Hope this helps

java.net.SocketException: Connection reset

Connection reset simply means that a TCP RST was received. This happens when your peer receives data that it can't process, and there can be various reasons for that.

The simplest is when you close the socket, and then write more data on the output stream. By closing the socket, you told your peer that you are done talking, and it can forget about your connection. When you send more data on that stream anyway, the peer rejects it with an RST to let you know it isn't listening.

In other cases, an intervening firewall or even the remote host itself might "forget" about your TCP connection. This could happen if you don't send any data for a long time (2 hours is a common time-out), or because the peer was rebooted and lost its information about active connections. Sending data on one of these defunct connections will cause a RST too.


Update in response to additional information:

Take a close look at your handling of the SocketTimeoutException. This exception is raised if the configured timeout is exceeded while blocked on a socket operation. The state of the socket itself is not changed when this exception is thrown, but if your exception handler closes the socket, and then tries to write to it, you'll be in a connection reset condition. setSoTimeout() is meant to give you a clean way to break out of a read() operation that might otherwise block forever, without doing dirty things like closing the socket from another thread.

Difference between binary semaphore and mutex

The answer may depend on the target OS. For example, at least one RTOS implementation I'm familiar with will allow multiple sequential "get" operations against a single OS mutex, so long as they're all from within the same thread context. The multiple gets must be replaced by an equal number of puts before another thread will be allowed to get the mutex. This differs from binary semaphores, for which only a single get is allowed at a time, regardless of thread contexts.

The idea behind this type of mutex is that you protect an object by only allowing a single context to modify the data at a time. Even if the thread gets the mutex and then calls a function that further modifies the object (and gets/puts the protector mutex around its own operations), the operations should still be safe because they're all happening under a single thread.

{
    mutexGet();  // Other threads can no longer get the mutex.

    // Make changes to the protected object.
    // ...

    objectModify();  // Also gets/puts the mutex.  Only allowed from this thread context.

    // Make more changes to the protected object.
    // ...

    mutexPut();  // Finally allows other threads to get the mutex.
}

Of course, when using this feature, you must be certain that all accesses within a single thread really are safe!

I'm not sure how common this approach is, or whether it applies outside of the systems with which I'm familiar. For an example of this kind of mutex, see the ThreadX RTOS.

How do I check if a given string is a legal/valid file name under Windows?

The question is are you trying to determine if a path name is a legal windows path, or if it's legal on the system where the code is running.? I think the latter is more important, so personally, I'd probably decompose the full path and try to use _mkdir to create the directory the file belongs in, then try to create the file.

This way you know not only if the path contains only valid windows characters, but if it actually represents a path that can be written by this process.

Getting PEAR to work on XAMPP (Apache/MySQL stack on Windows)

Try adding the drive letter:

include_path='.;c:\xampplite\php\pear\PEAR'

also verify that PEAR.php is actually there, it might be in \php\ instead:

include_path='.;c:\xampplite\php'

What is the best way to merge mp3 files?

I'd not heard of mp3wrap before. Looks great. I'm guessing someone's made it into a gui as well somewhere. But, just to respond to the original post, I've written a gui that does the COPY /b method. So, under the covers, nothing new under the sun, but the program is all about making the process less painful if you have a lot of files to merge...AND you don't want to re-encode AND each set of files to merge are the same bitrate. If you have that (and you're on Windows), check out Mp3Merge at: http://www.leighweb.com/david/mp3merge and see if that's what you're looking for.

How do I move a file (or folder) from one folder to another in TortoiseSVN?

From the command line, you can type svn mv path1 path2. This will create an add and a delete operation, but there's not really a way around that - as far as I know - in Subversion.

Ignore case in Python strings

import re
if re.match('tEXT', 'text', re.IGNORECASE):
    # is True

Should I use int or Int32

You shouldn't care. You should use int most of the time. It will help the porting of your program to a wider architecture in the future (currently int is an alias to System.Int32 but that could change). Only when the bit width of the variable matters (for instance: to control the layout in memory of a struct) you should use int32 and others (with the associated "using System;").

Deleting a file in VBA

An alternative way to code Brettski's answer, with which I otherwise agree entirely, might be

With New FileSystemObject
    If .FileExists(yourFilePath) Then
        .DeleteFile yourFilepath
    End If
End With

Same effect but fewer (well, none at all) variable declarations.

The FileSystemObject is a really useful tool and well worth getting friendly with. Apart from anything else, for text file writing it can actually sometimes be faster than the legacy alternative, which may surprise a few people. (In my experience at least, YMMV).

How to clone all remote branches in Git?

all the answers I saw here are valid but there is a much cleaner way to clone a repository and to pull all the branches at once.

When you clone a repository all the information of the branches is actually downloaded but the branches are hidden. With the command

$ git branch -a

you can show all the branches of the repository, and with the command

$ git checkout -b branchname origin/branchname

you can then "download" them manually one at a time.


However, when you want to clone a repo with a lot of branches all the ways illustrated are above are lengthy and tedious in respect to a much cleaner and quicker way that I am going to show, though it's a bit complicated. You need three steps to accomplish this:

  1. First step

create a new empty folder on your machine and clone a mirror copy of the .git folder from the repository:

$ cd ~/Desktop && mkdir my_repo_folder && cd my_repo_folder
$ git clone --mirror https://github.com/planetoftheweb/responsivebootstrap.git .git

the local repository inside the folder my_repo_folder is still empty, there is just a hidden .git folder now that you can see with a "ls -alt" command from the terminal.

  1. Second step

switch this repository from an empty (bare) repository to a regular repository by switching the boolean value "bare" of the git configurations to false:

$ git config --bool core.bare false
  1. Third Step

Grab everything that inside the current folder and create all the branches on the local machine, therefore making this a normal repo.

$ git reset --hard

So now you can just type the command "git branch" and you can see that all the branches are downloaded.

This is the quick way in which you can clone a git repository with all the branches at once, but it's not something you wanna do for every single project in this way.

How to import a module given the full path?

For Python 3.5+ use:

import importlib.util
spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py")
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.MyClass()

For Python 3.3 and 3.4 use:

from importlib.machinery import SourceFileLoader

foo = SourceFileLoader("module.name", "/path/to/file.py").load_module()
foo.MyClass()

(Although this has been deprecated in Python 3.4.)

For Python 2 use:

import imp

foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()

There are equivalent convenience functions for compiled Python files and DLLs.

See also http://bugs.python.org/issue21436.

What's the best free C++ profiler for Windows?

Proffy is quite cool: http://pauldoo.com/proffy/

Disclaimer: I wrote this.

Is Unit Testing worth the effort?

I didn't see this in any of the other answers, but one thing I noticed is that I could debug so much faster. You don't need to drill down through your app with just the right sequence of steps to get to the code your fixing, only to find you've made a boolean error and need to do it all again. With a unit test, you can just step directly into the code you're debugging.

How do you iterate through every file/directory recursively in standard C++?

You need to call OS-specific functions for filesystem traversal, like open() and readdir(). The C standard does not specify any filesystem-related functions.

Apple Cover-flow effect using jQuery or other library?

Is this what you are looking for?

"Create an Apple Itunes-like banner rotator/slideshow with jQuery" is an article explaining how you can make such effect using jQuery.

You can also view the live demo.

How do I quickly rename a MySQL database (change schema name)?

I posted this How do I change the database name using MySQL? today after days of head scratching and hair pulling. The solution is quite simple export a schema to a .sql file and open the file and change the database/schema name in the sql CREAT TABLE section at the top. There are three instances or more and may not be at the top of the page if multible schemas are saved to the file. It is posible to edit the entire database this way but I expect that in large databases it could be quite a pain following all instances of a table property or index.

Tree data structure in C#

I have a little extension to the solutions.

Using a recursive generic declaration and a deriving subclass you can better concentrate on your actual target.

Notice, it's different from a non generic implementation, you don`t need to cast 'node' in 'NodeWorker'.

Here's my example:

public class GenericTree<T> where T : GenericTree<T> // recursive constraint  
{
  // no specific data declaration  

  protected List<T> children;

  public GenericTree()
  {
    this.children = new List<T>();
  }

  public virtual void AddChild(T newChild)
  {
    this.children.Add(newChild);
  }

  public void Traverse(Action<int, T> visitor)
  {
    this.traverse(0, visitor);
  }

  protected virtual void traverse(int depth, Action<int, T> visitor)
  {
    visitor(depth, (T)this);
    foreach (T child in this.children)
      child.traverse(depth + 1, visitor);
  }
}

public class GenericTreeNext : GenericTree<GenericTreeNext> // concrete derivation
{
  public string Name {get; set;} // user-data example

  public GenericTreeNext(string name)
  {
    this.Name = name;
  }
}

static void Main(string[] args)  
{  
  GenericTreeNext tree = new GenericTreeNext("Main-Harry");  
  tree.AddChild(new GenericTreeNext("Main-Sub-Willy"));  
  GenericTreeNext inter = new GenericTreeNext("Main-Inter-Willy");  
  inter.AddChild(new GenericTreeNext("Inter-Sub-Tom"));  
  inter.AddChild(new GenericTreeNext("Inter-Sub-Magda"));  
  tree.AddChild(inter);  
  tree.AddChild(new GenericTreeNext("Main-Sub-Chantal"));  
  tree.Traverse(NodeWorker);  
}  

static void NodeWorker(int depth, GenericTreeNext node)  
{                                // a little one-line string-concatenation (n-times)
  Console.WriteLine("{0}{1}: {2}", String.Join("   ", new string[depth + 1]), depth, node.Name);  
}  

When is a CDATA section necessary within a script tag?

Do not use CDATA in HTML4 but you should use CDATA in XHTML and must use CDATA in XML if you have unescaped symbols like < and >.

Add a linebreak in an HTML text area

If it's not vb you can use &#013;&#010; (ascii codes for cr,lf)

When does System.gc() do something?

You need to be very careful if you call System.gc(). Calling it can add unnecessary performance issues to your application, and it is not guaranteed to actually perform a collection. It is actually possible to disable explicit System.gc() via the java argument -XX:+DisableExplicitGC.

I'd highly recommend reading through the documents available at Java HotSpot Garbage Collection for more in depth details about garbage collection.

How do you launch the JavaScript debugger in Google Chrome?

F12 opens the developer panel

CTRL + SHIFT + C Will open the hover-to-inspect tool where it highlights elements as you hover and you can click to show it in the elements tab.

CTRL + SHIFT + I Opens the developer panel with console tab

RIGHT-CLICK > Inspect Right click any element, and click "inspect" to select it in the Elements tab of the Developer panel.

ESC If you right-click and inspect element or similar and end up in the "Elements" tab looking at the DOM, you can press ESC to toggle the console up and down, which can be a nice way to use both.

What's the easiest way to install a missing Perl module?

Lots of recommendation for CPAN.pm, which is great, but if you're using Perl 5.10 then you've also got access to CPANPLUS.pm which is like CPAN.pm but better.

And, of course, it's available on CPAN for people still using older versions of Perl. Why not try:

$ cpan CPANPLUS

Unit Testing C Code

I don't use a framework, I just use autotools "check" target support. Implement a "main" and use assert(s).

My test dir Makefile.am(s) look like:

check_PROGRAMS = test_oe_amqp

test_oe_amqp_SOURCES = test_oe_amqp.c
test_oe_amqp_LDADD = -L$(top_builddir)/components/common -loecommon
test_oe_amqp_CFLAGS = -I$(top_srcdir)/components/common -static

TESTS = test_oe_amqp

How to put text in the upper right, or lower right corner of a "box" using css

If the position of the element containing the Lorum Ipsum is set absolute, you can specify the position via CSS. The "here" and "and here" elements would need to be contained in a block level element. I'll use markup like this.

print("<div id="lipsum">");
print("<div id="here">");
print("  here");
print("</div>");
print("<div id="andhere">");
print("and here");
print("</div>");
print("blah");
print("</div>");

Here's the CSS for above.

#lipsum {position:absolute;top:0;left:0;} /* example */
#here {position:absolute;top:0;right:0;}
#andhere {position:absolute;bottom:0;right:0;}

Again, the above only works (reliably) if #lipsum is positioned via absolute.

If not, you'll need to use the float property.

#here, #andhere {float:right;}

You'll also need to put your markup in the appropriate place. For better presentation, your two divs will probably need some padding and margins so that the text doesn't all run together.

Valid characters in a Java class name

What other rules govern Java class names (for instance, Java class names cannot begin with a number)?

  • Java class names usually begin with a capital letter.
  • Java class names cannot begin with a number.
  • if there are multiple words in the class name like "MyClassName" each word should begin with a capital letter. eg- "MyClassName".This naming convention is based on CamelCase Type.

How do I set up Vim autoindentation properly for editing Python files?

Ensure you are editing the correct configuration file for VIM. Especially if you are using windows, where the file could be named _vimrc instead of .vimrc as on other platforms.

In vim type

:help vimrc

and check your path to the _vimrc/.vimrc file with

:echo $HOME

:echo $VIM

Make sure you are only using one file. If you want to split your configuration into smaller chunks you can source other files from inside your _vimrc file.

:help source

IsNull function in DB2 SQL?

In DB2 there is a function NVL(field, value if null).

Example:

SELECT ID, NVL(NAME, "Internal) AS NAME, NVL(PRICE,0) AS PRICE FROM PRODUCT WITH UR;

Does a finally block always get executed in Java?

Yes, it will. No matter what happens in your try or catch block unless otherwise System.exit() called or JVM crashed. if there is any return statement in the block(s),finally will be executed prior to that return statement.

Remove border from IFrame

In addition to adding the frameBorder attribute you might want to consider setting the scrolling attribute to "no" to prevent scrollbars from appearing.

<iframe src="myURL" width="300" height="300" frameBorder="0" scrolling="no">Browser not compatible. </iframe > 

SQL Server 2005 How Create a Unique Constraint?

You are looking for something like the following

ALTER TABLE dbo.doc_exz
ADD CONSTRAINT col_b_def
UNIQUE column_b

MSDN Docs

Select data from "show tables" MySQL query

I don't understand why you want to use SELECT * FROM as part of the statement.

12.5.5.30. SHOW TABLES Syntax

Best way to convert text files between character sets?

iconv(1)

iconv -f FROM-ENCODING -t TO-ENCODING file.txt

Also there are iconv-based tools in many languages.

Why aren't Xcode breakpoints functioning?

Also make sure that the AppStore distribution of the app is not also installed on the device.

Error handling in Bash

Another consideration is the exit code to return. Just "1" is pretty standard, although there are a handful of reserved exit codes that bash itself uses, and that same page argues that user-defined codes should be in the range 64-113 to conform to C/C++ standards.

You might also consider the bit vector approach that mount uses for its exit codes:

 0  success
 1  incorrect invocation or permissions
 2  system error (out of memory, cannot fork, no more loop devices)
 4  internal mount bug or missing nfs support in mount
 8  user interrupt
16  problems writing or locking /etc/mtab
32  mount failure
64  some mount succeeded

OR-ing the codes together allows your script to signal multiple simultaneous errors.

How do you append an int to a string in C++?

cout << text << " " << i << endl;

'^M' character at end of lines

The cause is the difference between how a Windows-based based OS and a Unix based OS store the end-of-line markers.

Windows based operating systems, thanks to their DOS heritage, store an end-of-line as a pair of characters - 0x0D0A (carriage return + line feed). Unix-based operating systems just use 0x0A (a line feed). The ^M you're seeing is a visual representation of 0x0D (a carriage return).

dos2unix will help with this. You probably also need to adjust the source of the scripts to be 'Unix-friendly'.

What are valid values for the id attribute in HTML?

HTML5:

gets rid of the additional restrictions on the id attribute see here. The only requirements left (apart from being unique in the document) are:

  1. the value must contain at least one character (can’t be empty)
  2. it can’t contain any space characters.

PRE-HTML5:

ID should match:

[A-Za-z][-A-Za-z0-9_:.]*
  1. Must Start with A-Z or a-z characters
  2. May contain - (hyphen), _ (underscore), : (colon) and . (period)

but one should avoid : and . beacause:

For example, an ID could be labelled "a.b:c" and referenced in the style sheet as #a.b:c but as well as being the id for the element, it could mean id "a", class "b", pseudo-selector "c". Best to avoid the confusion and stay away from using . and : altogether.

Why are Python's 'private' methods not actually private?

The phrase commonly used is "we're all consenting adults here". By prepending a single underscore (don't expose) or double underscore (hide), you're telling the user of your class that you intend the member to be 'private' in some way. However, you're trusting everyone else to behave responsibly and respect that, unless they have a compelling reason not to (e.g. debuggers, code completion).

If you truly must have something that is private, then you can implement it in an extension (e.g. in C for CPython). In most cases, however, you simply learn the Pythonic way of doing things.

Does C# have a String Tokenizer like Java's?

You could use String.Split method.

class ExampleClass
{
    public ExampleClass()
    {
        string exampleString = "there is a cat";
        // Split string on spaces. This will separate all the words in a string
        string[] words = exampleString.Split(' ');
        foreach (string word in words)
        {
            Console.WriteLine(word);
            // there
            // is
            // a
            // cat
        }
    }
}

For more information see Sam Allen's article about splitting strings in c# (Performance, Regex)

Why is quicksort better than mergesort?

Mu! Quicksort is not better, it is well suited for a different kind of application, than mergesort.

Mergesort is worth considering if speed is of the essence, bad worst-case performance cannot be tolerated, and extra space is available.1

You stated that they «They're both O(nlogn) […]». This is wrong. «Quicksort uses about n^2/2 comparisons in the worst case.»1.

However the most important property according to my experience is the easy implementation of sequential access you can use while sorting when using programming languages with the imperative paradigm.

1 Sedgewick, Algorithms

Java inner class and static nested class

I don't think there is much to add here, most of the answers perfectly explain the differences between static nested class and Inner classes. However, consider the following issue when using nested classes vs inner classes. As mention in a couple of answers inner classes can not be instantiated without and instance of their enclosing class which mean that they HOLD a pointer to the instance of their enclosing class which can lead to memory overflow or stack overflow exception due to the fact the GC will not be able to garbage collect the enclosing classes even if they are not used any more. To make this clear check the following code out:

public class Outer {


    public  class Inner {

    }


    public Inner inner(){
        return new Inner();
    }

    @Override
    protected void finalize() throws Throwable {
    // as you know finalize is called by the garbage collector due to destroying an object instance
        System.out.println("I am destroyed !");
    }
}


public static void main(String arg[]) {

    Outer outer = new Outer();
    Outer.Inner inner = outer.new Inner();

    // out instance is no more used and should be garbage collected !!!
    // However this will not happen as inner instance is still alive i.e used, not null !
    // and outer will be kept in memory until inner is destroyed
    outer = null;

    //
    // inner = null;

    //kick out garbage collector
    System.gc();

}

If you remove the comment on // inner = null; The program will out put "I am destroyed !", but keeping this commented it will not.
The reason is that white inner instance is still referenced GC cannot collect it and because it references (has a pointer to) the outer instance it is not collected too. Having enough of these objects in your project and can run out of memory.
Compared to static inner classes which does not hold a point to inner class instance because it is not instance related but class related. The above program can print "I am destroyed !" if you make Inner class static and instantiated with Outer.Inner i = new Outer.Inner();

Single Form Hide on Startup

I had an issue similar to the poster's where the code to hide the form in the form_Load event was firing before the form was completely done loading, making the Hide() method fail (not crashing, just wasn't working as expected).

The other answers are great and work but I've found that in general, the form_Load event often has such issues and what you want to put in there can easily go in the constructor or the form_Shown event.

Anyways, when I moved that same code that checks some things then hides the form when its not needed (a login form when single sign on fails), its worked as expected.

What's the purpose of META-INF?

All answers are correct. Meta-inf has many purposes. In addition, here is an example about using tomcat container.

Go to Tomcat Doc and check " Standard Implementation > copyXML " attribute.

Description is below.

Set to true if you want a context XML descriptor embedded inside the application (located at /META-INF/context.xml) to be copied to the owning Host's xmlBase when the application is deployed. On subsequent starts, the copied context XML descriptor will be used in preference to any context XML descriptor embedded inside the application even if the descriptor embedded inside the application is more recent. The flag's value defaults to false. Note if the deployXML attribute of the owning Host is false or if the copyXML attribute of the owning Host is true, this attribute will have no effect.

How to Detect if I'm Compiling Code with a particular Visual Studio version?

_MSC_VER should be defined to a specific version number. You can either #ifdef on it, or you can use the actual define and do a runtime test. (If for some reason you wanted to run different code based on what compiler it was compiled with? Yeah, probably you were looking for the #ifdef. :))

Set 4 Space Indent in Emacs in Text Mode

(setq tab-width 4)
(setq tab-stop-list '(4 8 12 16 20 24 28 32 36 40 44 48 52 56 60 64 68 72 76 80))
(setq indent-tabs-mode nil)

Why don't self-closing script elements work?

Internet Explorer 8 and older don't support the proper MIME type for XHTML, application/xhtml+xml. If you're serving XHTML as text/html, which you have to for these older versions of Internet Explorer to do anything, it will be interpreted as HTML 4.01. You can only use the short syntax with any element that permits the closing tag to be omitted. See the HTML 4.01 Specification.

The XML 'short form' is interpreted as an attribute named /, which (because there is no equals sign) is interpreted as having an implicit value of "/". This is strictly wrong in HTML 4.01 - undeclared attributes are not permitted - but browsers will ignore it.

IE9 and later support XHTML 5 served with application/xhtml+xml.

Factory Pattern. When to use factory methods?

Factory methods should be considered as an alternative to constructors - mostly when constructors aren't expressive enough, ie.

class Foo{
  public Foo(bool withBar);
}

is not as expressive as:

class Foo{
  public static Foo withBar();
  public static Foo withoutBar();
}

Factory classes are useful when you need a complicated process for constructing the object, when the construction need a dependency that you do not want for the actual class, when you need to construct different objects etc.

Take a screenshot via a Python script on Linux

There is a python package for this Autopy

The bitmap module can to screen grabbing (bitmap.capture_screen) It is multiplateform (Windows, Linux, Osx).

Is there a way to make text unselectable on an HTML page?

The following works in Firefox interestingly enough if I remove the write line it doesn't work. Anyone have any insight why the write line is needed.

<script type="text/javascript">
document.write(".");
document.body.style.MozUserSelect='none';
</script>

Remote Linux server to remote linux server dir copy. How?

Use rsync so that you can continue if the connection gets broken. And if something changes you can copy them much faster too!

Rsync works with SSH so your copy operation is secure.

Is there a way to programmatically minimize a window

<form>.WindowState = FormWindowState.Minimized;

Tracking CPU and Memory usage per process

Although I have not tried this out, ProcDump seems like a better solution.

Description from site:

ProcDump is a command-line utility whose primary purpose is monitoring an application for CPU spikes and generating crash dumps during a spike that an administrator or developer can use to determine the cause of the spike. ProcDump also includes hung window monitoring (using the same definition of a window hang that Windows and Task Manager use), unhandled exception monitoring and can generate dumps based on the values of system performance counters. It also can serve as a general process dump utility that you can embed in other scripts.

Biggest differences of Thrift vs Protocol Buffers?

RPC is another key difference. Thrift generates code to implement RPC clients and servers wheres Protocol Buffers seems mostly designed as a data-interchange format alone.

How to implement a queue using two stacks?

An implementation of a queue using two stacks in Swift:

struct Stack<Element> {
    var items = [Element]()

    var count : Int {
        return items.count
    }

    mutating func push(_ item: Element) {
        items.append(item)
    }

    mutating func pop() -> Element? {
        return items.removeLast()
    }

    func peek() -> Element? {
        return items.last
    }
}

struct Queue<Element> {
    var inStack = Stack<Element>()
    var outStack = Stack<Element>()

    mutating func enqueue(_ item: Element) {
        inStack.push(item)
    }

    mutating func dequeue() -> Element? {
        fillOutStack() 
        return outStack.pop()
    }

    mutating func peek() -> Element? {
        fillOutStack()
        return outStack.peek()
    }

    private mutating func fillOutStack() {
        if outStack.count == 0 {
            while inStack.count != 0 {
                outStack.push(inStack.pop()!)
            }
        }
    }
}

Split long commands in multiple lines through Windows batch file

Multiple commands can be put in parenthesis and spread over numerous lines; so something like echo hi && echo hello can be put like this:

( echo hi
  echo hello )

Also variables can help:

set AFILEPATH="C:\SOME\LONG\PATH\TO\A\FILE"
if exist %AFILEPATH% (
  start "" /b %AFILEPATH% -option C:\PATH\TO\SETTING...
) else (
...

Also I noticed with carets (^) that the if conditionals liked them to follow only if a space was present:

if exist ^

Are static class variables possible in Python?

Variables declared inside the class definition, but not inside a method are class or static variables:

>>> class MyClass:
...     i = 3
...
>>> MyClass.i
3 

As @millerdev points out, this creates a class-level i variable, but this is distinct from any instance-level i variable, so you could have

>>> m = MyClass()
>>> m.i = 4
>>> MyClass.i, m.i
>>> (3, 4)

This is different from C++ and Java, but not so different from C#, where a static member can't be accessed using a reference to an instance.

See what the Python tutorial has to say on the subject of classes and class objects.

@Steve Johnson has already answered regarding static methods, also documented under "Built-in Functions" in the Python Library Reference.

class C:
    @staticmethod
    def f(arg1, arg2, ...): ...

@beidy recommends classmethods over staticmethod, as the method then receives the class type as the first argument, but I'm still a little fuzzy on the advantages of this approach over staticmethod. If you are too, then it probably doesn't matter.

How to parse a query string into a NameValueCollection in .NET

To do this without System.Web, without writing it yourself, and without additional NuGet packages:

  1. Add a reference to System.Net.Http.Formatting
  2. Add using System.Net.Http;
  3. Use this code:

    new Uri(uri).ParseQueryString()
    

https://msdn.microsoft.com/en-us/library/system.net.http.uriextensions(v=vs.118).aspx

How do I drag and drop files into an application?

Be aware of windows vista/windows 7 security rights - if you are running Visual Studio as administrator, you will not be able to drag files from a non-administrator explorer window into your program when you run it from within visual studio. The drag related events will not even fire! I hope this helps somebody else out there not waste hours of their life...

Multiple cases in switch statement

There is no syntax in C++ nor C# for the second method you mentioned.

There's nothing wrong with your first method. If however you have very big ranges, just use a series of if statements.

How to show loading spinner in jQuery?

I also want to contribute to this answer. I was looking for something similar in jQuery and this what I eventually ended up using.

I got my loading spinner from http://ajaxload.info/. My solution is based on this simple answer at http://christierney.com/2011/03/23/global-ajax-loading-spinners/.

Basically your HTML markup and CSS would look like this:

<style>
     #ajaxSpinnerImage {
          display: none;
     }
</style>

<div id="ajaxSpinnerContainer">
     <img src="~/Content/ajax-loader.gif" id="ajaxSpinnerImage" title="working..." />
</div>

And then you code for jQuery would look something like this:

<script>
     $(document).ready(function () {
          $(document)
          .ajaxStart(function () {
               $("#ajaxSpinnerImage").show();
          })
          .ajaxStop(function () {
               $("#ajaxSpinnerImage").hide();
          });

          var owmAPI = "http://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=YourAppID";
          $.getJSON(owmAPI)
          .done(function (data) {
               alert(data.coord.lon);
          })
          .fail(function () {
               alert('error');
          });
     });
</script>

It is as simple as that :)

Send file using POST from a Python script

def visit_v2(device_code, camera_code):
    image1 = MultipartParam.from_file("files", "/home/yuzx/1.txt")
    image2 = MultipartParam.from_file("files", "/home/yuzx/2.txt")
    datagen, headers = multipart_encode([('device_code', device_code), ('position', 3), ('person_data', person_data), image1, image2])
    print "".join(datagen)
    if server_port == 80:
        port_str = ""
    else:
        port_str = ":%s" % (server_port,)
    url_str = "http://" + server_ip + port_str + "/adopen/device/visit_v2"
    headers['nothing'] = 'nothing'
    request = urllib2.Request(url_str, datagen, headers)
    try:
        response = urllib2.urlopen(request)
        resp = response.read()
        print "http_status =", response.code
        result = json.loads(resp)
        print resp
        return result
    except urllib2.HTTPError, e:
        print "http_status =", e.code
        print e.read()

What is your single most favorite command-line trick using Bash?

Good for making an exact recursive copy/backup of a directory including symlinks (rather than following them or ignoring them like cp):

$ mkdir new_dir
$ cd old_dir
$ tar cf - . | ( cd ../old_dir; tar xf - )

How to copy a file to a remote server in Python using SCP or SSH?

Kind of hacky, but the following should work :)

import os
filePath = "/foo/bar/baz.py"
serverPath = "/blah/boo/boom.py"
os.system("scp "+filePath+" [email protected]:"+serverPath)

View/edit ID3 data for MP3 files

UltraID3Lib...

Be aware that UltraID3Lib is no longer officially available, and thus no longer maintained. See comments below for the link to a Github project that includes this library

//using HundredMilesSoftware.UltraID3Lib;
UltraID3 u = new UltraID3();
u.Read(@"C:\mp3\song.mp3");
//view
Console.WriteLine(u.Artist);
//edit
u.Artist = "New Artist";
u.Write();

How to create a windows service from java app

Exe4j is a very good option although it is not free. Check it out at Exe4j In the wizard to create the .exe file, you are give the option to create a service.

How to create batch file in Windows using "start" with a path and command with spaces

start "" "c:\path with spaces\app.exe" "C:\path parameter\param.exe"

When I used above suggestion, I've got:

'c:\path' is not recognized a an internal or external command, operable program or batch file.

I think second qoutation mark prevent command to run. After some search below solution save my day:

start "" CALL "c:\path with spaces\app.exe" "C:\path parameter\param.exe"

Auto number column in SharePoint list

Peetha has the best idea, I've done the same with a custom list in our SP site. Using a workflow to auto increment is the best way, and it is not that difficult. Check this website out: http://splittingshares.wordpress.com/2008/04/11/auto-increment-a-number-in-a-new-list-item/

I give much appreciation to the person who posted that solution, it is very cool!!

Should I add the Visual Studio .suo and .user files to source control?

Visual Studio will automatically create them. I don't recommend putting them in source control. There have been numerous times where a local developer's SOU file was causing VS to behave erratically on that developers box. Deleting the file and then letting VS recreate it always fixed the issues.

Recursion or Iteration?

You have to keep in mind that utilizing too deep recursion you will run into Stack Overflow, depending on allowed stack size. To prevent this make sure to provide some base case which ends you recursion.

How do I Validate the File Type of a File Upload?

From javascript, you should be able to get the filename in the onsubmit handler. So in your case, you should do something like:

<form onsubmit="if (document.getElementById('fileUpload').value.match(/xls$/) || document.getElementById('fileUpload').value.match(/xlsx$/)) { alert ('Bad file type') ; return false; } else { return true; }">...</form>

Forward declaring an enum in C++

If you really don't want your enum to appear in your header file AND ensure that it is only used by private methods, then one solution can be to go with the pimpl principle.

It's a technique that ensure to hide the class internals in the headers by just declaring:

class A 
{
public:
    ...
private:
    void* pImpl;
};

Then in your implementation file (cpp), you declare a class that will be the representation of the internals.

class AImpl
{
public:
    AImpl(A* pThis): m_pThis(pThis) {}

    ... all private methods here ...
private:
    A* m_pThis;
};

You must dynamically create the implementation in the class constructor and delete it in the destructor and when implementing public method, you must use:

((AImpl*)pImpl)->PrivateMethod();

There are pros for using pimpl, one is that it decouple your class header from its implementation, no need to recompile other classes when changing one class implementation. Another is that is speeds up your compilation time because your headers are so simple.

But it's a pain to use, so you should really ask yourself if just declaring your enum as private in the header is that much a trouble.

How to replace a character by a newline in Vim

\r can do the work here for you.

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

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

How can I find last row that contains data in a specific column?

How about:

Function GetLastRow(strSheet, strColumn) As Long
    Dim MyRange As Range

    Set MyRange = Worksheets(strSheet).Range(strColumn & "1")
    GetLastRow = Cells(Rows.Count, MyRange.Column).End(xlUp).Row
End Function

Regarding a comment, this will return the row number of the last cell even when only a single cell in the last row has data:

Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

How to remove Firefox's dotted outline on BUTTONS as well as links?

No need to define a selector.

:focus {outline:none;}
::-moz-focus-inner {border:0;}

However, this violates accessibility best practices from the W3C. The outline is there to help those navigating with keyboards.

https://www.w3.org/TR/WCAG20-TECHS/F78.html#F78-examples

SQL MAX of multiple columns?

I prefer solutions based on case-when, my assumption is that it should have the least impact on possible performance drop compared to other possible solutions like those with cross-apply, values(), custom functions etc.

Here is the case-when version that handles null values with most of possible test cases:

SELECT
    CASE 
        WHEN Date1 > coalesce(Date2,'0001-01-01') AND Date1 > coalesce(Date3,'0001-01-01') THEN Date1 
        WHEN Date2 > coalesce(Date3,'0001-01-01') THEN Date2 
        ELSE Date3
    END AS MostRecentDate
    , *
from 
(values
     (  1, cast('2001-01-01' as Date), cast('2002-01-01' as Date), cast('2003-01-01' as Date))
    ,(  2, cast('2001-01-01' as Date), cast('2003-01-01' as Date), cast('2002-01-01' as Date))
    ,(  3, cast('2002-01-01' as Date), cast('2001-01-01' as Date), cast('2003-01-01' as Date))
    ,(  4, cast('2002-01-01' as Date), cast('2003-01-01' as Date), cast('2001-01-01' as Date))
    ,(  5, cast('2003-01-01' as Date), cast('2001-01-01' as Date), cast('2002-01-01' as Date))
    ,(  6, cast('2003-01-01' as Date), cast('2002-01-01' as Date), cast('2001-01-01' as Date))
    ,( 11, cast(NULL         as Date), cast('2002-01-01' as Date), cast('2003-01-01' as Date))
    ,( 12, cast(NULL         as Date), cast('2003-01-01' as Date), cast('2002-01-01' as Date))
    ,( 13, cast('2003-01-01' as Date), cast(NULL         as Date), cast('2002-01-01' as Date))
    ,( 14, cast('2002-01-01' as Date), cast(NULL         as Date), cast('2003-01-01' as Date))
    ,( 15, cast('2003-01-01' as Date), cast('2002-01-01' as Date), cast(NULL         as Date))
    ,( 16, cast('2002-01-01' as Date), cast('2003-01-01' as Date), cast(NULL         as Date))
    ,( 21, cast('2003-01-01' as Date), cast(NULL         as Date), cast(NULL         as Date))
    ,( 22, cast(NULL         as Date), cast('2003-01-01' as Date), cast(NULL         as Date))
    ,( 23, cast(NULL         as Date), cast(NULL         as Date), cast('2003-01-01' as Date))
    ,( 31, cast(NULL         as Date), cast(NULL         as Date), cast(NULL         as Date))

) as demoValues(id, Date1,Date2,Date3)
order by id
;

and the result is:

MostRecent    id   Date1      Date2      Date3
2003-01-01    1    2001-01-01 2002-01-01 2003-01-01
2003-01-01    2    2001-01-01 2003-01-01 2002-01-01
2003-01-01    3    2002-01-01 2001-01-01 2002-01-01
2003-01-01    4    2002-01-01 2003-01-01 2001-01-01
2003-01-01    5    2003-01-01 2001-01-01 2002-01-01
2003-01-01    6    2003-01-01 2002-01-01 2001-01-01
2003-01-01    11   NULL       2002-01-01 2003-01-01
2003-01-01    12   NULL       2003-01-01 2002-01-01
2003-01-01    13   2003-01-01 NULL       2002-01-01
2003-01-01    14   2002-01-01 NULL       2003-01-01
2003-01-01    15   2003-01-01 2002-01-01 NULL
2003-01-01    16   2002-01-01 2003-01-01 NULL
2003-01-01    21   2003-01-01 NULL       NULL
2003-01-01    22   NULL       2003-01-01 NULL
2003-01-01    23   NULL       NULL       2003-01-01
NULL          31   NULL       NULL       NULL

Refreshing all the pivot tables in my excel workbook with a macro

Even we can refresh particular connection and in turn it will refresh all the pivots linked to it.

For this code I have created slicer from table present in Excel:

Sub UpdateConnection()
        Dim ServerName As String
        Dim ServerNameRaw As String
        Dim CubeName As String
        Dim CubeNameRaw As String
        Dim ConnectionString As String

        ServerNameRaw = ActiveWorkbook.SlicerCaches("Slicer_ServerName").VisibleSlicerItemsList(1)
        ServerName = Replace(Split(ServerNameRaw, "[")(3), "]", "")

        CubeNameRaw = ActiveWorkbook.SlicerCaches("Slicer_CubeName").VisibleSlicerItemsList(1)
        CubeName = Replace(Split(CubeNameRaw, "[")(3), "]", "")

        If CubeName = "All" Or ServerName = "All" Then
            MsgBox "Please Select One Cube and Server Name", vbOKOnly, "Slicer Info"
        Else
            ConnectionString = GetConnectionString(ServerName, CubeName)
            UpdateAllQueryTableConnections ConnectionString, CubeName
        End If
    End Sub

    Function GetConnectionString(ServerName As String, CubeName As String)
        Dim result As String
        result = "OLEDB;Provider=MSOLAP.5;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=" & CubeName & ";Data Source=" & ServerName & ";MDX Compatibility=1;Safety Options=2;MDX Missing Member Mode=Error;Update Isolation Level=2"
        '"OLEDB;Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=" & CubeName & ";Data Source=" & ServerName & ";Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False"
        GetConnectionString = result
    End Function

    Function GetConnectionString(ServerName As String, CubeName As String)
    Dim result As String
    result = "OLEDB;Provider=MSOLAP.5;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=" & CubeName & ";Data Source=" & ServerName & ";MDX Compatibility=1;Safety Options=2;MDX Missing Member Mode=Error;Update Isolation Level=2"
    GetConnectionString = result
End Function

Sub UpdateAllQueryTableConnections(ConnectionString As String, CubeName As String)
    Dim cn As WorkbookConnection
    Dim oledbCn As OLEDBConnection
    Dim Count As Integer, i As Integer
    Dim DBName As String
    DBName = "Initial Catalog=" + CubeName

    Count = 0
    For Each cn In ThisWorkbook.Connections
        If cn.Name = "ThisWorkbookDataModel" Then
            Exit For
        End If

        oTmp = Split(cn.OLEDBConnection.Connection, ";")
        For i = 0 To UBound(oTmp) - 1
            If InStr(1, oTmp(i), DBName, vbTextCompare) = 1 Then
                Set oledbCn = cn.OLEDBConnection
                oledbCn.SavePassword = True
                oledbCn.Connection = ConnectionString
                oledbCn.Refresh
                Count = Count + 1
            End If
        Next
    Next

    If Count = 0 Then
         MsgBox "Nothing to update", vbOKOnly, "Update Connection"
    ElseIf Count > 0 Then
        MsgBox "Update & Refresh Connection Successfully", vbOKOnly, "Update Connection"
    End If
End Sub

How to prompt for user input and read command-line arguments

If it's a 3.x version then just simply use:

variantname = input()

For example, you want to input 8:

x = input()
8

x will equal 8 but it's going to be a string except if you define it otherwise.

So you can use the convert command, like:

a = int(x) * 1.1343
print(round(a, 2)) # '9.07'
9.07

What is an efficient way to implement a singleton pattern in Java?

Really consider why you need a singleton before writing it. There is a quasi-religious debate about using them which you can quite easily stumble over if you google singletons in Java.

Personally, I try to avoid singletons as often as possible for many reasons, again most of which can be found by googling singletons. I feel that quite often singletons are abused because they're easy to understand by everybody. They're used as a mechanism for getting "global" data into an OO design and they are used because it is easy to circumvent object lifecycle management (or really thinking about how you can do A from inside B). Look at things like inversion of control (IoC) or dependency injection (DI) for a nice middle ground.

If you really need one then Wikipedia has a good example of a proper implementation of a singleton.

Sys is undefined

I hate adding to such a huge topic and so much later, but I've think I have a solution that work in VS2015 at the very least.

I was on a hunt to find a reason for the sys error, and the only solution that worked for me was to add EnableCdn="true" in a ScriptManager like this:

<asp:ScriptManager ID="ScriptManager1" runat="server" EnableCdn="true" />

See the MSDN for more information.

Why do we need to do this?

When working on a asp.net web application, you have to enable CDN so that Microsoft can download the Sys. library.

There was probably a script in your page that was using the Sys function. Setting EnableCdn="true" would ensure that the Sys library is downloaded before it is used.

What's CDN?

A quote from https://www.sitepoint.com/7-reasons-to-use-a-cdn/

Most CDNs are used to host static resources such as images, videos, audio clips, CSS files and JavaScript. You’ll find common JavaScript libraries, HTML5 shims, CSS resets, fonts and other assets available on a variety of public and private CDN systems.

Both Google and Microsoft have CDNs. All you have to do is add a reference. Usually CDNs are added via a script resource:

<script src="https://ajax.aspnetcdn.com/ajax/4.5.1/1/MicrosoftAjax.js" type="text/javascript"></script>

Once you set EnableCdn="true" and Microsoft will add it's little CDN reference (like the one above) in the page which downloads the Sys library.

I hope that helps anybody that ran into the same issue.

What is an unsigned char?

This is implementation dependent, as the C standard does NOT define the signed-ness of char. Depending on the platform, char may be signed or unsigned, so you need to explicitly ask for signed char or unsigned char if your implementation depends on it. Just use char if you intend to represent characters from strings, as this will match what your platform puts in the string.

The difference between signed char and unsigned char is as you'd expect. On most platforms, signed char will be an 8-bit two's complement number ranging from -128 to 127, and unsigned char will be an 8-bit unsigned integer (0 to 255). Note the standard does NOT require that char types have 8 bits, only that sizeof(char) return 1. You can get at the number of bits in a char with CHAR_BIT in limits.h. There are few if any platforms today where this will be something other than 8, though.

There is a nice summary of this issue here.

As others have mentioned since I posted this, you're better off using int8_t and uint8_t if you really want to represent small integers.

Create instance of generic type in Java?

You can use:

Class.forName(String).getConstructor(arguments types).newInstance(arguments)

But you need to supply the exact class name, including packages, eg. java.io.FileInputStream. I used this to create a math expressions parser.