Programs & Examples On #Rmdir

The `rmdir` command is a Linux and Windows command used to remove a directory or folder.

Delete directory with files in it?

Short function that does the job:

function deleteDir($path) {
    return is_file($path) ?
            @unlink($path) :
            array_map(__FUNCTION__, glob($path.'/*')) == @rmdir($path);
}

I use it in a Utils class like this:

class Utils {
    public static function deleteDir($path) {
        $class_func = array(__CLASS__, __FUNCTION__);
        return is_file($path) ?
                @unlink($path) :
                array_map($class_func, glob($path.'/*')) == @rmdir($path);
    }
}

With great power comes great responsibility: When you call this function with an empty value, it will delete files starting in root (/). As a safeguard you can check if path is empty:

function deleteDir($path) {
    if (empty($path)) { 
        return false;
    }
    return is_file($path) ?
            @unlink($path) :
            array_map(__FUNCTION__, glob($path.'/*')) == @rmdir($path);
}

How to remove files and directories quickly via terminal (bash shell)

So I was looking all over for a way to remove all files in a directory except for some directories, and files, I wanted to keep around. After much searching I devised a way to do it using find.

find -E . -regex './(dir1|dir2|dir3)' -and -type d -prune -o -print -exec rm -rf {} \;

Essentially it uses regex to select the directories to exclude from the results then removes the remaining files. Just wanted to put it out here in case someone else needed it.

How can I change the class of an element with jQuery>

To set a class completely, instead of adding one or removing one, use this:

$(this).attr("class","newclass");

Advantage of this is that you'll remove any class that might be set in there and reset it to how you like. At least this worked for me in one situation.

Is it possible in Java to catch two exceptions in the same catch block?

Java <= 6.x just allows you to catch one exception for each catch block:

try {

} catch (ExceptionType name) {

} catch (ExceptionType name) {

}

Documentation:

Each catch block is an exception handler and handles the type of exception indicated by its argument. The argument type, ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class.

For Java 7 you can have multiple Exception caught on one catch block:

catch (IOException|SQLException ex) {
    logger.log(ex);
    throw ex;
}

Documentation:

In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.

Reference: http://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html

Make a div into a link

Not sure if this is valid but it worked for me.

The code :

_x000D_
_x000D_
<div style='position:relative;background-color:#000000;width:600px;height:30px;border:solid;'>_x000D_
  <p style='display:inline;color:#ffffff;float:left;'> Whatever </p>     _x000D_
  <a style='position:absolute;top:0px;left:0px;width:100%;height:100%;display:inline;' href ='#'></a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I find if a string starts with another string in Ruby?

The method mentioned by steenslag is terse, and given the scope of the question it should be considered the correct answer. However it is also worth knowing that this can be achieved with a regular expression, which if you aren't already familiar with in Ruby, is an important skill to learn.

Have a play with Rubular: http://rubular.com/

But in this case, the following ruby statement will return true if the string on the left starts with 'abc'. The \A in the regex literal on the right means 'the beginning of the string'. Have a play with rubular - it will become clear how things work.

'abcdefg' =~  /\Aabc/ 

How do I compile and run a program in Java on my Mac?

I will give you steps to writing and compiling code. Use this example:

 public class Paycheck {
    public static void main(String args[]) {
        double amountInAccount;
        amountInAccount = 128.57;
        System.out.print("You earned $");
        System.out.print(amountInAccount);
        System.out.println(" at work today.");
    }
}
  1. Save the code as Paycheck.java
  2. Go to terminal and type cd Desktop
  3. Type javac Paycheck.java
  4. Type java Paycheck
  5. Enjoy your program!

How to delete row based on cell value

if you want to delete rows based on some specific cell value. let suppose we have a file containing 10000 rows, and a fields having value of NULL. and based on that null value want to delete all those rows and records.

here are some simple tip. First open up Find Replace dialog, and on Replace tab, make all those cell containing NULL values with Blank. then press F5 and select the Blank option, now right click on the active sheet, and select delete, then option for Entire row.

it will delete all those rows based on cell value of containing word NULL.

Can media queries resize based on a div element instead of the screen?

A Media Query inside of an iframe can function as an element query. I've successfully implement this. The idea came from a recent post about Responsive Ads by Zurb. No Javascript!

REST API Login Pattern

A big part of the REST philosophy is to exploit as many standard features of the HTTP protocol as possible when designing your API. Applying that philosophy to authentication, client and server would utilize standard HTTP authentication features in the API.

Login screens are great for human user use cases: visit a login screen, provide user/password, set a cookie, client provides that cookie in all future requests. Humans using web browsers can't be expected to provide a user id and password with each individual HTTP request.

But for a REST API, a login screen and session cookies are not strictly necessary, since each request can include credentials without impacting a human user; and if the client does not cooperate at any time, a 401 "unauthorized" response can be given. RFC 2617 describes authentication support in HTTP.

TLS (HTTPS) would also be an option, and would allow authentication of the client to the server (and vice versa) in every request by verifying the public key of the other party. Additionally this secures the channel for a bonus. Of course, a keypair exchange prior to communication is necessary to do this. (Note, this is specifically about identifying/authenticating the user with TLS. Securing the channel by using TLS / Diffie-Hellman is always a good idea, even if you don't identify the user by its public key.)

An example: suppose that an OAuth token is your complete login credentials. Once the client has the OAuth token, it could be provided as the user id in standard HTTP authentication with each request. The server could verify the token on first use and cache the result of the check with a time-to-live that gets renewed with each request. Any request requiring authentication returns 401 if not provided.

How to get different colored lines for different plots in a single figure?

Matplot colors your plot with different colors , but incase you wanna put specific colors

    import matplotlib.pyplot as plt
    import numpy as np
            
    x = np.arange(10)
            
    plt.plot(x, x)
    plt.plot(x, 2 * x,color='blue')
    plt.plot(x, 3 * x,color='red')
    plt.plot(x, 4 * x,color='green')
    plt.show()

Decimal number regular expression, where digit after decimal is optional

You need a regular expression like the following to do it properly:

/^[+-]?((\d+(\.\d*)?)|(\.\d+))$/

The same expression with whitespace, using the extended modifier (as supported by Perl):

/^  [+-]? ( (\d+ (\.\d*)?)  |  (\.\d+) ) $/x

or with comments:

/^           # Beginning of string
 [+-]?       # Optional plus or minus character
 (           # Followed by either:
   (           #   Start of first option
     \d+       #   One or more digits
     (\.\d*)?  #   Optionally followed by: one decimal point and zero or more digits
   )           #   End of first option
   |           # or
   (\.\d+)     #   One decimal point followed by one or more digits
 )           # End of grouping of the OR options
 $           # End of string (i.e. no extra characters remaining)
 /x          # Extended modifier (allows whitespace & comments in regular expression)

For example, it will match:

  • 123
  • 23.45
  • 34.
  • .45
  • -123
  • -273.15
  • -42.
  • -.45
  • +516
  • +9.8
  • +2.
  • +.5

And will reject these non-numbers:

  • . (single decimal point)
  • -. (negative decimal point)
  • +. (plus decimal point)
  • (empty string)

The simpler solutions can incorrectly reject valid numbers or match these non-numbers.

Get last field using awk substr

You can also use:

    sed -n 's/.*\/\([^\/]\{1,\}\)$/\1/p'

or

    sed -n 's/.*\/\([^\/]*\)$/\1/p'

Converting JSON data to Java object

If you use any kind of special maps with keys or values also of special maps, you will find it's not contemplated by the implementation of google.

Absolute vs relative URLs

I'm going to have to disagree with the majority here.

I think the relative URL scheme is "fine" when you want to quickly get something up and running and not think outside the box, particularly if your project is small with few developers (or just yourself).

However, once you start working on big, fatty systems where you switch domains and protocols all the time, I believe that a more elegant approach is in order.

When you compare absolute and relative URLs in essence, Absolute wins. Why? Because it won't ever break. Ever. An absolute URL is exactly what it says it is. The catch is when you have to MAINTAIN your absolute URLs.

The weak approach to absolute URL linking is actually hard coding the entire URL. Not a great idea, and probably the culprit of why people see them as dangerous/evil/annoying to maintain. A better approach is to write yourself an easy to use URL generator. These are easy to write, and can be incredibly powerful- automatically detecting your protocol, easy to config (literally set the url once for the whole app), etc, and it injects your domain all by itself. The nice thing about that: You go on coding using relative URLs, and at run time the application inserts your URLs as full absolutes on the fly. Awesome.

Seeing as how practically all modern sites use some sort of dynamic back-end, it's in the best interest of said site to do it that way. Absolute URLs do more than just make you certain of where they point to- they also can improve SEO performance.

I might add that the argument that absolute URLs is somehow going to change the load time of the page is a myth. If your domain weighs more than a few bytes and you're on a dialup modem in the 1980s, sure. But that's just not the case anymore. https://stackoverflow.com/ is 25 bytes, whereas the "topbar-sprite.png" file that they use for the nav area of the site weighs in at 9+ kb. That means that the additional URL data is .2% of the loaded data in comparison to the sprite file, and that file is not even considered a big performance hit.

That big, unoptimized, full-page background image is much more likely to slow your load times.

An interesting post about why relative URLs shouldn't be used is here: Why relative URLs should be forbidden for web developers

An issue that can arise with relatives, for instance, is that sometimes server mappings (mind you on big, messed up projects) don't line up with file names and the developer may make an assumption about a relative URL that just isn't true. I just saw that today on a project that I'm on and it brought an entire page down.

Or perhaps a developer forgot to switch a pointer and all of a sudden google indexed your entire test environment. Whoops- duplicate content (bad for SEO!).

Absolutes can be dangerous, but when used properly and in a way that can't break your build they are proven to be more reliable. Look at the article above which gives a bunch of reasons why the Wordpress url generator is super awesome.

:)

XAMPP Apache won't start

I gave all users full access on the xampp folder, inclusive subdirectories. Afterwards it worked.

Check if a value exists in ArrayList

Just use .contains. For example, if you were checking if an ArrayList arr contains a value val, you would simply run arr.contains(val), which would return a boolean representing if the value is contained. For more information, see the docs for .contains.

How to implement 2D vector array?

vector<int> adj[n]; // where n is number of rows in 2d vector.

Show animated GIF

I wanted to put the .gif file in a GUI but displayed with other elements. And the .gif file would be taken from the java project and not from an URL.

1 - Top of the interface would be a list of elements where we can choose one

2 - Center would be the animated GIF

3 - Bottom would display the element chosen from the list

Here is my code (I need 2 java files, the first (Interf.java) calls the second (Display.java)):

1 - Interf.java

public class Interface_for {

    public static void main(String[] args) {

        Display Fr = new Display();

    }
}

2 - Display.java

INFOS: Be shure to create a new source folder (NEW > source folder) in your java project and put the .gif inside for it to be seen as a file.

I get the gif file with the code below, so I can it export it in a jar project(it's then animated).

URL url = getClass().getClassLoader().getResource("fire.gif");

  public class Display extends JFrame {
  private JPanel container = new JPanel();
  private JComboBox combo = new JComboBox();
  private JLabel label = new JLabel("A list");
  private JLabel label_2 = new JLabel ("Selection");

  public Display(){
    this.setTitle("Animation");
    this.setSize(400, 350);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLocationRelativeTo(null);
    container.setLayout(new BorderLayout());
    combo.setPreferredSize(new Dimension(190, 20));
    //We create te list of elements for the top of the GUI
    String[] tab = {"Option 1","Option 2","Option 3","Option 4","Option 5"};
    combo = new JComboBox(tab);

    //Listener for the selected option
    combo.addActionListener(new ItemAction());

    //We add elements from the top of the interface
    JPanel top = new JPanel();
    top.add(label);
    top.add(combo);
    container.add(top, BorderLayout.NORTH);

    //We add elements from the center of the interface
    URL url = getClass().getClassLoader().getResource("fire.gif");
    Icon icon = new ImageIcon(url);
    JLabel center = new JLabel(icon);
    container.add(center, BorderLayout.CENTER);

    //We add elements from the bottom of the interface
    JPanel down = new JPanel();
    down.add(label_2);
    container.add(down,BorderLayout.SOUTH);

    this.setContentPane(container);
    this.setVisible(true);
    this.setResizable(false);
  }
  class ItemAction implements ActionListener{
      public void actionPerformed(ActionEvent e){
          label_2.setText("Chosen option: "+combo.getSelectedItem().toString());
      }
  }
}

Twitter Bootstrap modal: How to remove Slide down effect

.modal.fade, .modal.fade .modal-dialog {
    -webkit-transition: none;
    -moz-transition: none;
    -ms-transition: none;
    -o-transition: none;
    transition: none;
}

What's the actual use of 'fail' in JUnit test case?

The most important use case is probably exception checking.

While junit4 includes the expected element for checking if an exception occurred, it seems like it isn't part of the newer junit5. Another advantage of using fail() over the expected is that you can combine it with finally allowing test-case cleanup.

dao.insert(obj);
try {
  dao.insert(obj);
  fail("No DuplicateKeyException thrown.");
} catch (DuplicateKeyException e) {
  assertEquals("Error code doesn't match", 123, e.getErrorCode());
} finally {
  //cleanup
  dao.delete(obj);
}

As noted in another comment. Having a test to fail until you can finish implementing it sounds reasonable as well.

scroll image with continuous scrolling using marquee tag

You cannot scroll images continuously using the HTML marquee tag - it must have JavaScript added for the continuous scrolling functionality.

There is a JavaScript plugin called crawler.js available on the dynamic drive forum for achieving this functionality. This plugin was created by John Davenport Scheuer and has been modified over time to suit new browsers.

I have also implemented this plugin into my blog to document all the steps to use this plugin. Here is the sample code:

<head>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script src="assets/js/crawler.js" type="text/javascript" ></script>
</head>

<div id="mycrawler2" style="margin-top: -3px; " class="productswesupport">
    <img src="assets/images/products/ie.png" />
    <img src="assets/images/products/browser.png" />
    <img src="assets/images/products/chrome.png" />
    <img src="assets/images/products/safari.png" />
</div>

Here is the plugin configration:

marqueeInit({
    uniqueid: 'mycrawler2',
    style: {
    },
    inc: 5, //speed - pixel increment for each iteration of this marquee's movement
    mouse: 'cursor driven', //mouseover behavior ('pause' 'cursor driven' or false)
    moveatleast: 2,
    neutral: 150,
    savedirection: true,
    random: true
});

Loop through all nested dictionary values?

A alternative solution to work with lists based on Scharron's solution

def myprint(d):
    my_list = d.iteritems() if isinstance(d, dict) else enumerate(d)

    for k, v in my_list:
        if isinstance(v, dict) or isinstance(v, list):
            myprint(v)
        else:
            print u"{0} : {1}".format(k, v)

How to show PIL images on the screen?

Maybe you can use matplotlib for this, you can also plot normal images with it. If you call show() the image pops up in a window. Take a look at this:

http://matplotlib.org/users/image_tutorial.html

How to compare two files in Notepad++ v6.6.8

There is the "Compare" plugin. You can install it via Plugins > Plugin Manager.

Alternatively you can install a specialized file compare software like WinMerge.

What's the difference between eval, exec, and compile?

The short answer, or TL;DR

Basically, eval is used to evaluate a single dynamically generated Python expression, and exec is used to execute dynamically generated Python code only for its side effects.

eval and exec have these two differences:

  1. eval accepts only a single expression, exec can take a code block that has Python statements: loops, try: except:, class and function/method definitions and so on.

    An expression in Python is whatever you can have as the value in a variable assignment:

    a_variable = (anything you can put within these parentheses is an expression)
    
  2. eval returns the value of the given expression, whereas exec ignores the return value from its code, and always returns None (in Python 2 it is a statement and cannot be used as an expression, so it really does not return anything).

In versions 1.0 - 2.7, exec was a statement, because CPython needed to produce a different kind of code object for functions that used exec for its side effects inside the function.

In Python 3, exec is a function; its use has no effect on the compiled bytecode of the function where it is used.


Thus basically:

>>> a = 5
>>> eval('37 + a')   # it is an expression
42
>>> exec('37 + a')   # it is an expression statement; value is ignored (None is returned)
>>> exec('a = 47')   # modify a global variable as a side effect
>>> a
47
>>> eval('a = 47')  # you cannot evaluate a statement
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    a = 47
      ^
SyntaxError: invalid syntax

The compile in 'exec' mode compiles any number of statements into a bytecode that implicitly always returns None, whereas in 'eval' mode it compiles a single expression into bytecode that returns the value of that expression.

>>> eval(compile('42', '<string>', 'exec'))  # code returns None
>>> eval(compile('42', '<string>', 'eval'))  # code returns 42
42
>>> exec(compile('42', '<string>', 'eval'))  # code returns 42,
>>>                                          # but ignored by exec

In the 'eval' mode (and thus with the eval function if a string is passed in), the compile raises an exception if the source code contains statements or anything else beyond a single expression:

>>> compile('for i in range(3): print(i)', '<string>', 'eval')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print(i)
      ^
SyntaxError: invalid syntax

Actually the statement "eval accepts only a single expression" applies only when a string (which contains Python source code) is passed to eval. Then it is internally compiled to bytecode using compile(source, '<string>', 'eval') This is where the difference really comes from.

If a code object (which contains Python bytecode) is passed to exec or eval, they behave identically, excepting for the fact that exec ignores the return value, still returning None always. So it is possible use eval to execute something that has statements, if you just compiled it into bytecode before instead of passing it as a string:

>>> eval(compile('if 1: print("Hello")', '<string>', 'exec'))
Hello
>>>

works without problems, even though the compiled code contains statements. It still returns None, because that is the return value of the code object returned from compile.

In the 'eval' mode (and thus with the eval function if a string is passed in), the compile raises an exception if the source code contains statements or anything else beyond a single expression:

>>> compile('for i in range(3): print(i)', '<string>'. 'eval')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print(i)
      ^
SyntaxError: invalid syntax

The longer answer, a.k.a the gory details

exec and eval

The exec function (which was a statement in Python 2) is used for executing a dynamically created statement or program:

>>> program = '''
for i in range(3):
    print("Python is cool")
'''
>>> exec(program)
Python is cool
Python is cool
Python is cool
>>> 

The eval function does the same for a single expression, and returns the value of the expression:

>>> a = 2
>>> my_calculation = '42 * a'
>>> result = eval(my_calculation)
>>> result
84

exec and eval both accept the program/expression to be run either as a str, unicode or bytes object containing source code, or as a code object which contains Python bytecode.

If a str/unicode/bytes containing source code was passed to exec, it behaves equivalently to:

exec(compile(source, '<string>', 'exec'))

and eval similarly behaves equivalent to:

eval(compile(source, '<string>', 'eval'))

Since all expressions can be used as statements in Python (these are called the Expr nodes in the Python abstract grammar; the opposite is not true), you can always use exec if you do not need the return value. That is to say, you can use either eval('my_func(42)') or exec('my_func(42)'), the difference being that eval returns the value returned by my_func, and exec discards it:

>>> def my_func(arg):
...     print("Called with %d" % arg)
...     return arg * 2
... 
>>> exec('my_func(42)')
Called with 42
>>> eval('my_func(42)')
Called with 42
84
>>> 

Of the 2, only exec accepts source code that contains statements, like def, for, while, import, or class, the assignment statement (a.k.a a = 42), or entire programs:

>>> exec('for i in range(3): print(i)')
0
1
2
>>> eval('for i in range(3): print(i)')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print(i)
      ^
SyntaxError: invalid syntax

Both exec and eval accept 2 additional positional arguments - globals and locals - which are the global and local variable scopes that the code sees. These default to the globals() and locals() within the scope that called exec or eval, but any dictionary can be used for globals and any mapping for locals (including dict of course). These can be used not only to restrict/modify the variables that the code sees, but are often also used for capturing the variables that the executed code creates:

>>> g = dict()
>>> l = dict()
>>> exec('global a; a, b = 123, 42', g, l)
>>> g['a']
123
>>> l
{'b': 42}

(If you display the value of the entire g, it would be much longer, because exec and eval add the built-ins module as __builtins__ to the globals automatically if it is missing).

In Python 2, the official syntax for the exec statement is actually exec code in globals, locals, as in

>>> exec 'global a; a, b = 123, 42' in g, l

However the alternate syntax exec(code, globals, locals) has always been accepted too (see below).

compile

The compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1) built-in can be used to speed up repeated invocations of the same code with exec or eval by compiling the source into a code object beforehand. The mode parameter controls the kind of code fragment the compile function accepts and the kind of bytecode it produces. The choices are 'eval', 'exec' and 'single':

  • 'eval' mode expects a single expression, and will produce bytecode that when run will return the value of that expression:

    >>> dis.dis(compile('a + b', '<string>', 'eval'))
      1           0 LOAD_NAME                0 (a)
                  3 LOAD_NAME                1 (b)
                  6 BINARY_ADD
                  7 RETURN_VALUE
    
  • 'exec' accepts any kinds of python constructs from single expressions to whole modules of code, and executes them as if they were module top-level statements. The code object returns None:

    >>> dis.dis(compile('a + b', '<string>', 'exec'))
      1           0 LOAD_NAME                0 (a)
                  3 LOAD_NAME                1 (b)
                  6 BINARY_ADD
                  7 POP_TOP                             <- discard result
                  8 LOAD_CONST               0 (None)   <- load None on stack
                 11 RETURN_VALUE                        <- return top of stack
    
  • 'single' is a limited form of 'exec' which accepts a source code containing a single statement (or multiple statements separated by ;) if the last statement is an expression statement, the resulting bytecode also prints the repr of the value of that expression to the standard output(!).

    An if-elif-else chain, a loop with else, and try with its except, else and finally blocks is considered a single statement.

    A source fragment containing 2 top-level statements is an error for the 'single', except in Python 2 there is a bug that sometimes allows multiple toplevel statements in the code; only the first is compiled; the rest are ignored:

    In Python 2.7.8:

    >>> exec(compile('a = 5\na = 6', '<string>', 'single'))
    >>> a
    5
    

    And in Python 3.4.2:

    >>> exec(compile('a = 5\na = 6', '<string>', 'single'))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<string>", line 1
        a = 5
            ^
    SyntaxError: multiple statements found while compiling a single statement
    

    This is very useful for making interactive Python shells. However, the value of the expression is not returned, even if you eval the resulting code.

Thus greatest distinction of exec and eval actually comes from the compile function and its modes.


In addition to compiling source code to bytecode, compile supports compiling abstract syntax trees (parse trees of Python code) into code objects; and source code into abstract syntax trees (the ast.parse is written in Python and just calls compile(source, filename, mode, PyCF_ONLY_AST)); these are used for example for modifying source code on the fly, and also for dynamic code creation, as it is often easier to handle the code as a tree of nodes instead of lines of text in complex cases.


While eval only allows you to evaluate a string that contains a single expression, you can eval a whole statement, or even a whole module that has been compiled into bytecode; that is, with Python 2, print is a statement, and cannot be evalled directly:

>>> eval('for i in range(3): print("Python is cool")')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print("Python is cool")
      ^
SyntaxError: invalid syntax

compile it with 'exec' mode into a code object and you can eval it; the eval function will return None.

>>> code = compile('for i in range(3): print("Python is cool")',
                   'foo.py', 'exec')
>>> eval(code)
Python is cool
Python is cool
Python is cool

If one looks into eval and exec source code in CPython 3, this is very evident; they both call PyEval_EvalCode with same arguments, the only difference being that exec explicitly returns None.

Syntax differences of exec between Python 2 and Python 3

One of the major differences in Python 2 is that exec is a statement and eval is a built-in function (both are built-in functions in Python 3). It is a well-known fact that the official syntax of exec in Python 2 is exec code [in globals[, locals]].

Unlike majority of the Python 2-to-3 porting guides seem to suggest, the exec statement in CPython 2 can be also used with syntax that looks exactly like the exec function invocation in Python 3. The reason is that Python 0.9.9 had the exec(code, globals, locals) built-in function! And that built-in function was replaced with exec statement somewhere before Python 1.0 release.

Since it was desirable to not break backwards compatibility with Python 0.9.9, Guido van Rossum added a compatibility hack in 1993: if the code was a tuple of length 2 or 3, and globals and locals were not passed into the exec statement otherwise, the code would be interpreted as if the 2nd and 3rd element of the tuple were the globals and locals respectively. The compatibility hack was not mentioned even in Python 1.4 documentation (the earliest available version online); and thus was not known to many writers of the porting guides and tools, until it was documented again in November 2012:

The first expression may also be a tuple of length 2 or 3. In this case, the optional parts must be omitted. The form exec(expr, globals) is equivalent to exec expr in globals, while the form exec(expr, globals, locals) is equivalent to exec expr in globals, locals. The tuple form of exec provides compatibility with Python 3, where exec is a function rather than a statement.

Yes, in CPython 2.7 that it is handily referred to as being a forward-compatibility option (why confuse people over that there is a backward compatibility option at all), when it actually had been there for backward-compatibility for two decades.

Thus while exec is a statement in Python 1 and Python 2, and a built-in function in Python 3 and Python 0.9.9,

>>> exec("print(a)", globals(), {'a': 42})
42

has had identical behaviour in possibly every widely released Python version ever; and works in Jython 2.5.2, PyPy 2.3.1 (Python 2.7.6) and IronPython 2.6.1 too (kudos to them following the undocumented behaviour of CPython closely).

What you cannot do in Pythons 1.0 - 2.7 with its compatibility hack, is to store the return value of exec into a variable:

Python 2.7.11+ (default, Apr 17 2016, 14:00:29) 
[GCC 5.3.1 20160413] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = exec('print(42)')
  File "<stdin>", line 1
    a = exec('print(42)')
           ^
SyntaxError: invalid syntax

(which wouldn't be useful in Python 3 either, as exec always returns None), or pass a reference to exec:

>>> call_later(exec, 'print(42)', delay=1000)
  File "<stdin>", line 1
    call_later(exec, 'print(42)', delay=1000)
                  ^
SyntaxError: invalid syntax

Which a pattern that someone might actually have used, though unlikely;

Or use it in a list comprehension:

>>> [exec(i) for i in ['print(42)', 'print(foo)']
  File "<stdin>", line 1
    [exec(i) for i in ['print(42)', 'print(foo)']
        ^
SyntaxError: invalid syntax

which is abuse of list comprehensions (use a for loop instead!).

Error: Module not specified (IntelliJ IDEA)

This is because the className value which you are passing as argument for
forName(String className) method is not found or doesn't exists, or you a re passing the wrong value as the class name. Here is also a link which could help you.

1. https://docs.oracle.com/javase/7/docs/api/java/lang/ClassNotFoundException.html
2. https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#forName(java.lang.String)

Update

Module not specified

According to the snapshot you have provided this problem is because you have not determined the app module of your project, so I suggest you to choose the app module from configuration. For example:

enter image description here

XSS prevention in JSP/Servlet web application

My personal opinion is that you should avoid using JSP/ASP/PHP/etc pages. Instead output to an API similar to SAX (only designed for calling rather than handling). That way there is a single layer that has to create well formed output.

How to set a:link height/width with css?

Anchors will need to be a different display type than their default to take a height. display:inline-block; or display:block;.

Also check on line-height which might be interesting with this.

Converting Milliseconds to Minutes and Seconds?

After converting millis to seconds (by dividing by 1000), you can use / 60 to get the minutes value, and % 60 (remainder) to get the "seconds in minute" value.

long millis = .....;  // obtained from StopWatch
long minutes = (millis / 1000)  / 60;
int seconds = (int)((millis / 1000) % 60);

Printing all properties in a Javascript Object

What about this:

var txt="";
var nyc = {
    fullName: "New York City",
    mayor: "Michael Bloomberg",
    population: 8000000,
    boroughs: 5
};

for (var x in nyc){
    txt += nyc[x];
}

How to compile .c file with OpenSSL includes?

If the OpenSSL headers are in the openssl sub-directory of the current directory, use:

gcc -I. -o Opentest Opentest.c -lcrypto

The pre-processor looks to create a name such as "./openssl/ssl.h" from the "." in the -I option and the name specified in angle brackets. If you had specified the names in double quotes (#include "openssl/ssl.h"), you might never have needed to ask the question; the compiler on Unix usually searches for headers enclosed in double quotes in the current directory automatically, but it does not do so for headers enclosed in angle brackets (#include <openssl/ssl.h>). It is implementation defined behaviour.

You don't say where the OpenSSL libraries are - you might need to add an appropriate option and argument to specify that, such as '-L /opt/openssl/lib'.

XSD - how to allow elements in any order any number of times?

If none of the above is working, you are probably working on EDI trasaction where you need to validate your result against an HIPPA schema or any other complex xsd for that matter. The requirement is that, say there 8 REF segments and any of them have to appear in any order and also not all are required, means to say you may have them in following order 1st REF, 3rd REF , 2nd REF, 9th REF. Under default situation EDI receive will fail, beacause default complex type is

<xs:sequence>
  <xs:element.../>
</xs:sequence>

The situation is even complex when you are calling your element by refrence and then that element in its original spot is quite complex itself. for example:

<xs:element>
<xs:complexType>
<xs:sequence>
<element name="REF1"  ref= "REF1_Mycustomelment" minOccurs="0" maxOccurs="1">
<element name="REF2"  ref= "REF2_Mycustomelment" minOccurs="0" maxOccurs="1">
<element name="REF3"  ref= "REF3_Mycustomelment" minOccurs="0" maxOccurs="1">
</xs:sequence>
</xs:complexType>
</xs:element>

Solution:

Here simply replacing "sequence" with "all" or using "choice" with min/max combinations won't work!

First thing replace "xs:sequence" with "<xs:all>" Now,You need to make some changes where you are Referring the element from, There go to:

<xs:annotation>
  <xs:appinfo>
    <b:recordinfo structure="delimited" field.........Biztalk/2003">

***Now in the above segment add trigger point in the end like this trigger_field="REF01_...complete name.." trigger_value = "38" Do the same for other REF segments where trigger value will be different like say "18", "XX" , "YY" etc..so that your record info now looks like:b:recordinfo structure="delimited" field.........Biztalk/2003" trigger_field="REF01_...complete name.." trigger_value="38">


This will make each element unique, reason being All REF segements (above example) have same structure like REF01, REF02, REF03. And during validation the structure validation is ok but it doesn't let the values repeat because it tries to look for remaining values in first REF itself. Adding triggers will make them all unique and they will pass in any order and situational cases (like use 5 out 9 and not all 9/9).

Hope it helps you, for I spent almost 20 hrs on this.

Good Luck

How to list the size of each file and directory and sort by descending size in Bash?

Another simple solution.

$ for entry in $(ls); do du -s "$entry"; done | sort -n

the result will look like

2900    tmp
6781    boot
8428    bin
24932   lib64
34436   sbin
90084   var
106676  etc
125216  lib
3313136 usr
4828700 opt

changing "du -s" to "du -sh" will show human readable size, but we won't be able to sort in this method.

Visual Studio build fails: unable to copy exe-file from obj\debug to bin\debug

Disable antivirus and try. I was also facing that problem... but in my case antivirus was blocking my application when I disabled antivirus it resolved.

How can I get the number of records affected by a stored procedure?

@@RowCount will give you the number of records affected by a SQL Statement.

The @@RowCount works only if you issue it immediately afterwards. So if you are trapping errors, you have to do it on the same line. If you split it up, you will miss out on whichever one you put second.

SELECT @NumRowsChanged = @@ROWCOUNT, @ErrorCode = @@ERROR

If you have multiple statements, you will have to capture the number of rows affected for each one and add them up.

SELECT @NumRowsChanged = @NumRowsChanged  + @@ROWCOUNT, @ErrorCode = @@ERROR

DBMS_OUTPUT.PUT_LINE not printing

  1. Ensure that you have your Dbms Output window open through the view option in the menubar.
  2. Click on the green '+' sign and add your database name.
  3. Write 'DBMS_OUTPUT.ENABLE;' within your procedure as the first line. Hope this solves your problem.

How to jump to top of browser page

Without animation, you can use plain JS:

scroll(0,0)

With animation, check Nick's answer.

Installing PHP Zip Extension

I tried changing the repository list with:

http://security.ubuntu.com/ubuntu bionic-security main universe http://archive.ubuntu.com/ubuntu bionic main restricted universe

But none of them seem to work, but I finally found a repository that works running the following command

add-apt-repository ppa:ondrej/php

And then updating and installing normally the package using apt-get

As you can see it's installed at last.

How do I read a string entered by the user in C?

On a POSIX system, you probably should use getline if it's available.

You also can use Chuck Falconer's public domain ggets function which provides syntax closer to gets but without the problems. (Chuck Falconer's website is no longer available, although archive.org has a copy, and I've made my own page for ggets.)

Add class to <html> with Javascript?

Like this:

var root = document.getElementsByTagName( 'html' )[0]; // '0' to assign the first (and only `HTML` tag)

root.setAttribute( 'class', 'myCssClass' );

Or use this as your 'setter' line to preserve any previously applied classes: (thanks @ama2)

root.className += ' myCssClass';

Or, depending on the required browser support, you can use the classList.add() method:

root.classList.add('myCssClass');

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList http://caniuse.com/#feat=classlist

UPDATE:

A more elegant solution for referencing the HTML element might be this:

var root = document.documentElement;
root.className += ' myCssClass';
// ... or:
//  root.classList.add('myCssClass');
//

What's alternative to angular.copy in Angular

let newObj = JSON.parse(JSON.stringify(obj))

The JSON.stringify() method converts a JavaScript object or value to a JSON string

How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

First, what you are looking for is a column or bar diagram, not really a histogram. A histogram is made from a frequency distribution of a continuous variable that is separated into bins. Here you have a column against separate labels.

To make a bar diagram with matplotlib, use the matplotlib.pyplot.bar() method. Have a look at this page of the matplotlib documentation that explains very well with examples and source code how to do it.

If it is possible though, I would just suggest that for a simple task like this if you could avoid writing code that would be better. If you have any spreadsheet program this should be a piece of cake because that's exactly what they are for, and you won't have to 'reinvent the wheel'. The following is the plot of your data in Excel:

Bar diagram plot in Excel

I just copied your data from the question, used the text import wizard to put it in two columns, then I inserted a column diagram.

How to run a program automatically as admin on Windows 7 at startup?

This is not possible.
However, you can create a service that runs under an administrative user.

The service can run automatically at startup and communicate with your existing application.
When the application needs to do something as an administrator, it can ask the service to do it for it.

Remember that multiple users can be logged on at once.

Switch statement with returns -- code correctness

Interesting. The consensus from most of these answers seems to be that the redundant break statement is unnecessary clutter. On the other hand, I read the break statement in a switch as the 'closing' of a case. case blocks that don't end in a break tend to jump out at me as potential fall though bugs.

I know that that's not how it is when there's a return instead of a break, but that's how my eyes 'read' the case blocks in a switch, so I personally would prefer that each case be paired with a break. But many compilers do complain about the break after a return being superfluous/unreachable, and apparently I seem to be in the minority anyway.

So get rid of the break following a return.

NB: all of this is ignoring whether violating the single entry/exit rule is a good idea or not. As far as that goes, I have an opinion that unfortunately changes depending on the circumstances...

In Java, how can I determine if a char array contains a particular character?

Here's a variation of Oscar's first version that doesn't use a for-each loop.

for (int i = 0; i < charArray.length; i++) {
    if (charArray[i] == 'q') {
        // do something
        break;
    }
}

You could have a boolean variable that gets set to false before the loop, then make "do something" set the variable to true, which you could test for after the loop. The loop could also be wrapped in a function call then just use 'return true' instead of the break, and add a 'return false' statement after the for loop.

PDO's query vs execute

query runs a standard SQL statement and requires you to properly escape all data to avoid SQL Injections and other issues.

execute runs a prepared statement which allows you to bind parameters to avoid the need to escape or quote the parameters. execute will also perform better if you are repeating a query multiple times. Example of prepared statements:

$sth = $dbh->prepare('SELECT name, colour, calories FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories);
$sth->bindParam(':colour', $colour);
$sth->execute();
// $calories or $color do not need to be escaped or quoted since the
//    data is separated from the query

Best practice is to stick with prepared statements and execute for increased security.

See also: Are PDO prepared statements sufficient to prevent SQL injection?

How to find the Windows version from the PowerShell command line

If you want to differentiate between Windows 8.1 (6.3.9600) and Windows 8 (6.2.9200) use

(Get-CimInstance Win32_OperatingSystem).Version 

to get the proper version. [Environment]::OSVersion doesn't work properly in Windows 8.1 (it returns a Windows 8 version).

How to get current date time in milliseconds in android

try this

  Calendar c = Calendar.getInstance(); 
  int mseconds = c.get(Calendar.MILLISECOND)

an alternative would be

 Calendar rightNow = Calendar.getInstance();

 long offset = rightNow.get(Calendar.ZONE_OFFSET) +
        rightNow.get(Calendar.DST_OFFSET);
 long sinceMid = (rightNow.getTimeInMils() + offset) %
       (24 * 60 * 60 * 1000);

  System.out.println(sinceMid + " milliseconds since midnight");

What are .tpl files? PHP, web design

.tpl shows there is a smarty! Smarty is a template language to split out PHP code from HTML code. Which gives us to the ability to do design stuff on a page which has not included PHP code.

Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused

Just some thoughts on my case.

If you have changed the dbPath and logPath dirs to your custom values (say /data/mongodb/data, /data/mongodb/log), you must chown them to mongodb user, otherwise, the non-existent /data/db/ dir will be used.

sudo chown -R mongodb:mongodb /data/mongodb/

sudo service mongod restart

pop/remove items out of a python tuple

In Python 3 this is no longer an issue, and you really don't want to use list comprehension, coercion, filters, functions or lambdas for something like this.

Just use

popped = unpopped[:-1]

Remember that it's an immutable, so you will have to reassign the value if you want it to change

my_tuple = my_tuple[:-1]

Example

>>> foo= 3,5,2,4,78,2,1
>>> foo
(3, 5, 2, 4, 78, 2, 1)
foo[:-1]
(3, 5, 2, 4, 78, 2)

how to set ulimit / file descriptor on docker container the image tag is phusion/baseimage-docker

Actually, I have tried the above answer, but it did not seem to work.

To get my containers to acknowledge the ulimit change, I had to update the docker.conf file before starting them:

$ sudo service docker stop
$ sudo bash -c "echo \"limit nofile 262144 262144\" >> /etc/init/docker.conf"
$ sudo service docker start

Populating a ListView using an ArrayList?

public class Example extends Activity
{
    private ListView lv;
    ArrayList<String> arrlist=new ArrayList<String>();
    //let me assume that you are putting the values in this arraylist
    //Now convert your arraylist to array

    //You will get an exmaple here

    //http://www.java-tips.org/java-se-tips/java.lang/how-to-convert-an-arraylist-into-an-array.html 

    private String arr[]=convert(arrlist);
    @Override
    public void onCreate(Bundle bun)
    {
        super.onCreate(bun);
        setContentView(R.layout.main);
        lv=(ListView)findViewById(R.id.lv);
        lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , arr));
        }
    }

How to use a variable of one method in another method?

You can't. Variables defined inside a method are local to that method.

If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).


Looks like you're using instance methods instead of static ones.

If you don't want to create an object, you should declare all your methods static, so something like

private static void methodName(Argument args...)

If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.

private static int[][] array = new int[3][5];

Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.

Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.

Here's a final (shortened) example of what your code should be like:

public class Test3 {
    //Use this array in your methods
    private static int[][] scores = new int[3][5];

    /* Rather than just "Scores" name it so people know what
     * to expect
     */
    private static void createScores() {
        //Code...
    }
    //Other methods...

    /* Since you're now using static methods, you don't 
     * have to initialise an object and call its methods.
     */
    public static void main(String[] args){
        createScores();
        MD();   //Don't know what these do
        sumD(); //so I'll leave them.
    }
}

Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.

How to quickly drop a user with existing privileges

In commandline, there is a command dropuser available to do drop user from postgres.

$ dropuser someuser

Convert Enum to String

I create a "Description" extension method and attach it to the enum so that i can get truly user-friendly naming that includes spaces and casing. I have never liked using the enum value itself as displayable text because it is something we developers use to create more readable code. It is not intended for UI display purposes. I want to be able to change the UI without going through and changing enums all over.

Difference between attr_accessor and attr_accessible

A quick & concise difference overview :

attr_accessor is an easy way to create read and write accessors in your class. It is used when you do not have a column in your database, but still want to show a field in your forms. This field is a “virtual attribute” in a Rails model.

virtual attribute – an attribute not corresponding to a column in the database.

attr_accessible is used to identify attributes that are accessible by your controller methods makes a property available for mass-assignment.. It will only allow access to the attributes that you specify, denying the rest.

Unit Tests not discovered in Visual Studio 2017

Be sure that you are using the correct Microsoft.NET.Test.Sdk:

<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.0.0" />

Do not use pre-release ones. Or you have to change to console app (not library). I have the similar issue, but with the latest release (15.0.0), it starts working again.

Also, you may have to add:

<ItemGroup>
  <Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />
</ItemGroup>

but I do not think it is nessesary.

Display two fields side by side in a Bootstrap Form

How about using an input group to style it on the same line?

Here's the final HTML to use:

<div class="input-group">
    <input type="text" class="form-control" placeholder="Start"/>
    <span class="input-group-addon">-</span>
    <input type="text" class="form-control" placeholder="End"/>
</div>

Which will look like this:

screenshot

Here's a Stack Snippet Demo:

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="input-group">_x000D_
    <input type="text" class="form-control" placeholder="Start"/>_x000D_
    <span class="input-group-addon">-</span>_x000D_
    <input type="text" class="form-control" placeholder="End"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

I'll leave it as an exercise to the reader to translate it into an asp:textbox element

How can I run a html file from terminal?

It is possible to view a html file from terminal using lynx or links. But none of those browswers support the onload javascript feature. By using lynx or links you will have to actively click the submit button.

Enable tcp\ip remote connections to sql server express already installed database with code or script(query)

I recommend to use SMO (Enable TCP/IP Network Protocol for SQL Server). However, it was not available in my case.

I rewrote the WMI commands from Krzysztof Kozielczyk to PowerShell.

# Enable TCP/IP

Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocol -Filter "InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'" |
Invoke-CimMethod -Name SetEnable

# Open the right ports in the firewall
New-NetFirewallRule -DisplayName 'MSSQL$SQLEXPRESS' -Direction Inbound -Action Allow -Protocol TCP -LocalPort 1433

# Modify TCP/IP properties to enable an IP address

$properties = Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocolProperty -Filter "InstanceName='SQLEXPRESS' and ProtocolName = 'Tcp' and IPAddressName='IPAll'"
$properties | ? { $_.PropertyName -eq 'TcpPort' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '1433' }
$properties | ? { $_.PropertyName -eq 'TcpPortDynamic' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '' }

# Restart SQL Server

Restart-Service 'MSSQL$SQLEXPRESS'

CSS selector for a checked radio button's label

UPDATE:

This only worked for me because our existing generated html was wacky, generating labels along with radios and giving them both checked attribute.

Never mind, and big ups for Brilliand for bringing it up!

If your label is a sibling of a checkbox (which is usually the case), you can use the ~ sibling selector, and a label[for=your_checkbox_id] to address it... or give the label an id if you have multiple labels (like in this example where I use labels for buttons)


Came here looking for the same - but ended up finding my answer in the docs.

a label element with checked attribute can be selected like so:

label[checked] {
  ...
}

I know it's an old question, but maybe it helps someone out there :)

What should my Objective-C singleton look like?

@interface MySingleton : NSObject
{
}

+ (MySingleton *)sharedSingleton;
@end

@implementation MySingleton

+ (MySingleton *)sharedSingleton
{
  static MySingleton *sharedSingleton;

  @synchronized(self)
  {
    if (!sharedSingleton)
      sharedSingleton = [[MySingleton alloc] init];

    return sharedSingleton;
  }
}

@end

[Source]

The forked VM terminated without saying properly goodbye. VM crash or System.exit called

This seems to be a thread sync issue on certain Windows machines. If you're having this problem with Windows, try redirecting the output to a file: mvn clean install > output.txt

Check if an element is present in a Bash array

array=("word" "two words") # let's look for "two words"

using grep and printf:

(printf '%s\n' "${array[@]}" | grep -x -q "two words") && <run_your_if_found_command_here>

using for:

(for e in "${array[@]}"; do [[ "$e" == "two words" ]] && exit 0; done; exit 1) && <run_your_if_found_command_here>

For not_found results add || <run_your_if_notfound_command_here>

How to prepend a string to a column value in MySQL?

You can use the CONCAT function to do that:

UPDATE tbl SET col=CONCAT('test',col);

If you want to get cleverer and only update columns which don't already have test prepended, try

UPDATE tbl SET col=CONCAT('test',col)
WHERE col NOT LIKE 'test%';

How to request Administrator access inside a batch file

Another PowerShell Solution...

This is not about running a batch script as admin per, but rather how to elevate another program from batch...

I have a batch file "wrapper" for an exe. They have the same "root file name", but alternate extensions. I am able to launch the exe as admin, and set the working directory to the one containing the script, with the following one line powershell invocation:

@powershell "Start-Process -FilePath '%~n0.exe' -WorkingDirectory '%~dp0' -Verb RunAs"

More info

There are a whole slew of additional Start-Process options as well that you can apply! Check out: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/start-process?view=powershell-6

Note that I use the @ prefix. That's equivalent to @echo off for the one line. I use %~n0 here to get the "root name" of the batch script, then I concatenate the .exe to point it the adjancent binary. The use of %~dp0 provides the full path to the directory which the batch resides. And, of course, the -Verb RunAs parameter provides the elevation.

How to set environment variables in Jenkins?

For some reason sudo su - jenkins does not log me to jenkins user, I ended up using different approach.

I was successful setting the global env variables using using jenkins config.xml at /var/lib/jenkins/config.xml (installed in Linux/ RHEL) - without using external plugins.

I simply had to stop jenkins add then add globalNodeProperties, and then restart.

Example, I'm defining variables APPLICATION_ENVIRONMENT and SPRING_PROFILES_ACTIVE to continious_integration below,

<?xml version='1.0' encoding='UTF-8'?>
<hudson>

  <globalNodeProperties>
    <hudson.slaves.EnvironmentVariablesNodeProperty>
      <envVars serialization="custom">
        <unserializable-parents/>
        <tree-map>
          <default>
            <comparator class="hudson.util.CaseInsensitiveComparator"/>
          </default>
          <int>2</int>
          <string>APPLICATION_ENVIRONMENT</string>
          <string>continious_integration</string>
          <string>SPRING_PROFILES_ACTIVE</string>
          <string>continious_integration</string>
        </tree-map>
      </envVars>
    </hudson.slaves.EnvironmentVariablesNodeProperty>
  </globalNodeProperties>
</hudson>

.prop() vs .attr()

One thing .attr() can do that .prop() can't: affect CSS selectors

Here's an issue I didn't see in the other answers.

CSS selector [name=value]

  • will respond to .attr('name', 'value')
  • but not always to .prop('name', 'value')

.prop() affects only a few attribute-selectors

.attr() affects all attribute-selectors

How to import XML file into MySQL database table using XML_LOAD(); function

you can specify fields like this:

LOAD XML LOCAL INFILE '/pathtofile/file.xml' 
INTO TABLE my_tablename(personal_number, firstname, ...); 

TypeError: sequence item 0: expected string, int found

Replace

values = ",".join(value_list)

with

values = ','.join([str(i) for i in value_list])

OR

values = ','.join(str(value_list)[1:-1])

How to get TimeZone from android mobile?

All the answers here seem to suggest setting the daylite parameter to false. This is incorrect for many timezones which change abbreviated names depending on the time of the year (e.g. EST vs EDT).

The solution below will give you the correct abbreviation according to the current date for the timezone.

val tz = TimeZone.getDefault()
val isDaylite = tz.inDaylightTime(Date())
val timezone = tz.getDisplayName(isDaylite, TimeZone.SHORT)

How can I select all rows with sqlalchemy?

I use the following snippet to view all the rows in a table. Use a query to find all the rows. The returned objects are the class instances. They can be used to view/edit the values as required:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, Sequence
from sqlalchemy import String, Integer, Float, Boolean, Column
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class MyTable(Base):
    __tablename__ = 'MyTable'
    id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
    some_col = Column(String(500))

    def __init__(self, some_col):
        self.some_col = some_col

engine = create_engine('sqlite:///sqllight.db', echo=True)
Session = sessionmaker(bind=engine)
session = Session()

for class_instance in session.query(MyTable).all():
    print(vars(class_instance))

session.close()

Generic type conversion FROM string

TypeDescriptor.GetConverter(PropertyObject).ConvertFrom(Value)

TypeDescriptor is class having method GetConvertor which accept a Type object and then you can call ConvertFrom method to convert the value for that specified object.

Truncate/round whole number in JavaScript?

Math.trunc() function removes all the fractional digits.

For positive number it behaves exactly the same as Math.floor():

console.log(Math.trunc(89.13349)); // output is 89

For negative numbers it behaves same as Math.ceil():

console.log(Math.trunc(-89.13349)); //output is -89

Removing highcharts.com credits link

credits : null

also works to disable the credits

Android emulator: could not get wglGetExtensionsStringARB error

For me changing the Emulated Performance setting to "Store a snapshot for faster startup" and unchecking "Use Host GPU" fixed the problem.

:first-child not working as expected

The element cannot directly inherit from <body> tag. You can try to put it in a <dir style="padding-left:0px;"></dir> tag.

How to convert a Hibernate proxy to a real entity object

I found a solution to deproxy a class using standard Java and JPA API. Tested with hibernate, but does not require hibernate as a dependency and should work with all JPA providers.

Onle one requirement - its necessary to modify parent class (Address) and add a simple helper method.

General idea: add helper method to parent class which returns itself. when method called on proxy, it will forward the call to real instance and return this real instance.

Implementation is a little bit more complex, as hibernate recognizes that proxied class returns itself and still returns proxy instead of real instance. Workaround is to wrap returned instance into a simple wrapper class, which has different class type than the real instance.

In code:

class Address {
   public AddressWrapper getWrappedSelf() {
       return new AddressWrapper(this);
   }
...
}

class AddressWrapper {
    private Address wrappedAddress;
...
}

To cast Address proxy to real subclass, use following:

Address address = dao.getSomeAddress(...);
Address deproxiedAddress = address.getWrappedSelf().getWrappedAddress();
if (deproxiedAddress instanceof WorkAddress) {
WorkAddress workAddress = (WorkAddress)deproxiedAddress;
}

How to truncate a foreign key constrained table?

I would simply do it with :

DELETE FROM mytest.instance;
ALTER TABLE mytest.instance AUTO_INCREMENT = 1;

SessionTimeout: web.xml vs session.maxInactiveInterval()

Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.

No, that's not true. The session-timeout configures a per session timeout in case of inactivity.

Are these methods equivalent? Should I favour the web.xml config?

The setting in the web.xml is global, it applies to all sessions of a given context. Programatically, you can change this for a particular session.

How to change the background color on a Java panel?

setBackground() is the right method to use. Did you repaint after you changed it? If you change it before you make the panel (or its containing frame) visible it should work

MySQL Results as comma separated list

Instead of using group concat() you can use just concat()

Select concat(Col1, ',', Col2) as Foo_Bar from Table1;

edit this only works in mySQL; Oracle concat only accepts two arguments. In oracle you can use something like select col1||','||col2||','||col3 as foobar from table1; in sql server you would use + instead of pipes.

ImportError: no module named win32api

I had an identical problem, which I solved by restarting my Python editor and shell. I had installed pywin32 but the new modules were not picked up until the restarts.

If you've already done that, do a search in your Python installation for win32api and you should find win32api.pyd under ${PYTHON_HOME}\Lib\site-packages\win32.

How to replace four spaces with a tab in Sublime Text 2?

To configure Sublime to always use tabs try the adding the following to preferences->settings-user:

{
    "tab_size": 4,
    "translate_tabs_to_spaces": false
}

More information here: http://www.sublimetext.com/docs/2/indentation.html

Why does Git tell me "No such remote 'origin'" when I try to push to origin?

I faced this issue when I was tring to link a locally created repo with a blank repo on github. Initially I was trying git remote set-url but I had to do git remote add instead.

git remote add origin https://github.com/VijayNew/NewExample.git

How to make a <div> or <a href="#"> to align center

You can put in in a paragraph

<p style="text-align:center;"><a href="contact.html" class="button large hpbottom">Get Started</a></p>

To align a div in the center, you have to do 2 things: - Make the div a fixed width - Set the left and right margin properties variable

<div class="container">
 <div style="width:100px; margin:0 auto;">
     <span>a centered div</span>
  </div>
</div>

Determining type of an object in ruby

The proper way to determine the "type" of an object, which is a wobbly term in the Ruby world, is to call object.class.

Since classes can inherit from other classes, if you want to determine if an object is "of a particular type" you might call object.is_a?(ClassName) to see if object is of type ClassName or derived from it.

Normally type checking is not done in Ruby, but instead objects are assessed based on their ability to respond to particular methods, commonly called "Duck typing". In other words, if it responds to the methods you want, there's no reason to be particular about the type.

For example, object.is_a?(String) is too rigid since another class might implement methods that convert it into a string, or make it behave identically to how String behaves. object.respond_to?(:to_s) would be a better way to test that the object in question does what you want.

Convert string to integer type in Go?

For example,

package main

import (
    "flag"
    "fmt"
    "os"
    "strconv"
)

func main() {
    flag.Parse()
    s := flag.Arg(0)
    // string to int
    i, err := strconv.Atoi(s)
    if err != nil {
        // handle error
        fmt.Println(err)
        os.Exit(2)
    }
    fmt.Println(s, i)
}

Android ADB commands to get the device properties

From Linux Terminal:

adb shell getprop | grep "model\|version.sdk\|manufacturer\|hardware\|platform\|revision\|serialno\|product.name\|brand"

From Windows PowerShell:

adb shell 
getprop | grep -e 'model' -e 'version.sdk' -e 'manufacturer' -e 'hardware' -e 'platform' -e 'revision' -e 'serialno' -e 'product.name' -e 'brand'

Sample output for Samsung:

[gsm.version.baseband]: [G900VVRU2BOE1]
[gsm.version.ril-impl]: [Samsung RIL v3.0]
[net.knoxscep.version]: [2.0.1]
[net.knoxsso.version]: [2.1.1]
[net.knoxvpn.version]: [2.2.0]
[persist.service.bdroid.version]: [4.1]
[ro.board.platform]: [msm8974]
[ro.boot.hardware]: [qcom]
[ro.boot.serialno]: [xxxxxx]
[ro.build.version.all_codenames]: [REL]
[ro.build.version.codename]: [REL]
[ro.build.version.incremental]: [G900VVRU2BOE1]
[ro.build.version.release]: [5.0]
[ro.build.version.sdk]: [21]
[ro.build.version.sdl]: [2101]
[ro.com.google.gmsversion]: [5.0_r2]
[ro.config.timaversion]: [3.0]
[ro.hardware]: [qcom]
[ro.opengles.version]: [196108]
[ro.product.brand]: [Verizon]
[ro.product.manufacturer]: [samsung]
[ro.product.model]: [SM-G900V]
[ro.product.name]: [kltevzw]
[ro.revision]: [14]
[ro.serialno]: [e5ce97c7]

ssh: connect to host github.com port 22: Connection timed out

The main reason was the change from the proxy installed by the company recently, which has blocked other ssh connections other than those to the company domain.

I was able to connect successfully by following these steps:

  1. Double checked that the issue is what I am assuming by ssh -T [email protected]

It should end up in a timeout.

  1. Edited the local remote URL by

ssh config --local -e

and from

[email protected]:asheeshjanghu/Journal.git

to

url=https://github.com/asheeshjanghu/Journal.git

The important point is that in the url you have to change at 2 places.

from git@ to https:// and from github:username to github/username

In the end verify by doing a git fetch

How do I skip a header from CSV files in Spark?

You could load each file separately, filter them with file.zipWithIndex().filter(_._2 > 0) and then union all the file RDDs.

If the number of files is too large, the union could throw a StackOverflowExeption.

Activity restart on rotation Android

What you describe is the default behavior. You have to detect and handle these events yourself by adding:

android:configChanges

to your manifest and then the changes that you want to handle. So for orientation, you would use:

android:configChanges="orientation"

and for the keyboard being opened or closed you would use:

android:configChanges="keyboardHidden"

If you want to handle both you can just separate them with the pipe command like:

android:configChanges="keyboardHidden|orientation"

This will trigger the onConfigurationChanged method in whatever Activity you call. If you override the method you can pass in the new values.

Hope this helps.

How can I create a "Please Wait, Loading..." animation using jQuery?

This would make the buttons disappear, then an animation of "loading" would appear in their place and finally just display a success message.

$(function(){
    $('#submit').click(function(){
        $('#submit').hide();
        $("#form .buttons").append('<img src="assets/img/loading.gif" alt="Loading..." id="loading" />');
        $.post("sendmail.php",
                {emailFrom: nameVal, subject: subjectVal, message: messageVal},
                function(data){
                    jQuery("#form").slideUp("normal", function() {                 
                        $("#form").before('<h1>Success</h1><p>Your email was sent.</p>');
                    });
                }
        );
    });
});

Scheduling Python Script to run every hour accurately

To run something every 10 minutes past the hour.

from datetime import datetime, timedelta

while 1:
    print 'Run something..'

    dt = datetime.now() + timedelta(hours=1)
    dt = dt.replace(minute=10)

    while datetime.now() < dt:
        time.sleep(1)

Change placeholder text

Using jquery you can do this by following code:

<input type="text" id="tbxEmail" name="Email" placeholder="Some Text"/>

$('#tbxEmail').attr('placeholder','Some New Text');

Difference between abstraction and encapsulation?

Encapsulation: Is hiding unwanted/un-expected/propriety implementation details from the actual users of object. e.g.

List<string> list = new List<string>();
list.Sort(); /* Here, which sorting algorithm is used and hows its 
implemented is not useful to the user who wants to perform sort, that's 
why its hidden from the user of list. */

Abstraction: Is a way of providing generalization and hence a common way to work with objects of vast diversity. e.g.

class Aeroplane : IFlyable, IFuelable, IMachine
{ // Aeroplane's Design says:
  // Aeroplane is a flying object
  // Aeroplane can be fueled
  // Aeroplane is a Machine
}
// But the code related to Pilot, or Driver of Aeroplane is not bothered 
// about Machine or Fuel. Hence,
// pilot code:
IFlyable flyingObj = new Aeroplane();
flyingObj.Fly();
// fighter Pilot related code
IFlyable flyingObj2 = new FighterAeroplane();
flyingObj2.Fly();
// UFO related code 
IFlyable ufoObj = new UFO();
ufoObj.Fly();
// **All the 3 Above codes are genaralized using IFlyable,
// Interface Abstraction**
// Fly related code knows how to fly, irrespective of the type of 
// flying object they are.

// Similarly, Fuel related code:
// Fueling an Aeroplane
IFuelable fuelableObj = new Aeroplane();
fuelableObj.FillFuel();
// Fueling a Car
IFuelable fuelableObj2 = new Car(); // class Car : IFuelable { }
fuelableObj2.FillFuel();

// ** Fueling code does not need know what kind of vehicle it is, so far 
// as it can Fill Fuel**

How can I wrap text in a label using WPF?

Often you cannot replace a Label with a TextBlock as you want to the use the Target property (which sets focus to the targeted control when using the keyboard e.g. ALT+C in the sample code below), as that's all a Label really offers over a TextBlock.

However, a Label uses a TextBlock to render text (if a string is placed in the Content property, which it typically is); therefore, you can add a style for TextBlock inside the Label like so:

<Label              
    Content="_Content Text:"
    Target="{Binding ElementName=MyTargetControl}">
    <Label.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="TextWrapping" Value="Wrap" />
        </Style>
    </Label.Resources>
 </Label>
 <CheckBox x:Name = "MyTargetControl" />

This way you get to keep the functionality of a Label whilst also being able to wrap the text.

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.

Cross-browser bookmark/add to favorites JavaScript

function bookmark(title, url) {
  if (window.sidebar) { 
    // Firefox
    window.sidebar.addPanel(title, url, '');
  } 
  else if (window.opera && window.print) 
  { 
    // Opera
    var elem = document.createElement('a');
    elem.setAttribute('href', url);
    elem.setAttribute('title', title);
    elem.setAttribute('rel', 'sidebar');
    elem.click(); //this.title=document.title;
  } 
  else if (document.all) 
  { 
    // ie
    window.external.AddFavorite(url, title);
  }
}

I used this & works great in IE, FF, Netscape. Chrome, Opera and safari do not support it!

Google Play error "Error while retrieving information from server [DF-DFERH-01]"

I had the same issue. Solved it simply; I have (2) google accounts linked to my Play Store. It just so happens that I installed "an" app from "account B", and I was trying to rate it from "account A". So, switched accounts, and voilá.

Get lengths of a list in a jinja2 template

Alex' comment looks good but I was still confused with using range. The following worked for me while working on a for condition using length within range.

{% for i in range(0,(nums['list_users_response']['list_users_result']['users'])| length) %}
<li>    {{ nums['list_users_response']['list_users_result']['users'][i]['user_name'] }} </li>
{% endfor %}

Replace one character with another in Bash

You could use tr, like this:

tr " " .

Example:

# echo "hello world" | tr " " .
hello.world

From man tr:

DESCRIPTION
     Translate, squeeze, and/or delete characters from standard input, writ- ing to standard output.

How to set DialogFragment's width and height?

You can use percentage for width.

<style name="Theme.Holo.Dialog.MinWidth">
<item name="android:windowMinWidthMajor">70%</item>

I used Holo Theme for this example.

Dialogs / AlertDialogs: How to "block execution" while dialog is up (.NET-style)

A simplified version of Daniel's answer above. This function gets a yes or no from user in an alert dialog but could easily be modified to get other input.

private boolean mResult;
public boolean getYesNoWithExecutionStop(String title, String message, Context context) {
    // make a handler that throws a runtime exception when a message is received
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message mesg) {
            throw new RuntimeException();
        } 
    };

    // make a text input dialog and show it
    AlertDialog.Builder alert = new AlertDialog.Builder(context);
    alert.setTitle(title);
    alert.setMessage(message);
    alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            mResult = true;
            handler.sendMessage(handler.obtainMessage());
        }
    });
    alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            mResult = false;
            handler.sendMessage(handler.obtainMessage());
        }
    });
    alert.show();

    // loop till a runtime exception is triggered.
    try { Looper.loop(); }
    catch(RuntimeException e2) {}

    return mResult;
}

How to check View Source in Mobile Browsers (Both Android && Feature Phone)

The view-source url prefix trick didn't work for me using chrome on an iphone. There are apps I could have installed to do this I guess but for whatever reason I just preferred to do it myself rather than install 'yet another app'.

I found this nice quick tutorial for how to setup a bookmark on mobile safari that will automatically open the view source of a page: https://appletoolbox.com/2014/03/how-to-view-webpage-html-source-codes-on-ipad-iphone-no-app-required/

It worked flawlessly for me and now I have it set as a permanent bookmark any time I want, with no app installed.

Edit: There are basically 6 steps which should work for either Chrome or Safari. Instructions for Safari are:

  1. Open Safari and browse to an arbitrary page.
  2. Select the "Share" (or action") button in Safari (looks like a square with an arrow coming out of the top).
  3. Select "Add Bookmark"
  4. Delete the page title and replace it with something useful like "Show Page Source". Click Save.
  5. Next browse to this exact Stack Overflow answer on your phone and copy the javascript code below to your phone clipboard (code credit: Rob Flaherty):
javascript:(function(){var a=window.open('about:blank').document;a.write('<!DOCTYPE html><html><head><title>Source of '+location.href+'</title><meta name="viewport" content="width=device-width" /></head><body></body></html>');a.close();var b=a.body.appendChild(a.createElement('pre'));b.style.overflow='auto';b.style.whiteSpace='pre-wrap';b.appendChild(a.createTextNode(document.documentElement.innerHTML))})();
  1. Open the "Bookmarks" in Safari and opt to Edit the newly created Show Page Source bookmark. Delete whatever was previously saved in the Address field and instead paste in the Javascript code. Save it.
  2. (Optional) Profit!

Concatenating variables in Bash

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

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

explanations

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

mystring="$arg112$arg2endoffile"

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

another solution

(less portable : require bash > 3.1)

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

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

How to get bitmap from a url in android?

This is a simple one line way to do it:

    try {
        URL url = new URL("http://....");
        Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
    } catch(IOException e) {
        System.out.println(e);
    }

Python 101: Can't open file: No such file or directory

Prior to running python, type cd in the commmand line, and it will tell you the directory you are currently in. When python runs, it can only access files in this directory. hello.py needs to be in this directory, so you can move hello.py from its existing location to this folder as you would move any other file in Windows or you can change directories and run python in the directory hello.py is.

Edit: Python cannot access the files in the subdirectory unless a path to it provided. You can access files in any directory by providing the path. python C:\Python27\Projects\hello.p

Class file for com.google.android.gms.internal.zzaja not found

As stated in the Google documentation, Add the latest version of the Google Service plugin (4.0.1 on 06/04/18). Hope this hepls!

buildscript {
    // ...
    dependencies {
        // ...
        classpath 'com.google.gms:google-services:4.0.1' // google-services plugin
    }
}
`

Convert special characters to HTML in Javascript

Here's a good library I've found very useful in this context.

https://github.com/mathiasbynens/he

According to its author:

It supports all standardized named character references as per HTML, handles ambiguous ampersands and other edge cases just like a browser would, has an extensive test suite, and — contrary to many other JavaScript solutions — he handles astral Unicode symbols just fine

Best PHP IDE for Mac? (Preferably free!)

Here's the lowdown on Mac IDE's for PHP

NetBeans Free! Plus, the best functionality of all offerings. Includes inline database connections, code completion, syntax checking, color coding, split views etc. Downside: It's a memory hog on the Mac. Be prepared to allow half a gig of memory then you'll need to shut down and restart.

Komodo A step above a Text Editor. Does not support database connections or split views. Color coding and syntax checking are there to an extent. The project control on Komodo is very unwieldy and strange compared to the other IDEs.

Aptana The perfect solution. Eclipsed based and uses the Aptana PHP plug in. Real time syntax checking, word wrap, drag and drop split views, database connections and a slew of other excellent features. Downside: Not a supported product any more. Aptana Studio 2.0+ uses PDT which is a watered down, under-developed (at present) php plug in.

Zend Studio - Almost identical to Aptana, except no word wrap and you can't change alot of the php configuration on the MAC apparently due to bugs.

Coda Created by Panic, Coda has nice integration with source control and their popular FTP client, transmit. They also have a collaboration feature which is cool for pair-programming.

PhpEd with Parallels or Wine. The best IDE for Windows has all the feature you could need and is worth the effort to pass it through either Parallels or Wine.

Dreamweaver Good for Javascript/HTML/CSS, but only marginal for PHP. There is some color coding, but no syntax checking or code completion native to the package. Database connections are supported, and so are split views.

I'm using NetBeans, which is free, and feature rich. I can deal with the memory issues for a while, but it could be slow coming to the MAC.

Cheers! Korky Kathman Senior Partner Entropy Dynamics, LLC

How to pass parameters to the DbContext.Database.ExecuteSqlCommand method?

public static class DbEx {
    public static IEnumerable<T> SqlQueryPrm<T>(this System.Data.Entity.Database database, string sql, object parameters) {
        using (var tmp_cmd = database.Connection.CreateCommand()) {
            var dict = ToDictionary(parameters);
            int i = 0;
            var arr = new object[dict.Count];
            foreach (var one_kvp in dict) {
                var param = tmp_cmd.CreateParameter();
                param.ParameterName = one_kvp.Key;
                if (one_kvp.Value == null) {
                    param.Value = DBNull.Value;
                } else {
                    param.Value = one_kvp.Value;
                }
                arr[i] = param;
                i++;
            }
            return database.SqlQuery<T>(sql, arr);
        }
    }
    private static IDictionary<string, object> ToDictionary(object data) {
        var attr = System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance;
        var dict = new Dictionary<string, object>();
        foreach (var property in data.GetType().GetProperties(attr)) {
            if (property.CanRead) {
                dict.Add(property.Name, property.GetValue(data, null));
            }
        }
        return dict;
    }
}

Usage:

var names = db.Database.SqlQueryPrm<string>("select name from position_category where id_key=@id_key", new { id_key = "mgr" }).ToList();

Copying text to the clipboard using Java

This is the accepted answer written in a decorative way:

Toolkit.getDefaultToolkit()
        .getSystemClipboard()
        .setContents(
                new StringSelection(txtMySQLScript.getText()),
                null
        );

Multi-dimensional arraylist or list in C#?

If you want to modify this I'd go with either of the following:

List<string[]> results;

-- or --

List<List<string>> results;

depending on your needs...

How to add a form load event (currently not working)

You got half of the answer! Now that you created the event handler, you need to hook it to the form so that it actually gets called when the form is loading. You can achieve that by doing the following:

 public class ProgramViwer : Form{
  public ProgramViwer()
  {
       InitializeComponent();
       Load += new EventHandler(ProgramViwer_Load);
  }
  private void ProgramViwer_Load(object sender, System.EventArgs e)
  {
       formPanel.Controls.Clear();
       formPanel.Controls.Add(wel);
  }
}

What is git fast-forwarding?

In Git, to "fast forward" means to update the HEAD pointer in such a way that its new value is a direct descendant of the prior value. In other words, the prior value is a parent, or grandparent, or grandgrandparent, ...

Fast forwarding is not possible when the new HEAD is in a diverged state relative to the stream you want to integrate. For instance, you are on master and have local commits, and git fetch has brought new upstream commits into origin/master. The branch now diverges from its upstream and cannot be fast forwarded: your master HEAD commit is not an ancestor of origin/master HEAD. To simply reset master to the value of origin/master would discard your local commits. The situation requires a rebase or merge.

If your local master has no changes, then it can be fast-forwarded: simply updated to point to the same commit as the latestorigin/master. Usually, no special steps are needed to do fast-forwarding; it is done by merge or rebase in the situation when there are no local commits.

Is it ok to assume that fast-forward means all commits are replayed on the target branch and the HEAD is set to the last commit on that branch?

No, that is called rebasing, of which fast-forwarding is a special case when there are no commits to be replayed (and the target branch has new commits, and the history of the target branch has not been rewritten, so that all the commits on the target branch have the current one as their ancestor.)

What issues should be considered when overriding equals and hashCode in Java?

Still amazed that none recommended the guava library for this.

 //Sample taken from a current working project of mine just to illustrate the idea

    @Override
    public int hashCode(){
        return Objects.hashCode(this.getDate(), this.datePattern);
    }

    @Override
    public boolean equals(Object obj){
        if ( ! obj instanceof DateAndPattern ) {
            return false;
        }
        return Objects.equal(((DateAndPattern)obj).getDate(), this.getDate())
                && Objects.equal(((DateAndPattern)obj).getDate(), this.getDatePattern());
    }

How to save LogCat contents to file?

To save LogCat log to file programmatically on your device use for example this code:

String filePath = Environment.getExternalStorageDirectory() + "/logcat.txt";
Runtime.getRuntime().exec(new String[]{"logcat", "-f", filepath, "MyAppTAG:V", "*:S"});

"MyAppTAG:V" sets the priority level for all tags to Verbose (lowest priority)

"*:S" sets the priority level for all tags to "silent"

More information about logcat here.

git push rejected

First, attempt to pull from the same refspec that you are trying to push to.

If this does not work, you can force a git push by using git push -f <repo> <refspec>, but use caution: this method can cause references to be deleted on the remote repository.

SQL query: Delete all records from the table except latest N?

If your id is incremental then use something like

delete from table where id < (select max(id) from table)-N

SQL Server Installation - What is the Installation Media Folder?

For me the Issue was I didn't run the setup as Administrator, after running the setup as administrator the message go away and I was prompted to install and continue process.

How do I find the size of a struct?

Contrary to what some of the other answers have said, on most systems, in the absence of a pragma or compiler option, the size of the structure will be at least 6 bytes and, on most 32-bit systems, 8 bytes. For 64-bit systems, the size could easily be 16 bytes. Alignment does come into play; always. The sizeof a single struct has to be such that an array of those sizes can be allocated and the individual members of the array are sufficiently aligned for the processor in question. Consequently, if the size of the struct was 5 as others have hypothesized, then an array of two such structures would be 10 bytes long, and the char pointer in the second array member would be aligned on an odd byte, which would (on most processors) cause a major bottleneck in the performance.

Given a class, see if instance has method (Ruby)

While respond_to? will return true only for public methods, checking for "method definition" on a class may also pertain to private methods.

On Ruby v2.0+ checking both public and private sets can be achieved with

Foo.private_instance_methods.include?(:bar) || Foo.instance_methods.include?(:bar)

How can I get the count of milliseconds since midnight for the current?

Joda-Time

I think you can use Joda-Time to do this. Take a look at the DateTime class and its getMillisOfSecond method. Something like

int ms = new DateTime().getMillisOfSecond() ;

Why am I getting an error "Object literal may only specify known properties"?

As of TypeScript 1.6, properties in object literals that do not have a corresponding property in the type they're being assigned to are flagged as errors.

Usually this error means you have a bug (typically a typo) in your code, or in the definition file. The right fix in this case would be to fix the typo. In the question, the property callbackOnLoactionHash is incorrect and should have been callbackOnLocationHash (note the mis-spelling of "Location").

This change also required some updates in definition files, so you should get the latest version of the .d.ts for any libraries you're using.

Example:

interface TextOptions {
    alignment?: string;
    color?: string;
    padding?: number;
}
function drawText(opts: TextOptions) { ... }
drawText({ align: 'center' }); // Error, no property 'align' in 'TextOptions'

But I meant to do that

There are a few cases where you may have intended to have extra properties in your object. Depending on what you're doing, there are several appropriate fixes

Type-checking only some properties

Sometimes you want to make sure a few things are present and of the correct type, but intend to have extra properties for whatever reason. Type assertions (<T>v or v as T) do not check for extra properties, so you can use them in place of a type annotation:

interface Options {
    x?: string;
    y?: number;
}

// Error, no property 'z' in 'Options'
let q1: Options = { x: 'foo', y: 32, z: 100 };
// OK
let q2 = { x: 'foo', y: 32, z: 100 } as Options;
// Still an error (good):
let q3 = { x: 100, y: 32, z: 100 } as Options;

These properties and maybe more

Some APIs take an object and dynamically iterate over its keys, but have 'special' keys that need to be of a certain type. Adding a string indexer to the type will disable extra property checking

Before

interface Model {
  name: string;
}
function createModel(x: Model) { ... }

// Error
createModel({name: 'hello', length: 100});

After

interface Model {
  name: string;
  [others: string]: any;
}
function createModel(x: Model) { ... }

// OK
createModel({name: 'hello', length: 100});

This is a dog or a cat or a horse, not sure yet

interface Animal { move; }
interface Dog extends Animal { woof; }
interface Cat extends Animal { meow; }
interface Horse extends Animal { neigh; }

let x: Animal;
if(...) {
  x = { move: 'doggy paddle', woof: 'bark' };
} else if(...) {
  x = { move: 'catwalk', meow: 'mrar' };
} else {
  x = { move: 'gallop', neigh: 'wilbur' };
}

Two good solutions come to mind here

Specify a closed set for x

// Removes all errors
let x: Dog|Cat|Horse;

or Type assert each thing

// For each initialization
  x = { move: 'doggy paddle', woof: 'bark' } as Dog;

This type is sometimes open and sometimes not

A clean solution to the "data model" problem using intersection types:

interface DataModelOptions {
  name?: string;
  id?: number;
}
interface UserProperties {
  [key: string]: any;
}
function createDataModel(model: DataModelOptions & UserProperties) {
 /* ... */
}
// findDataModel can only look up by name or id
function findDataModel(model: DataModelOptions) {
 /* ... */
}
// OK
createDataModel({name: 'my model', favoriteAnimal: 'cat' });
// Error, 'ID' is not correct (should be 'id')
findDataModel({ ID: 32 });

See also https://github.com/Microsoft/TypeScript/issues/3755

Create text file and fill it using bash

Assuming you mean UNIX shell commands, just run

echo >> file.txt

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

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

echo > file.txt

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

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

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

Import local function from a module housed in another directory with relative imports in Jupyter Notebook using Python 3

All other answers here depends on adding code the the notebook(!)

In my opinion is bad practice to hardcode a specific path into the notebook code, or otherwise depend on the location, since this makes it really hard to refactor you code later on. Instead I would recommend you to add the root project folder to PYTHONPATH when starting up your Jupyter notebook server, either directly from the project folder like so

env PYTHONPATH=`pwd` jupyter notebook

or if you are starting it up from somewhere else, use the absolute path like so

env PYTHONPATH=/Users/foo/bar/project/ jupyter notebook

Best way to represent a fraction in Java?

Specifically: Is there a better way to handle being passed a zero denominator? Setting the denominator to 1 is feels mighty arbitrary. How can I do this right?

I would say throw a ArithmeticException for divide by zero, since that's really what's happening:

public Fraction(int numerator, int denominator) {
    if(denominator == 0)
        throw new ArithmeticException("Divide by zero.");
    this.numerator = numerator;
    this.denominator = denominator;
}

Instead of "Divide by zero.", you might want to make the message say "Divide by zero: Denominator for Fraction is zero."

svn cleanup: sqlite: database disk image is malformed

cd to folder containing .svn

rm -rf .svn
svn co http://mon.svn/mondepot/ . --force

How do you create an asynchronous HTTP request in JAVA?

Note that java11 now offers a new HTTP api HttpClient, which supports fully asynchronous operation, using java's CompletableFuture.

It also supports a synchronous version, with calls like send, which is synchronous, and sendAsync, which is asynchronous.

Example of an async request (taken from the apidoc):

   HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://example.com/"))
        .timeout(Duration.ofMinutes(2))
        .header("Content-Type", "application/json")
        .POST(BodyPublishers.ofFile(Paths.get("file.json")))
        .build();
   client.sendAsync(request, BodyHandlers.ofString())
        .thenApply(HttpResponse::body)
        .thenAccept(System.out::println);

removing html element styles via javascript

In jQuery, you can use

$(".className").attr("style","");

CharSequence VS String in Java?

CharSequence is a readable sequence of char values which implements String. it has 4 methods

  1. charAt(int index)
  2. length()
  3. subSequence(int start, int end)
  4. toString()

Please refer documentation CharSequence documentation

Conditional formatting using AND() function

You can use a much simpler formula. I just created a new workbook to test it.

Column A = Date1 | Column B = Date2 | Column C = Date3

Highlight Column A and enter the conditional formatting formula:

=AND(A1>B1,A1<C1)

How to detect if CMD is running as Administrator/has elevated privileges?

This trick only requires one command: type net session into the command prompt.

If you are NOT an admin, you get an access is denied message.

System error 5 has occurred.

Access is denied.

If you ARE an admin, you get a different message, the most common being:

There are no entries in the list.

From MS Technet:

Used without parameters, net session displays information about all sessions with the local computer.

How do you attach and detach from Docker's process?

Update

I typically used docker attach to see what STDOUT was displaying, for troubleshooting containers. I just found docker logs --follow 621a4334f97b, which lets me see the STDOUT whilst also being able to ctrl+c off of it without affecting container operation! Exactly what I've always wanted.

... naturally you'll need to substitue in your own container ID.

Original Answer

I wanted to leave the container running, but had attached without starting the container with -it. My solution was to sacrifice my SSH connection instead (since I was SSHed into the machine that was running the containers). Killing that ssh session left the container intact but detached me from it.

Java 8 Stream and operation on arrays

Please note that Arrays.stream(arr) create a LongStream (or IntStream, ...) instead of Stream so the map function cannot be used to modify the type. This is why .mapToLong, mapToObject, ... functions are provided.

Take a look at why-cant-i-map-integers-to-strings-when-streaming-from-an-array

How do I reset the scale/zoom of a web app on an orientation change on the iPhone?

If you have the width set in the viewport :

<meta name = "viewport" content = "width=device-width; initial-scale=1.0;
 maximum-scale=1.0;" />

And then change the orientation it will randomly zoom in sometimes (especially if you are dragging on the screen) to fix this don't set a width here I used :

<meta id="viewport" name="viewport" content="initial-scale=1.0; user-scalable=0;
minimum-scale=1.0; maximum-scale=1.0" />

This fixes the zoom whatever happens then you can use either window.onorientationchange event or if you want it to be platform independant (handy for testing) the window.innerWidth method.

Selenium: Can I set any of the attribute value of a WebElement in Selenium?

Fancy C# extension method based on previous answers:

public static IWebElement SetAttribute(this IWebElement element, string name, string value)
{
    var driver = ((IWrapsDriver)element).WrappedDriver;
    var jsExecutor = (IJavaScriptExecutor)driver;
    jsExecutor.ExecuteScript("arguments[0].setAttribute(arguments[1], arguments[2]);", element, name, value);

    return element;
}

Usage:

driver.FindElement(By.Id("some_option")).SetAttribute("selected", "selected");

Waiting for HOME ('android.process.acore') to be launched

This problem occurs because while creating the AVD manager in the "Create new Android virtual device(AVD)" dialog window ,"Snapshot" was marked as "Enabled" by me.

Solution:

Create a new AVD manager with the "Enabled" checkbox not checked and then try running the project with the newly created AVD manager as "Target" , the problem will not occur anymore

How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?

While a lot of the above answers give ways to embed an image using a file or with Python code, there is a way to embed an image in the jupyter notebook itself using only markdown and base64!

To view an image in the browser, you can visit the link data:image/png;base64,**image data here** for a base64-encoded PNG image, or data:image/jpg;base64,**image data here** for a base64-encoded JPG image. An example link can be found at the end of this answer.

To embed this into a markdown page, simply use a similar construct as the file answers, but with a base64 link instead: ![**description**](data:image/**type**;base64,**base64 data**). Now your image is 100% embedded into your Jupyter Notebook file!

Example link: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABHNCSVQICAgIfAhkiAAAAD9JREFUGJW1jzEOADAIAqHx/1+mE4ltNXEpI3eJQknCIGsiHSLJB+aO/06PxOo/x2wBgKR2jCeEy0rOO6MDdzYQJRcVkl1NggAAAABJRU5ErkJggg==

Example markdown: ![smile](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABHNCSVQICAgIfAhkiAAAAD9JREFUGJW1jzEOADAIAqHx/1+mE4ltNXEpI3eJQknCIGsiHSLJB+aO/06PxOo/x2wBgKR2jCeEy0rOO6MDdzYQJRcVkl1NggAAAABJRU5ErkJggg==)

What special characters must be escaped in regular expressions?

POSIX recognizes multiple variations on regular expressions - basic regular expressions (BRE) and extended regular expressions (ERE). And even then, there are quirks because of the historical implementations of the utilities standardized by POSIX.

There isn't a simple rule for when to use which notation, or even which notation a given command uses.

Check out Jeff Friedl's Mastering Regular Expressions book.

Paste a multi-line Java String in Eclipse

If your building that SQL in a tool like TOAD or other SQL oriented IDE they often have copy markup to the clipboard. For example, TOAD has a CTRL+M which takes the SQL in your editor and does exactly what you have in your code above. It also covers the reverse... when your grabbing a formatted string out of your Java and want to execute it in TOAD. Pasting the SQL back into TOAD and perform a CTRL+P to remove the multi-line quotes.

Generics in C#, using type of a variable as parameter

One way to get around this is to use implicit casting:

bool DoesEntityExist<T>(T entity, Guid guid, ITransaction transaction) where T : IGloballyIdentifiable;

calling it like so:

DoesEntityExist(entity, entityGuid, transaction);

Going a step further, you can turn it into an extension method (it will need to be declared in a static class):

static bool DoesEntityExist<T>(this T entity, Guid guid, ITransaction transaction) where T : IGloballyIdentifiable;

calling as so:

entity.DoesEntityExist(entityGuid, transaction);

Android: How to Enable/Disable Wifi or Internet Connection Programmatically

add this permission in your manifest and than use the above code to change WiFi state:

 <!--permission ge enable and disable WIFI in android-->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>

Excel: the Incredible Shrinking and Expanding Controls

This has been plaguing me for years, on and off. There are a number of fixes around, but they seem hit and miss. It was still occurring in Excel 2010 (happening to me May 2014), and is still occurring in Excel 2013 by some reports. The best description I have found that matches my situation at least (Excel 2010, no RDP involved, no Print Preview involved) is here:

Microsoft Excel Support Team Blog: ActiveX and form controls resize themselves when clicked or doing a print preview (in Excel 2010)

(This might not help for users of Excel 2013 sorry)

EDIT: Adding detail in case technet link ever goes dead, the technet article says:

FIRSTLY install Microsoft Hotfix 2598144 for Excel 2010, available: here.

SECONDLY, if your symptom is "An ActiveX button changes to the incorrect size after you click it in an Excel 2010 worksheet", then you should:

  • Click Start, click Run, type regedit in the Open box, and then click OK.
  • Locate and then select the following registry subkey HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\Excel\Options
  • On the Edit menu, point to New, and then click DWORD (32-bit) value.
  • Type LegacyAnchorResize, and then press Enter.
  • In the Details pane, right-click LegacyAnchorResize, and then click Modify.
  • In the Value data box, type 1, and then click OK.
  • Exit Registry Editor.

OR SECONDLY, if your symptom is "A button form control is displayed incorrectly in a workbook after you view the print preview of the workbook in Excel 2010", then you should:

  • Click Start, click Run, type regedit in the Open box, and then click OK.
  • Locate and then select the following registry subkey: HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\Excel\Options
  • On the Edit menu, point to New, and then click DWORD (32-bit) value.
  • Type MultiSheetPrint, and then press Enter.
  • In the Details pane, right-click MultiSheetPrint, and then click Modify.
  • In the Value data box, type 1, and then click OK.
  • Select the following registry subkey again: HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\Excel\Options
  • On the Edit menu, point to New, and then click DWORD (32-bit) value.
  • Type LegacyAnchorResize, and then press Enter.
  • In the Details pane, right-click LegacyAnchorResize, and then click Modify.
  • In the Value data box, type 1, and then click OK.
  • Exit Registry Editor.

OR SECONDLY, if your symptom is "An ActiveX button is changed to an incorrect size in an Excel 2010 worksheet after you view the print preview of the worksheet", then you should:

  • Click Start, click Run, type regedit in the Open box, and then click OK.
  • Locate and then select the following registry subkey: HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\Excel\Options
  • On the Edit menu, point to New, and then click DWORD (32-bit) value.
  • Type LegacyAnchorResize, and then press Enter.
  • In the Details pane, right-click LegacyAnchorResize, and then click Modify.
  • In the Value data box, type 1, and then click OK.
  • Exit Registry Editor.

Good luck. This issue is such a pain...

Setting DIV width and height in JavaScript

Fix the typos in your code ("document" is spelled wrong on lines 3 & 4 of your function, and change the onclick event handler to read: onclick="show_update_profile()" and then you'll be fine. You should really follow jmort's advice and simply set up 2 css classes that you switch between in javascript -- it would make your life a lot easier and save yourself from all the extra typing. The typos you've committed are a perfect example of why this is the better approach.

For brownie points, you should also check out element.addEventListener for assigning event handlers to your elements.

Create excel ranges using column numbers in vba?

I really like stackPusher's ConvertToLetter function as a solution. However, in working with it I noticed several errors occurring at very specific inputs due to some flaws in the math. For example, inputting 392 returns 'N\', 418 returns 'O\', 444 returns 'P\', etc.

I reworked the function and the result produces the correct output for all input up to 703 (which is the first triple-letter column index, AAA).

Function ConvertToLetter2(iCol As Integer) As String
    Dim First As Integer
    Dim Second As Integer
    Dim FirstChar As String
    Dim SecondChar As String

    First = Int(iCol / 26)
    If First = iCol / 26 Then
        First = First - 1
    End If
    If First = 0 Then
        FirstChar = ""
    Else
        FirstChar = Chr(First + 64)
    End If

    Second = iCol Mod 26
    If Second = 0 Then
        SecondChar = Chr(26 + 64)
    Else
        SecondChar = Chr(Second + 64)
    End If

    ConvertToLetter2 = FirstChar & SecondChar

End Function

Apply CSS styles to an element depending on its child elements

Basically, no. The following would be what you were after in theory:

div.a < div { border: solid 3px red; }

Unfortunately it doesn't exist.

There are a few write-ups along the lines of "why the hell not". A well fleshed out one by Shaun Inman is pretty good:

http://www.shauninman.com/archive/2008/05/05/css_qualified_selectors

How to Implement DOM Data Binding in JavaScript

Bind any html input

<input id="element-to-bind" type="text">

define two functions:

function bindValue(objectToBind) {
var elemToBind = document.getElementById(objectToBind.id)    
elemToBind.addEventListener("change", function() {
    objectToBind.value = this.value;
})
}

function proxify(id) { 
var handler = {
    set: function(target, key, value, receiver) {
        target[key] = value;
        document.getElementById(target.id).value = value;
        return Reflect.set(target, key, value);
    },
}
return new Proxy({id: id}, handler);
}

use the functions:

var myObject = proxify('element-to-bind')
bindValue(myObject);

How to set up a cron job to run an executable every hour?

Since I could not run the C executable that way, I wrote a simple shell script that does the following

cd /..path_to_shell_script
./c_executable_name

In the cron jobs list, I call the shell script.

How do I remove a specific element from a JSONArray?

Try this code

ArrayList<String> list = new ArrayList<String>();     
JSONArray jsonArray = (JSONArray)jsonObject; 
int len = jsonArray.length();
if (jsonArray != null) { 
   for (int i=0;i<len;i++){ 
    list.add(jsonArray.get(i).toString());
   } 
}
//Remove the element from arraylist
list.remove(position);
//Recreate JSON Array
JSONArray jsArray = new JSONArray(list);

Edit: Using ArrayList will add "\" to the key and values. So, use JSONArray itself

JSONArray list = new JSONArray();     
JSONArray jsonArray = new JSONArray(jsonstring); 
int len = jsonArray.length();
if (jsonArray != null) { 
   for (int i=0;i<len;i++)
   { 
       //Excluding the item at position
        if (i != position) 
        {
            list.put(jsonArray.get(i));
        }
   } 
}

How to set cookie in node js using express framework?

Setting cookie in the express is easy

  1. first install cookie parser
npm install cookie parser
  1. using middleware
const cookieParser = require('cookie-parser');
app.use(cookieParser());
  1. Set cookie know more
res.cookie('cookieName', '1', { expires: new Date(Date.now() + 900000), httpOnly: true })
  1. Accessing that cookie know more
console.dir(req.cookies.cookieName)

Properly escape a double quote in CSV

I know this is an old post, but here's how I solved it (along with converting null values to empty string) in C# using an extension method.

Create a static class with something like the following:

    /// <summary>
    /// Wraps value in quotes if necessary and converts nulls to empty string
    /// </summary>
    /// <param name="value"></param>
    /// <returns>String ready for use in CSV output</returns>
    public static string Q(this string value)
    {
        if (value == null)
        {
            return string.Empty;
        }
        if (value.Contains(",") || (value.Contains("\"") || value.Contains("'") || value.Contains("\\"))
        {
            return "\"" + value + "\"";
        }
        return value;
    }

Then for each string you're writing to CSV, instead of:

stringBuilder.Append( WhateverVariable );

You just do:

stringBuilder.Append( WhateverVariable.Q() );

Write HTML to string

The most straight forward way is to use an XmlWriter object. This can be used to produce valid HTML and will take care of all of the nasty escape sequences for you.

How to convert a string to number in TypeScript?

You can follow either of the following ways.

var str = '54';

var num = +str; //easy way by using + operator
var num = parseInt(str); //by using the parseInt operation 

How to run C program on Mac OS X using Terminal?

Working in 2019 By default, you can compile your name.c using the terminal

 cc name.c

and if you need to run just write

 ./name.out

Two models in one view in ASP MVC 3

I hope you find it helpfull !!

i use ViewBag For Project and Model for task so in this way i am using two model in single view and in controller i defined viewbag's value or data

_x000D_
_x000D_
List<tblproject> Plist = new List<tblproject>();_x000D_
            Plist = ps.getmanagerproject(c, id);_x000D_
_x000D_
            ViewBag.projectList = Plist.Select(x => new SelectListItem_x000D_
            {_x000D_
                Value = x.ProjectId.ToString(),_x000D_
                Text = x.Title_x000D_
            });
_x000D_
_x000D_
_x000D_

and in view tbltask and projectlist are my two diff models

@{

IEnumerable<SelectListItem> plist = ViewBag.projectList;

} @model List

How to send file contents as body entity using cURL

I know the question has been answered, but in my case I was trying to send the content of a text file to the Slack Webhook api and for some reason the above answer did not work. Anywho, this is what finally did the trick for me:

curl -X POST -H --silent --data-urlencode "payload={\"text\": \"$(cat file.txt | sed "s/\"/'/g")\"}" https://hooks.slack.com/services/XXX

Set ImageView width and height programmatically?

This simple way to do your task:

setContentView(R.id.main);    
ImageView iv = (ImageView) findViewById(R.id.left);
int width = 60;
int height = 60;
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(width,height);
iv.setLayoutParams(parms);

and another way if you want to give screen size in height and width then use below code :

setContentView(R.id.main);    
Display display = getWindowManager().getDefaultDisplay();
ImageView iv = (LinearLayout) findViewById(R.id.left);
int width = display.getWidth(); // ((display.getWidth()*20)/100)
int height = display.getHeight();// ((display.getHeight()*30)/100)
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(width,height);
iv.setLayoutParams(parms);

hope use full to you.

how to concat two columns into one with the existing column name in mysql?

As aziz-shaikh has pointed out, there is no way to suppress an individual column from the * directive, however you might be able to use the following hack:

SELECT CONCAT(c.FIRSTNAME, ',', c.LASTNAME) AS FIRSTNAME,
       c.*
FROM   `customer` c;

Doing this will cause the second occurrence of the FIRSTNAME column to adopt the alias FIRSTNAME_1 so you should be able to safely address your customised FIRSTNAME column. You need to alias the table because * in any position other than at the start will fail if not aliased.

Hope that helps!

How to remove first and last character of a string?

This will gives you basic idea

    String str="";
    String str1="";
    Scanner S=new Scanner(System.in);
    System.out.println("Enter the string");
    str=S.nextLine();
    int length=str.length();
    for(int i=0;i<length;i++)
    {
        str1=str.substring(1, length-1);
    }
    System.out.println(str1);

c# - How to get sum of the values from List?

How about this?

List<string> monValues = Application["mondayValues"] as List<string>;
int sum = monValues.ConvertAll(Convert.ToInt32).Sum();

Formatting html email for Outlook

I used VML(Vector Markup Language) based formatting in my email template. In VML Based you have write your code within comment I took help from this site.

https://litmus.com/blog/a-guide-to-bulletproof-buttons-in-email-design#supporttable

Are there any worse sorting algorithms than Bogosort (a.k.a Monkey Sort)?

I'm surprised no one has mentioned sleepsort yet... Or haven't I noticed it? Anyway:

#!/bin/bash
function f() {
    sleep "$1"
    echo "$1"
}
while [ -n "$1" ]
do
    f "$1" &
    shift
done
wait

example usage:

./sleepsort.sh 5 3 6 3 6 3 1 4 7
./sleepsort.sh 8864569 7

In terms of performance it is terrible (especially the second example). Waiting almost 3.5 months to sort 2 numbers is kinda bad.

How to set selected index JComboBox by value

public static void setSelectedValue(JComboBox comboBox, int value)
    {
        ComboItem item;
        for (int i = 0; i < comboBox.getItemCount(); i++)
        {
            item = (ComboItem)comboBox.getItemAt(i);
            if (item.getValue().equalsIgnoreCase(value))
            {
                comboBox.setSelectedIndex(i);
                break;
            }
        }
    }

Hope this help :)

Pad a number with leading zeros in JavaScript

For fun, instead of using a loop to create the extra zeros:

function zeroPad(n,length){
  var s=n+"",needed=length-s.length;
  if (needed>0) s=(Math.pow(10,needed)+"").slice(1)+s;
  return s;
}

What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types

I have a slightly different perspective on the difference between a DATETIME and a TIMESTAMP. A DATETIME stores a literal value of a date and time with no reference to any particular timezone. So, I can set a DATETIME column to a value such as '2019-01-16 12:15:00' to indicate precisely when my last birthday occurred. Was this Eastern Standard Time? Pacific Standard Time? Who knows? Where the current session time zone of the server comes into play occurs when you set a DATETIME column to some value such as NOW(). The value stored will be the current date and time using the current session time zone in effect. But once a DATETIME column has been set, it will display the same regardless of what the current session time zone is.

A TIMESTAMP column on the other hand takes the '2019-01-16 12:15:00' value you are setting into it and interprets it in the current session time zone to compute an internal representation relative to 1/1/1970 00:00:00 UTC. When the column is displayed, it will be converted back for display based on whatever the current session time zone is. It's a useful fiction to think of a TIMESTAMP as taking the value you are setting and converting it from the current session time zone to UTC for storing and then converting it back to the current session time zone for displaying.

If my server is in San Francisco but I am running an event in New York that starts on 9/1/1029 at 20:00, I would use a TIMESTAMP column for holding the start time, set the session time zone to 'America/New York' and set the start time to '2009-09-01 20:00:00'. If I want to know whether the event has occurred or not, regardless of the current session time zone setting I can compare the start time with NOW(). Of course, for displaying in a meaningful way to a perspective customer, I would need to set the correct session time zone. If I did not need to do time comparisons, then I would probably be better off just using a DATETIME column, which will display correctly (with an implied EST time zone) regardless of what the current session time zone is.

TIMESTAMP LIMITATION

The TIMESTAMP type has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC and so it may not usable for your particular application. In that case you will have to use a DATETIME type. You will, of course, always have to be concerned that the current session time zone is set properly whenever you are using this type with date functions such as NOW().

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

Python 3.3 and later now uses the 2010 compiler. To best way to solve the issue is to just install Visual C++ Express 2010 for free.

Now comes the harder part for 64 bit users and to be honest I just moved to 32 bit but 2010 express doesn't come with a 64 bit compiler (you get a new error, ValueError: ['path'] ) so you have to install Microsoft SDK 7.1 and follow the directions here to get the 64 bit compiler working with python: Python PIP has issues with path for MS Visual Studio 2010 Express for 64-bit install on Windows 7

It may just be easier for you to use the 32 bit version for now. In addition to getting the compiler working, you can bypass the need to compile many modules by getting the binary wheel file from this locaiton http://www.lfd.uci.edu/~gohlke/pythonlibs/

Just download the .whl file you need, shift + right click the download folder and select "open command window here" and run

pip install module-name.whl 

I used that method on 64 bit 3.4.3 before I broke down and decided to just get a working compiler for pip compiles modules from source by default, which is why the binary wheel files work and having pip build from source doesn't.

People getting this (vcvarsall.bat) error on Python 2.7 can instead install "Microsoft Visual C++ Compiler for Python 2.7"

How do I copy to the clipboard in JavaScript?

If you want a really simple solution (takes less than 5 minutes to integrate) and looks good right out of the box, then Clippy is a nice alternative to some of the more complex solutions.

It was written by a cofounder of GitHub. Example Flash embed code below:

<object
    classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
    width="110"
    height="14"
    id="clippy">

    <param name="movie" value="/flash/clippy.swf"/>
    <param name="allowScriptAccess" value="always"/>
    <param name="quality" value="high"/>
    <param name="scale" value="noscale"/>
    <param NAME="FlashVars" value="text=#{text}"/>
    <param name="bgcolor" value="#{bgcolor}"/>
    <embed
        src="/flash/clippy.swf"
        width="110"
        height="14"
        name="clippy"
        quality="high"
        allowScriptAccess="always"
        type="application/x-shockwave-flash"
        pluginspage="http://www.macromedia.com/go/getflashplayer"
        FlashVars="text=#{text}"
        bgcolor="#{bgcolor}"/>
</object>

Remember to replace #{text} with the text you need copied, and #{bgcolor} with a color.

Python: finding lowest integer

Cast the variable to a float before doing the comparison:

if float(i) < float(x):

The problem is that you are comparing strings to floats, which will not work.

How can I use external JARs in an Android project?

For Eclipse

A good way to add external JARs to your Android project or any Java project is:

  1. Create a folder called libs in your project's root folder
  2. Copy your JAR files to the libs folder
  3. Now right click on the Jar file and then select Build Path > Add to Build Path, which will create a folder called 'Referenced Libraries' within your project

    By doing this, you will not lose your libraries that are being referenced on your hard drive whenever you transfer your project to another computer.

For Android Studio

  1. If you are in Android View in project explorer, change it to Project view as below

Missing Image

  1. Right click the desired module where you would like to add the external library, then select New > Directroy and name it as 'libs'
  2. Now copy the blah_blah.jar into the 'libs' folder
  3. Right click the blah_blah.jar, Then select 'Add as Library..'. This will automatically add and entry in build.gradle as compile files('libs/blah_blah.jar') and sync the gradle. And you are done

Please Note : If you are using 3rd party libraries then it is better to use transitive dependencies where Gradle script automatically downloads the JAR and the dependency JAR when gradle script run.

Ex : compile 'com.google.android.gms:play-services-ads:9.4.0'

Read more about Gradle Dependency Mangement

How to detect orientation change?

I need to detect rotation while using the camera with AVFoundation, and found that the didRotate (now deprecated) & willTransition methods were unreliable for my needs. Using the notification posted by David did work, but is not current for Swift 3.x & above.

The following makes use of a closure, which appears to be Apple's preference going forward.

var didRotate: (Notification) -> Void = { notification in
        switch UIDevice.current.orientation {
        case .landscapeLeft, .landscapeRight:
            print("landscape")
        case .portrait, .portraitUpsideDown:
            print("Portrait")
        default:
            print("other (such as face up & down)")
        }
    }

To set up the notification:

NotificationCenter.default.addObserver(forName: UIDevice.orientationDidChangeNotification,
                                       object: nil,
                                       queue: .main,
                                       using: didRotate)

To tear down the notification:

NotificationCenter.default.removeObserver(self,
                                          name: UIDevice.orientationDidChangeNotification,
                                          object: nil)

Regarding the deprecation statement, my initial comment was misleading, so I wanted to update that. As noted, the usage of @objc inference has been deprecated, which in turn was needed to use a #selector. By using a closure instead, this can be avoided and you now have a solution that should avoid a crash due to calling an invalid selector.

iPhone 6 and 6 Plus Media Queries

iPhone 6

  • Landscape

    @media only screen 
        and (min-device-width : 375px) // or 213.4375em or 3in or 9cm
        and (max-device-width : 667px) // or 41.6875em
        and (width : 667px) // or 41.6875em
        and (height : 375px) // or 23.4375em
        and (orientation : landscape) 
        and (color : 8)
        and (device-aspect-ratio : 375/667)
        and (aspect-ratio : 667/375)
        and (device-pixel-ratio : 2)
        and (-webkit-min-device-pixel-ratio : 2)
    { }
    
  • Portrait

    @media only screen 
        and (min-device-width : 375px) // or 213.4375em
        and (max-device-width : 667px) // or 41.6875em
        and (width : 375px) // or 23.4375em
        and (height : 559px) // or 34.9375em
        and (orientation : portrait) 
        and (color : 8)
        and (device-aspect-ratio : 375/667)
        and (aspect-ratio : 375/559)
        and (device-pixel-ratio : 2)
        and (-webkit-min-device-pixel-ratio : 2)
    { }
    

    if you prefer you can use (device-width : 375px) and (device-height: 559px) in place of the min- and max- settings.

    It is not necessary to use all of these settings, and these are not all the possible settings. These are just the majority of possible options so you can pick and choose whichever ones meet your needs.

  • User Agent

    tested with my iPhone 6 (model MG6G2LL/A) with iOS 9.0 (13A4305g)

    # Safari
    Mozilla/5.0 (iPhone; CPU iPhone OS 9_0 like Mac OS X) AppleWebKit/601.1.39 (KHTML, like Gecko) Version/9.0 Mobile/13A4305g Safari 601.1
    # Google Chrome
    Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/534.53.11 (KHTML, like Gecko) Version/5.1.3 Safari/534.53.10 (000102)
    # Mercury
    Mozilla/5.0 (iPhone; CPU iPhone OS 7_0_4 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11B554a Safari/9537.53
    
  • Launch images

    • 750 x 1334 (@2x) for portrait
    • 1334 x 750 (@2x) for landscape
  • App icon

    • 120 x 120

iPhone 6+

  • Landscape

    @media only screen 
        and (min-device-width : 414px) 
        and (max-device-width : 736px) 
        and (orientation : landscape) 
        and (-webkit-min-device-pixel-ratio : 3) 
    { }
    
  • Portrait

    @media only screen 
        and (min-device-width : 414px) 
        and (max-device-width : 736px)
        and (device-width : 414px)
        and (device-height : 736px)
        and (orientation : portrait) 
        and (-webkit-min-device-pixel-ratio : 3) 
        and (-webkit-device-pixel-ratio : 3)
    { }
    
  • Launch images

    • 1242 x 2208 (@3x) for portrait
    • 2208 x 1242 (@3x) for landscape
  • App icon

    • 180 x 180

iPhone 6 and 6+

@media only screen 
    and (max-device-width: 640px), 
    only screen and (max-device-width: 667px), 
    only screen and (max-width: 480px)
{ }

Predicted

According to the Apple website the iPhone 6 Plus will have 401 pixels-per-inch and be 1920 x 1080. The smaller version of the iPhone 6 will be 1334 x 750 with 326 PPI.

So, assuming that information is correct, we can write a media query for the iPhone 6:

@media screen 
    and (min-device-width : 1080px) 
    and (max-device-width : 1920px) 
    and (min-resolution: 401dpi) 
    and (device-aspect-ratio:16/9) 
{ }

@media screen 
    and (min-device-width : 750px) 
    and (max-device-width : 1334px) 
    and (min-resolution: 326dpi) 
{ }

Note that will be deprecated in http://dev.w3.org/csswg/mediaqueries-4/ and replaced with

Min-width and max-width may be something like 1704 x 960.


Apple Watch (speculative)

Specs on the Watch are still a bit speculative since (as far as I'm aware) there has been no official spec sheet yet. But Apple did mention in this press release that the Watch will be available in two sizes.. 38mm and 42mm.

Further assuming.. that those sizes refer to the screen size rather than the overall size of the Watch face these media queries should work.. And I'm sure you could give or take a few millimeters to cover either scenario without sacrificing any unwanted targeting because..

@media (!small) and (damn-small), (omfg) { }

or

@media 
    (max-device-width:42mm) 
    and (min-device-width:38mm) 
{ }

It's worth noting that Media Queries Level 4 from W3C currently only available as a first public draft, once available for use will bring with it a lot of new features designed with smaller wearable devices like this in mind.

How to run PyCharm in Ubuntu - "Run in Terminal" or "Run"?

To make it a bit more user-friendly: After you've unpacked it, go into the directory, and run bin/pycharm.sh. Once it opens, it either offers you to create a desktop entry, or if it doesn't, you can ask it to do so by going to the Tools menu and selecting Create Desktop Entry...

Then close PyCharm, and in the future you can just click on the created menu entry. (or copy it onto your Desktop)

To answer the specifics between Run and Run in Terminal: It's essentially the same, but "Run in Terminal" actually opens a terminal window first and shows you console output of the program. Chances are you don't want that :)

(Unless you are trying to debug an application, you usually do not need to see the output of it.)

Convert base-2 binary number string to int

For the record to go back and forth in basic python3:

a = 10
bin(a)
# '0b1010'

int(bin(a), 2)
# 10
eval(bin(a))
# 10

Using BufferedReader to read Text File

Maybe you mean this:

public class Reader {

public static void main(String[]args) throws IOException{

    FileReader in = new FileReader("C:/test.txt");
    BufferedReader br = new BufferedReader(in);
    String line = br.readLine();
    while (line!=null) {
        System.out.println(line);
        line = br.readLine();
    }
    in.close();

}

Confirm Password with jQuery Validate

jQuery('.validatedForm').validate({
        rules : {
            password : {
                minlength : 5
            },
            password_confirm : {
                minlength : 5,
                equalTo : '[name="password"]'
            }
        }

In general, you will not use id="password" like this. So, you can use [name="password"] instead of "#password"

How can I open a URL in Android's web browser from my application?

A short code version...

 if (!strUrl.startsWith("http://") && !strUrl.startsWith("https://")){
     strUrl= "http://" + strUrl;
 }


 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(strUrl)));

`IF` statement with 3 possible answers each based on 3 different ranges

Your formula should be of the form =IF(X2 >= 85,0.559,IF(X2 >= 80,0.327,IF(X2 >=75,0.255,0))). This simulates the ELSE-IF operand Excel lacks. Your formulas were using two conditions in each, but the second parameter of the IF formula is the value to use if the condition evaluates to true. You can't chain conditions in that manner.

How can I use an http proxy with node.js http.Client?

For using a proxy with https I tried the advice on this website (using dependency https-proxy-agent) and it worked for me:

http://codingmiles.com/node-js-making-https-request-via-proxy/

What's the easiest way to call a function every 5 seconds in jQuery?

you can use window.setInterval and time must to be define in miliseconds, in below case the function will call after every single second (1000 miliseconds)

<script>
  var time = 3670;
window.setInterval(function(){

  // Time calculations for days, hours, minutes and seconds
    var h = Math.floor(time / 3600);
    var m = Math.floor(time % 3600 / 60);
    var s = Math.floor(time % 3600 % 60);

  // Display the result in the element with id="demo"
  document.getElementById("demo").innerHTML =  h + "h "
  + m + "m " + s + "s ";

  // If the count down is finished, write some text 
  if (time < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }

  time--;
}, 1000);


</script>

How to disable HTML links

Bootstrap 4.1 provides a class named disabled and aria-disabled="true" attribute.

example"

<a href="#" 
        class="btn btn-primary btn-lg disabled" 
        tabindex="-1" 
        role="button" aria-disabled="true"
>
    Primary link
</a>

More is on getbootstrap.com

So if you want to make it dynamically, and you don't want to care if it is button or ancor than in JS script you need something like that

   let $btn=$('.myClass');
   $btn.attr('disabled', true);
   if ($btn[0].tagName == 'A'){
        $btn.off();
        $btn.addClass('disabled');
        $btn.attr('aria-disabled', true);
   }

But be carefull

The solution only works on links with classes btn btn-link.

Sometimes bootstrap recommends using card-link class, in this case solution will not work.

When should I use h:outputLink instead of h:commandLink?

I also see that the page loading (performance) takes a long time on using h:commandLink than h:link. h:link is faster compared to h:commandLink

Xpath for href element

Below works fine.

//a[@id='oldcontent']

If you've tried certain ones and they haven't worked, then let us know, otherwise something simple like this should work.

Set default option in mat-select

Try this

<mat-form-field>
    <mat-select [(ngModel)]="modeselect" [placeholder]="modeselect">
        <mat-option value="domain">Domain</mat-option>
        <mat-option value="exact">Exact</mat-option>
    </mat-select>
</mat-form-field>

Component:

export class SelectValueBindingExample {
    public modeselect = 'Domain';
}

Live demo

Also, don't forget to import FormsModule in your app.module

Use a content script to access the page context variables and functions

I've also faced the problem of ordering of loaded scripts, which was solved through sequential loading of scripts. The loading is based on Rob W's answer.

function scriptFromFile(file) {
    var script = document.createElement("script");
    script.src = chrome.extension.getURL(file);
    return script;
}

function scriptFromSource(source) {
    var script = document.createElement("script");
    script.textContent = source;
    return script;
}

function inject(scripts) {
    if (scripts.length === 0)
        return;
    var otherScripts = scripts.slice(1);
    var script = scripts[0];
    var onload = function() {
        script.parentNode.removeChild(script);
        inject(otherScripts);
    };
    if (script.src != "") {
        script.onload = onload;
        document.head.appendChild(script);
    } else {
        document.head.appendChild(script);
        onload();
    }
}

The example of usage would be:

var formulaImageUrl = chrome.extension.getURL("formula.png");
var codeImageUrl = chrome.extension.getURL("code.png");

inject([
    scriptFromSource("var formulaImageUrl = '" + formulaImageUrl + "';"),
    scriptFromSource("var codeImageUrl = '" + codeImageUrl + "';"),
    scriptFromFile("EqEditor/eq_editor-lite-17.js"),
    scriptFromFile("EqEditor/eq_config.js"),
    scriptFromFile("highlight/highlight.pack.js"),
    scriptFromFile("injected.js")
]);

Actually, I'm kinda new to JS, so feel free to ping me to the better ways.

C# Validating input for textbox on winforms

With WinForms you can use the ErrorProvider in conjunction with the Validating event to handle the validation of user input. The Validating event provides the hook to perform the validation and ErrorProvider gives a nice consistent approach to providing the user with feedback on any error conditions.

http://msdn.microsoft.com/en-us/library/system.windows.forms.errorprovider.aspx

process.env.NODE_ENV is undefined

In macOS for those who are using the express version 4.x.x and using the DOTENV plugin, need to use like this:

  1. After installing the plugin import like the following in the file where you init the application: require('dotenv').config({path: path.resolve(__dirname+'/.env')});

  2. In the root directory create a file '.env' and add the varaiable like:

    NODE_ENV=development or NODE_ENV = development

How to put php inside JavaScript?

The only proper way to put server side data into generated javascript code:

<?php $jsString= 'testing'; ?>
<html>
  <body>
    <script type="text/javascript">      
      var jsStringFromPhp=<?php echo json_encode($jsString); ?>;
      alert(jsStringFromPhp);
    </script>
  </body>
</html>

With simple quotes the content of your variable is not escaped against HTML and javascript, so it is vulnerable by XSS attacks...

For similar reasons I recommend to use document.createTextNode() instead of setting the innerHTML. Ofc. it is slower, but more secure...

Output Django queryset as JSON

You can use JsonResponse with values. Simple example:

from django.http import JsonResponse

def some_view(request):
    data = list(SomeModel.objects.values())  # wrap in list(), because QuerySet is not JSON serializable
    return JsonResponse(data, safe=False)  # or JsonResponse({'data': data})

Or another approach with Django's built-in serializers:

from django.core import serializers
from django.http import HttpResponse

def some_view(request):
    qs = SomeModel.objects.all()
    qs_json = serializers.serialize('json', qs)
    return HttpResponse(qs_json, content_type='application/json')

In this case result is slightly different (without indent by default):

[
    {
        "model": "some_app.some_model",
        "pk": 1,
        "fields": {
            "name": "Elon",
            "age": 48,
            ...
        }
    },
    ...
]

I have to say, it is good practice to use something like marshmallow to serialize queryset.

...and a few notes for better performance:

  • use pagination if your queryset is big;
  • use objects.values() to specify list of required fields to avoid serialization and sending to client unnecessary model's fields (you also can pass fields to serializers.serialize);

How to send UTF-8 email?

I'm using rather specified charset (ISO-8859-2) because not every mail system (for example: http://10minutemail.com) can read UTF-8 mails. If you need this:

function utf8_to_latin2($str)
{
    return iconv ( 'utf-8', 'ISO-8859-2' , $str );
}
function my_mail($to,$s,$text,$form, $reply)
    {
        mail($to,utf8_to_latin2($s),utf8_to_latin2($text),
        "From: $form\r\n".
        "Reply-To: $reply\r\n".
        "X-Mailer: PHP/" . phpversion());
    }

I have made another mailer function, because apple device could not read well the previous version.

function utf8mail($to,$s,$body,$from_name="x",$from_a = "[email protected]", $reply="[email protected]")
{
    $s= "=?utf-8?b?".base64_encode($s)."?=";
    $headers = "MIME-Version: 1.0\r\n";
    $headers.= "From: =?utf-8?b?".base64_encode($from_name)."?= <".$from_a.">\r\n";
    $headers.= "Content-Type: text/plain;charset=utf-8\r\n";
    $headers.= "Reply-To: $reply\r\n";  
    $headers.= "X-Mailer: PHP/" . phpversion();
    mail($to, $s, $body, $headers);
}

MySQL - ERROR 1045 - Access denied

If you actually have set a root password and you've just lost/forgotten it:

  1. Stop MySQL
  2. Restart it manually with the skip-grant-tables option: mysqld_safe --skip-grant-tables

  3. Now, open a new terminal window and run the MySQL client: mysql -u root

  4. Reset the root password manually with this MySQL command: UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root'; If you are using MySQL 5.7 (check using mysql --version in the Terminal) then the command is:

    UPDATE mysql.user SET authentication_string=PASSWORD('password')  WHERE  User='root';
    
  5. Flush the privileges with this MySQL command: FLUSH PRIVILEGES;

From http://www.tech-faq.com/reset-mysql-password.shtml

(Maybe this isn't what you need, Abs, but I figure it could be useful for people stumbling across this question in the future)

Get values from an object in JavaScript

I am sorry that your concluding question is not that clear but you are wrong from the very first line. The variable data is an Object not an Array

To access the attributes of an object is pretty easy:

alert(data.second);

But, if this does not completely answer your question, please clarify it and post back.

Thanks !

Explanation of <script type = "text/template"> ... </script>

Those script tags are a common way to implement templating functionality (like in PHP) but on the client side.

By setting the type to "text/template", it's not a script that the browser can understand, and so the browser will simply ignore it. This allows you to put anything in there, which can then be extracted later and used by a templating library to generate HTML snippets.

Backbone doesn't force you to use any particular templating library - there are quite a few out there: Mustache, Haml, Eco,Google Closure template, and so on (the one used in the example you linked to is underscore.js). These will use their own syntax for you to write within those script tags.

How to create a checkbox with a clickable label?

<label for="my_checkbox">Check me</label>
<input type="checkbox" name="my_checkbox" value="Car" />

How to call a method in another class in Java?

class A{
  public void methodA(){
    new B().methodB();
    //or
    B.methodB1();
  }
}

class B{
  //instance method
  public void methodB(){
  }
  //static method
  public static  void methodB1(){
  }
}