Programs & Examples On #Equation

A statement that the values of two expressions are equal indicated by the sign = .

How can I solve equations in Python?

There are two ways to approach this problem: numerically and symbolically.

To solve it numerically, you have to first encode it as a "runnable" function - stick a value in, get a value out. For example,

def my_function(x):
    return 2*x + 6

It is quite possible to parse a string to automatically create such a function; say you parse 2x + 6 into a list, [6, 2] (where the list index corresponds to the power of x - so 6*x^0 + 2*x^1). Then:

def makePoly(arr):
    def fn(x):
        return sum(c*x**p for p,c in enumerate(arr))
    return fn

my_func = makePoly([6, 2])
my_func(3)    # returns 12

You then need another function which repeatedly plugs an x-value into your function, looks at the difference between the result and what it wants to find, and tweaks its x-value to (hopefully) minimize the difference.

def dx(fn, x, delta=0.001):
    return (fn(x+delta) - fn(x))/delta

def solve(fn, value, x=0.5, maxtries=1000, maxerr=0.00001):
    for tries in xrange(maxtries):
        err = fn(x) - value
        if abs(err) < maxerr:
            return x
        slope = dx(fn, x)
        x -= err/slope
    raise ValueError('no solution found')

There are lots of potential problems here - finding a good starting x-value, assuming that the function actually has a solution (ie there are no real-valued answers to x^2 + 2 = 0), hitting the limits of computational accuracy, etc. But in this case, the error minimization function is suitable and we get a good result:

solve(my_func, 16)    # returns (x =) 5.000000000000496

Note that this solution is not absolutely, exactly correct. If you need it to be perfect, or if you want to try solving families of equations analytically, you have to turn to a more complicated beast: a symbolic solver.

A symbolic solver, like Mathematica or Maple, is an expert system with a lot of built-in rules ("knowledge") about algebra, calculus, etc; it "knows" that the derivative of sin is cos, that the derivative of kx^p is kpx^(p-1), and so on. When you give it an equation, it tries to find a path, a set of rule-applications, from where it is (the equation) to where you want to be (the simplest possible form of the equation, which is hopefully the solution).

Your example equation is quite simple; a symbolic solution might look like:

=> LHS([6, 2]) RHS([16])

# rule: pull all coefficients into LHS
LHS, RHS = [lh-rh for lh,rh in izip_longest(LHS, RHS, 0)], [0]

=> LHS([-10,2]) RHS([0])

# rule: solve first-degree poly
if RHS==[0] and len(LHS)==2:
    LHS, RHS = [0,1], [-LHS[0]/LHS[1]]

=> LHS([0,1]) RHS([5])

and there is your solution: x = 5.

I hope this gives the flavor of the idea; the details of implementation (finding a good, complete set of rules and deciding when each rule should be applied) can easily consume many man-years of effort.

number several equations with only one number

How about something like:

\documentclass{article}

\usepackage{amssymb,amsmath}

\begin{document}

\begin{equation}\label{A_Label}
  \begin{split}
    w^T x_i + b \geqslant 1-\xi_i \text{ if } y_i &= 1, \\
    w^T x_i + b \leqslant -1+\xi_i \text{ if } y_i &= -1
  \end{split}
\end{equation}

\end{document}

which produces:

enter image description here

How to label each equation in align environment?

\tag also works in align*. Example:

\begin{align*}
  a(x)^{2} &= bx\tag{1}\\ 
  a(x)^{2} &= b\tag{2}\\ 
  ax &= b\tag{3}\\ 
  a(x)^{2}+bx &= c\tag{4}\\ 
  a(x)^{2}+c &= bx\tag{5}\\ 
  a(x)^{2} &= bx+c\tag{6}\\ \\ 
  Where\quad a, b, c \, \in N
\end{align*}

Output:

PDF output for \tag example

How can I use "e" (Euler's number) and power operation in python 2.7

Python's power operator is ** and Euler's number is math.e, so:

 from math import e
 x.append(1-e**(-value1**2/2*value2**2))

What is the easiest way to encrypt a password when I save it to the registry?

If you want to be able to decrypt the password, I think the easiest way would be to use DPAPI (user store mode) to encrypt/decrypt. This way you don't have to fiddle with encryption keys, store them somewhere or hard-code them in your code - in both cases somebody can discover them by looking into registry, user settings or using Reflector.

Otherwise use hashes SHA1 or MD5 like others have said here.

AngularJS - Find Element with attribute

Rather than querying the DOM for elements (which isn't very angular see "Thinking in AngularJS" if I have a jQuery background?) you should perform your DOM manipulation within your directive. The element is available to you in your link function.

So in your myDirective

return {
    link: function (scope, element, attr) {
        element.html('Hello world');
    }
}

If you must perform the query outside of the directive then it would be possible to use querySelectorAll in modern browers

angular.element(document.querySelectorAll("[my-directive]"));

however you would need to use jquery to support IE8 and backwards

angular.element($("[my-directive]"));

or write your own method as demonstrated here Get elements by attribute when querySelectorAll is not available without using libraries?

How to distinguish between left and right mouse click with jQuery

There are a lot of very good answers, but I just want to touch on one major difference between IE9 and IE < 9 when using event.button.

According to the old Microsoft specification for event.button the codes differ from the ones used by W3C. W3C considers only 3 cases:

  1. Left mouse button is clicked - event.button === 1
  2. Right mouse button is clicked - event.button === 3
  3. Middle mouse button is clicked - event.button === 2

In older Internet Explorers however Microsoft are flipping a bit for the pressed button and there are 8 cases:

  1. No button is clicked - event.button === 0 or 000
  2. Left button is clicked - event.button === 1 or 001
  3. Right button is clicked - event.button === 2 or 010
  4. Left and right buttons are clicked - event.button === 3 or 011
  5. Middle button is clicked - event.button === 4 or 100
  6. Middle and left buttons are clicked - event.button === 5 or 101
  7. Middle and right buttons are clicked - event.button === 6 or 110
  8. All 3 buttons are clicked - event.button === 7 or 111

Despite the fact that this is theoretically how it should work, no Internet Explorer has ever supported the cases of two or three buttons simultaneously pressed. I am mentioning it because the W3C standard cannot even theoretically support this.

Catching an exception while using a Python 'with' statement

Catching an exception while using a Python 'with' statement

The with statement has been available without the __future__ import since Python 2.6. You can get it as early as Python 2.5 (but at this point it's time to upgrade!) with:

from __future__ import with_statement

Here's the closest thing to correct that you have. You're almost there, but with doesn't have an except clause:

with open("a.txt") as f: 
    print(f.readlines())
except:                    # <- with doesn't have an except clause.
    print('oops')

A context manager's __exit__ method, if it returns False will reraise the error when it finishes. If it returns True, it will suppress it. The open builtin's __exit__ doesn't return True, so you just need to nest it in a try, except block:

try:
    with open("a.txt") as f:
        print(f.readlines())
except Exception as error: 
    print('oops')

And standard boilerplate: don't use a bare except: which catches BaseException and every other possible exception and warning. Be at least as specific as Exception, and for this error, perhaps catch IOError. Only catch errors you're prepared to handle.

So in this case, you'd do:

>>> try:
...     with open("a.txt") as f:
...         print(f.readlines())
... except IOError as error: 
...     print('oops')
... 
oops

Convert Python program to C/C++ code?

Yes. Look at Cython. It does just that: Converts Python to C for speedups.

Subscript out of bounds - general definition and solution?

If this helps anybody, I encountered this while using purr::map() with a function I wrote which was something like this:

find_nearby_shops <- function(base_account) {
   states_table %>% 
        filter(state == base_account$state) %>% 
        left_join(target_locations, by = c('border_states' = 'state')) %>% 
        mutate(x_latitude = base_account$latitude,
               x_longitude = base_account$longitude) %>% 
        mutate(dist_miles = geosphere::distHaversine(p1 = cbind(longitude, latitude), 
                                                     p2 = cbind(x_longitude, x_latitude))/1609.344)
}

nearby_shop_numbers <- base_locations %>% 
    split(f = base_locations$id) %>% 
    purrr::map_df(find_nearby_shops) 

I would get this error sometimes with samples, but most times I wouldn't. The root of the problem is that some of the states in the base_locations table (PR) did not exist in the states_table, so essentially I had filtered out everything, and passed an empty table on to mutate. The moral of the story is that you may have a data issue and not (just) a code problem (so you may need to clean your data.)

Thanks for agstudy and zx8754's answers above for helping with the debug.

How do you disable browser Autocomplete on web form field / input tag?

So here is it:

_x000D_
_x000D_
function turnOnPasswordStyle() {_x000D_
  $('#inputpassword').attr('type', "password");_x000D_
}
_x000D_
<input oninput="turnOnPasswordStyle()" id="inputpassword" type="text">
_x000D_
_x000D_
_x000D_

Linking to a specific part of a web page

Just append a # followed by the ID of the <a> tag (or other HTML tag, like a <section>) that you're trying to get to. For example, if you are trying to link to the header in this HTML:

<p>This is some content.</p>
<h2><a id="target">Some Header</a></h2>
<p>This is some more content.</p>

You could use the link <a href="http://url.to.site/index.html#target">Link</a>.

What does "Content-type: application/json; charset=utf-8" really mean?

Note that IETF RFC4627 has been superseded by IETF RFC7158. In section [8.1] it retracts the text cited by @Drew earlier by saying:

Implementations MUST NOT add a byte order mark to the beginning of a JSON text.

make image( not background img) in div repeat?

It would probably be easier to just fake it by using a div. Just make sure you set the height if its empty so that it can actually appear. Say for instance you want it to be 50px tall set the div height to 50px.

<div id="rightflower">
<div id="divImg"></div> 
</div>

And in your style sheet just add the background and its properties, height and width, and what ever positioning you had in mind.

Unique constraint on multiple columns

By using the constraint definition on table creation, you can specify one or multiple constraints that span multiple columns. The syntax, simplified from technet's documentation, is in the form of:

CONSTRAINT constraint_name UNIQUE [ CLUSTERED | NONCLUSTERED ] 
(
    column [ ASC | DESC ] [ ,...n ]
)

Therefore, the resuting table definition would be:

CREATE TABLE [dbo].[user](
    [userID] [int] IDENTITY(1,1) NOT NULL,
    [fcode] [int] NULL,
    [scode] [int] NULL,
    [dcode] [int] NULL,
    [name] [nvarchar](50) NULL,
    [address] [nvarchar](50) NULL,
    CONSTRAINT [PK_user_1] PRIMARY KEY CLUSTERED 
    (
        [userID] ASC
    ),
    CONSTRAINT [UQ_codes] UNIQUE NONCLUSTERED
    (
        [fcode], [scode], [dcode]
    )
) ON [PRIMARY]

Proper way to exit iPhone application?

Have you tried exit(0)?

Alternatively, [[NSThread mainThread] exit], although I have not tried that it seems like the more appropriate solution.

How to obfuscate Python code effectively?

Maybe you can try on pyconcrete

encrypt .pyc to .pye and decrypt when import it

encrypt & decrypt by library OpenAES

Usage

Full encrypted

  • convert all of your .py to *.pye

    $ pyconcrete-admin.py compile --source={your py script}  --pye
    $ pyconcrete-admin.py compile --source={your py module dir} --pye
    
  • remove *.py *.pyc or copy *.pye to other folder

  • main.py encrypted as main.pye, it can't be executed by normal python. You must use pyconcrete to process the main.pye script. pyconcrete(exe) will be installed in your system path (ex: /usr/local/bin)

    pyconcrete main.pye
    src/*.pye  # your libs
    

Partial encrypted (pyconcrete as lib)

  • download pyconcrete source and install by setup.py

    $ python setup.py install \
      --install-lib={your project path} \
      --install-scripts={where you want to execute pyconcrete-admin.py and pyconcrete(exe)}
    
  • import pyconcrete in your main script

  • recommendation project layout

    main.py       # import pyconcrete and your lib
    pyconcrete/*  # put pyconcrete lib in project root, keep it as original files
    src/*.pye     # your libs
    

get UTC time in PHP

Using gmdate will always return a GMT date. Syntax is same as for date.

T-SQL Cast versus Convert

You should also not use CAST for getting the text of a hash algorithm. CAST(HASHBYTES('...') AS VARCHAR(32)) is not the same as CONVERT(VARCHAR(32), HASHBYTES('...'), 2). Without the last parameter, the result would be the same, but not a readable text. As far as I know, You cannot specify that last parameter in CAST.

Running multiple async tasks and waiting for them all to complete

This is how I do it with an array Func<>:

var tasks = new Func<Task>[]
{
   () => myAsyncWork1(),
   () => myAsyncWork2(),
   () => myAsyncWork3()
};

await Task.WhenAll(tasks.Select(task => task()).ToArray()); //Async    
Task.WaitAll(tasks.Select(task => task()).ToArray()); //Or use WaitAll for Sync

Setting "checked" for a checkbox with jQuery

As @livefree75 said:

jQuery 1.5.x and below

You can also extend the $.fn object with new methods:

(function($)  {
   $.fn.extend({
      check : function()  {
         return this.filter(":radio, :checkbox").attr("checked", true);
      },
      uncheck : function()  {
         return this.filter(":radio, :checkbox").removeAttr("checked");
      }
   });
}(jQuery));

But in new versions of jQuery, we have to use something like this:

jQuery 1.6+

    (function($)  {
       $.fn.extend({
          check : function()  {
             return this.filter(":radio, :checkbox").prop("checked", true);
          },
          uncheck : function()  {
             return this.filter(":radio, :checkbox").prop("checked",false);
          }
       });
    }(jQuery));

Then you can just do:

    $(":checkbox").check();
    $(":checkbox").uncheck();

Simple Pivot Table to Count Unique Values

I found the easiest approach is to use the Distinct Count option under Value Field Settings (left click the field in the Values pane). The option for Distinct Count is at the very bottom of the list.

Location of where to click

Here are the before (TOP; normal Count) and after (BOTTOM; Distinct Count)

COUNT

DISTINCT COUNT

sql server invalid object name - but tables are listed in SSMS tables list

did you try: right click the database, and click "refresh"

Android how to convert int to String?

Use this String.valueOf(value);

curl_exec() always returns false

This happened to me yesterday and in my case was because I was following a PDF manual to develop some module to communicate with an API and while copying the link directly from the manual, for some odd reason, the hyphen from the copied link was in a different encoding and hence the curl_exec() was always returning false because it was unable to communicate with the server.

It took me a couple hours to finally understand the diference in the characters bellow:

https://www.e-example.com/api
https://www.e-example.com/api

Every time I tried to access the link directly from a browser it converted to something likehttps://www.xn--eexample-0m3d.com/api.

It may seem to you that they are equal but if you check the encoding of the hyphens here you'll see that the first hyphen is a unicode characters U+2010 and the other is a U+002D.

Hope this helps someone.

ORA-01652: unable to extend temp segment by 128 in tablespace SYSTEM: How to extend?

Each tablespace has one or more datafiles that it uses to store data.

The max size of a datafile depends on the block size of the database. I believe that, by default, that leaves with you with a max of 32gb per datafile.

To find out if the actual limit is 32gb, run the following:

select value from v$parameter where name = 'db_block_size';

Compare the result you get with the first column below, and that will indicate what your max datafile size is.

I have Oracle Personal Edition 11g r2 and in a default install it had an 8,192 block size (32gb per data file).

Block Sz   Max Datafile Sz (Gb)   Max DB Sz (Tb)

--------   --------------------   --------------

   2,048                  8,192          524,264

   4,096                 16,384        1,048,528

   8,192                 32,768        2,097,056

  16,384                 65,536        4,194,112

  32,768                131,072        8,388,224

You can run this query to find what datafiles you have, what tablespaces they are associated with, and what you've currrently set the max file size to (which cannot exceed the aforementioned 32gb):

select bytes/1024/1024 as mb_size,
       maxbytes/1024/1024 as maxsize_set,
       x.*
from   dba_data_files x

MAXSIZE_SET is the maximum size you've set the datafile to. Also relevant is whether you've set the AUTOEXTEND option to ON (its name does what it implies).

If your datafile has a low max size or autoextend is not on you could simply run:

alter database datafile 'path_to_your_file\that_file.DBF' autoextend on maxsize unlimited;

However if its size is at/near 32gb an autoextend is on, then yes, you do need another datafile for the tablespace:

alter tablespace system add datafile 'path_to_your_datafiles_folder\name_of_df_you_want.dbf' size 10m autoextend on maxsize unlimited;

How to reference static assets within vue javascript

Having a default structure of folders generated by Vue CLI such as src/assets you can place your image there and refer this from HTML as follows <img src="../src/assets/img/logo.png"> as well (works automatically without any changes on deployment too).

Create list or arrays in Windows Batch

@echo off
setlocal
set "list=a b c d"
(
 for %%i in (%list%) do (
  echo(%%i
  echo(
 )
)>file.txt

You don't need - actually, can't "declare" variables in batch. Assigning a value to a variable creates it, and assigning an empty string deletes it. Any variable name that doesn't have an assigned value HAS a value of an empty string. ALL variables are strings - WITHOUT exception. There ARE operations that appear to perform (integer) mathematical functions, but they operate by converting back and forth from strings.

Batch is sensitive to spaces in variable names, so your assignment as posted would assign the string "A B C D" - including the quotes, to the variable "list " - NOT including the quotes, but including the space. The syntax set "var=string" is used to assign the value string to var whereas set var=string will do the same thing. Almost. In the first case, any stray trailing spaces after the closing quote are EXCLUDED from the value assigned, in the second, they are INCLUDED. Spaces are a little hard to see when printed.

ECHO echoes strings. Clasically, it is followed by a space - one of the default separators used by batch (the others are TAB, COMMA, SEMICOLON - any of these do just as well BUT TABS often get transformed to a space-squence by text-editors and the others have grown quirks of their own over the years.) Other characters following the O in ECHO have been found to do precisely what the documented SPACE should do. DOT is common. Open-parenthesis ( is probably the most useful since the command

ECHO.%emptyvalue%

will produce a report of the ECHO state (ECHO is on/off) whereas

ECHO(%emptyvalue%

will produce an empty line.

The problem with ECHO( is that the result "looks" unbalanced.

How to display a list inline using Twitter's Bootstrap

Bootstrap 2.3.2

<ul class="inline">
  <li>...</li>
</ul>

Bootstrap 3

<ul class="list-inline">
  <li>...</li>
</ul>

Bootstrap 4

<ul class="list-inline">
  <li class="list-inline-item">Lorem ipsum</li>
  <li class="list-inline-item">Phasellus iaculis</li>
  <li class="list-inline-item">Nulla volutpat</li>
</ul>

source: http://v4-alpha.getbootstrap.com/content/typography/#inline

Updated link https://getbootstrap.com/docs/4.4/content/typography/#inline

"unary operator expected" error in Bash if condition

Try assigning a value to $aug1 before use it in if[] statements; the error message will disappear afterwards.

High CPU Utilization in java application - why?

Your first approach should be to find all references to Thread.sleep and check that:

  1. Sleeping is the right thing to do - you should use some sort of wait mechanism if possible - perhaps careful use of a BlockingQueue would help.

  2. If sleeping is the right thing to do, are you sleeping for the right amount of time - this is often a very difficult question to answer.

The most common mistake in multi-threaded design is to believe that all you need to do when waiting for something to happen is to check for it and sleep for a while in a tight loop. This is rarely an effective solution - you should always try to wait for the occurrence.

The second most common issue is to loop without sleeping. This is even worse and is a little less easy to track down.

Detect Scroll Up & Scroll down in ListView

Trick about detect scroll up or down in listview, you just call this function on onScroll function in OnScrollListener of ListView.

private int oldFirstVisibleItem = -1;
    private protected int oldTop = -1;
    // you can change this value (pixel)
    private static final int MAX_SCROLL_DIFF = 5;

    private void calculateListScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        if (firstVisibleItem == oldFirstVisibleItem) {
            int top = view.getChildAt(0).getTop();
            // range between new top and old top must greater than MAX_SCROLL_DIFF
            if (top > oldTop && Math.abs(top - oldTop) > MAX_SCROLL_DIFF) {
                // scroll up
            } else if (top < oldTop && Math.abs(top - oldTop) > MAX_SCROLL_DIFF) {
                // scroll down
            }
            oldTop = top;
        } else {
            View child = view.getChildAt(0);
            if (child != null) {
                oldFirstVisibleItem = firstVisibleItem;
                oldTop = child.getTop();
            }
        }
    }

How to get Git to clone into current directory

Do

git clone https://[email protected]/user/projectname.git .

Directory must be empty

Safest way to run BAT file from Powershell script

Assuming my-app is a subdirectory under the current directory. The $LASTEXITCODE should be there from the last command:

.\my-app\my-fle.bat

If it was from a fileshare:

\\server\my-file.bat

Are members of a C++ struct initialized to 0 by default?

In general, no. However, a struct declared as file-scope or static in a function /will/ be initialized to 0 (just like all other variables of those scopes):

int x; // 0
int y = 42; // 42
struct { int a, b; } foo; // 0, 0

void foo() {
  struct { int a, b; } bar; // undefined
  static struct { int c, d; } quux; // 0, 0
}

Java String encoding (UTF-8)

How is this different from the following?

This line of code here:

String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));

constructs a new String object (i.e. a copy of oldString), while this line of code:

String newString = oldString;

declares a new variable of type java.lang.String and initializes it to refer to the same String object as the variable oldString.

Is there any scenario in which the two lines will have different outputs?

Absolutely:

String newString = oldString;
boolean isSameInstance = newString == oldString; // isSameInstance == true

vs.

String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
 // isSameInstance == false (in most cases)    
boolean isSameInstance = newString == oldString;

a_horse_with_no_name (see comment) is right of course. The equivalent of

String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));

is

String newString = new String(oldString);

minus the subtle difference wrt the encoding that Peter Lawrey explains in his answer.

super() raises "TypeError: must be type, not classobj" for new-style class

Alright, it's the usual "super() cannot be used with an old-style class".

However, the important point is that the correct test for "is this a new-style instance (i.e. object)?" is

>>> class OldStyle: pass
>>> instance = OldStyle()
>>> issubclass(instance.__class__, object)
False

and not (as in the question):

>>> isinstance(instance, object)
True

For classes, the correct "is this a new-style class" test is:

>>> issubclass(OldStyle, object)  # OldStyle is not a new-style class
False
>>> issubclass(int, object)  # int is a new-style class
True

The crucial point is that with old-style classes, the class of an instance and its type are distinct. Here, OldStyle().__class__ is OldStyle, which does not inherit from object, while type(OldStyle()) is the instance type, which does inherit from object. Basically, an old-style class just creates objects of type instance (whereas a new-style class creates objects whose type is the class itself). This is probably why the instance OldStyle() is an object: its type() inherits from object (the fact that its class does not inherit from object does not count: old-style classes merely construct new objects of type instance). Partial reference: https://stackoverflow.com/a/9699961/42973.

PS: The difference between a new-style class and an old-style one can also be seen with:

>>> type(OldStyle)  # OldStyle creates objects but is not itself a type
classobj
>>> isinstance(OldStyle, type)
False
>>> type(int)  # A new-style class is a type
type

(old-style classes are not types, so they cannot be the type of their instances).

Why would you use Expression<Func<T>> rather than Func<T>?

Overly simplified here, but Func is a machine, whereas Expression is a blueprint. :D

How to sum array of numbers in Ruby?

Alternatively (just for comparison), if you have Rails installed (actually just ActiveSupport):

require 'activesupport'
array.sum

What is the use of static variable in C#? When to use it? Why can't I declare the static variable inside method?

Static classes don't require you to create an object of that class/instantiate them, you can prefix the C# keyword static in front of the class name, to make it static.

Remember: we're not instantiating the Console class, String class, Array Class.

class Book
{
    public static int myInt = 0;
}

public class Exercise
{
    static void Main()
    {
        Book book = new Book();
       //Use the class name directly to call the property myInt, 
      //don't use the object to access the value of property myInt

        Console.WriteLine(Book.myInt);

        Console.ReadKey();

    }
}

How to restart remote MySQL server running on Ubuntu linux?

  • To restart mysql use this command

sudo service mysql restart

Or

sudo restart mysql

Reference

How can I make my flexbox layout take 100% vertical space?

Let me show you another way that works 100%. I will also add some padding for the example.

<div class = "container">
  <div class = "flex-pad-x">
    <div class = "flex-pad-y">
      <div class = "flex-pad-y">
        <div class = "flex-grow-y">
         Content Centered
        </div>
      </div>
    </div>
  </div>
</div>

.container {
  position: fixed;
  top: 0px;
  left: 0px;
  bottom: 0px;
  right: 0px;
  width: 100%;
  height: 100%;
}

  .flex-pad-x {
    padding: 0px 20px;
    height: 100%;
    display: flex;
  }

  .flex-pad-y {
    padding: 20px 0px;
    width: 100%;
    display: flex;
    flex-direction: column;
  }

  .flex-grow-y {
    flex-grow: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
   }

As you can see we can achieve this with a few wrappers for control while utilising the flex-grow & flex-direction attribute.

1: When the parent "flex-direction" is a "row", its child "flex-grow" works horizontally. 2: When the parent "flex-direction" is "columns", its child "flex-grow" works vertically.

Hope this helps

Daniel

Get the client IP address using PHP

It also works fine for internal IP addresses:

 function get_client_ip()
 {
      $ipaddress = '';
      if (getenv('HTTP_CLIENT_IP'))
          $ipaddress = getenv('HTTP_CLIENT_IP');
      else if(getenv('HTTP_X_FORWARDED_FOR'))
          $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
      else if(getenv('HTTP_X_FORWARDED'))
          $ipaddress = getenv('HTTP_X_FORWARDED');
      else if(getenv('HTTP_FORWARDED_FOR'))
          $ipaddress = getenv('HTTP_FORWARDED_FOR');
      else if(getenv('HTTP_FORWARDED'))
          $ipaddress = getenv('HTTP_FORWARDED');
      else if(getenv('REMOTE_ADDR'))
          $ipaddress = getenv('REMOTE_ADDR');
      else
          $ipaddress = 'UNKNOWN';

      return $ipaddress;
 }

How do I convert NSMutableArray to NSArray?

Objective-C

Below is way to convert NSMutableArray to NSArray:

//oldArray is having NSMutableArray data-type.
//Using Init with Array method.
NSArray *newArray1 = [[NSArray alloc]initWithArray:oldArray];

//Make copy of array
NSArray *newArray2 = [oldArray copy];

//Make mutablecopy of array
NSArray *newArray3 = [oldArray mutableCopy];

//Directly stored NSMutableArray to NSArray.
NSArray *newArray4 = oldArray;

Swift

In Swift 3.0 there is new data type Array. Declare Array using let keyword then it would become NSArray And if declare using var keyword then it's become NSMutableArray.

Sample code:

let newArray = oldArray as Array

Responsive image map

For those who don't want to resort to JavaScript, here's an image slicing example:

http://codepen.io/anon/pen/cbzrK

As you scale the window, the clown image will scale accordingly, and when it does, the nose of the clown remains hyperlinked.

Typescript: React event types

For those who are looking for a solution to get an event and store something, in my case a HTML 5 element, on a useState here's my solution:

const [anchorElement, setAnchorElement] = useState<HTMLButtonElement | null>(null);

const handleMenu = (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) : void => {
    setAnchorElement(event.currentTarget);
};

Hidden Features of C#?

PreviousPage property:

"The System.Web.UI.Page representing the page that transferred control to the current page."

It is very useful.

What is the proper way to check if a string is empty in Perl?

To check for an empty string you could also do something as follows

if (!defined $val || $val eq '')
{
    # empty
}

List of IP addresses/hostnames from local network in Python

If by "local" you mean on the same network segment, then you have to perform the following steps:

  1. Determine your own IP address
  2. Determine your own netmask
  3. Determine the network range
  4. Scan all the addresses (except the lowest, which is your network address and the highest, which is your broadcast address).
  5. Use your DNS's reverse lookup to determine the hostname for IP addresses which respond to your scan.

Or you can just let Python execute nmap externally and pipe the results back into your program.

How to prevent page scrolling when scrolling a DIV element?

I needed to add this event to multiple elements that might have a scrollbar. For the cases where no scrollbar was present, the main scrollbar didn't work as it should. So i made a small change to @Šime code as follows:

$( '.scrollable' ).on( 'mousewheel DOMMouseScroll', function ( e ) {
    if($(this).prop('scrollHeight') > $(this).height())
    {
        var e0 = e.originalEvent, delta = e0.wheelDelta || -e0.detail;

        this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30;
        e.preventDefault();
    }       
});

Now, only elements with a scrollbar will prevent the main scroll from begin stopped.

Rank function in MySQL

While the most upvoted answer ranks, it doesn't partition, You can do a self Join to get the whole thing partitioned also:

SELECT    a.first_name,
      a.age,
      a.gender,
        count(b.age)+1 as rank
FROM  person a left join person b on a.age>b.age and a.gender=b.gender 
group by  a.first_name,
      a.age,
      a.gender

Use Case

CREATE TABLE person (id int, first_name varchar(20), age int, gender char(1));

INSERT INTO person VALUES (1, 'Bob', 25, 'M');
INSERT INTO person VALUES (2, 'Jane', 20, 'F');
INSERT INTO person VALUES (3, 'Jack', 30, 'M');
INSERT INTO person VALUES (4, 'Bill', 32, 'M');
INSERT INTO person VALUES (5, 'Nick', 22, 'M');
INSERT INTO person VALUES (6, 'Kathy', 18, 'F');
INSERT INTO person VALUES (7, 'Steve', 36, 'M');
INSERT INTO person VALUES (8, 'Anne', 25, 'F');

Answer:

Bill    32  M   4
Bob     25  M   2
Jack    30  M   3
Nick    22  M   1
Steve   36  M   5
Anne    25  F   3
Jane    20  F   2
Kathy   18  F   1

How to add white spaces in HTML paragraph

You can try it by adding &nbsp;

Forward declaration of a typedef in C++

Because to declare a type, its size needs to be known. You can forward declare a pointer to the type, or typedef a pointer to the type.

If you really want to, you can use the pimpl idiom to keep the includes down. But if you want to use a type, rather than a pointer, the compiler has to know its size.

Edit: j_random_hacker adds an important qualification to this answer, basically that the size needs to be know to use the type, but a forward declaration can be made if we only need to know the type exists, in order to create pointers or references to the type. Since the OP didn't show code, but complained it wouldn't compile, I assumed (probably correctly) that the OP was trying to use the type, not just refer to it.

Update data on a page without refreshing

In general, if you don't know how something works, look for an example which you can learn from.

For this problem, consider this DEMO

You can see loading content with AJAX is very easily accomplished with jQuery:

$(function(){
    // don't cache ajax or content won't be fresh
    $.ajaxSetup ({
        cache: false
    });
    var ajax_load = "<img src='http://automobiles.honda.com/images/current-offers/small-loading.gif' alt='loading...' />";

    // load() functions
    var loadUrl = "http://fiddle.jshell.net/deborah/pkmvD/show/";
    $("#loadbasic").click(function(){
        $("#result").html(ajax_load).load(loadUrl);
    });

// end  
});

Try to understand how this works and then try replicating it. Good luck.

You can find the corresponding tutorial HERE

Update

Right now the following event starts the ajax load function:

$("#loadbasic").click(function(){
        $("#result").html(ajax_load).load(loadUrl);
    });

You can also do this periodically: How to fire AJAX request Periodically?

(function worker() {
  $.ajax({
    url: 'ajax/test.html', 
    success: function(data) {
      $('.result').html(data);
    },
    complete: function() {
      // Schedule the next request when the current one's complete
      setTimeout(worker, 5000);
    }
  });
})();

I made a demo of this implementation for you HERE. In this demo, every 2 seconds (setTimeout(worker, 2000);) the content is updated.

You can also just load the data immediately:

$("#result").html(ajax_load).load(loadUrl);

Which has THIS corresponding demo.

Error # 1045 - Cannot Log in to MySQL server -> phpmyadmin

When you change your passwords in the security tab, there are two sections, one above and one below. I think the common mistake here is that others try to log-in with the account they have set "below" the one used for htaccess, whereas they should log in to the password they set on the above section. That's how I fixed mine.

how to use Spring Boot profiles

Create specific .yml files in the resources directory for each and every environment(Eg: dev,qa,stg etc.) that you need to run the application. image of .yml files in resources directory

If you are using spring-boot-maven-plugin 2.0.5.RELEASE in your pom.xml file you can add the profiles within the dependency tag as follows. image of pom.xml spring-boot-maven-plugin (you can configure multiple profiles using multiple profile tags)

Then you can use the following commands to build and run the project.

1) mvn clean install
2) mvn spring-boot:run -Dspring-boot.run.default==qa

Then you will see that the default profile is set as qa while running the project. displaying the default profile when running the application

What is bootstrapping?

Bootstrapping has yet another meaning in the context of reinforcement learning that may be useful to know for developers, in addition to its use in software development (most answers here, e.g. by kdgregory) and its use in statistics as discussed by Dirk Eddelbuettel.

From Sutton and Barto:

Widrow, Gupta, and Maitra (1973) modified the Least-Mean-Square (LMS) algorithm of Widrow and Hoff (1960) to produce a reinforcement learning rule that could learn from success and failure signals instead of from training examples. They called this form of learning “selective bootstrap adaptation” and described it as “learning with a critic” instead of “learning with a teacher.” They analyzed this rule and showed how it could learn to play blackjack. This was an isolated foray into reinforcement learning by Widrow, whose contributions to supervised learning were much more influential.

The book describes various reinforcement algorithms where the target value is based on a previous approximation as bootstrap methods:

Finally, we note one last special property of DP [Dynamic Programming] methods. All of them update estimates of the values of states based on estimates of the values of successor states. That is, they update estimates on the basis of other estimates. We call this general idea bootstrapping. Many reinforcement learning methods perform bootstrapping, even those that do not require, as DP requires, a complete and accurate model of the environment.

Note that this differs from bootstrap aggregating and intelligence explosion that is mentioned on the wikipedia page on bootstrapping.

How do I limit the number of results returned from grep?

Using tail:

#dmesg 
...
...
...
[132059.017752] cfg80211:   (57240000 KHz - 65880000 KHz @ 2160000 KHz), (N/A, 4000 mBm)
[132116.566238] cfg80211: Calling CRDA to update world regulatory domain
[132116.568939] cfg80211: World regulatory domain updated:
[132116.568942] cfg80211:   (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp)
[132116.568944] cfg80211:   (2402000 KHz - 2472000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)
[132116.568945] cfg80211:   (2457000 KHz - 2482000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)
[132116.568947] cfg80211:   (2474000 KHz - 2494000 KHz @ 20000 KHz), (300 mBi, 2000 mBm)
[132116.568948] cfg80211:   (5170000 KHz - 5250000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)
[132116.568949] cfg80211:   (5735000 KHz - 5835000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)
[132120.288218] cfg80211: Calling CRDA for country: GB
[132120.291143] cfg80211: Regulatory domain changed to country: GB
[132120.291146] cfg80211:   (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp)
[132120.291148] cfg80211:   (2402000 KHz - 2482000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291150] cfg80211:   (5170000 KHz - 5250000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291152] cfg80211:   (5250000 KHz - 5330000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291153] cfg80211:   (5490000 KHz - 5710000 KHz @ 40000 KHz), (N/A, 2700 mBm)
[132120.291155] cfg80211:   (57240000 KHz - 65880000 KHz @ 2160000 KHz), (N/A, 4000 mBm)
alex@ubuntu:~/bugs/navencrypt/dev-tools$ dmesg | grep cfg8021 | head 2
head: cannot open ‘2’ for reading: No such file or directory
alex@ubuntu:~/bugs/navencrypt/dev-tools$ dmesg | grep cfg8021 | tail -2
[132120.291153] cfg80211:   (5490000 KHz - 5710000 KHz @ 40000 KHz), (N/A, 2700 mBm)
[132120.291155] cfg80211:   (57240000 KHz - 65880000 KHz @ 2160000 KHz), (N/A, 4000 mBm)
alex@ubuntu:~/bugs/navencrypt/dev-tools$ dmesg | grep cfg8021 | tail -5
[132120.291148] cfg80211:   (2402000 KHz - 2482000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291150] cfg80211:   (5170000 KHz - 5250000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291152] cfg80211:   (5250000 KHz - 5330000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291153] cfg80211:   (5490000 KHz - 5710000 KHz @ 40000 KHz), (N/A, 2700 mBm)
[132120.291155] cfg80211:   (57240000 KHz - 65880000 KHz @ 2160000 KHz), (N/A, 4000 mBm)
alex@ubuntu:~/bugs/navencrypt/dev-tools$ dmesg | grep cfg8021 | tail -6
[132120.291146] cfg80211:   (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp)
[132120.291148] cfg80211:   (2402000 KHz - 2482000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291150] cfg80211:   (5170000 KHz - 5250000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291152] cfg80211:   (5250000 KHz - 5330000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291153] cfg80211:   (5490000 KHz - 5710000 KHz @ 40000 KHz), (N/A, 2700 mBm)
[132120.291155] cfg80211:   (57240000 KHz - 65880000 KHz @ 2160000 KHz), (N/A, 4000 mBm)
alex@ubuntu:~/bugs/navencrypt/dev-tools$ 

How does one reorder columns in a data frame?

You can also use the subset function:

data <- subset(data, select=c(3,2,1))

You should better use the [] operator as in the other answers, but it may be useful to know that you can do a subset and a column reorder operation in a single command.

Update:

You can also use the select function from the dplyr package:

data = data %>% select(Time, out, In, Files)

I am not sure about the efficiency, but thanks to dplyr's syntax this solution should be more flexible, specially if you have a lot of columns. For example, the following will reorder the columns of the mtcars dataset in the opposite order:

mtcars %>% select(carb:mpg)

And the following will reorder only some columns, and discard others:

mtcars %>% select(mpg:disp, hp, wt, gear:qsec, starts_with('carb'))

Read more about dplyr's select syntax.

PHP7 : install ext-dom issue

simply run

sudo apt install php-xml

its worked for me

Conda activate not working?

I just ran into a similar issue. Recently started developing on windows, so getting used to the PowerShell. Ironically when trying to use 'conda activate ' in Git-bash i got the error

$ conda activate obf

CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'.
If using 'conda activate' from a batch script, change your
invocation to 'CALL conda.bat activate'.

To initialize your shell, run

    $ conda init <SHELL_NAME>

Currently supported shells are:
  - bash
  - cmd.exe
  - fish
  - tcsh
  - xonsh
  - zsh
  - powershell

See 'conda init --help' for more information and options.

IMPORTANT: You may need to close and restart your shell after running 'conda init'. 

Running the command in my PowerShell (elevated) as instructed did the trick for me.

conda init powershell 

This should be true across all terminal environments, just strange PowerShell didn't return this error itself.

PHP + MySQL transactions examples

I had this, but not sure if this is correct. Could try this out also.

mysql_query("START TRANSACTION");
$flag = true;
$query = "INSERT INTO testing (myid) VALUES ('test')";

$query2 = "INSERT INTO testing2 (myid2) VALUES ('test2')";

$result = mysql_query($query) or trigger_error(mysql_error(), E_USER_ERROR);
if (!$result) {
$flag = false;
}

$result = mysql_query($query2) or trigger_error(mysql_error(), E_USER_ERROR);
if (!$result) {
$flag = false;
}

if ($flag) {
mysql_query("COMMIT");
} else {        
mysql_query("ROLLBACK");
}

Idea from here: http://www.phpknowhow.com/mysql/transactions/

How does HttpContext.Current.User.Identity.Name know which usernames exist?

For windows authentication

select your project.

Press F4

Disable "Anonymous Authentication" and enable "Windows Authentication"

enter image description here

Launch an app from within another (iPhone)

No it's not. Besides the documented URL handlers, there's no way to communicate with/launch another app.

git pull remote branch cannot find remote ref

check your branch on your repo. maybe someone delete it.

What's the regular expression that matches a square bracket?

does it work with an antislash before the [ ?

\[ or \\[ ?

Sublime Text 3 how to change the font size of the file sidebar?

I use Soda Dark 3 with icons enabled. So by just renaming it erases all the icons enabled with it. So I just leave the Default as it is and created a new file Soda Dark 3.sublime-theme and just have the following in the content

[
{
    "class": "label_control",
    "color": [150, 25, 25],
    "shadow_color": [24, 24, 24],
    "shadow_offset": [0, -1],
    "font.size": 16,
    "font.bold": true
},

]

So in Mac is it at /Users/gugovind/Library/Application Support/Sublime Text 3/Packages/User/

jQuery if statement, syntax

If you're using Jquery to manipulate the DOM, then I have found the following a good way to include logic in a Jquery statement:

$(selector).addClass(A && B?'classIfTrue':'');

Algorithm for solving Sudoku

Not gonna write full code, but I did a sudoku solver a long time ago. I found that it didn't always solve it (the thing people do when they have a newspaper is incomplete!), but now think I know how to do it.

  • Setup: for each square, have a set of flags for each number showing the allowed numbers.
  • Crossing out: just like when people on the train are solving it on paper, you can iteratively cross out known numbers. Any square left with just one number will trigger another crossing out. This will either result in solving the whole puzzle, or it will run out of triggers. This is where I stalled last time.
  • Permutations: there's only 9! = 362880 ways to arrange 9 numbers, easily precomputed on a modern system. All of the rows, columns, and 3x3 squares must be one of these permutations. Once you have a bunch of numbers in there, you can do what you did with the crossing out. For each row/column/3x3, you can cross out 1/9 of the 9! permutations if you have one number, 1/(8*9) if you have 2, and so forth.
  • Cross permutations: Now you have a bunch of rows and columns with sets of potential permutations. But there's another constraint: once you set a row, the columns and 3x3s are vastly reduced in what they might be. You can do a tree search from here to find a solution.

SQL DELETE with JOIN another table for WHERE condition

Due to the locking implementation issues, MySQL does not allow referencing the affected table with DELETE or UPDATE.

You need to make a JOIN here instead:

DELETE  gc.*
FROM    guide_category AS gc 
LEFT JOIN
        guide AS g 
ON      g.id_guide = gc.id_guide
WHERE   g.title IS NULL

or just use a NOT IN:

DELETE  
FROM    guide_category AS gc 
WHERE   id_guide NOT IN
        (
        SELECT  id_guide
        FROM    guide
        )

Post an object as data using Jquery Ajax

I will leave my original answer in place but the below is how you need to approach it. (Forgive me but it is a long time since I have used regular asp.net / web services with jquery:)

You need to use the following js lib json2 library, you can then use the stringify method to ensure your json is in the correct format for the service.

var data0 = {numberId: "1", companyId : "531"};

var json = JSON2.stringify(data0 ); 

$.ajax({
 type: "POST",
 url: "TelephoneNumbers.aspx/DeleteNumber",
 data: json,
 contentType: "application/json; charset=utf-8",
 dataType: "json",
 success: function(msg) {
 alert('In Ajax');
 }
});

UPDATE: Same issue / answer here

Image resolution for new iPhone 6 and 6+, @3x support added?

ios will always tries to take the best image, but will fall back to other options .. so if you only have normal images in the app and it needs @2x images it will use the normal images.

if you only put @2x in the project and you open the app on a normal device it will scale the images down to display.

if you target ios7 and ios8 devices and want best quality you would need @2x and @3x for phone and normal and @2x for ipad assets, since there is no non retina phone left and no @3x ipad.

maybe it is better to create the assets in the app from vector graphic... check http://mattgemmell.com/using-pdf-images-in-ios-apps/

What are the default access modifiers in C#?

I would like to add some documentation link. Check out more detail here.

enter image description here

mysql update column with value from another table

If you have common field in both table then it's so easy !....

Table-1 = table where you want to update. Table-2 = table where you from take data.

  1. make query in Table-1 and find common field value.
  2. make a loop and find all data from Table-2 according to table 1 value.
  3. again make update query in table 1.

$qry_asseet_list = mysql_query("SELECT 'primary key field' FROM `table-1`");

$resultArray = array();
while ($row = mysql_fetch_array($qry_asseet_list)) {
$resultArray[] = $row;
}



foreach($resultArray as $rec) {

    $a = $rec['primary key field'];

    $cuttable_qry = mysql_query("SELECT * FROM `Table-2` WHERE `key field name` = $a");

    $cuttable = mysql_fetch_assoc($cuttable_qry);



    echo $x= $cuttable['Table-2 field']; echo " ! ";
    echo $y= $cuttable['Table-2 field'];echo " ! ";
    echo $z= $cuttable['Table-2 field'];echo " ! ";


    $k = mysql_query("UPDATE `Table-1` SET `summary_style` = '$x', `summary_color` = '$y', `summary_customer` = '$z' WHERE `summary_laysheet_number` = $a;");

    if ($k) {
        echo "done";
    } else {
        echo mysql_error();
    }


}

How do you delete all text above a certain line

:1,.d deletes lines 1 to current.
:1,.-1d deletes lines 1 to above current.

(Personally I'd use dgg or kdgg like the other answers, but TMTOWTDI.)

Create a asmx web service in C# using visual studio 2013

Check your namespaces. I had and issue with that. I found that out by adding another web service to the project to dup it like you did yours and noticed the namespace was different. I had renamed it at the beginning of the project and it looks like its persisted.

How to randomly pick an element from an array

You can use the Random generator to generate a random index and return the element at that index:

//initialization
Random generator = new Random();
int randomIndex = generator.nextInt(myArray.length);
return myArray[randomIndex];

Hidden Columns in jqGrid

This thread is pretty old I suppose, but in case anyone else stumbles across this question... I had to grab a value from the selected row of a table, but I didn't want to show the column that row was from. I used hideCol, but had the same problem as Andy where it looked messy. To fix it (call it a hack) I just re-set the width of the grid.

jQuery(document).ready(function() {

       jQuery("#ItemGrid").jqGrid({ 
                ..., 
                width: 700,
                ...
        }).hideCol('StoreId').setGridWidth(700)

Since my row widths are automatic, when I reset the width of the table it reset the column widths but excluded the hidden one, so they filled in the gap.

What is the difference between square brackets and parentheses in a regex?

Your team's advice is almost right, except for the mistake that was made. Once you find out why, you will never forget it. Take a look at this mistake.

/^(7|8|9)\d{9}$/

What this does:

  • ^ and $ denotes anchored matches, which asserts that the subpattern in between these anchors are the entire match. The string will only match if the subpattern matches the entirety of it, not just a section.
  • () denotes a capturing group.
  • 7|8|9 denotes matching either of 7, 8, or 9. It does this with alternations, which is what the pipe operator | does — alternating between alternations. This backtracks between alternations: If the first alternation is not matched, the engine has to return before the pointer location moved during the match of the alternation, to continue matching the next alternation; Whereas the character class can advance sequentially. See this match on a regex engine with optimizations disabled:
Pattern: (r|f)at
Match string: carat

alternations

Pattern: [rf]at
Match string: carat

class

  • \d{9} matches nine digits. \d is a shorthanded metacharacter, which matches any digits.
/^[7|8|9][\d]{9}$/

Look at what it does:

  • ^ and $ denotes anchored matches as well.
  • [7|8|9] is a character class. Any characters from the list 7, |, 8, |, or 9 can be matched, thus the | was added in incorrectly. This matches without backtracking.
  • [\d] is a character class that inhabits the metacharacter \d. The combination of the use of a character class and a single metacharacter is a bad idea, by the way, since the layer of abstraction can slow down the match, but this is only an implementation detail and only applies to a few of regex implementations. JavaScript is not one, but it does make the subpattern slightly longer.
  • {9} indicates the previous single construct is repeated nine times in total.

The optimal regex is /^[789]\d{9}$/, because /^(7|8|9)\d{9}$/ captures unnecessarily which imposes a performance decrease on most regex implementations ( happens to be one, considering the question uses keyword var in code, this probably is JavaScript). The use of which runs on PCRE for preg matching will optimize away the lack of backtracking, however we're not in PHP either, so using classes [] instead of alternations | gives performance bonus as the match does not backtrack, and therefore both matches and fails faster than using your previous regular expression.

how to redirect to home page

strRetMsg ="<script>window.location.href = '../Other/Home.htm';</script>";

Page.ClientScript.RegisterStartupScript(this.GetType(), "Script", strRetMsg,false);

Put this code in Page Load.

How to get the position of a character in Python?

>>> s="mystring"
>>> s.index("r")
4
>>> s.find("r")
4

"Long winded" way

>>> for i,c in enumerate(s):
...   if "r"==c: print i
...
4

to get substring,

>>> s="mystring"
>>> s[4:10]
'ring'

Explanation of 'String args[]' and static in 'public static void main(String[] args)'

I would point a beginner to the Wiki article on the Main function, then supplement it with this.

  • Java only starts running a program with the specific public static void main(String[] args) signature, and one can think of a signature like their own name - it's how Java can tell the difference between someone else's main() and the one true main().

  • String[] args is a collection of Strings, separated by a space, which can be typed into the program on the terminal. More times than not, the beginner isn't going to use this variable, but it's always there just in case.

How to install a plugin in Jenkins manually

I have created a simple script that does the following:

  • Download one or more plugins to the plugin directory
  • Scan all plugins in that directory for missing dependencies
  • download this dependencies as well
  • loop until no open dependencies are left

The script requires no running jenkins - I use it to provision a docker box.

https://gist.github.com/micw/e80d739c6099078ce0f3

create multiple tag docker image

You can't create tags with Dockerfiles but you can create multiple tags on your images via the command line.

Use this to list your image ids:

$ docker images

Then tag away:

$ docker tag 9f676bd305a4 ubuntu:13.10
$ docker tag 9f676bd305a4 ubuntu:saucy
$ docker tag eb601b8965b8 ubuntu:raring
...

Running CMake on Windows

The default generator for Windows seems to be set to NMAKE. Try to use:

cmake -G "MinGW Makefiles"

Or use the GUI, and select MinGW Makefiles when prompted for a generator. Don't forget to cleanup the directory where you tried to run CMake, or delete the cache in the GUI. Otherwise, it will try again with NMAKE.

Multiple WHERE Clauses with LINQ extension methods

Two ways:

results = results.Where(o => (o.OrderStatus == OrderStatus.Open) &&
                             (o.CustomerID == customerID));

or:

results = results.Where(o => (o.OrderStatus == OrderStatus.Open))
                 .Where(o => (o.CustomerID == customerID));

I usually prefer the latter. But it's worth profiling the SQL server to check the query execution and see which one performs better for your data (if there's any difference at all).

A note about chaining the .Where() methods: You can chain together all the LINQ methods you want. Methods like .Where() don't actually execute against the database (yet). They defer execution until the actual results are calculated (such as with a .Count() or a .ToList()). So, as you chain together multiple methods (more calls to .Where(), maybe an .OrderBy() or something to that effect, etc.) they build up what's called an expression tree. This entire tree is what gets executed against the data source when the time comes to evaluate it.

usr/bin/ld: cannot find -l<nameOfTheLibrary>

If your library name is say libxyz.so and it is located on path say:

/home/user/myDir

then to link it to your program:

g++ -L/home/user/myDir -lxyz myprog.cpp -o myprog

MS-DOS Batch file pause with enter key

pause command is what you looking for. If you looking ONLY the case when enter is hit you can abuse the runas command:

runas /user:# "" >nul 2>&1

the screen will be frozen until enter is hit.What I like more than set/p= is that if you press other buttons than enter they will be not displayed.

git diff file against its last change

One of the ways to use git diff is:

git diff <commit> <path>

And a common way to refer one commit of the last commit is as a relative path to the actual HEAD. You can reference previous commits as HEAD^ (in your example this will be 123abc) or HEAD^^ (456def in your example), etc ...

So the answer to your question is:

git diff HEAD^^ myfile

Python: How to pip install opencv2 with specific version 2.4.9?

There's another easy way, you can type in terminal

sudo apt-get install python-opencv

Install OpenCV-Python in Ubuntu

After installing it, you can use opencv version 2.4 in both c++ and python.

But I recommend you should use opencv 3.2.0 and opencv-contrib, it gives more features

Hope this can help!

Error message "Linter pylint is not installed"

Try doing this if you're running Visual Studio Code on a Windows machine and getting this error (I'm using Windows 10).

Go to the settings and change the Python path to the location of YOUR python installation.

I.e.,

Change: "python.pythonPath": "python"

To: "python.pythonPath": "C:\\Python36\\python.exe"

And then: Save and reload Visual Studio Code.

Now when you get the prompt telling you that "Linter pylint is not installed", just select the option to 'install pylint'.

Since you've now provided the correct path to your Python installation, the Pylint installation will be successfully completed in the Windows PowerShell Terminal.

How to run a .awk file?

The file you give is a shell script, not an awk program. So, try sh my.awk.

If you want to use awk -f my.awk life.csv > life_out.cs, then remove awk -F , ' and the last line from the file and add FS="," in BEGIN.

Number format in excel: Showing % value without multiplying with 100

Be aware that a value of 1 equals 100% in Excel's interpretation. If you enter 5.66 and you want to show 5.66%, then AxGryndr's hack with the formatting will work, but it is a display format only and does not represent the true numeric value. If you want to use that percentage in further calculations, these calculations will return the wrong result unless you divide by 100 at calculation time.

The consistent and less error-prone way is to enter 0.0566 and format the number with the built-in percentage format. That way, you can easily calculate 5.6% of A1 by just multiplying A1 with the value.

The good news is that you don't need to go through the rigmarole of entering 0.0566 and then formatting as percent. You can simply type

5.66%

into the cell, including the percentage symbol, and Excel will take care of the rest and store the number correctly as 0.0566 if formatted as General.

What is the .idea folder?

When you use the IntelliJ IDE, all the project-specific settings for the project are stored under the .idea folder.

Project settings are stored with each specific project as a set of xml files under the .idea folder. If you specify the default project settings, these settings will be automatically used for each newly created project.

Check this documentation for the IDE settings and here is their recommendation on Source Control and an example .gitignore file.

Note: If you are using git or some version control system, you might want to set this folder "ignore". Example - for git, add this directory to .gitignore. This way, the application is not IDE-specific.

Where can I download JSTL jar

You can downlod JSTL jar from this link

http://findjar.com/jar/javax/servlet/jstl/1.2/jstl-1.2.jar.html

How to convert minutes to hours/minutes and add various time values together using jQuery?

The function below will take as input # of minutes and output time in the following format: Hours:minutes. I used Math.trunc(), which is a new method added in 2015. It returns the integral part of a number by removing any fractional digits.

function display(a){
  var hours = Math.trunc(a/60);
  var minutes = a % 60;
  console.log(hours +":"+ minutes);
}

display(120); //"2:0"
display(60); //"1:0:
display(100); //"1:40"
display(126); //"2:6"
display(45); //"0:45"

Extract year from date

This is more advice than a specific answer, but my suggestion is to convert dates to date variables immediately, rather than keeping them as strings. This way you can use date (and time) functions on them, rather than trying to use very troublesome workarounds.

As pointed out, the lubridate package has nice extraction functions.

For some projects, I have found that piecing dates out from the start is helpful: create year, month, day (of month) and day (of week) variables to start with. This can simplify summaries, tables and graphs, because the extraction code is separate from the summary/table/graph code, and because if you need to change it, you don't have to roll out those changes in multiple spots.

PHP function to build query string from array

As this question is quite old and for PHP, here is a way to do it in the (currently) very popular PHP framework Laravel.

To encode the query string for a path in your application, give your routes names and then use the route() helper function like so:

route('documents.list.', ['foo' => 'bar']);

The result will look something like:

http://localhost/documents/list?foo=bar

Also be aware that if your route has any path segment parameters e.g. /documents/{id}, then make sure you pass an id argument to the route() parameters too, otherwise it will default to using the value of the first parameter.

MySQL, update multiple tables with one query

That's usually what stored procedures are for: to implement several SQL statements in a sequence. Using rollbacks, you can ensure that they are treated as one unit of work, ie either they are all executed or none of them are, to keep data consistent.

SQL Server - In clause with a declared variable

Try this:

CREATE PROCEDURE MyProc @excludedlist integer_list_tbltype READONLY AS
  SELECT * FROM A WHERE ID NOT IN (@excludedlist)

And then call it like this:

DECLARE @ExcludedList integer_list_tbltype
INSERT @ExcludedList(n) VALUES(3, 4, 22)
exec MyProc @ExcludedList

SQL select everything in an array

SELECT * FROM products WHERE catid IN ('1', '2', '3', '4')

Sort objects in ArrayList by date?

Given MyObject that has a DateTime member with a getDateTime() method, you can sort an ArrayList that contains MyObject elements by the DateTime objects like this:

Collections.sort(myList, new Comparator<MyObject>() {
    public int compare(MyObject o1, MyObject o2) {
        return o1.getDateTime().lt(o2.getDateTime()) ? -1 : 1;
    }
});

What does LINQ return when the results are empty

It will return an empty enumerable. It wont be null. You can sleep sound :)

Load Image from javascript

If you are loading the image via AJAX you could use a callback to check if the image is loaded and do the hiding and src attribute assigning. Something like this:

$.ajax({ 
  url: [image source],
  success: function() {
  // Do the hiding here and the attribute setting
  }
});

For more reading refer to this JQuery AJAX

Is it possible to run an .exe or .bat file on 'onclick' in HTML

You can not run/execute an .exe file that is in the users local machine or through a site. The user must first download the exe file and then run the executable file.
So there is no possible way

The following code works only when the EXE is Present in the User's Machine.

<a href = "C:\folder_name\program.exe">

Java random number with given length

try this:

public int getRandomNumber(int min, int max) {
    return (int) Math.floor(Math.random() * (max - min + 1)) + min;
}

jQuery return ajax result into outside variable

Using 'async': false to prevent asynchronous code is a bad practice,

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. https://xhr.spec.whatwg.org/

On the surface setting async to false fixes a lot of issues because, as the other answers show, you get your data into a variable. However, while waiting for the post data to return (which in some cases could take a few seconds because of database calls, slow connections, etc.) the rest of your Javascript functionality (like triggered events, Javascript handled buttons, JQuery transitions (like accordion, or autocomplete (JQuery UI)) will not be able to occur while the response is pending (which is really bad if the response never comes back as your site is now essentially frozen).

Try this instead,

var return_first;
function callback(response) {
  return_first = response;
  //use return_first variable here
}

$.ajax({
  'type': "POST",
  'global': false,
  'dataType': 'html',
  'url': "ajax.php?first",
  'data': { 'request': "", 'target': arrange_url, 'method': method_target },
  'success': function(data){
       callback(data);
  },
});

#pragma pack effect

You'd likely only want to use this if you were coding to some hardware (e.g. a memory mapped device) which had strict requirements for register ordering and alignment.

However, this looks like a pretty blunt tool to achieve that end. A better approach would be to code a mini-driver in assembler and give it a C calling interface rather than fumbling around with this pragma.

Matlab: Running an m-file from command-line

A command like this runs the m-file successfully:

"C:\<a long path here>\matlab.exe" -nodisplay -nosplash -nodesktop -r "run('C:\<a long path here>\mfile.m'); exit;"

How to count the number of true elements in a NumPy bool array

In terms of comparing two numpy arrays and counting the number of matches (e.g. correct class prediction in machine learning), I found the below example for two dimensions useful:

import numpy as np
result = np.random.randint(3,size=(5,2)) # 5x2 random integer array
target = np.random.randint(3,size=(5,2)) # 5x2 random integer array

res = np.equal(result,target)
print result
print target
print np.sum(res[:,0])
print np.sum(res[:,1])

which can be extended to D dimensions.

The results are:

Prediction:

[[1 2]
 [2 0]
 [2 0]
 [1 2]
 [1 2]]

Target:

[[0 1]
 [1 0]
 [2 0]
 [0 0]
 [2 1]]

Count of correct prediction for D=1: 1

Count of correct prediction for D=2: 2

in linux terminal, how do I show the folder's last modification date, taking its content into consideration?

If I could, I would vote for the answer by Paulo. I tested it and understood the concept. I can confirm it works. The find command can output many parameters. For example, add the following to the --printf clause:

%a for attributes in the octal format
%n for the file name including a complete path

Example:

find Desktop/ -exec stat \{} --printf="%y %n\n" \; | sort -n -r | head -1
2011-02-14 22:57:39.000000000 +0100 Desktop/new file

Let me raise this question as well: Does the author of this question want to solve his problem using Bash or PHP? That should be specified.

How do you set your pythonpath in an already-created virtualenv?

I modified my activate script to source the file .virtualenvrc, if it exists in the current directory, and to save/restore PYTHONPATH on activate/deactivate.

You can find the patched activate script here.. It's a drop-in replacement for the activate script created by virtualenv 1.11.6.

Then I added something like this to my .virtualenvrc:

export PYTHONPATH="${PYTHONPATH:+$PYTHONPATH:}/some/library/path"

How do you push a tag to a remote repository using Git?

To expand on Trevor's answer, you can push a single tag or all of your tags at once.

Push a Single Tag

git push <remote> <tag>

This is a summary of the relevant documentation that explains this (some command options omitted for brevity):

git push [[<repository> [<refspec>…]]

<refspec>...

The format of a <refspec> parameter is…the source ref <src>, followed by a colon :, followed by the destination ref <dst>

The <dst> tells which ref on the remote side is updated with this push…If :<dst> is omitted, the same ref as <src> will be updated…

tag <tag> means the same as refs/tags/<tag>:refs/tags/<tag>.

Push All of Your Tags at Once

git push --tags <remote>
# Or
git push <remote> --tags

Here is a summary of the relevant documentation (some command options omitted for brevity):

git push [--all | --mirror | --tags] [<repository> [<refspec>…]]

--tags

All refs under refs/tags are pushed, in addition to refspecs explicitly listed on the command line.

Filter output in logcat by tagname

Here is how I create a tag:

private static final String TAG = SomeActivity.class.getSimpleName();
 Log.d(TAG, "some description");

You could use getCannonicalName

Here I have following TAG filters:

  • any (*) View - VERBOSE
  • any (*) Activity - VERBOSE
  • any tag starting with Xyz(*) - ERROR
  • System.out - SILENT (since I am using Log in my own code)

Here what I type in terminal:

$  adb logcat *View:V *Activity:V Xyz*:E System.out:S

Assign one struct to another in C

First Look at this example :

The C code for a simple C program is given below

struct Foo {
    char a;
    int b;
    double c;
    } foo1,foo2;

void foo_assign(void)
{
    foo1 = foo2;
}
int main(/*char *argv[],int argc*/)
{
    foo_assign();
return 0;
}

The Equivalent ASM Code for foo_assign() is

00401050 <_foo_assign>:
  401050:   55                      push   %ebp
  401051:   89 e5                   mov    %esp,%ebp
  401053:   a1 20 20 40 00          mov    0x402020,%eax
  401058:   a3 30 20 40 00          mov    %eax,0x402030
  40105d:   a1 24 20 40 00          mov    0x402024,%eax
  401062:   a3 34 20 40 00          mov    %eax,0x402034
  401067:   a1 28 20 40 00          mov    0x402028,%eax
  40106c:   a3 38 20 40 00          mov    %eax,0x402038
  401071:   a1 2c 20 40 00          mov    0x40202c,%eax
  401076:   a3 3c 20 40 00          mov    %eax,0x40203c
  40107b:   5d                      pop    %ebp
  40107c:   c3                      ret    

As you can see that a assignment is simply replaced by a "mov" instruction in assembly, the assignment operator simply means moving data from one memory location to another memory location. The assignment will only do it for immediate members of a structures and will fail to copy when you have Complex datatypes in a structure. Here COMPLEX means that you cant have array of pointers ,pointing to lists.

An array of characters within a structure will itself not work on most compilers, this is because assignment will simply try to copy without even looking at the datatype to be of complex type.

Single vs double quotes in JSON

Two issues with answers given so far, if , for instance, one streams such non-standard JSON. Because then one might have to interpret an incoming string (not a python dictionary).

Issue 1 - demjson: With Python 3.7.+ and using conda I wasn't able to install demjson since obviosly it does not support Python >3.5 currently. So I need a solution with simpler means, for instance astand/or json.dumps.

Issue 2 - ast & json.dumps: If a JSON is both single quoted and contains a string in at least one value, which in turn contains single quotes, the only simple yet practical solution I have found is applying both:

In the following example we assume line is the incoming JSON string object :

>>> line = str({'abc':'008565','name':'xyz','description':'can control TV\'s and more'})

Step 1: convert the incoming string into a dictionary using ast.literal_eval()
Step 2: apply json.dumps to it for the reliable conversion of keys and values, but without touching the contents of values:

>>> import ast
>>> import json
>>> print(json.dumps(ast.literal_eval(line)))
{"abc": "008565", "name": "xyz", "description": "can control TV's and more"}

json.dumps alone would not do the job because it does not interpret the JSON, but only see the string. Similar for ast.literal_eval(): although it interprets correctly the JSON (dictionary), it does not convert what we need.

Jquery href click - how can I fire up an event?

It doesn't because the href value is not sign_up.It is #sign_up. Try like below, You need to add "#" to indicate the id of the href value.

$('a[href="#sign_up"]').click(function(){
  alert('Sign new href executed.'); 
}); 

DEMO: http://jsfiddle.net/pnGbP/

How to get elements with multiple classes

querySelectorAll with standard class selectors also works for this.

document.querySelectorAll('.class1.class2');

Selenium and xPath - locating a link by containing text

@FindBy(xpath = "//button[@class='btn btn-primary' and contains(text(), 'Submit')]") private WebElementFacade submitButton;

public void clickOnSubmitButton() {
    submitButton.click();
}   

How to go back (ctrl+z) in vi/vim

The answer, u, (and many others) is in $ vimtutor.

Checking for empty or null List<string>

Checkout L-Four's answer.

A less-efficient answer:

if(myList.Count == 0){
    // nothing is there. Add here
}

Basically new List<T> will not be null but will have no elements. As is noted in the comments, the above will throw an exception if the list is uninstantiated. But as for the snippet in the question, where it is instantiated, the above will work just fine.

If you need to check for null, then it would be:

if(myList != null && myList.Count == 0){
  // The list is empty. Add something here
}

Even better would be to use !myList.Any() and as is mentioned in the aforementioned L-Four's answer as short circuiting is faster than linear counting of the elements in the list.

Java correct way convert/cast object to Double

In Java version prior to 1.7 you cannot cast object to primitive type

double d = (double) obj;

You can cast an Object to a Double just fine

Double d = (Double) obj;

Beware, it can throw a ClassCastException if your object isn't a Double

SSRS Conditional Formatting Switch or IIF

To dynamically change the color of a text box goto properties, goto font/Color and set the following expression

=SWITCH(Fields!CurrentRiskLevel.Value = "Low", "Green",
Fields!CurrentRiskLevel.Value = "Moderate", "Blue",
Fields!CurrentRiskLevel.Value = "Medium", "Yellow",
Fields!CurrentRiskLevel.Value = "High", "Orange",
Fields!CurrentRiskLevel.Value = "Very High", "Red"
)

Same way for tolerance

=SWITCH(Fields!Tolerance.Value = "Low", "Red",
Fields!Tolerance.Value = "Moderate", "Orange",
Fields!Tolerance.Value = "Medium", "Yellow",
Fields!Tolerance.Value = "High", "Blue",
Fields!Tolerance.Value = "Very High", "Green")

Assigning a function to a variable

When you assign a function to a variable you don't use the () but simply the name of the function.

In your case given def x(): ..., and variable silly_var you would do something like this:

silly_var = x

and then you can call the function either with

x()

or

silly_var()

Set timeout for webClient.DownloadFile()

My answer comes from here

You can make a derived class, which will set the timeout property of the base WebRequest class:

using System;
using System.Net;

public class WebDownload : WebClient
{
    /// <summary>
    /// Time in milliseconds
    /// </summary>
    public int Timeout { get; set; }

    public WebDownload() : this(60000) { }

    public WebDownload(int timeout)
    {
        this.Timeout = timeout;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address);
        if (request != null)
        {
            request.Timeout = this.Timeout;
        }
        return request;
    }
}

and you can use it just like the base WebClient class.

What's the difference between an id and a class?

In advanced development ids we can basically use JavaScript.

For repeatable purposes, classes come handy contrary to ids which supposed to be unique.

Below is an example illustrating the expressions above:

<div id="box" class="box bg-color-red">this is a box</div>
<div id="box1" class="box bg-color-red">this is a box</div>

Now you can see in here box and box1 are two (2) different <div> elements, but we can apply the box and bg-color-red classes to both of them.

The concept is inheritance in an OOP language.

How to insert data into SQL Server

string saveStaff = "INSERT into student (stud_id,stud_name) " + " VALUES ('" + SI+ "', '" + SN + "');";
cmd = new SqlCommand(saveStaff,con);
cmd.ExecuteNonQuery();

How do I fetch lines before/after the grep result in bash?

You can use the -B and -A to print lines before and after the match.

grep -i -B 10 'error' data

Will print the 10 lines before the match, including the matching line itself.

warning: incompatible implicit declaration of built-in function ‘xyz’

In the case of some programs, these errors are normal and should not be fixed.

I get these error messages when compiling the program phrap (for example). This program happens to contain code that modifies or replaces some built in functions, and when I include the appropriate header files to fix the warnings, GCC instead generates a bunch of errors. So fixing the warnings effectively breaks the build.

If you got the source as part of a distribution that should compile normally, the errors might be normal. Consult the documentation to be sure.

Checking for duplicate strings in JavaScript array

You can do this using a Set. You have to create a Set and put all the values in your Array, in that Set. Then, you check whether they have the same length or not. If not, you know there are duplicate values, because a Set can only have unique values. It is explained in the link below:

https://medium.com/dailyjs/how-to-remove-array-duplicates-in-es6-5daa8789641c

Lotus Notes email as an attachment to another email

If you are using Lotus Notes V9.X, it is better to drag the mail to desktop as .eml and then attach it to the mail. Safest way so far.

How to convert a String into an ArrayList?

If you want to convert a string into a ArrayList try this:

public ArrayList<Character> convertStringToArraylist(String str) {
    ArrayList<Character> charList = new ArrayList<Character>();      
    for(int i = 0; i<str.length();i++){
        charList.add(str.charAt(i));
    }
    return charList;
}

But i see a string array in your example, so if you wanted to convert a string array into ArrayList use this:

public static ArrayList<String> convertStringArrayToArraylist(String[] strArr){
    ArrayList<String> stringList = new ArrayList<String>();
    for (String s : strArr) {
        stringList.add(s);
    }
    return stringList;
}

The application has stopped unexpectedly: How to Debug?

  1. From the Home screen, press the Menu key.
  2. List item
  3. Touch Settings.
  4. Touch Applications.
  5. Touch Manage Applications.
  6. Touch All.
  7. Select the application that is having issues.
  8. Touch Clear data and Clear cache if they are available. This resets the app as if it was new, and may delete personal data stored in the app.

extra qualification error in C++

Are you putting this line inside the class declaration? In that case you should remove the JSONDeserializer::.

Can an Android Toast be longer than Toast.LENGTH_LONG?

If you dig deeper in android code, you can find the lines that clearly indicate, that we cannot change the duration of Toast message.

 NotificationManagerService.scheduleTimeoutLocked() {
    ...
    long delay = immediate ? 0 : (r.duration == Toast.LENGTH_LONG ? LONG_DELAY : SHORT_DELAY);
    }

and default values for duration are

private static final int LONG_DELAY = 3500; // 3.5 seconds
private static final int SHORT_DELAY = 2000; // 2 seconds

how to include glyphicons in bootstrap 3

I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.

Bootstrap requires a specific file structure to work. I see from your code you have this:

<link href="bootstrap.css" rel="stylesheet" media="screen">

Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.

But first, let me recommend you setup your folder structure like so:

/css      <-- Bootstrap.css here
/fonts    <-- Bootstrap fonts here
/img
/js       <-- Bootstrap JavaScript here
index.html

If you notice, this is also how Bootstrap structures its files in its download ZIP.

You then include your Bootstrap file like so:

<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">

Depending on your server structure or what you're going for.

The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).

The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.

So, why do this?

Bootstrap.css has this specific line for Glyphfonts:

@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.

The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:

/fonts
Bootstrap.css
index.html

The CSS file is going one level deeper than looking for a /fonts folder.

So, let's say the actual location of these files are:

C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html

The CSS file would technically be looking for a folder at:

C:\fonts

but your folder is actually in:

C:\www\fonts

So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.

When you get that fixed, your HTML should simply be:

<span class="glyphicon glyphicon-comment"></span>

Note, you need both classes. The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.

How to change button text or link text in JavaScript?

You can simply use:

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

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

How to convert String to DOM Document object in java?

DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = db.parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))); //remove the parameter UTF-8 if you don't want to specify the Encoding type.

this works well for me even though the XML structure is complex.

And please make sure your xmlString is valid for XML, notice the escape character should be added "\" at the front.

The main problem might not come from the attributes.

Cannot delete directory with Directory.Delete(path, true)

One important thing which should be mentioned (I'd added it as a comment but I'm not allowed to) is that the overload's behavior changed from .NET 3.5 to .NET 4.0.

Directory.Delete(myPath, true);

Starting from .NET 4.0 it deletes files in the folder itself but NOT in 3.5. This can be seen in the MSDN documentation as well.

.NET 4.0

Deletes the specified directory and, if indicated, any subdirectories and files in the directory.

.NET 3.5

Deletes an empty directory and, if indicated, any subdirectories and files in the directory.

':app:lintVitalRelease' error when generating signed apk

My problem was a missing translation. I had a settings.xml that was not translated as it was not needed, so I had to add "translatable="false" to the strings:

<string translatable="false" name="stringname">This string doesn't need translation</string>

What is default list styling (CSS)?

I think this is actually what you're looking for:

.my_container ul
{
    list-style: initial;
    margin: initial;
    padding: 0 0 0 40px;
}

.my_container li
{
    display: list-item;
}

Count number of columns in a table row

$('#table1').find(input).length

Extract subset of key-value pairs from Python dictionary object?

You could try:

dict((k, bigdict[k]) for k in ('l', 'm', 'n'))

... or in Python 3 Python versions 2.7 or later (thanks to Fábio Diniz for pointing that out that it works in 2.7 too):

{k: bigdict[k] for k in ('l', 'm', 'n')}

Update: As Håvard S points out, I'm assuming that you know the keys are going to be in the dictionary - see his answer if you aren't able to make that assumption. Alternatively, as timbo points out in the comments, if you want a key that's missing in bigdict to map to None, you can do:

{k: bigdict.get(k, None) for k in ('l', 'm', 'n')}

If you're using Python 3, and you only want keys in the new dict that actually exist in the original one, you can use the fact to view objects implement some set operations:

{k: bigdict[k] for k in bigdict.keys() & {'l', 'm', 'n'}}

Symfony 2 EntityManager injection in service

For modern reference, in Symfony 2.4+, you cannot name the arguments for the Constructor Injection method anymore. According to the documentation You would pass in:

services:
    test.common.userservice:
        class:  Test\CommonBundle\Services\UserService
        arguments: [ "@doctrine.orm.entity_manager" ]

And then they would be available in the order they were listed via the arguments (if there are more than 1).

public function __construct(EntityManager $entityManager) {
    $this->em = $entityManager;
}

How to get mouse position in jQuery without mouse-events?

I don't believe there's a way to query the mouse position, but you can use a mousemove handler that just stores the information away, so you can query the stored information.

jQuery(function($) {
    var currentMousePos = { x: -1, y: -1 };
    $(document).mousemove(function(event) {
        currentMousePos.x = event.pageX;
        currentMousePos.y = event.pageY;
    });

    // ELSEWHERE, your code that needs to know the mouse position without an event
    if (currentMousePos.x < 10) {
        // ....
    }
});

But almost all code, other than setTimeout code and such, runs in response to an event, and most events provide the mouse position. So your code that needs to know where the mouse is probably already has access to that information...

Applying CSS styles to all elements inside a DIV

#applyCSS > * {
  /* Your style */
}

Check this JSfiddle

It will style all children and grandchildren, but will exclude loosely flying text in the div itself and only target wrapped (by tags) content.

Removing underline with href attribute

Add a style with the attribute text-decoration:none;:

There are a number of different ways of doing this.

Inline style:

<a href="xxx.html" style="text-decoration:none;">goto this link</a>

Inline stylesheet:

<html>
<head>
<style type="text/css">
   a {
      text-decoration:none;
   }
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

External stylesheet:

<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

stylesheet.css:

a {
      text-decoration:none;
   }

How to save final model using keras?

You can use model.save(filepath) to save a Keras model into a single HDF5 file which will contain:

  • the architecture of the model, allowing to re-create the model.
  • the weights of the model.
  • the training configuration (loss, optimizer)
  • the state of the optimizer, allowing to resume training exactly where you left off.

In your Python code probable the last line should be:

model.save("m.hdf5")

This allows you to save the entirety of the state of a model in a single file. Saved models can be reinstantiated via keras.models.load_model().

The model returned by load_model() is a compiled model ready to be used (unless the saved model was never compiled in the first place).

model.save() arguments:

  • filepath: String, path to the file to save the weights to.
  • overwrite: Whether to silently overwrite any existing file at the target location, or provide the user with a manual prompt.
  • include_optimizer: If True, save optimizer's state together.

System.Data.SqlClient.SqlException: Invalid object name 'dbo.Projects'

If you are in that phase of development where you have an method inside your context class that creates testdata for you, don't call it in your constructor, it will try to create those test records while you don't have tables yet. Just sharing my mistake...

Fixing the order of facets in ggplot

Here's a solution that keeps things within a dplyr pipe chain. You sort the data in advance, and then using mutate_at to convert to a factor. I've modified the data slightly to show how this solution can be applied generally, given data that can be sensibly sorted:

# the data
temp <- data.frame(type=rep(c("T", "F", "P"), 4),
                    size=rep(c("50%", "100%", "200%", "150%"), each=3), # cannot sort this
                    size_num = rep(c(.5, 1, 2, 1.5), each=3), # can sort this
                    amount=c(48.4, 48.1, 46.8, 
                             25.9, 26.0, 24.9,
                             20.8, 21.5, 16.5,
                             21.1, 21.4, 20.1))

temp %>% 
  arrange(size_num) %>% # sort
  mutate_at(vars(size), funs(factor(., levels=unique(.)))) %>% # convert to factor

  ggplot() + 
  geom_bar(aes(x = type, y=amount, fill=type), 
           position="dodge", stat="identity") + 
  facet_grid(~ size)

You can apply this solution to arrange the bars within facets, too, though you can only choose a single, preferred order:

    temp %>% 
  arrange(size_num) %>%
  mutate_at(vars(size), funs(factor(., levels=unique(.)))) %>%
  arrange(desc(amount)) %>%
  mutate_at(vars(type), funs(factor(., levels=unique(.)))) %>%
  ggplot() + 
  geom_bar(aes(x = type, y=amount, fill=type), 
           position="dodge", stat="identity") + 
  facet_grid(~ size)


  ggplot() + 
  geom_bar(aes(x = type, y=amount, fill=type), 
           position="dodge", stat="identity") + 
  facet_grid(~ size)

Difference between datetime and timestamp in sqlserver?

According to the documentation, timestamp is a synonym for rowversion - it's automatically generated and guaranteed1 to be unique. datetime isn't - it's just a data type which handles dates and times, and can be client-specified on insert etc.


1 Assuming you use it properly, of course. See comments.

How to safely upgrade an Amazon EC2 instance from t1.micro to large?

Use the AWS EC2 console, not ElasticFox.

First Way:

  • Create a new AMI of the instance
  • Launch it

Alternative Way:

  • Make a snapshot of the disk
  • Launch a large EBS instance with the same AMI type (please note that at this point the disk will contain the data that was present when this AMI was created, not your latest changes)
  • Once is fully booted, stop the new instance
  • Detach the root volume from the stopped instance
  • Create a virtual disk from the snapshot created before in the same availability zone of the new instance
  • Attach the root volume to /dev/sda1
  • Start the new instance again

Hide Text with CSS, Best Practice?

Can't you use simply display: none; like this

HTML

<div id="web-title">
   <a href="http://website.com" title="Website" rel="home">
       <span class="webname">Website Name</span>
   </a>
</div>

CSS

.webname {
   display: none;
}

Or how about playing with visibility if you are concerned to reserve the space

.webname {
   visibility: hidden;
}

What is the command to truncate a SQL Server log file?

backup log logname with truncate_only followed by a dbcc shrinkfile command

SQL Server : SUM() of multiple rows including where clauses

Use a common table expression to add grand total row, top 100 is required for order by to work.

With Detail as 
(
    SELECT  top 100 propertyId, SUM(Amount) as TOTAL_COSTS
    FROM MyTable
    WHERE EndDate IS NULL
    GROUP BY propertyId
    ORDER BY TOTAL_COSTS desc
)

Select * from Detail
Union all
Select ' Total ', sum(TOTAL_COSTS) from Detail

Git: Installing Git in PATH with GitHub client for Windows

Git’s executable is actually located in: C:\Users\<user>\AppData\Local\GitHub\PortableGit_<guid>\bin\git.exe

Now that we have located the executable all we have to do is add it to our PATH:

  • Right-Click on My Computer
  • Click Advanced System Settings
  • Click Environment Variables
  • Then under System Variables look for the path variable and click edit
  • Add the path to git’s bin and cmd at the end of the string like this:

;C:\Users\<user>\AppData\Local\GitHub\PortableGit_<guid>\bin;C:\Users\<user>\AppData\Local\GitHub\PortableGit_<guid>\cmd

How to change the port of Tomcat from 8080 to 80?

Just goto conf folder of tomcat

open the server.xml file

Goto one of the connector node which look like the following

<Connector port="8080" protocol="HTTP/1.1" 
           connectionTimeout="20000" 
           redirectPort="8443" />

Simply change the port

save and restart tomcat

How to position absolute inside a div?

The absolute divs are taken out of the flow of the document so the containing div does not have any content except for the padding. Give #box a height to fill it out.

#box {
    background-color: #000;
    position: relative;
    padding: 10px;
    width: 220px;
    height:30px;
}

Is there a simple way to remove unused dependencies from a maven pom.xml?

As others have said, you can use the dependency:analyze goal to find which dependencies are used and declared, used and undeclared, or unused and declared. You may also find dependency:analyze-dep-mgt useful to look for mismatches in your dependencyManagement section.

You can simply remove unwanted direct dependencies from your POM, but if they are introduced by third-party jars, you can use the <exclusions> tags in a dependency to exclude the third-party jars (see the section titled Dependency Exclusions for details and some discussion). Here is an example excluding commons-logging from the Spring dependency:

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring</artifactId>
  <version>2.5.5</version>
  <exclusions>
    <exclusion>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
    </exclusion>
  </exclusions> 
</dependency>

Get value of a specific object property in C# without knowing the class behind

Reflection and dynamic value access are correct solutions to this question but are quite slow. If your want something faster then you can create dynamic method using expressions:

  object value = GetValue();
  string propertyName = "MyProperty";

  var parameter = Expression.Parameter(typeof(object));
  var cast = Expression.Convert(parameter, value.GetType());
  var propertyGetter = Expression.Property(cast, propertyName);
  var castResult = Expression.Convert(propertyGetter, typeof(object));//for boxing

  var propertyRetriver = Expression.Lambda<Func<object, object>>(castResult, parameter).Compile();

 var retrivedPropertyValue = propertyRetriver(value);

This way is faster if you cache created functions. For instance in dictionary where key would be the actual type of object assuming that property name is not changing or some combination of type and property name.

How can I generate Unix timestamps?

In Bash 5 there's a new variable:

echo $EPOCHSECONDS

Or if you want higher precision (in microseconds):

echo $EPOCHREALTIME

Checking network connection

For my projects I use script modified to ping the google public DNS server 8.8.8.8. Using a timeout of 1 second and core python libraries with no external dependencies:

import struct
import socket
import select


def send_one_ping(to='8.8.8.8'):
   ping_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname('icmp'))
   checksum = 49410
   header = struct.pack('!BBHHH', 8, 0, checksum, 0x123, 1)
   data = b'BCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwx'
   header = struct.pack(
      '!BBHHH', 8, 0, checksum, 0x123, 1
   )
   packet = header + data
   ping_socket.sendto(packet, (to, 1))
   inputready, _, _ = select.select([ping_socket], [], [], 1.0)
   if inputready == []:
      raise Exception('No internet') ## or return False
   _, address = ping_socket.recvfrom(2048)
   print(address) ## or return True


send_one_ping()

The select timeout value is 1, but can be a floating point number of choice to fail more readily than the 1 second in this example.

Can a unit test project load the target application's app.config file?

I use NUnit and in my project directory I have a copy of my App.Config that I change some configuration (example I redirect to a test database...). You need to have it in the same directory of the tested project and you will be fine.

How to run jenkins as a different user

ISSUE 1:

Started by user anonymous

That does not mean that Jenkins started as an anonymous user.

It just means that the person who started the build was not logged in. If you enable Jenkins security, you can create usernames for people and when they log in, the

"Started by anonymous" 

will change to

"Started by < username >". 

Note: You do not have to enable security in order to run jenkins or to clone correctly.

If you want to enable security and create users, you should see the options at Manage Jenkins > Configure System.


ISSUE 2:

The "can't clone" error is a different issue altogether. It has nothing to do with you logging in to jenkins or enabling security. It just means that Jenkins does not have the credentials to clone from your git SCM.

Check out the Jenkins Git Plugin to see how to set up Jenkins to work with your git repository.

Hope that helps.

Detecting Windows or Linux?

I think It's a best approach to use Apache lang dependency to decide which OS you're running programmatically through Java

import org.apache.commons.lang3.SystemUtils;

public class App {
    public static void main( String[] args ) {
        if(SystemUtils.IS_OS_WINDOWS_7)
            System.out.println("It's a Windows 7 OS");
        if(SystemUtils.IS_OS_WINDOWS_8)
            System.out.println("It's a Windows 8 OS");
        if(SystemUtils.IS_OS_LINUX)
            System.out.println("It's a Linux OS");
        if(SystemUtils.IS_OS_MAC)
            System.out.println("It's a MAC OS");
    }
}

Add Favicon with React and Webpack

In my case -- I am running Visual Studio (Professional 2017) in debug mode with webpack 2.4.1 -- it was necessary to put the favicon.ico into the root directory of the project, right where the folder src is rather than in a folder public, even though according to https://create-react-app.dev/docs/using-the-public-folder the latter should be the official location.

How to set session attribute in java?

Try this.

<%@page language="java" session="true" %>

How to edit CSS style of a div using C# in .NET

This question makes me nervous. It indicates that maybe you don't understand how using server-side code will impact you're page's DOM state.

Whenever you run server-side code the entire page is rebuilt from scratch. This has several implications:

  • A form is submitted from the client to the web server. This is about the slowest action that a web browser can take, especially in ASP.Net where the form might be padded with extra fields (ie: ViewState). Doing it too often for trivial activities will make your app appear to be sluggish, even if everything else is nice and snappy.
  • It adds load to your server, in terms of bandwidth (up and down stream) and CPU/memory. Everything involved in rebuilding your page will have to happen again. If there are dynamic controls on the page, don't forget to create them.
  • Anything you've done to the DOM since the last request is lost, unless you remember to do it again for this request. Your page's DOM is reset.

If you can get away with it, you might want to push this down to javascript and avoid the postback. Perhaps use an XmlHttpRequest() call to trigger any server-side action you need.

Is it possible to get only the first character of a String?

Answering for C++ 14,

Yes, you can get the first character of a string simply by the following code snippet.

string s = "Happynewyear";
cout << s[0];

if you want to store the first character in a separate string,

string s = "Happynewyear";
string c = "";
c.push_back(s[0]);
cout << c;

How to get every first element in 2 dimensional list

If you have access to numpy,

import numpy as np
a_transposed = a.T
# Get first row
print(a_transposed[0])

The benefit of this method is that if you want the "second" element in a 2d list, all you have to do now is a_transposed[1]. The a_transposed object is already computed, so you do not need to recalculate.

Description

Finding the first element in a 2-D list can be rephrased as find the first column in the 2d list. Because your data structure is a list of rows, an easy way of sampling the value at the first index in every row is just by transposing the matrix and sampling the first list.

Comparison of DES, Triple DES, AES, blowfish encryption for data

                DES                               AES
Developed       1977                              2000
Key Length      56 bits                           128, 192, or 256 bits
Cipher Type     Symmetric                         Symmetric
Block Size      64 bits                           128 bits
Security        inadequate                        secure
Performance     Fast                              Slow

How to check if variable's type matches Type stored in a variable

GetType() exists on every single framework type, because it is defined on the base object type. So, regardless of the type itself, you can use it to return the underlying Type

So, all you need to do is:

u.GetType() == t

Script Tag - async & defer

Rendering engine goes several steps till it paints anything on the screen.

it looks like this:

  1. Converting HTML bytes to characters depending on encoding we set to the document;
  2. Tokens are created according to characters. Tokens mean analyze characters and specify opening tangs and nested tags;
  3. From tokens separated nodes are created. they are objects and according to information delivered from tokenization process, engine creates objects which includes all necessary information about each node;
  4. after that DOM is created. DOM is tree data structure and represents whole hierarchy and information about relationship and specification of tags;

The same process goes to CSS. for CSS rendering engine creates different/separated data structure for CSS but it's called CSSOM (CSS Object Model)

Browser works only with Object models so it needs to know all information about DOM and CSSDOM.

The next step is combining somehow DOM and CSSOM. because without CSSOM browser do not know how to style each element during rendering process.

All information above means that, anything you provide in your html (javascript, css ) browser will pause DOM construction process. If you are familiar with event loop, there is simple rule how event loop executes tasks:

  1. Execute macro tasks;
  2. execute micro tasks;
  3. Rendering;

So when you provide Javascript file, browser do not know what JS code is going to do and stops all DOM construction process and Javascript interptreter starts parsing and executing Javascript code.

Even you provide Javascript in the end of body tag, Browser will proceed all above steps to HTML and CSS but except rendering. it will find out Script tag and will stop until JS is done.

But HTML provided two additional options for script tag: async and defer.

Async - means execute code when it is downloaded and do not block DOM construction during downloading process.

Defer - means execute code after it's downloaded and browser finished DOM construction and rendering process.

How to extract table as text from the PDF using Python?

If your pdf is text-based and not a scanned document (i.e. if you can click and drag to select text in your table in a PDF viewer), then you can use the module camelot-py with

import camelot
tables = camelot.read_pdf('foo.pdf')

You then can choose how you want to save the tables (as csv, json, excel, html, sqlite), and whether the output should be compressed in a ZIP archive.

tables.export('foo.csv', f='csv', compress=False)

Edit: tabula-py appears roughly 6 times faster than camelot-py so that should be used instead.

import camelot
import cProfile
import pstats
import tabula

cmd_tabula = "tabula.read_pdf('table.pdf', pages='1', lattice=True)"
prof_tabula = cProfile.Profile().run(cmd_tabula)
time_tabula = pstats.Stats(prof_tabula).total_tt

cmd_camelot = "camelot.read_pdf('table.pdf', pages='1', flavor='lattice')"
prof_camelot = cProfile.Profile().run(cmd_camelot)
time_camelot = pstats.Stats(prof_camelot).total_tt

print(time_tabula, time_camelot, time_camelot/time_tabula)

gave

1.8495559890000015 11.057014036000016 5.978199147125147

How can I export data to an Excel file

MS provides the OpenXML SDK V 2.5 - see https://msdn.microsoft.com/en-us/library/bb448854(v=office.15).aspx

This can read+write MS Office files (including Excel)...

Another option see http://www.codeproject.com/KB/office/OpenXML.aspx

IF you need more like rendering, formulas etc. then there are different commercial libraries like Aspose and Flexcel...

configuring project ':app' failed to find Build Tools revision

also try to increase gradle version in your project's build.gradle. It helped me

How to pass variable number of arguments to a PHP function

Here is a solution using the magic method __invoke

(Available since php 5.3)

class Foo {
    public function __invoke($method=null, $args=[]){
        if($method){
            return call_user_func_array([$this, $method], $args);
        }
        return false;
    }

    public function methodName($arg1, $arg2, $arg3){

    }
}

From inside same class:

$this('methodName', ['arg1', 'arg2', 'arg3']);

From an instance of an object:

$obj = new Foo;
$obj('methodName', ['arg1', 'arg2', 'arg3'])

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

I tested below code with SQL Server 2008 R2 Express and I believe we should have solution for all 6 steps you outlined. Let's take on them one-by-one:

1 - Enable TCP/IP

We can enable TCP/IP protocol with WMI:

set wmiComputer = GetObject( _
    "winmgmts:" _
    & "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProtocols = wmiComputer.ExecQuery( _
    "select * from ServerNetworkProtocol " _
    & "where InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'")

if tcpProtocols.Count = 1 then
    ' set tcpProtocol = tcpProtocols(0)
    ' I wish this worked, but unfortunately 
    ' there's no int-indexed Item property in this type

    ' Doing this instead
    for each tcpProtocol in tcpProtocols
        dim setEnableResult
            setEnableResult = tcpProtocol.SetEnable()
            if setEnableResult <> 0 then 
                Wscript.Echo "Failed!"
            end if
    next
end if

2 - Open the right ports in the firewall

I believe your solution will work, just make sure you specify the right port. I suggest we pick a different port than 1433 and make it a static port SQL Server Express will be listening on. I will be using 3456 in this post, but please pick a different number in the real implementation (I feel that we will see a lot of applications using 3456 soon :-)

3 - Modify TCP/IP properties enable a IP address

We can use WMI again. Since we are using static port 3456, we just need to update two properties in IPAll section: disable dynamic ports and set the listening port to 3456:

set wmiComputer = GetObject( _
    "winmgmts:" _
    & "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProperties = wmiComputer.ExecQuery( _
    "select * from ServerNetworkProtocolProperty " _
    & "where InstanceName='SQLEXPRESS' and " _
    & "ProtocolName='Tcp' and IPAddressName='IPAll'")

for each tcpProperty in tcpProperties
    dim setValueResult, requestedValue

    if tcpProperty.PropertyName = "TcpPort" then
        requestedValue = "3456"
    elseif tcpProperty.PropertyName ="TcpDynamicPorts" then
        requestedValue = ""
    end if

    setValueResult = tcpProperty.SetStringValue(requestedValue)
    if setValueResult = 0 then 
        Wscript.Echo "" & tcpProperty.PropertyName & " set."
    else
        Wscript.Echo "" & tcpProperty.PropertyName & " failed!"
    end if
next

Note that I didn't have to enable any of the individual addresses to make it work, but if it is required in your case, you should be able to extend this script easily to do so.

Just a reminder that when working with WMI, WBEMTest.exe is your best friend!

4 - Enable mixed mode authentication in sql server

I wish we could use WMI again, but unfortunately this setting is not exposed through WMI. There are two other options:

  1. Use LoginMode property of Microsoft.SqlServer.Management.Smo.Server class, as described here.

  2. Use LoginMode value in SQL Server registry, as described in this post. Note that by default the SQL Server Express instance is named SQLEXPRESS, so for my SQL Server 2008 R2 Express instance the right registry key was HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQLServer.

5 - Change user (sa) default password

You got this one covered.

6 - Finally (connect to the instance)

Since we are using a static port assigned to our SQL Server Express instance, there's no need to use instance name in the server address anymore.

SQLCMD -U sa -P newPassword -S 192.168.0.120,3456

Please let me know if this works for you (fingers crossed!).

How to add a file to the last commit in git?

If you didn't push the update in remote then the simple solution is remove last local commit using following command: git reset HEAD^. Then add all files and commit again.

How to get exception message in Python properly

I too had the same problem. Digging into this I found that the Exception class has an args attribute, which captures the arguments that were used to create the exception. If you narrow the exceptions that except will catch to a subset, you should be able to determine how they were constructed, and thus which argument contains the message.

try:
   # do something that may raise an AuthException
except AuthException as ex:
   if ex.args[0] == "Authentication Timeout.":
      # handle timeout
   else:
      # generic handling

Check if passed argument is file or directory in Bash

#!/bin/bash                                                                                               
echo "Please Enter a file name :"                                                                          
read filename                                                                                             
if test -f $filename                                                                                      
then                                                                                                      
        echo "this is a file"                                                                             
else                                                                                                      
        echo "this is not a file"                                                                         
fi 

T-SQL How to create tables dynamically in stored procedures?

You are using a table variable i.e. you should declare the table. This is not a temporary table.

You create a temp table like so:

CREATE TABLE #customer
(
     Name varchar(32) not null
)

You declare a table variable like so:

DECLARE @Customer TABLE
(
      Name varchar(32) not null
)

Notice that a temp table is declared using # and a table variable is declared using a @. Go read about the difference between table variables and temp tables.

UPDATE:

Based on your comment below you are actually trying to create tables in a stored procedure. For this you would need to use dynamic SQL. Basically dynamic SQL allows you to construct a SQL Statement in the form of a string and then execute it. This is the ONLY way you will be able to create a table in a stored procedure. I am going to show you how and then discuss why this is not generally a good idea.

Now for a simple example (I have not tested this code but it should give you a good indication of how to do it):

CREATE PROCEDURE sproc_BuildTable 
    @TableName NVARCHAR(128)
   ,@Column1Name NVARCHAR(32)
   ,@Column1DataType NVARCHAR(32)
   ,@Column1Nullable NVARCHAR(32)
AS

   DECLARE @SQLString NVARCHAR(MAX)
   SET @SQString = 'CREATE TABLE '+@TableName + '( '+@Column1Name+' '+@Column1DataType +' '+@Column1Nullable +') ON PRIMARY '

   EXEC (@SQLString)
   GO

This stored procedure can be executed like this:

sproc_BuildTable 'Customers','CustomerName','VARCHAR(32)','NOT NULL'

There are some major problems with this type of stored procedure.

Its going to be difficult to cater for complex tables. Imagine the following table structure:

CREATE TABLE [dbo].[Customers] (
    [CustomerID] [int] IDENTITY(1,1) NOT NULL,
    [CustomerName] [nvarchar](64) NOT NULL,
    [CustomerSUrname] [nvarchar](64) NOT NULL,
    [CustomerDateOfBirth] [datetime] NOT NULL,
    [CustomerApprovedDiscount] [decimal](3, 2) NOT NULL,
    [CustomerActive] [bit] NOT NULL,
    CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED 
    (
        [CustomerID] ASC
    ) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,      ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[Customers] ADD CONSTRAINT [DF_Customers_CustomerApprovedDiscount] DEFAULT ((0.00)) FOR [CustomerApprovedDiscount]
GO 

This table is a little more complex than the first example, but not a lot. The stored procedure will be much, much more complex to deal with. So while this approach might work for small tables it is quickly going to be unmanageable.

Creating tables require planning. When you create tables they should be placed strategically on different filegroups. This is to ensure that you don't cause disk I/O contention. How will you address scalability if everything is created on the primary file group?

Could you clarify why you need tables to be created dynamically?

UPDATE 2:

Delayed update due to workload. I read your comment about needing to create a table for each shop and I think you should look at doing it like the example I am about to give you.

In this example I make the following assumptions:

  1. It's an e-commerce site that has many shops
  2. A shop can have many items (goods) to sell.
  3. A particular item (good) can be sold at many shops
  4. A shop will charge different prices for different items (goods)
  5. All prices are in $ (USD)

Let say this e-commerce site sells gaming consoles (i.e. Wii, PS3, XBOX360).

Looking at my assumptions I see a classical many-to-many relationship. A shop can sell many items (goods) and items (goods) can be sold at many shops. Let's break this down into tables.

First I would need a shop table to store all the information about the shop.

A simple shop table might look like this:

CREATE TABLE [dbo].[Shop](
    [ShopID] [int] IDENTITY(1,1) NOT NULL,
    [ShopName] [nvarchar](128) NOT NULL,
    CONSTRAINT [PK_Shop] PRIMARY KEY CLUSTERED 
    (
      [ShopID] ASC
    ) WITH (
              PAD_INDEX  = OFF
              , STATISTICS_NORECOMPUTE  = OFF
              , IGNORE_DUP_KEY = OFF
              , ALLOW_ROW_LOCKS  = ON
              , ALLOW_PAGE_LOCKS  = ON
    ) ON [PRIMARY]
    ) ON [PRIMARY]

    GO

Let's insert three shops into the database to use during our example. The following code will insert three shops:

INSERT INTO Shop
SELECT 'American Games R US'
UNION
SELECT 'Europe Gaming Experience'
UNION
SELECT 'Asian Games Emporium'

If you execute a SELECT * FROM Shop you will probably see the following:

ShopID  ShopName
1           American Games R US
2           Asian Games Emporium
3           Europe Gaming Experience

Right, so now let's move onto the Items (goods) table. Since the items/goods are products of various companies I am going to call the table product. You can execute the following code to create a simple Product table.

CREATE TABLE [dbo].[Product](
    [ProductID] [int] IDENTITY(1,1) NOT NULL,
    [ProductDescription] [nvarchar](128) NOT NULL,
 CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED 
 (
     [ProductID] ASC
 )WITH (PAD_INDEX  = OFF
        , STATISTICS_NORECOMPUTE  = OFF
        , IGNORE_DUP_KEY = OFF
        ,     ALLOW_ROW_LOCKS  = ON
         , ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
  ) ON [PRIMARY]

GO

Let's populate the products table with some products. Execute the following code to insert some products:

INSERT INTO Product
SELECT 'Wii'
UNION 
SELECT 'PS3'
UNION 
SELECT 'XBOX360'

If you execute SELECT * FROM Product you will probably see the following:

ProductID   ProductDescription
1           PS3
2           Wii
3           XBOX360

OK, at this point you have both product and shop information. So how do you bring them together? Well we know we can identify the shop by its ShopID primary key column and we know we can identify a product by its ProductID primary key column. Also, since each shop has a different price for each product we need to store the price the shop charges for the product.

So we have a table that maps the Shop to the product. We will call this table ShopProduct. A simple version of this table might look like this:

CREATE TABLE [dbo].[ShopProduct](
[ShopID] [int] NOT NULL,
[ProductID] [int] NOT NULL,
[Price] [money] NOT NULL,
CONSTRAINT [PK_ShopProduct] PRIMARY KEY CLUSTERED 
 (
     [ShopID] ASC,
      [ProductID] ASC
 )WITH (PAD_INDEX  = OFF,
     STATISTICS_NORECOMPUTE  = OFF, 
     IGNORE_DUP_KEY = OFF, 
     ALLOW_ROW_LOCKS  = ON,
     ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
  ) ON [PRIMARY]

 GO

So let's assume the American Games R Us shop only sells American consoles, the Europe Gaming Experience sells all consoles and the Asian Games Emporium sells only Asian consoles. We would need to map the primary keys from the shop and product tables into the ShopProduct table.

Here is how we are going to do the mapping. In my example the American Games R Us has a ShopID value of 1 (this is the primary key value) and I can see that the XBOX360 has a value of 3 and the shop has listed the XBOX360 for $159.99

By executing the following code you would complete the mapping:

INSERT INTO ShopProduct VALUES(1,3,159.99)

Now we want to add all product to the Europe Gaming Experience shop. In this example we know that the Europe Gaming Experience shop has a ShopID of 3 and since it sells all consoles we will need to insert the ProductID 1, 2 and 3 into the mapping table. Let's assume the prices for the consoles (products) at the Europe Gaming Experience shop are as follows: 1- The PS3 sells for $259.99 , 2- The Wii sells for $159.99 , 3- The XBOX360 sells for $199.99.

To get this mapping done you would need to execute the following code:

INSERT INTO ShopProduct VALUES(3,2,159.99) --This will insert the WII console into the mapping table for the Europe Gaming Experience Shop with a price of 159.99
INSERT INTO ShopProduct VALUES(3,1,259.99) --This will insert the PS3 console into the mapping table for the Europe Gaming Experience Shop with a price of 259.99
INSERT INTO ShopProduct VALUES(3,3,199.99) --This will insert the XBOX360 console into the mapping table for the Europe Gaming Experience Shop with a price of 199.99

At this point you have mapped two shops and their products into the mapping table. OK, so now how do I bring this all together to show a user browsing the website? Let's say you want to show all the product for the European Gaming Experience to a user on a web page – you would need to execute the following query:

SELECT      Shop.*
        , ShopProduct.*
        , Product.*
FROM         Shop 
INNER JOIN  ShopProduct ON Shop.ShopID = ShopProduct.ShopID 
INNER JOIN  Product ON ShopProduct.ProductID = Product.ProductID
WHERE       Shop.ShopID=3

You will probably see the following results:

ShopID     ShopName                 ShopID  ProductID   Price   ProductID   ProductDescription
3          Europe Gaming Experience   3         1       259.99  1           PS3
3          Europe Gaming Experience   3         2       159.99  2           Wii
3          Europe Gaming Experience   3         3       199.99  3           XBOX360

Now for one last example, let's assume that your website has a feature which finds the cheapest price for a console. A user asks to find the cheapest prices for XBOX360.

You can execute the following query:

 SELECT     Shop.*
        , ShopProduct.*
        , Product.*
 FROM         Shop 
 INNER JOIN  ShopProduct ON Shop.ShopID = ShopProduct.ShopID 
 INNER JOIN  Product ON ShopProduct.ProductID = Product.ProductID
 WHERE      Product.ProductID =3  -- You can also use Product.ProductDescription = 'XBOX360'
 ORDER BY    Price ASC

This query will return a list of all shops which sells the XBOX360 with the cheapest shop first and so on.

You will notice that I have not added the Asian Games shop. As an exercise, add the Asian games shop to the mapping table with the following products: the Asian Games Emporium sells the Wii games console for $99.99 and the PS3 console for $159.99. If you work through this example you should now understand how to model a many-to-many relationship.

I hope this helps you in your travels with database design.

How to get system time in Java without creating a new Date

As jzd says, you can use System.currentTimeMillis. If you need it in a Date object but don't want to create a new Date object, you can use Date.setTime to reuse an existing Date object. Personally I hate the fact that Date is mutable, but maybe it's useful to you in this particular case. Similarly, Calendar has a setTimeInMillis method.

If possible though, it would probably be better just to keep it as a long. If you only need a timestamp, effectively, then that would be the best approach.

Why is it faster to check if dictionary contains the key, rather than catch the exception in case it doesn't?

Dictionaries are specifically designed to do super fast key lookups. They are implemented as hashtables and the more entries the faster they are relative to other methods. Using the exception engine is only supposed to be done when your method has failed to do what you designed it to do because it is a large set of object that give you a lot of functionality for handling errors. I built an entire library class once with everything surrounded by try catch blocks once and was appalled to see the debug output which contained a seperate line for every single one of over 600 exceptions!

Understanding the Gemfile.lock file

I've spent the last few months messing around with Gemfiles and Gemfile.locks a lot whilst building an automated dependency update tool1. The below is far from definitive, but it's a good starting point for understanding the Gemfile.lock format. You might also want to check out the source code for Bundler's lockfile parser.

You'll find the following headings in a lockfile generated by Bundler 1.x:

GEM (optional but very common)

These are dependencies sourced from a Rubygems server. That may be the main Rubygems index, at Rubygems.org, or it may be a custom index, such as those available from Gemfury and others. Within this section you'll see:

  • remote: one or more lines specifying the location of the Rubygems index(es)
  • specs: a list of dependencies, with their version number, and the constraints on any subdependencies

GIT (optional)

These are dependencies sourced from a given git remote. You'll see a different one of these sections for each git remote, and within each section you'll see:

  • remote: the git remote. E.g., [email protected]:rails/rails
  • revision: the commit reference the Gemfile.lock is locked to
  • tag: (optional) the tag specified in the Gemfile
  • specs: the git dependency found at this remote, with its version number, and the constraints on any subdependencies

PATH (optional)

These are dependencies sourced from a given path, provided in the Gemfile. You'll see a different one of these sections for each path dependency, and within each section you'll see:

  • remote: the path. E.g., plugins/vendored-dependency
  • specs: the git dependency found at this remote, with its version number, and the constraints on any subdependencies

PLATFORMS

The Ruby platform the Gemfile.lock was generated against. If any dependencies in the Gemfile specify a platform then they will only be included in the Gemfile.lock when the lockfile is generated on that platform (e.g., through an install).

DEPENDENCIES

A list of the dependencies which are specified in the Gemfile, along with the version constraint specified there.

Dependencies specified with a source other than the main Rubygems index (e.g., git dependencies, path-based, dependencies) have a ! which means they are "pinned" to that source2 (although one must sometimes look in the Gemfile to determine in).

RUBY VERSION (optional)

The Ruby version specified in the Gemfile, when this Gemfile.lock was created. If a Ruby version is specified in a .ruby_version file instead this section will not be present (as Bundler will consider the Gemfile / Gemfile.lock agnostic to the installer's Ruby version).

BUNDLED WITH (Bundler >= v1.10.x)

The version of Bundler used to create the Gemfile.lock. Used to remind installers to update their version of Bundler, if it is older than the version that created the file.

PLUGIN SOURCE (optional and very rare)

In theory, a Gemfile can specify Bundler plugins, as well as gems3, which would then be listed here. In practice, I'm not aware of any available plugins, as of July 2017. This part of Bundler is still under active development!


  1. https://dependabot.com
  2. https://github.com/bundler/bundler/issues/4631
  3. http://andre.arko.net/2012/07/23/towards-a-bundler-plugin-system/

Time comparison

You can use the compareTo() method from Java Date class

public int result = date.compareTo(Date anotherDate); 

Return Value: The function gives three return values specified below:

It returns the value 0 if the argument Date is equal to this Date. It returns a value less than 0 if this Date is before the Date argument. It returns a value greater than 0 if this Date is after the Date argument.

Java 8 lambda Void argument

The syntax you're after is possible with a little helper function that converts a Runnable into Action<Void, Void> (you can place it in Action for example):

public static Action<Void, Void> action(Runnable runnable) {
    return (v) -> {
        runnable.run();
        return null;
    };
}

// Somewhere else in your code
 Action<Void, Void> action = action(() -> System.out.println("foo"));

Difference between Mutable objects and Immutable objects

Immutable objects are simply objects whose state (the object's data) cannot change after construction. Examples of immutable objects from the JDK include String and Integer.

For example:(Point is mutable and string immutable)

     Point myPoint = new Point( 0, 0 );
    System.out.println( myPoint );
    myPoint.setLocation( 1.0, 0.0 );
    System.out.println( myPoint );

    String myString = new String( "old String" );
    System.out.println( myString );
    myString.replaceAll( "old", "new" );
    System.out.println( myString );

The output is:

java.awt.Point[0.0, 0.0]
java.awt.Point[1.0, 0.0]
old String
old String

Serializing/deserializing with memory stream

BinaryFormatter may produce invalid output in some specific cases. For example it will omit unpaired surrogate characters. It may also have problems with values of interface types. Read this documentation page including community content.

If you find your error to be persistent you may want to consider using XML serializer like DataContractSerializer or XmlSerializer.

ignoring any 'bin' directory on a git project

Before version 1.8.2, ** didn't have any special meaning in the .gitignore. As of 1.8.2 git supports ** to mean zero or more sub-directories (see release notes).

The way to ignore all directories called bin anywhere below the current level in a directory tree is with a .gitignore file with the pattern:

bin/

In the man page, there an example of ignoring a directory called foo using an analogous pattern.

Edit: If you already have any bin folders in your git index which you no longer wish to track then you need to remove them explicitly. Git won't stop tracking paths that are already being tracked just because they now match a new .gitignore pattern. Execute a folder remove (rm) from index only (--cached) recursivelly (-r). Command line example for root bin folder:

git rm -r --cached bin

jQuery - keydown / keypress /keyup ENTERKEY detection?

JavaScript/jQuery

$("#entersomething").keyup(function(e){ 
    var code = e.key; // recommended to use e.key, it's normalized across devices and languages
    if(code==="Enter") e.preventDefault();
    if(code===" " || code==="Enter" || code===","|| code===";"){
        $("#displaysomething").html($(this).val());
    } // missing closing if brace
});

HTML

<input id="entersomething" type="text" /> <!-- put a type attribute in -->
<div id="displaysomething"></div>

Nullable DateTime conversion

Cast the null literal: (DateTime?)null or (Nullable<DateTime>)null.

You can also use default(DateTime?) or default(Nullable<DateTime>)

And, as other answers have noted, you can also apply the cast to the DateTime value rather than to the null literal.

EDIT (adapted from my comment to Prutswonder's answer):

The point is that the conditional operator does not consider the type of its assignment target, so it will only compile if there is an implicit conversion from the type of its second operand to the type of its third operand, or from the type of its third operand to the type of its second operand.

For example, this won't compile:

bool b = GetSomeBooleanValue();
object o = b ? "Forty-two" : 42;

Casting either the second or third operand to object, however, fixes the problem, because there is an implicit conversion from int to object and also from string to object:

object o = b ? "Forty-two" : (object)42;

or

object o = b ? (object)"Forty-two" : 42;

How to show alert message in mvc 4 controller?

It is not possible to display alerts from the controller. Because MVC views and controllers are entirely separated from each other. You can only display information in the view only. So it is required to pass the information to be displayed from controller to view by using either ViewBag, ViewData or TempData. If you are trying to display the content stored in TempData["Message"], It is possible to perform in the view page by adding few javascript lines.

<script>
  alert(@TempData["Message"]);
</script>

How to pass query parameters with a routerLink

queryParams

queryParams is another input of routerLink where they can be passed like

<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}">Somewhere</a>

fragment

<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}" [fragment]="yyy">Somewhere</a>

routerLinkActiveOptions

To also get routes active class set on parent routes:

[routerLinkActiveOptions]="{ exact: false }"

To pass query parameters to this.router.navigate(...) use

let navigationExtras: NavigationExtras = {
  queryParams: { 'session_id': sessionId },
  fragment: 'anchor'
};

// Navigate to the login page with extras
this.router.navigate(['/login'], navigationExtras);

See also https://angular.io/guide/router#query-parameters-and-fragments

Postgresql 9.2 pg_dump version mismatch

I experienced a similar problem on my Fedora 17 installation. This is what I did to get around the issue

  • Delete the builtin pg_dump at /usr/bin/pg_dump (as root: "rm /usr/bin/pg_dump")
  • Now make a symbolic link of the postgresql installation

    Again as root ln -s /usr/pgsql-9.2/bin/pg_dump /usr/bin/pg_dump

That should do the trick

An error has occured. Please see log file - eclipse juno

For me it was down to a locking/permissions bug on

(path to Eclipse IDE)\configuration\org.eclipse.osgi.manager.fileTableLock

See here

Spring Tool Suite 4 (64 bit for Windows Server 2016)

Version: 4.2.2.RELEASE Build Id: 201905232009

based on Eclipse

Version: 2.2.500.v20190307-0500 Build id: I20190307-0500

wouldn't launch and a pop up dialog appeared saying:

launch error has occurred see log file null

(This became apparent from the latest text log file in the folder (path to Eclipse IDE)\configuration)

!ENTRY org.eclipse.osgi 4 0 
2019-06-19 18:41:10.408
!MESSAGE Error reading configuration: C:\opt\sts-4.2.2.RELEASE\configuration\org.eclipse.osgi\.manager\.fileTableLock (Access is denied)
!STACK 0
java.io.FileNotFoundException: C:\opt\sts-4.2.2.RELEASE\configuration\org.eclipse.osgi\.manager\.fileTableLock (Access is denied)
...

I had to go and tweak the permissions via File Explorer (Full access).

It appeared as if the IDE was doing nothing for a while.

The splash screen for Spring Tool Suite (based on Eclipse) eventually disappeared and the IDE started up again.

Now everything is back working correctly again.

Pandas read_csv low_memory and dtype options

Try:

dashboard_df = pd.read_csv(p_file, sep=',', error_bad_lines=False, index_col=False, dtype='unicode')

According to the pandas documentation:

dtype : Type name or dict of column -> type

As for low_memory, it's True by default and isn't yet documented. I don't think its relevant though. The error message is generic, so you shouldn't need to mess with low_memory anyway. Hope this helps and let me know if you have further problems

Angular ng-if="" with multiple arguments

For people looking to do if statements with multiple 'or' values.

<div ng-if="::(a || b || c || d || e || f)"><div>

Retrieve Button value with jQuery

Inspired by postpostmodern I have made this, to make .val() work throughout my javascript code:

jQuery(function($) {

    if($.browser.msie) {
        // Fixes a know issue, that buttons value is overwritten with the text

        // Someone with more jQuery experience can probably tell me
        // how not to polute jQuery.fn here:
        jQuery.fn._orig_val = jQuery.fn.val

        jQuery.fn.val = function(value) {
            var elem = $(this);
            var html
            if(elem.attr('type') == 'button') {
                // if button, hide button text while getting val()
                html = elem.html()
                elem.html('')
            }
            // Use original function
            var result = elem._orig_val(value);
            if(elem.attr('type') == 'button') {
                elem.html(html)
            }
            return result;
        }
    }
})

It does however, not solve the submit problem, solved by postpostmodern. Perhaps this could be included in postpostmodern's solution here: http://gist.github.com/251287

Sql Server 'Saving changes is not permitted' error ? Prevent saving changes that require table re-creation

Prevent saving changes that require table re-creation

Five swift clicks

Prevent saving changes that require table re-creation in five clicks

  1. Tools
  2. Options
  3. Designers
  4. Prevent saving changes that require table re-creation
  5. OK.

After saving, repeat the proceudure to re-tick the box. This safe-guards against accidental data loss.

Further explanation

  • By default SQL Server Management Studio prevents the dropping of tables, because when a table is dropped its data contents are lost.*

  • When altering a column's datatype in the table Design view, when saving the changes the database drops the table internally and then re-creates a new one.

*Your specific circumstances will not pose a consequence since your table is empty. I provide this explanation entirely to improve your understanding of the procedure.

javascript: detect scroll end

I created a event based solution based on Bjorn Tipling's answer:

(function(doc){
    'use strict';

    window.onscroll = function (event) {
        if (isEndOfElement(doc.body)){
            sendNewEvent('end-of-page-reached');
        }
    };

    function isEndOfElement(element){
        //visible height + pixel scrolled = total height 
        return element.offsetHeight + element.scrollTop >= element.scrollHeight;
    }

    function sendNewEvent(eventName){
        var event = doc.createEvent('Event');
        event.initEvent(eventName, true, true);
        doc.dispatchEvent(event);
    }
}(document));

And you use the event like this:

document.addEventListener('end-of-page-reached', function(){
    console.log('you reached the end of the page');
});

BTW: you need to add this CSS for javascript to know how long the page is

html, body {
    height: 100%;
}

Demo: http://plnkr.co/edit/CCokKfB16iWIMddtWjPC?p=preview

How do you save/store objects in SharedPreferences on Android?

An other way to save and restore an object from android sharedpreferences without using the Json format

private static ExampleObject getObject(Context c,String db_name){
            SharedPreferences sharedPreferences = c.getSharedPreferences(db_name, Context.MODE_PRIVATE);
            ExampleObject o = new ExampleObject();
            Field[] fields = o.getClass().getFields();
            try {
                for (Field field : fields) {
                    Class<?> type = field.getType();
                    try {
                        final String name = field.getName();
                        if (type == Character.TYPE || type.equals(String.class)) {
                            field.set(o,sharedPreferences.getString(name, ""));
                        } else if (type.equals(int.class) || type.equals(Short.class))
                            field.setInt(o,sharedPreferences.getInt(name, 0));
                        else if (type.equals(double.class))
                            field.setDouble(o,sharedPreferences.getFloat(name, 0));
                        else if (type.equals(float.class))
                            field.setFloat(o,sharedPreferences.getFloat(name, 0));
                        else if (type.equals(long.class))
                            field.setLong(o,sharedPreferences.getLong(name, 0));
                        else if (type.equals(Boolean.class))
                            field.setBoolean(o,sharedPreferences.getBoolean(name, false));
                        else if (type.equals(UUID.class))
                            field.set(
                                    o,
                                    UUID.fromString(
                                            sharedPreferences.getString(
                                                    name,
                                                    UUID.nameUUIDFromBytes("".getBytes()).toString()
                                            )
                                    )
                            );

                    } catch (IllegalAccessException e) {
                        Log.e(StaticConfig.app_name, "IllegalAccessException", e);
                    } catch (IllegalArgumentException e) {
                        Log.e(StaticConfig.app_name, "IllegalArgumentException", e);
                    }
                }
            } catch (Exception e) {
                System.out.println("Exception: " + e);
            }
            return o;
        }
        private static void setObject(Context context, Object o, String db_name) {
            Field[] fields = o.getClass().getFields();
            SharedPreferences sp = context.getSharedPreferences(db_name, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            for (Field field : fields) {
                Class<?> type = field.getType();
                try {
                    final String name = field.getName();
                    if (type == Character.TYPE || type.equals(String.class)) {
                        Object value = field.get(o);
                        if (value != null)
                            editor.putString(name, value.toString());
                    } else if (type.equals(int.class) || type.equals(Short.class))
                        editor.putInt(name, field.getInt(o));
                    else if (type.equals(double.class))
                        editor.putFloat(name, (float) field.getDouble(o));
                    else if (type.equals(float.class))
                        editor.putFloat(name, field.getFloat(o));
                    else if (type.equals(long.class))
                        editor.putLong(name, field.getLong(o));
                    else if (type.equals(Boolean.class))
                        editor.putBoolean(name, field.getBoolean(o));
                    else if (type.equals(UUID.class))
                        editor.putString(name, field.get(o).toString());

                } catch (IllegalAccessException e) {
                    Log.e(StaticConfig.app_name, "IllegalAccessException", e);
                } catch (IllegalArgumentException e) {
                    Log.e(StaticConfig.app_name, "IllegalArgumentException", e);
                }
            }

            editor.apply();
        }

Verilog generate/genvar in an always block

Within a module, Verilog contains essentially two constructs: items and statements. Statements are always found in procedural contexts, which include anything in between begin..end, functions, tasks, always blocks and initial blocks. Items, such as generate constructs, are listed directly in the module. For loops and most variable/constant declarations can exist in both contexts.

In your code, it appears that you want the for loop to be evaluated as a generate item but the loop is actually part of the procedural context of the always block. For a for loop to be treated as a generate loop it must be in the module context. The generate..endgenerate keywords are entirely optional(some tools require them) and have no effect. See this answer for an example of how generate loops are evaluated.

//Compiler sees this
parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
genvar c;

    always @(posedge sysclk) //Procedural context starts here
    begin
        for (c = 0; c < ROWBITS; c = c + 1) begin: test
            temp[c] <= 1'b0; //Still a genvar
        end
    end