Programs & Examples On #Dotfiles

Your configuration specifies to merge with the <branch name> from the remote, but no such ref was fetched.?

This can also happen if you/someone renamed the branch. So follow these steps (if you know that branch name is renamed) Assuming earlier branch name as wrong-branch-name and someone renamed it to correct-branch-name So.

git checkout correct-branch-name

git pull (you'll see this "Your configuration specifies..")

git branch --unset-upstream

git push --set-upstream origin correct-branch-name

git pull (you'll not get the earlier message )

Broken references in Virtualenvs

All the answers are great here, I tried a couple of solutions mentioned above by Ryan, Chris and couldn't resolve the issue, so had to follow a quick and dirty way.

  1. rm -rf <project dir> (or mv <project dir> <backup projct dir> if you want to keep a backup)
  2. git clone <project git url>
  3. Move on!

Nothing novel here, but it makes life easier!

Why Git is not allowing me to commit even after configuration?

Do you have a local user.name or user.email that's overriding the global one?

git config --list --global | grep user
  user.name=YOUR NAME
  user.email=YOUR@EMAIL
git config --list --local | grep user
  user.name=YOUR NAME
  user.email=

If so, remove them

git config --unset --local user.name
git config --unset --local user.email

The local settings are per-clone, so you'll have to unset the local user.name and user.email for each of the repos on your machine.

tmux status bar configuration

The man page has very detailed descriptions of all of the various options (the status bar is highly configurable). Your best bet is to read through man tmux and pay particular attention to those options that begin with status-.

So, for example, status-bg red would set the background colour of the bar.

The three components of the bar, the left and right sections and the window-list in the middle, can all be configured to suit your preferences. status-left and status-right, in addition to having their own variables (like #S to list the session name) can also call custom scripts to display, for example, system information like load average or battery time.

The option to rename windows or panes based on what is currently running in them is automatic-rename. You can set, or disable it globally with:

setw -g automatic-rename [on | off]

The most straightforward way to become comfortable with building your own status bar is to start with a vanilla one and then add changes incrementally, reloading the config as you go.1

You might also want to have a look around on github or bitbucket for other people's conf files to provide some inspiration. You can see mine here2.



1 You can automate this by including this line in your .tmux.conf:

bind R source-file ~/.tmux.conf \; display-message "Config reloaded..."

You can then test your new functionality with Ctrlb,Shiftr. tmux will print a helpful error message—including a line number of the offending snippet—if you misconfigure an option.

2 Note: I call a different status bar depending on whether I am in X or the console - I find this quite useful.

Git status shows files as changed even though contents are the same

I was able to fix the problems on Windows machine by changing core.autocrlf from false to core.autocrlf=input

git config core.autocrlf input

as it's suggested in https://stackoverflow.com/a/1112313/52277

How to get anchor text/href on click using jQuery?

Updated code

$('a','div.res').click(function(){
  var currentAnchor = $(this);
  alert(currentAnchor.text());
  alert(currentAnchor.attr('href'));
});

How to add title to subplots in Matplotlib?

In case you have multiple images and you want to loop though them and show them 1 by 1 along with titles - this is what you can do. No need to explicitly define ax1, ax2, etc.

  1. The catch is you can define dynamic axes(ax) as in Line 1 of code and you can set its title inside a loop.
  2. The rows of 2D array is length (len) of axis(ax)
  3. Each row has 2 items i.e. It is list within a list (Point No.2)
  4. set_title can be used to set title, once the proper axes(ax) or subplot is selected.
import matplotlib.pyplot as plt    
fig, ax = plt.subplots(2, 2, figsize=(6, 8))  
for i in range(len(ax)): 
    for j in range(len(ax[i])):
        ## ax[i,j].imshow(test_images_gr[0].reshape(28,28))
        ax[i,j].set_title('Title-' + str(i) + str(j))

Set IDENTITY_INSERT ON is not working

In VB code, when trying to submit an INSERT query, you must submit a double query in the same 'executenonquery' like this:

sqlQuery = "SET IDENTITY_INSERT dbo.TheTable ON; INSERT INTO dbo.TheTable (Col1, COl2) VALUES (Val1, Val2); SET IDENTITY_INSERT dbo.TheTable OFF;"

I used a ; separator instead of a GO.

Works for me. Late but efficient!

Get Application Directory

PackageManager m = getPackageManager();
String s = getPackageName();
PackageInfo p = m.getPackageInfo(s, 0);
s = p.applicationInfo.dataDir;

If eclipse worries about an uncaught NameNotFoundException, you can use:

PackageManager m = getPackageManager();
String s = getPackageName();
try {
    PackageInfo p = m.getPackageInfo(s, 0);
    s = p.applicationInfo.dataDir;
} catch (PackageManager.NameNotFoundException e) {
    Log.w("yourtag", "Error Package name not found ", e);
}

How to loop through all elements of a form jQuery

From the jQuery :input selector page:

Because :input is a jQuery extension and not part of the CSS specification, queries using :input cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :input to select elements, first select the elements using a pure CSS selector, then use .filter(":input").

This is the best choice.

$('#new_user_form *').filter(':input').each(function(){
    //your code here
});

What is the best way to update the entity in JPA

It depends on number of entities which are going to be updated, if you have large number of entities using JPA Query Update statement is better as you dont have to load all the entities from database, if you are going to update just one entity then using find and update is fine.

How can I join elements of an array in Bash?

Use perl for multicharacter separators:

function join {
   perl -e '$s = shift @ARGV; print join($s, @ARGV);' "$@"; 
}

join ', ' a b c # a, b, c

Or in one line:

perl -le 'print join(shift, @ARGV);' ', ' 1 2 3
1, 2, 3

sed edit file in place

The -i option streams the edited content into a new file and then renames it behind the scenes, anyway.

Example:

sed -i 's/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g' filename

and

sed -i '' 's/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g' filename

on macOS.

How do I align views at the bottom of the screen?

You can just give your top child view (the TextView @+id/TextView) an attribute: android:layout_weight="1".

This will force all other elements below it to the bottom.

How to find the Center Coordinate of Rectangle?

The center of rectangle is the midpoint of the diagonal end points of rectangle.

Here the midpoint is ( (x1 + x2) / 2, (y1 + y2) / 2 ).

That means:
xCenter = (x1 + x2) / 2
yCenter = (y1 + y2) / 2

Let me know your code.

Select count(*) from multiple tables

As additional information, to accomplish same thing in SQL Server, you just need to remove the "FROM dual" part of the query.

How to check ASP.NET Version loaded on a system?

I had same problem to find a way to check whether ASP.NET 4.5 is on the Server. Because v4.5 is in place replace to v4.0, if you look at c:\windows\Microsoft.NET\Framework, you will not see v4.5 folder. Actually there is a simple way to see the version installed in the machine. Under Windows Server 2008 or Windows 7, just go to control panel -> Programs and Features, you will find "Microsoft .NET Framework 4.5" if it is installed.

Make var_dump look pretty

You could use this one debugVar() instead of var_dump()

Check out: https://github.com/E1NSER/php-debug-function

How do I detect if Python is running as a 64-bit application?

import platform
platform.architecture()

From the Python docs:

Queries the given executable (defaults to the Python interpreter binary) for various architecture information.

Returns a tuple (bits, linkage) which contain information about the bit architecture and the linkage format used for the executable. Both values are returned as strings.

How to use SqlClient in ASP.NET Core?

Try this one Open your projectname.csproj file its work for me.

<PackageReference Include="System.Data.SqlClient" Version="4.6.0" />

You need to add this Reference "ItemGroup" tag inside.

Raise an event whenever a property's value changed?

Raising an event when a property changes is precisely what INotifyPropertyChanged does. There's one required member to implement INotifyPropertyChanged and that is the PropertyChanged event. Anything you implemented yourself would probably be identical to that implementation, so there's no advantage to not using it.

jQuery: how do I animate a div rotation?

I've been using

_x000D_
_x000D_
$.fn.rotate = function(degrees, step, current) {_x000D_
    var self = $(this);_x000D_
    current = current || 0;_x000D_
    step = step || 5;_x000D_
    current += step;_x000D_
    self.css({_x000D_
        '-webkit-transform' : 'rotate(' + current + 'deg)',_x000D_
        '-moz-transform' : 'rotate(' + current + 'deg)',_x000D_
        '-ms-transform' : 'rotate(' + current + 'deg)',_x000D_
        'transform' : 'rotate(' + current + 'deg)'_x000D_
    });_x000D_
    if (current != degrees) {_x000D_
        setTimeout(function() {_x000D_
            self.rotate(degrees, step, current);_x000D_
        }, 5);_x000D_
    }_x000D_
};_x000D_
_x000D_
$(".r90").click(function() { $("span").rotate(90) });_x000D_
$(".r0").click(function() { $("span").rotate(0, -5, 90) });
_x000D_
span { display: inline-block }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>_x000D_
<span>potato</span>_x000D_
_x000D_
<button class="r90">90 degrees</button>_x000D_
<button class="r0">0 degrees</button>
_x000D_
_x000D_
_x000D_

Bind failed: Address already in use

I was also facing that problem, but I resolved it. Make sure that both the programs for client-side and server-side are on different projects in your IDE, in my case NetBeans. Then assuming you're using localhost, I recommend you to implement both the programs as two different projects.

Using ConfigurationManager to load config from an arbitrary location

This should do the trick :

AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", "newAppConfig.config);

Source : https://www.codeproject.com/Articles/616065/Why-Where-and-How-of-NET-Configuration-Files

How to use SQL Select statement with IF EXISTS sub query?

SELECT Id, 'TRUE' AS NewFiled FROM TABEL1
INTERSECT
SELECT Id, 'TRUE' AS NewFiled FROM TABEL2
UNION
SELECT Id, 'FALSE' AS NewFiled FROM TABEL1
EXCEPT
SELECT Id, 'FALSE' AS NewFiled FROM TABEL2;

Java null check why use == instead of .equals()

here is an example where str != null but str.equals(null) when using org.json

 JSONObject jsonObj = new JSONObject("{field :null}");
 Object field = jsonObj.get("field");
 System.out.println(field != null);        // => true
 System.out.println( field.equals(null)); //=> true
 System.out.println( field.getClass());  // => org.json.JSONObject$Null




EDIT: here is the org.json.JSONObject$Null class:

/**
 * JSONObject.NULL is equivalent to the value that JavaScript calls null,
 * whilst Java's null is equivalent to the value that JavaScript calls
 * undefined.
 */
private static final class Null {

    /**
     * A Null object is equal to the null value and to itself.
     *
     * @param object
     *            An object to test for nullness.
     * @return true if the object parameter is the JSONObject.NULL object or
     *         null.
     */
    @Override
    public boolean equals(Object object) {
        return object == null || object == this;
    }  
}

Convert string to Python class object?

Warning: eval() can be used to execute arbitrary Python code. You should never use eval() with untrusted strings. (See Security of Python's eval() on untrusted strings?)

This seems simplest.

>>> class Foo(object):
...     pass
... 
>>> eval("Foo")
<class '__main__.Foo'>

change figure size and figure format in matplotlib

If you need to change the figure size after you have created it, use the methods

fig = plt.figure()
fig.set_figheight(value_height)
fig.set_figwidth(value_width)

where value_height and value_width are in inches. For me this is the most practical way.

how to show alternate image if source image is not found? (onerror working in IE but not in mozilla)

If you're open to a PHP solution:

<td><img src='<?PHP
  $path1 = "path/to/your/image.jpg";
  $path2 = "alternate/path/to/another/image.jpg";

  echo file_exists($path1) ? $path1 : $path2; 
  ?>' alt='' />
</td>

////EDIT OK, here's a JS version:

<table><tr>
<td><img src='' id='myImage' /></td>
</tr></table>

<script type='text/javascript'>
  document.getElementById('myImage').src = "newImage.png";

  document.getElementById('myImage').onload = function() { 
    alert("done"); 
  }

  document.getElementById('myImage').onerror = function() { 
    alert("Inserting alternate");
    document.getElementById('myImage').src = "alternate.png"; 
  }
</script>

How to get the max of two values in MySQL?

Use GREATEST()

E.g.:

SELECT GREATEST(2,1);

Note: Whenever if any single value contains null at that time this function always returns null (Thanks to user @sanghavi7)

Get the short Git version hash

A simple way to see the Git commit short version and the Git commit message is:

git log --oneline

Note that this is shorthand for

git log --pretty=oneline --abbrev-commit

How comment a JSP expression?

You can use this comment in jsp page

 <%--your comment --%>

Second way of comment declaration in jsp page you can use the comment of two typ in jsp code

 single line comment
 <% your code //your comment%>

multiple line comment 

<% your code 
/**
your another comment
**/

%>

And you can also comment on jsp page from html code for example:

<!-- your commment -->

What is the difference between Session.Abandon() and Session.Clear()

Clearing a session removes the values that were stored there, but you still can add new ones there. After destroying the session you cannot add new values there.

DataTables fixed headers misaligned with columns in wide tables

I know there has been an answer flagged already, but for someone with similar problems that the above does not work for. I'm using it in conjunction with bootstrap theme.

There is a line that can be altered in the dataTables.fixedHeader.js file. the default layout of the function looks as follows.

    _matchWidths: function (from, to) {
        var get = function (name) {
            return $(name, from)
                .map(function () {
                    return $(this).width();
                }).toArray();
        };

        var set = function (name, toWidths) {
            $(name, to).each(function (i) {
                $(this).css({
                    width: toWidths[i],
                    minWidth: toWidths[i]
                });
            });
        };

        var thWidths = get('th');
        var tdWidths = get('td');

        set('th', thWidths);
        set('td', tdWidths);
    },

change the

    return $(this).width();

to

    return $(this).outerWidth();

outerWidth() is a function that is contained in jquery.dimensions.js if you are usingg a newer version of jquery. ie. jquery-3.1.1.js

what the above function does is it maps the th of the original table, then applies them to the "cloned" table(fixed header). in my case they were always off by about 5px to 8px when misaligned. Most probably not the best fix out there but provides a solution to all other tables in the solution without having to specify it per table declaration. It has only been tested in Chrome so far, but it should provide an adjudicate solution on all browsers.

Exchange Powershell - How to invoke Exchange 2010 module from inside script?

import-module Microsoft.Exchange.Management.PowerShell.E2010aTry with some implementation like:

$exchangeser = "MTLServer01"
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionURI http://${exchangeserver}/powershell/ -Authentication kerberos
import-PSSession $session 

or

add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010

Rename multiple files based on pattern in Unix

rename might not be in every system. so if you don't have it, use the shell this example in bash shell

for f in fgh*; do mv "$f" "${f/fgh/xxx}";done

How do I find a particular value in an array and return its index?

#include <vector>
#include <algorithm>

int main()
{
     int arr[5] = {4, 1, 3, 2, 6};
     int x = -1;
     std::vector<int> testVector(arr, arr + sizeof(arr) / sizeof(int) );

     std::vector<int>::iterator it = std::find(testVector.begin(), testVector.end(), 3);
     if (it != testVector.end())
     {
          x = it - testVector.begin();
     }
     return 0;
}

Or you can just build a vector in a normal way, without creating it from an array of ints and then use the same solution as shown in my example.

Java foreach loop: for (Integer i : list) { ... }

Another way, you can use a pass-through object to capture the last value and then do something with it:

List<Integer> list = new ArrayList<Integer>();
Integer lastValue = null;
for (Integer i : list) {
    // do stuff
    lastValue = i;
}
// do stuff with last value

Get content uri from file path in android

Is better to use a validation to support versions pre Android N, example:

  if (Build.VERSION.SDK_INT >=  Build.VERSION_CODES.N) {
     imageUri = Uri.parse(filepath);
  } else{
     imageUri = Uri.fromFile(new File(filepath));
  }

  if (Build.VERSION.SDK_INT >=  Build.VERSION_CODES.N) {
     ImageView.setImageURI(Uri.parse(new File("/sdcard/cats.jpg").toString()));         
  } else{
     ImageView.setImageURI(Uri.fromFile(new File("/sdcard/cats.jpg")));
  }

https://es.stackoverflow.com/questions/71443/reporte-crash-android-os-fileuriexposedexception-en-android-n

How to programmatically set cell value in DataGridView?

private void btn_Addtoreciept_Click(object sender, EventArgs e)
{            
    serial_number++;
    dataGridView_inventory.Rows[serial_number - 1].Cells[0].Value = serial_number;
    dataGridView_inventory.Rows[serial_number - 1].Cells[1].Value =comboBox_Reciept_name.Text;
    dataGridView_inventory.Rows[serial_number - 1].Cells[2].Value = numericUpDown_recieptprice.Value;
    dataGridView_inventory.Rows[serial_number - 1].Cells[3].Value = numericUpDown_Recieptpieces.Value;
    dataGridView_inventory.Rows[serial_number - 1].Cells[4].Value = numericUpDown_recieptprice.Value * numericUpDown_Recieptpieces.Value;
    numericUpDown_RecieptTotal.Value = serial_number;
}

on first time it goes well but pressing 2nd time it gives me error "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index" but when i click on the cell another row appears and then it works for the next row, and carry on ...

ImportError: Cannot import name X

To make logic clear is very important. This problem appear, because the reference become a dead loop.

If you don't want to change the logic, you can put the some import statement which caused ImportError to the other position of file, for example the end.

a.py

from test.b import b2

def a1():
    print('a1')
    b2()

b.py

from test.a import a1

def b1():
    print('b1')
    a1()

def b2():
    print('b2')

if __name__ == '__main__':
    b1()

You will get Import Error: ImportError: cannot import name 'a1'

But if we change the position of from test.b import b2 in A like below:

a.py

def a1():
    print('a1')
    b2()

from test.b import b2

And the we can get what we want:

b1
a1
b2

Alert handling in Selenium WebDriver (selenium 2) with Java

You could try

 try{
        if(webDriver.switchTo().alert() != null){
           Alert alert = webDriver.switchTo().alert();
           alert.getText();
           //etc.
        }
    }catch(Exception e){}

If that doesn't work, you could try looping through all the window handles and see if the alert exists. I'm not sure if the alert opens as a new window using selenium.

for(String s: webDriver.getWindowHandles()){
 //see if alert exists here.
}

How many bits or bytes are there in a character?

It depends what is the character and what encoding it is in:

  • An ASCII character in 8-bit ASCII encoding is 8 bits (1 byte), though it can fit in 7 bits.

  • An ISO-8895-1 character in ISO-8859-1 encoding is 8 bits (1 byte).

  • A Unicode character in UTF-8 encoding is between 8 bits (1 byte) and 32 bits (4 bytes).

  • A Unicode character in UTF-16 encoding is between 16 (2 bytes) and 32 bits (4 bytes), though most of the common characters take 16 bits. This is the encoding used by Windows internally.

  • A Unicode character in UTF-32 encoding is always 32 bits (4 bytes).

  • An ASCII character in UTF-8 is 8 bits (1 byte), and in UTF-16 - 16 bits.

  • The additional (non-ASCII) characters in ISO-8895-1 (0xA0-0xFF) would take 16 bits in UTF-8 and UTF-16.

That would mean that there are between 0.03125 and 0.125 characters in a bit.

What is phtml, and when should I use a .phtml extension rather than .php?

.phtml files tell the webserver that those are html files with dynamic content which is generated by the server... just like .php files in a browser behave. So, in productive usage you should experience no difference from .phtml to .php files.

Route.get() requires callback functions but got a "object Undefined"

I got the same error. After debugging, I found that I misspelled the method name that I imported from the controller into the route file. Please check the method name.

AngularJS disable partial caching on dev machine

This snippet helped me in getting rid of template caching

app.run(function($rootScope, $templateCache) {
    $rootScope.$on('$routeChangeStart', function(event, next, current) {
        if (typeof(current) !== 'undefined'){
            $templateCache.remove(current.templateUrl);
        }
    });
});

The details of following snippet can be found on this link: http://oncodesign.io/2014/02/19/safely-prevent-template-caching-in-angularjs/

jQuery event to trigger action when a div is made visible

Hope this will do the job in simplest manner:

$("#myID").on('show').trigger('displayShow');

$('#myID').off('displayShow').on('displayShow', function(e) {
    console.log('This event will be triggered when myID will be visible');
});

Update a dataframe in pandas while iterating row by row

You can assign values in the loop using df.set_value:

for i, row in df.iterrows():
    ifor_val = something
    if <condition>:
        ifor_val = something_else
    df.set_value(i,'ifor',ifor_val)

If you don't need the row values you could simply iterate over the indices of df, but I kept the original for-loop in case you need the row value for something not shown here.

update

df.set_value() has been deprecated since version 0.21.0 you can use df.at() instead:

for i, row in df.iterrows():
    ifor_val = something
    if <condition>:
        ifor_val = something_else
    df.at[i,'ifor'] = ifor_val

How to paginate with Mongoose in Node.js?

This is a sample example you can try this,

var _pageNumber = 2,
  _pageSize = 50;

Student.count({},function(err,count){
  Student.find({}, null, {
    sort: {
      Name: 1
    }
  }).skip(_pageNumber > 0 ? ((_pageNumber - 1) * _pageSize) : 0).limit(_pageSize).exec(function(err, docs) {
    if (err)
      res.json(err);
    else
      res.json({
        "TotalCount": count,
        "_Array": docs
      });
  });
 });

How to open a web page from my application?

System.Diagnostics.Process.Start("http://www.webpage.com");

One of many ways.

htaccess - How to force the client's browser to clear the cache?

Change the name of the .CSS file Load the page and then change the file again in the original name it works for me.

PHP Undefined Index

The checking of the presence of the member before assigning it is, in my opinion, quite ugly.

Kohana has a useful function to make selecting parameters simple.

You can make your own like so...

function arrayGet($array, $key, $default = NULL)
{
    return isset($array[$key]) ? $array[$key] : $default;
}

And then do something like...

$page = arrayGet($_GET, 'p', 1);

PHP $_FILES['file']['tmp_name']: How to preserve filename and extension?

$_FILES['file']['tmp_name']; will contain the temporary file name of the file on the server. This is just a placeholder on your server until you process the file

$_FILES['file']['name']; contains the original name of the uploaded file from the user's computer.

Executing multi-line statements in the one-line command-line?

I wanted a solution with the following properties:

  1. Readable
  2. Read stdin for processing output of other tools

Both requirements were not provided in the other answers, so here's how to read stdin while doing everything on the command line:

grep special_string -r | sort | python3 <(cat <<EOF
import sys
for line in sys.stdin:
    tokens = line.split()
    if len(tokens) == 4:
        print("%-45s %7.3f    %s    %s" % (tokens[0], float(tokens[1]), tokens[2], tokens[3]))
EOF
)

How to do something to each file in a directory with a batch script

Alternatively, use:

forfiles /s /m *.png /c "cmd /c echo @path"

The forfiles command is available in Windows Vista and up.

Scroll to a div using jquery

First, your code does not contain a contact div, it has a contacts div!

In sidebar you have contact in the div at the bottom of the page you have contacts. I removed the final s for the code sample. (you also misspelled the projectslink id in the sidebar).

Second, take a look at some of the examples for click on the jQuery reference page. You have to use click like, object.click( function() { // Your code here } ); in order to bind a click event handler to the object.... Like in my example below. As an aside, you can also just trigger a click on an object by using it without arguments, like object.click().

Third, scrollTo is a plugin in jQuery. I don't know if you have the plugin installed. You can't use scrollTo() without the plugin. In this case, the functionality you desire is only 2 lines of code, so I see no reason to use the plugin.

Ok, now on to a solution.

The code below will scroll to the correct div if you click a link in the sidebar. The window does have to be big enough to allow scrolling:

// This is a functions that scrolls to #{blah}link
function goToByScroll(id) {
    // Remove "link" from the ID
    id = id.replace("link", "");
    // Scroll
    $('html,body').animate({
        scrollTop: $("#" + id).offset().top
    }, 'slow');
}

$("#sidebar > ul > li > a").click(function(e) {
    // Prevent a page reload when a link is pressed
    e.preventDefault();
    // Call the scroll function
    goToByScroll(this.id);
});

Live Example

( Scroll to function taken from here )


PS: Obviously you should have a compelling reason to go this route instead of using anchor tags <a href="#gohere">blah</a> ... <a name="gohere">blah title</a>

Why cannot change checkbox color whatever I do?

Although the question is answered and is older, In exploring some options to overcome the the styling of check boxes issue I encountered this awesome set of CSS3 only styling of check boxes and radio buttons controlling background colors and other appearances. Thought this might be right up the alley of this question.

JSFiddle

_x000D_
_x000D_
body {_x000D_
    background: #555;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
    color: #eee;_x000D_
    font: 30px Arial, sans-serif;_x000D_
    -webkit-font-smoothing: antialiased;_x000D_
    text-shadow: 0px 1px black;_x000D_
    text-align: center;_x000D_
    margin-bottom: 50px;_x000D_
}_x000D_
_x000D_
input[type=checkbox] {_x000D_
    visibility: hidden;_x000D_
}_x000D_
_x000D_
/* SLIDE ONE */_x000D_
.slideOne {_x000D_
    width: 50px;_x000D_
    height: 10px;_x000D_
    background: #333;_x000D_
    margin: 20px auto;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
    position: relative;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
}_x000D_
_x000D_
.slideOne label {_x000D_
    display: block;_x000D_
    width: 16px;_x000D_
    height: 16px;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
_x000D_
    -webkit-transition: all .4s ease;_x000D_
    -moz-transition: all .4s ease;_x000D_
    -o-transition: all .4s ease;_x000D_
    -ms-transition: all .4s ease;_x000D_
    transition: all .4s ease;_x000D_
    cursor: pointer;_x000D_
    position: absolute;_x000D_
    top: -3px;_x000D_
    left: -3px;_x000D_
_x000D_
    -webkit-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);_x000D_
    -moz-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);_x000D_
    box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);_x000D_
    background: #fcfff4;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -moz-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -o-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -ms-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfff4', endColorstr='#b3bead',GradientType=0 );_x000D_
}_x000D_
_x000D_
.slideOne input[type=checkbox]:checked + label {_x000D_
    left: 37px;_x000D_
}_x000D_
_x000D_
/* SLIDE TWO */_x000D_
.slideTwo {_x000D_
    width: 80px;_x000D_
    height: 30px;_x000D_
    background: #333;_x000D_
    margin: 20px auto;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
    position: relative;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
}_x000D_
_x000D_
.slideTwo:after {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    top: 14px;_x000D_
    left: 14px;_x000D_
    height: 2px;_x000D_
    width: 52px;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
    background: #111;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
}_x000D_
_x000D_
.slideTwo label {_x000D_
    display: block;_x000D_
    width: 22px;_x000D_
    height: 22px;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
_x000D_
    -webkit-transition: all .4s ease;_x000D_
    -moz-transition: all .4s ease;_x000D_
    -o-transition: all .4s ease;_x000D_
    -ms-transition: all .4s ease;_x000D_
    transition: all .4s ease;_x000D_
    cursor: pointer;_x000D_
    position: absolute;_x000D_
    top: 4px;_x000D_
    z-index: 1;_x000D_
    left: 4px;_x000D_
_x000D_
    -webkit-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);_x000D_
    -moz-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);_x000D_
    box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);_x000D_
    background: #fcfff4;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -moz-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -o-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -ms-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfff4', endColorstr='#b3bead',GradientType=0 );_x000D_
}_x000D_
_x000D_
.slideTwo label:after {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    width: 10px;_x000D_
    height: 10px;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
    background: #333;_x000D_
    left: 6px;_x000D_
    top: 6px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,1), 0px 1px 0px rgba(255,255,255,0.9);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,1), 0px 1px 0px rgba(255,255,255,0.9);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,1), 0px 1px 0px rgba(255,255,255,0.9);_x000D_
}_x000D_
_x000D_
.slideTwo input[type=checkbox]:checked + label {_x000D_
    left: 54px;_x000D_
}_x000D_
_x000D_
.slideTwo input[type=checkbox]:checked + label:after {_x000D_
    background: #00bf00;_x000D_
}_x000D_
_x000D_
/* SLIDE THREE */_x000D_
.slideThree {_x000D_
    width: 80px;_x000D_
    height: 26px;_x000D_
    background: #333;_x000D_
    margin: 20px auto;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
    position: relative;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
}_x000D_
_x000D_
.slideThree:after {_x000D_
    content: 'OFF';_x000D_
    font: 12px/26px Arial, sans-serif;_x000D_
    color: #000;_x000D_
    position: absolute;_x000D_
    right: 10px;_x000D_
    z-index: 0;_x000D_
    font-weight: bold;_x000D_
    text-shadow: 1px 1px 0px rgba(255,255,255,.15);_x000D_
}_x000D_
_x000D_
.slideThree:before {_x000D_
    content: 'ON';_x000D_
    font: 12px/26px Arial, sans-serif;_x000D_
    color: #00bf00;_x000D_
    position: absolute;_x000D_
    left: 10px;_x000D_
    z-index: 0;_x000D_
    font-weight: bold;_x000D_
}_x000D_
_x000D_
.slideThree label {_x000D_
    display: block;_x000D_
    width: 34px;_x000D_
    height: 20px;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
_x000D_
    -webkit-transition: all .4s ease;_x000D_
    -moz-transition: all .4s ease;_x000D_
    -o-transition: all .4s ease;_x000D_
    -ms-transition: all .4s ease;_x000D_
    transition: all .4s ease;_x000D_
    cursor: pointer;_x000D_
    position: absolute;_x000D_
    top: 3px;_x000D_
    left: 3px;_x000D_
    z-index: 1;_x000D_
_x000D_
    -webkit-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);_x000D_
    -moz-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);_x000D_
    box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);_x000D_
    background: #fcfff4;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -moz-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -o-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -ms-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfff4', endColorstr='#b3bead',GradientType=0 );_x000D_
}_x000D_
_x000D_
.slideThree input[type=checkbox]:checked + label {_x000D_
    left: 43px;_x000D_
}_x000D_
_x000D_
/* ROUNDED ONE */_x000D_
.roundedOne {_x000D_
    width: 28px;_x000D_
    height: 28px;_x000D_
    background: #fcfff4;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -moz-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -o-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -ms-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfff4', endColorstr='#b3bead',GradientType=0 );_x000D_
    margin: 20px auto;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    -moz-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.roundedOne label {_x000D_
    cursor: pointer;_x000D_
    position: absolute;_x000D_
    width: 20px;_x000D_
    height: 20px;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
    left: 4px;_x000D_
    top: 4px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -moz-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -o-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -ms-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#222', endColorstr='#45484d',GradientType=0 );_x000D_
}_x000D_
_x000D_
.roundedOne label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
    filter: alpha(opacity=0);_x000D_
    opacity: 0;_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    width: 16px;_x000D_
    height: 16px;_x000D_
    background: #00bf00;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
    background: -moz-linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
    background: -o-linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
    background: -ms-linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
    background: linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
    top: 2px;_x000D_
    left: 2px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    -moz-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
}_x000D_
_x000D_
.roundedOne label:hover::after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=30)";_x000D_
    filter: alpha(opacity=30);_x000D_
    opacity: 0.3;_x000D_
}_x000D_
_x000D_
.roundedOne input[type=checkbox]:checked + label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";_x000D_
    filter: alpha(opacity=100);_x000D_
    opacity: 1;_x000D_
}_x000D_
_x000D_
/* ROUNDED TWO */_x000D_
.roundedTwo {_x000D_
    width: 28px;_x000D_
    height: 28px;_x000D_
    background: #fcfff4;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -moz-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -o-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -ms-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfff4', endColorstr='#b3bead',GradientType=0 );_x000D_
    margin: 20px auto;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    -moz-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.roundedTwo label {_x000D_
    cursor: pointer;_x000D_
    position: absolute;_x000D_
    width: 20px;_x000D_
    height: 20px;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
    left: 4px;_x000D_
    top: 4px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -moz-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -o-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -ms-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#222', endColorstr='#45484d',GradientType=0 );_x000D_
}_x000D_
_x000D_
.roundedTwo label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
    filter: alpha(opacity=0);_x000D_
    opacity: 0;_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    width: 9px;_x000D_
    height: 5px;_x000D_
    background: transparent;_x000D_
    top: 5px;_x000D_
    left: 4px;_x000D_
    border: 3px solid #fcfff4;_x000D_
    border-top: none;_x000D_
    border-right: none;_x000D_
_x000D_
    -webkit-transform: rotate(-45deg);_x000D_
    -moz-transform: rotate(-45deg);_x000D_
    -o-transform: rotate(-45deg);_x000D_
    -ms-transform: rotate(-45deg);_x000D_
    transform: rotate(-45deg);_x000D_
}_x000D_
_x000D_
.roundedTwo label:hover::after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=30)";_x000D_
    filter: alpha(opacity=30);_x000D_
    opacity: 0.3;_x000D_
}_x000D_
_x000D_
.roundedTwo input[type=checkbox]:checked + label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";_x000D_
    filter: alpha(opacity=100);_x000D_
    opacity: 1;_x000D_
}_x000D_
_x000D_
/* SQUARED ONE */_x000D_
.squaredOne {_x000D_
    width: 28px;_x000D_
    height: 28px;_x000D_
    background: #fcfff4;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -moz-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -o-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -ms-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfff4', endColorstr='#b3bead',GradientType=0 );_x000D_
    margin: 20px auto;_x000D_
    -webkit-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    -moz-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.squaredOne label {_x000D_
    cursor: pointer;_x000D_
    position: absolute;_x000D_
    width: 20px;_x000D_
    height: 20px;_x000D_
    left: 4px;_x000D_
    top: 4px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -moz-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -o-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -ms-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#222', endColorstr='#45484d',GradientType=0 );_x000D_
}_x000D_
_x000D_
.squaredOne label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
    filter: alpha(opacity=0);_x000D_
    opacity: 0;_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    width: 16px;_x000D_
    height: 16px;_x000D_
    background: #00bf00;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
    background: -moz-linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
    background: -o-linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
    background: -ms-linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
    background: linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
_x000D_
    top: 2px;_x000D_
    left: 2px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    -moz-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
}_x000D_
_x000D_
.squaredOne label:hover::after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=30)";_x000D_
    filter: alpha(opacity=30);_x000D_
    opacity: 0.3;_x000D_
}_x000D_
_x000D_
.squaredOne input[type=checkbox]:checked + label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";_x000D_
    filter: alpha(opacity=100);_x000D_
    opacity: 1;_x000D_
}_x000D_
_x000D_
/* SQUARED TWO */_x000D_
.squaredTwo {_x000D_
    width: 28px;_x000D_
    height: 28px;_x000D_
    background: #fcfff4;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -moz-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -o-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -ms-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfff4', endColorstr='#b3bead',GradientType=0 );_x000D_
    margin: 20px auto;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    -moz-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.squaredTwo label {_x000D_
    cursor: pointer;_x000D_
    position: absolute;_x000D_
    width: 20px;_x000D_
    height: 20px;_x000D_
    left: 4px;_x000D_
    top: 4px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -moz-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -o-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -ms-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#222', endColorstr='#45484d',GradientType=0 );_x000D_
}_x000D_
_x000D_
.squaredTwo label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
    filter: alpha(opacity=0);_x000D_
    opacity: 0;_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    width: 9px;_x000D_
    height: 5px;_x000D_
    background: transparent;_x000D_
    top: 4px;_x000D_
    left: 4px;_x000D_
    border: 3px solid #fcfff4;_x000D_
    border-top: none;_x000D_
    border-right: none;_x000D_
_x000D_
    -webkit-transform: rotate(-45deg);_x000D_
    -moz-transform: rotate(-45deg);_x000D_
    -o-transform: rotate(-45deg);_x000D_
    -ms-transform: rotate(-45deg);_x000D_
    transform: rotate(-45deg);_x000D_
}_x000D_
_x000D_
.squaredTwo label:hover::after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=30)";_x000D_
    filter: alpha(opacity=30);_x000D_
    opacity: 0.3;_x000D_
}_x000D_
_x000D_
.squaredTwo input[type=checkbox]:checked + label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";_x000D_
    filter: alpha(opacity=100);_x000D_
    opacity: 1;_x000D_
}_x000D_
_x000D_
_x000D_
/* SQUARED THREE */_x000D_
.squaredThree {_x000D_
    width: 20px;    _x000D_
    margin: 20px auto;_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.squaredThree label {_x000D_
    cursor: pointer;_x000D_
    position: absolute;_x000D_
    width: 20px;_x000D_
    height: 20px;_x000D_
    top: 0;_x000D_
    border-radius: 4px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,.4);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,.4);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,.4);_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -moz-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -o-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -ms-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#222', endColorstr='#45484d',GradientType=0 );_x000D_
}_x000D_
_x000D_
.squaredThree label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
    filter: alpha(opacity=0);_x000D_
    opacity: 0;_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    width: 9px;_x000D_
    height: 5px;_x000D_
    background: transparent;_x000D_
    top: 4px;_x000D_
    left: 4px;_x000D_
    border: 3px solid #fcfff4;_x000D_
    border-top: none;_x000D_
    border-right: none;_x000D_
_x000D_
    -webkit-transform: rotate(-45deg);_x000D_
    -moz-transform: rotate(-45deg);_x000D_
    -o-transform: rotate(-45deg);_x000D_
    -ms-transform: rotate(-45deg);_x000D_
    transform: rotate(-45deg);_x000D_
}_x000D_
_x000D_
.squaredThree label:hover::after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=30)";_x000D_
    filter: alpha(opacity=30);_x000D_
    opacity: 0.3;_x000D_
}_x000D_
_x000D_
.squaredThree input[type=checkbox]:checked + label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";_x000D_
    filter: alpha(opacity=100);_x000D_
    opacity: 1;_x000D_
}_x000D_
_x000D_
/* SQUARED FOUR */_x000D_
.squaredFour {_x000D_
    width: 20px;    _x000D_
    margin: 20px auto;_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.squaredFour label {_x000D_
    cursor: pointer;_x000D_
    position: absolute;_x000D_
    width: 20px;_x000D_
    height: 20px;_x000D_
    top: 0;_x000D_
    border-radius: 4px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    -moz-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    background: #fcfff4;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -moz-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -o-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -ms-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfff4', endColorstr='#b3bead',GradientType=0 );_x000D_
}_x000D_
_x000D_
.squaredFour label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
    filter: alpha(opacity=0);_x000D_
    opacity: 0;_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    width: 9px;_x000D_
    height: 5px;_x000D_
    background: transparent;_x000D_
    top: 4px;_x000D_
    left: 4px;_x000D_
    border: 3px solid #333;_x000D_
    border-top: none;_x000D_
    border-right: none;_x000D_
_x000D_
    -webkit-transform: rotate(-45deg);_x000D_
    -moz-transform: rotate(-45deg);_x000D_
    -o-transform: rotate(-45deg);_x000D_
    -ms-transform: rotate(-45deg);_x000D_
    transform: rotate(-45deg);_x000D_
}_x000D_
_x000D_
.squaredFour label:hover::after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=30)";_x000D_
    filter: alpha(opacity=30);_x000D_
    opacity: 0.5;_x000D_
}_x000D_
_x000D_
.squaredFour input[type=checkbox]:checked + label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";_x000D_
    filter: alpha(opacity=100);_x000D_
    opacity: 1;_x000D_
}
_x000D_
<h1>CSS3 Checkbox Styles</h1>_x000D_
_x000D_
<!-- Slide ONE -->_x000D_
<div class="slideOne">  _x000D_
    <input type="checkbox" value="None" id="slideOne" name="check" />_x000D_
    <label for="slideOne"></label>_x000D_
</div>_x000D_
_x000D_
<!-- Slide TWO -->_x000D_
<div class="slideTwo">  _x000D_
    <input type="checkbox" value="None" id="slideTwo" name="check" />_x000D_
    <label for="slideTwo"></label>_x000D_
</div>_x000D_
_x000D_
<!-- Slide THREE -->_x000D_
<div class="slideThree">    _x000D_
    <input type="checkbox" value="None" id="slideThree" name="check" />_x000D_
    <label for="slideThree"></label>_x000D_
</div>_x000D_
_x000D_
<!-- Rounded ONE -->_x000D_
<div class="roundedOne">_x000D_
    <input type="checkbox" value="None" id="roundedOne" name="check" />_x000D_
    <label for="roundedOne"></label>_x000D_
</div>_x000D_
_x000D_
<!-- Rounded TWO -->_x000D_
<div class="roundedTwo">_x000D_
    <input type="checkbox" value="None" id="roundedTwo" name="check" />_x000D_
    <label for="roundedTwo"></label>_x000D_
</div>_x000D_
_x000D_
<!-- Squared ONE -->_x000D_
<div class="squaredOne">_x000D_
    <input type="checkbox" value="None" id="squaredOne" name="check" />_x000D_
    <label for="squaredOne"></label>_x000D_
</div>_x000D_
_x000D_
<!-- Squared TWO -->_x000D_
<div class="squaredTwo">_x000D_
    <input type="checkbox" value="None" id="squaredTwo" name="check" />_x000D_
    <label for="squaredTwo"></label>_x000D_
</div>_x000D_
_x000D_
<!-- Squared THREE -->_x000D_
<div class="squaredThree">_x000D_
    <input type="checkbox" value="None" id="squaredThree" name="check" />_x000D_
    <label for="squaredThree"></label>_x000D_
</div>_x000D_
_x000D_
<!-- Squared FOUR -->_x000D_
<div class="squaredFour">_x000D_
    <input type="checkbox" value="None" id="squaredFour" name="check" />_x000D_
    <label for="squaredFour"></label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to extract 1 screenshot for a video with ffmpeg at a given time?

Use the -ss option:

ffmpeg -ss 01:23:45 -i input -vframes 1 -q:v 2 output.jpg
  • For JPEG output use -q:v to control output quality. Full range is a linear scale of 1-31 where a lower value results in a higher quality. 2-5 is a good range to try.

  • The select filter provides an alternative method for more complex needs such as selecting only certain frame types, or 1 per 100, etc.

  • Placing -ss before the input will be faster. See FFmpeg Wiki: Seeking and this excerpt from the ffmpeg cli tool documentation:

-ss position (input/output)

When used as an input option (before -i), seeks in this input file to position. Note the in most formats it is not possible to seek exactly, so ffmpeg will seek to the closest seek point before position. When transcoding and -accurate_seek is enabled (the default), this extra segment between the seek point and position will be decoded and discarded. When doing stream copy or when -noaccurate_seek is used, it will be preserved.

When used as an output option (before an output filename), decodes but discards input until the timestamps reach position.

position may be either in seconds or in hh:mm:ss[.xxx] form.

c# foreach (property in object)... Is there a simple way of doing this?

Your'e almost there, you just need to get the properties from the type, rather than expect the properties to be accessible in the form of a collection or property bag:

var property in obj.GetType().GetProperties()

From there you can access like so:

property.Name
property.GetValue(obj, null)

With GetValue the second parameter will allow you to specify index values, which will work with properties returning collections - since a string is a collection of chars, you can also specify an index to return a character if needs be.

open link of google play store in mobile version android

You can check if the Google Play Store app is installed and, if this is the case, you can use the "market://" protocol.

final String my_package_name = "........."  // <- HERE YOUR PACKAGE NAME!!
String url = "";

try {
    //Check whether Google Play store is installed or not:
    this.getPackageManager().getPackageInfo("com.android.vending", 0);

    url = "market://details?id=" + my_package_name;
} catch ( final Exception e ) {
    url = "https://play.google.com/store/apps/details?id=" + my_package_name;
}


//Open the app page in Google Play store:
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(intent);

disable past dates on datepicker

$(function () {
    $("#date").datepicker({ minDate: 0 });
});

trying to animate a constraint in swift

With Swift 5 and iOS 12.3, according to your needs, you may choose one of the 3 following ways in order to solve your problem.


#1. Using UIView's animate(withDuration:animations:) class method

animate(withDuration:animations:) has the following declaration:

Animate changes to one or more views using the specified duration.

class func animate(withDuration duration: TimeInterval, animations: @escaping () -> Void)

The Playground code below shows a possible implementation of animate(withDuration:animations:) in order to animate an Auto Layout constraint's constant change.

import UIKit
import PlaygroundSupport

class ViewController: UIViewController {

    let textView = UITextView()
    lazy var heightConstraint = textView.heightAnchor.constraint(equalToConstant: 50)

    override func viewDidLoad() {
        view.backgroundColor = .white
        view.addSubview(textView)

        textView.backgroundColor = .orange
        textView.isEditable = false
        textView.text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

        textView.translatesAutoresizingMaskIntoConstraints = false
        textView.topAnchor.constraint(equalToSystemSpacingBelow: view.layoutMarginsGuide.topAnchor, multiplier: 1).isActive = true
        textView.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor).isActive = true
        textView.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor).isActive = true
        heightConstraint.isActive = true

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(doIt(_:)))
        textView.addGestureRecognizer(tapGesture)
    }

    @objc func doIt(_ sender: UITapGestureRecognizer) {
        heightConstraint.constant = heightConstraint.constant == 50 ? 150 : 50
        UIView.animate(withDuration: 2) {
            self.view.layoutIfNeeded()
        }
    }

}

PlaygroundPage.current.liveView = ViewController()

#2. Using UIViewPropertyAnimator's init(duration:curve:animations:) initialiser and startAnimation() method

init(duration:curve:animations:) has the following declaration:

Initializes the animator with a built-in UIKit timing curve.

convenience init(duration: TimeInterval, curve: UIViewAnimationCurve, animations: (() -> Void)? = nil)

The Playground code below shows a possible implementation of init(duration:curve:animations:) and startAnimation() in order to animate an Auto Layout constraint's constant change.

import UIKit
import PlaygroundSupport

class ViewController: UIViewController {

    let textView = UITextView()
    lazy var heightConstraint = textView.heightAnchor.constraint(equalToConstant: 50)

    override func viewDidLoad() {
        view.backgroundColor = .white
        view.addSubview(textView)

        textView.backgroundColor = .orange
        textView.isEditable = false
        textView.text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

        textView.translatesAutoresizingMaskIntoConstraints = false
        textView.topAnchor.constraint(equalToSystemSpacingBelow: view.layoutMarginsGuide.topAnchor, multiplier: 1).isActive = true
        textView.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor).isActive = true
        textView.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor).isActive = true
        heightConstraint.isActive = true

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(doIt(_:)))
        textView.addGestureRecognizer(tapGesture)
    }

    @objc func doIt(_ sender: UITapGestureRecognizer) {
        heightConstraint.constant = heightConstraint.constant == 50 ? 150 : 50
        let animator = UIViewPropertyAnimator(duration: 2, curve: .linear, animations: {
            self.view.layoutIfNeeded()
        })
        animator.startAnimation()
    }

}

PlaygroundPage.current.liveView = ViewController()

#3. Using UIViewPropertyAnimator's runningPropertyAnimator(withDuration:delay:options:animations:completion:) class method

runningPropertyAnimator(withDuration:delay:options:animations:completion:) has the following declaration:

Creates and returns an animator object that begins running its animations immediately.

class func runningPropertyAnimator(withDuration duration: TimeInterval, delay: TimeInterval, options: UIViewAnimationOptions = [], animations: @escaping () -> Void, completion: ((UIViewAnimatingPosition) -> Void)? = nil) -> Self

The Playground code below shows a possible implementation of runningPropertyAnimator(withDuration:delay:options:animations:completion:) in order to animate an Auto Layout constraint's constant change.

import UIKit
import PlaygroundSupport

class ViewController: UIViewController {

    let textView = UITextView()
    lazy var heightConstraint = textView.heightAnchor.constraint(equalToConstant: 50)

    override func viewDidLoad() {
        view.backgroundColor = .white
        view.addSubview(textView)

        textView.backgroundColor = .orange
        textView.isEditable = false
        textView.text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

        textView.translatesAutoresizingMaskIntoConstraints = false
        textView.topAnchor.constraint(equalToSystemSpacingBelow: view.layoutMarginsGuide.topAnchor, multiplier: 1).isActive = true
        textView.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor).isActive = true
        textView.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor).isActive = true
        heightConstraint.isActive = true

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(doIt(_:)))
        textView.addGestureRecognizer(tapGesture)
    }

    @objc func doIt(_ sender: UITapGestureRecognizer) {
        heightConstraint.constant = heightConstraint.constant == 50 ? 150 : 50
        UIViewPropertyAnimator.runningPropertyAnimator(withDuration: 2, delay: 0, options: [], animations: {
            self.view.layoutIfNeeded()
        })
    }

}

PlaygroundPage.current.liveView = ViewController()

Java Could not reserve enough space for object heap error

If you go thru this IBM link on java, it says that on 32 bit windows the recommended heap size is 1.5 GB and the Maximum heap size is 1.8 GB. So your jvm does not gets initialized for -Xmx2G and above.

Also if you go thru this SO answer, clearly the DLL bindings are an issue for memory reservation changing which is no trivial task. Hence what may be recommended is that you go for 64-bit Windows and a 64-bit JVM. while it will chew up more RAM, you will have much more contiguous virtual address space.

What's the best CRLF (carriage return, line feed) handling strategy with Git?

This is just a workaround solution:

In normal cases, use the solutions that are shipped with git. These work great in most cases. Force to LF if you share the development on Windows and Unix based systems by setting .gitattributes.

In my case there were >10 programmers developing a project in Windows. This project was checked in with CRLF and there was no option to force to LF.

Some settings were internally written on my machine without any influence on the LF format; thus some files were globally changed to LF on each small file change.

My solution:

Windows-Machines: Let everything as it is. Care about nothing, since you are a default windows 'lone wolf' developer and you have to handle like this: "There is no other system in the wide world, is it?"

Unix-Machines

  1. Add following lines to a config's [alias] section. This command lists all changed (i.e. modified/new) files:

    lc = "!f() { git status --porcelain \
                 | egrep -r \"^(\?| ).\*\\(.[a-zA-Z])*\" \
                 | cut -c 4- ; }; f "
    
  2. Convert all those changed files into dos format:

    unix2dos $(git lc)
    
  3. Optionally ...

    1. Create a git hook for this action to automate this process

    2. Use params and include it and modify the grep function to match only particular filenames, e.g.:

      ... | egrep -r "^(\?| ).*\.(txt|conf)" | ...
      
    3. Feel free to make it even more convenient by using an additional shortcut:

      c2dos = "!f() { unix2dos $(git lc) ; }; f "
      

      ... and fire the converted stuff by typing

      git c2dos
      

standard size for html newsletter template

Bdizzle,

I would recommend that you read this link

You will see that Newsletters can have different widths, There seems to be no major standard, What is recommended is that the width will be about 95% of the page width, as different browsers use the extra margins differently. You will also find that email readers have problems when reading css so applying the guide lines in this tutorial might help you save some time and trouble-shooting down the road.

Be happy, Julian

How to give color to each class in scatter plot in R?

Here is how I do it in 2018. Who knows, maybe an R newbie will see it one day and fall in love with ggplot2.

library(ggplot2)

ggplot(data = iris, aes(Petal.Length, Petal.Width, color = Species)) +
  geom_point() +
  scale_color_manual(values = c("setosa" = "red", "versicolor" = "blue", "virginica" = "yellow"))

MySQL root password change

Or just use interactive configuration:

sudo mysql_secure_installation

What exactly is the difference between Web API and REST API in MVC?

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

REST

RESTs sweet spot is when you are exposing a public API over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface.

SOAP

SOAP brings it’s own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.

Though SOAP is commonly referred to as “web services” this is a misnomer. SOAP has very little if anything to do with the Web. REST provides true “Web services” based on URIs and HTTP.

Reference: http://spf13.com/post/soap-vs-rest

And finally: What they could be referring to is REST vs. RPC See this: http://encosia.com/rest-vs-rpc-in-asp-net-web-api-who-cares-it-does-both/

Can we use join for two different database tables?

You could use Synonyms part in the database.

enter image description here

Then in view wizard from Synonyms tab find your saved synonyms and add to view and set inner join simply. enter image description here

How to Correctly handle Weak Self in Swift Blocks with Arguments

Use Capture list

Defining a Capture List

Each item in a capture list is a pairing of the weak or unowned keyword with a reference to a class instance (such as self) or a variable initialized with some value (such as delegate = self.delegate!). These pairings are written within a pair of square braces, separated by commas.

Place the capture list before a closure’s parameter list and return type if they are provided:

lazy var someClosure: (Int, String) -> String = {
    [unowned self, weak delegate = self.delegate!] (index: Int, stringToProcess: String) -> String in
    // closure body goes here 
} 

If a closure does not specify a parameter list or return type because they can be inferred from context, place the capture list at the very start of the closure, followed by the in keyword:

lazy var someClosure: Void -> String = {
    [unowned self, weak delegate = self.delegate!] in
    // closure body goes here
}

additional explanations

Convert DataTable to List<T>

There is a little example that you can use

            DataTable dt = GetCustomersDataTable(null);            

            IEnumerable<SelectListItem> lstCustomer = dt.AsEnumerable().Select(x => new SelectListItem()
            {
                Value = x.Field<string>("CustomerId"),
                Text = x.Field<string>("CustomerDescription")
            }).ToList();

            return lstCustomer;

How to retrieve a single file from a specific revision in Git?

Using git show $REV:$FILE as it was already pointed out by others is probably the right answer. I'm posting another answer because when I tried this method, I sometimes got the following error from git:

fatal: path 'link/foo' exists on disk, but not in 'HEAD'

The problem occurs when parts of the path to the file are a symbolic link. In those cases, the git show $REV:$FILE method will not work. Steps to reproduce:

$ git init .
$ mkdir test
$ echo hello > test/foo
$ ln -s test link
$ git add .
$ git commit -m "initial commit"
$ cat link/foo
hello
$ git show HEAD:link/foo
fatal: path 'link/foo' exists on disk, but not in 'HEAD'

The problem is, that utilities like realpath don't help here, because the symlink might not exist in the current commit anymore. I don't know about a good general solution. In my case, I knew that the symlink could only exist in the first component of the path, so I solved the problem by using the git show $REV:$FILE method twice. This works, because when git show $REV:$FILE is used on a symlink, then its target gets printed:

$ git show HEAD:link
test

Whereas with directories, the command will output a header, followed by the directory content:

$ git show HEAD:test
tree HEAD:test

foo

So in my case, I just checked the output of the first call to git show $REV:$FILE and if it was only a single line, then I replaced the first component of my path with the result to resolve the symlink through git.

Settings to Windows Firewall to allow Docker for Windows to share drive

None of the suggestions above worked for me, but uninstalling Docker Desktop (restart PC) and reinstalling Docked finally resolved the issue.

Jquery select this + class

if you need a performance trick use below:

$(".yourclass", this);

find() method makes a search everytime in selector.

Looping through rows in a DataView

The DataView object itself is used to loop through DataView rows.

DataView rows are represented by the DataRowView object. The DataRowView.Row property provides access to the original DataTable row.

C#

foreach (DataRowView rowView in dataView)
{
    DataRow row = rowView.Row;
    // Do something //
}

VB.NET

For Each rowView As DataRowView in dataView
    Dim row As DataRow = rowView.Row
    ' Do something '
Next

Elegant ways to support equivalence ("equality") in Python classes

The way you describe is the way I've always done it. Since it's totally generic, you can always break that functionality out into a mixin class and inherit it in classes where you want that functionality.

class CommonEqualityMixin(object):

    def __eq__(self, other):
        return (isinstance(other, self.__class__)
            and self.__dict__ == other.__dict__)

    def __ne__(self, other):
        return not self.__eq__(other)

class Foo(CommonEqualityMixin):

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

Laravel 5 route not defined, while it is?

I'm using Laravel 5.7 and tried all of the above answers but nothing seemed to be hitting the spot.

For me, it was a rather simple fix by removing the cache files created by Laravel.
It seemed that my changes were not being reflected, and therefore my application wasn't seeing the routes.

A bit overkill, but I decided to reset all my cache at the same time using the following commands:

php artisan route:clear
php artisan view:clear
php artisan cache:clear

The main one here is the first command which will delete the bootstrap/cache/routes.php file.
The second command will remove the cached files for the views that are stored in the storage/framework/cache folder.
Finally, the last command will clear the application cache.

How do relative file paths work in Eclipse?

Yeah, eclipse sees the top directory as the working/root directory, for the purposes of paths.

...just thought I'd add some extra info. I'm new here! I'd like to help.

How can I get CMake to find my alternative Boost installation?

I ran into a similar problem on a Linux server, where two versions of Boost have been installed. One is the precompiled 1.53.0 version which counts as old in 2018; it's in /usr/include and /usr/lib64. The version I want to use is 1.67.0, as a minimum version of 1.65.1 is required for another C++ library I'm installing; it's in /opt/boost, which has include and lib subdirectories. As suggested in previous answers, I set variables in CMakeLists.txt to specify where to look for Boost 1.67.0 as follows

include_directories(/opt/boost/include/)
include_directories(/opt/boost/lib/)
set(BOOST_ROOT /opt/boost/)
set(BOOST_INCLUDEDIR /opt/boost/include/)
set(BOOST_LIBRARYDIR /opt/boost/lib)
set(Boost_NO_SYSTEM_PATHS TRUE)
set(Boost_NO_BOOST_CMAKE TRUE)

But CMake doesn't honor those changes. Then I found an article online: CMake can use a local Boost, and realized that I need to change the variables in CMakeCache.txt. There I found that the Boost-related variables are still pointing to the default Boost 1.53.0, so no wonder CMake doesn't honor my changes in CMakeLists.txt. Then I set the Boost-related variables in CMakeCache.txt

Boost_DIR:PATH=Boost_DIR-NOTFOUND
Boost_INCLUDE_DIR:PATH=/opt/boost/include/
Boost_LIBRARY_DIR_DEBUG:PATH=/opt/boost/lib
Boost_LIBRARY_DIR_RELEASE:PATH=/opt/boost/lib

I also changed the variables pointing to the non-header, compiled parts of the Boost library to point to the version I want. Then CMake successfully built the library that depends on a recent version of Boost.

return, return None, and no return at all?

In terms of functionality these are all the same, the difference between them is in code readability and style (which is important to consider)

How to set 00:00:00 using moment.js

You've not shown how you're creating the string 2016-01-12T23:00:00.000Z, but I assume via .format().

Anyway, .set() is using your local time zone, but the Z in the time string indicates zero time, otherwise known as UTC.

https://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators

So I assume your local timezone is 23 hours from UTC?

saikumar's answer showed how to load the time in as UTC, but the other option is to use a .format() call that outputs using your local timezone, rather than UTC.

http://momentjs.com/docs/#/get-set/
http://momentjs.com/docs/#/displaying/format/

How do I modify the URL without reloading the page?

This code works for me. I used it into my application in ajax.

history.pushState({ foo: 'bar' }, '', '/bank');

Once a page load into an ID using ajax, It does change the browser url automatically without reloading the page.

This is ajax function bellow.

function showData(){
    $.ajax({
      type: "POST",
      url: "Bank.php", 
      data: {}, 
      success: function(html){          
        $("#viewpage").html(html).show();
        $("#viewpage").css("margin-left","0px");
      }
    });
  }

Example: From any page or controller like "Dashboard", When I click on the bank, it loads bank list using the ajax code without reloading the page. At this time, browser URL will not be changed.

history.pushState({ foo: 'bar' }, '', '/bank');

But when I use this code into the ajax, it change the browser url without reloading the page. This is the full ajax code here in the bellow.

function showData(){
        $.ajax({
          type: "POST",
          url: "Bank.php", 
          data: {}, 
          success: function(html){          
            $("#viewpage").html(html).show();
            $("#viewpage").css("margin-left","0px");
            history.pushState({ foo: 'bar' }, '', '/bank');
          }
        });
      }

Select all DIV text with single mouse click

There is pure CSS4 solution:

.selectable{
    -webkit-touch-callout: all; /* iOS Safari */
    -webkit-user-select: all; /* Safari */
    -khtml-user-select: all; /* Konqueror HTML */
    -moz-user-select: all; /* Firefox */
    -ms-user-select: all; /* Internet Explorer/Edge */
    user-select: all; /* Chrome and Opera */

}

user-select is a CSS Module Level 4 specification, that is currently a draft and non-standard CSS property, but browsers support it well — see #search=user-select.

_x000D_
_x000D_
.selectable{
    -webkit-touch-callout: all; /* iOS Safari */
    -webkit-user-select: all; /* Safari */
    -khtml-user-select: all; /* Konqueror HTML */
    -moz-user-select: all; /* Firefox */
    -ms-user-select: all; /* Internet Explorer/Edge */
    user-select: all; /* Chrome and Opera */

}
_x000D_
<div class="selectable">
click and all this will be selected
</div>
_x000D_
_x000D_
_x000D_

Read more on user-select here on MDN and play with it here in w3scools

Font Awesome icon inside text input element

You're right. :before and :after pseudo content is not intended to work on replaced content like img and input elements. Adding a wrapping element and declare a font-family is one of the possibilities, as is using a background image. Or maybe a html5 placeholder text fits your needs:

<input name="username" placeholder="&#61447;">

Browsers that don’t support the placeholder attribute will simply ignore it.

UPDATE

The before content selector selects the input: input[type="text"]:before. You should select the wrapper: .wrapper:before. See http://jsfiddle.net/allcaps/gA4rx/ . I also added the placeholder suggestion where the wrapper is redundant.

.wrapper input[type="text"] {
    position: relative; 
}

input { font-family: 'FontAwesome'; } /* This is for the placeholder */

.wrapper:before {
    font-family: 'FontAwesome';
    color:red;
    position: relative;
    left: -5px;
    content: "\f007";
}

<p class="wrapper"><input placeholder="&#61447; Username"></p>

Fallback

Font Awesome uses the Unicode Private Use Area (PUA) to store icons. Other characters are not present and fall back to the browser default. That should be the same as any other input. If you define a font on input elements, then supply the same font as fallback for situations where us use an icon. Like this:

input { font-family: 'FontAwesome', YourFont; }

Mocking Logger and LoggerFactory with PowerMock and Mockito

I think you can reset the invocations using Mockito.reset(mockLog). You should call this before every test, so inside @Before would be a good place.

How can I quantify difference between two images?

Check out how Haar Wavelets are implemented by isk-daemon. You could use it's imgdb C++ code to calculate the difference between images on-the-fly:

isk-daemon is an open source database server capable of adding content-based (visual) image searching to any image related website or software.

This technology allows users of any image-related website or software to sketch on a widget which image they want to find and have the website reply to them the most similar images or simply request for more similar photos at each image detail page.

mysqli_real_connect(): (HY000/2002): No such file or directory

I'm trying this before

cd /opt/lampp/phpmyadmin

Then

gedit config.inc.php

Find this

$cfg['Servers'][$i]['host'] = 

If there is localhost change it to 127.0.0.1

Note : if there is '//' remove // before $cfg['Servers'][$i]['host']

I checked again http://localhost/phpmyadmin/

Mysqli said:

"phpMyAdmin tried to connect to the MySQL server, and the server rejected the connection. You should check the host, username and password in your configuration and make sure that they correspond to the information given by the administrator of the MySQL server."

I'm opening again config.inc.php and I found

$cfg['Servers'][$i]['password'] =

Fill the password with your password

It worked for me. It may work for you too.

Not equal <> != operator on NULL

The only test for NULL is IS NULL or IS NOT NULL. Testing for equality is nonsensical because by definition one doesn't know what the value is.

Here is a wikipedia article to read:

https://en.wikipedia.org/wiki/Null_(SQL)

invalid use of incomplete type

You can get around this by using a traits class:
It requires you set up a specialsed traits class for each actuall class you use.

template<typename SubClass>
class SubClass_traits
{};

template<typename Subclass>
class A {
    public:
        void action(typename SubClass_traits<Subclass>::mytype var)
        {
                (static_cast<Subclass*>(this))->do_action(var);
        }
};


// Definitions for B
class B;   // Forward declare

template<> // Define traits for B. So other classes can use it.
class SubClass_traits<B>
{
    public:
        typedef int mytype;
};

// Define B
class B : public A<B>
{
    // Define mytype in terms of the traits type.
    typedef SubClass_traits<B>::mytype  mytype;
    public:

        B() {}

        void do_action(mytype var) {
                // Do stuff
        }
};

int main(int argc, char** argv)
{
    B myInstance;
    return 0;
} 

RSA: Get exponent and modulus given a public key

Beware the leading 00 that can appear in the modulus when using:

openssl rsa -pubin -inform PEM -text -noout < public.key

The example modulus contains 257 bytes rather than 256 bytes because of that 00, which is included because the 9 in 98 looks like a negative signed number.

How can I add (simple) tracing in C#?

I followed around five different answers as well as all the blog posts in the previous answers and still had problems. I was trying to add a listener to some existing code that was tracing using the TraceSource.TraceEvent(TraceEventType, Int32, String) method where the TraceSource object was initialised with a string making it a 'named source'.

For me the issue was not creating a valid combination of source and switch elements to target this source. Here is an example that will log to a file called tracelog.txt. For the following code:

TraceSource source = new TraceSource("sourceName");
source.TraceEvent(TraceEventType.Verbose, 1, "Trace message");

I successfully managed to log with the following diagnostics configuration:

<system.diagnostics>
    <sources>
        <source name="sourceName" switchName="switchName">
            <listeners>
                <add
                    name="textWriterTraceListener"
                    type="System.Diagnostics.TextWriterTraceListener"
                    initializeData="tracelog.txt" />
            </listeners>
        </source>
    </sources>

    <switches>
        <add name="switchName" value="Verbose" />
    </switches>
</system.diagnostics>

How can I force a hard reload in Chrome for Android

The only reliable way I've found that doesn't require plugging the phone in to a PC is as follows:

1. Force stop the Chrome app.

This must be done first, and you cannot re-open Chrome until you finish these steps. There are several ways to force stop. Most home launchers will let you get to "App info" by holding down your finger on the chrome icon and selecting an "i" icon. Alternately, you may be able to go to Android settings and simply search for "Chrome".

Once in "App info", select "Force stop" as shown below:


2. Clear Chrome's cache

Select "Storage" from the same screen:


Finally, select "Clear cache".

When you return to the Chrome app, the page should reload itself and serve a non-cached version.

Additionally, I found a site that makes it easy to test if you've cleared your cache: https://refreshyourcache.com/en/cache-test/
I am in no way affiliated with it. Note that the method to clear the cache mentioned on that site is in fact outdated and no longer valid.

How to install Python packages from the tar.gz file without using pip install

For those of you using python3 you can use:

python3 setup.py install

allowing only alphabets in text box using java script

You can use HTML5 pattern attribute to do this:

<form>
    <input type='text' pattern='[A-Za-z\\s]*'/>
</form>

If the user enters an input that conflicts with the pattern, it will show an error dialogue automatically.

How can I split a shell command over multiple lines when using an IF statement?

The line-continuation will fail if you have whitespace (spaces or tab characters[1]) after the backslash and before the newline. With no such whitespace, your example works fine for me:

$ cat test.sh
if ! fab --fabfile=.deploy/fabfile.py \
   --forward-agent \
   --disable-known-hosts deploy:$target; then
     echo failed
else
     echo succeeded
fi

$ alias fab=true; . ./test.sh
succeeded
$ alias fab=false; . ./test.sh
failed

Some detail promoted from the comments: the line-continuation backslash in the shell is not really a special case; it is simply an instance of the general rule that a backslash "quotes" the immediately-following character, preventing any special treatment it would normally be subject to. In this case, the next character is a newline, and the special treatment being prevented is terminating the command. Normally, a quoted character winds up included literally in the command; a backslashed newline is instead deleted entirely. But otherwise, the mechanism is the same. Most importantly, the backslash only quotes the immediately-following character; if that character is a space or tab, you just get a literal space or tab, and any subsequent newline remains unquoted.

[1] or carriage returns, for that matter, as Czechnology points out. Bash does not get along with Windows-formatted text files, not even in WSL. Or Cygwin, but at least their Bash port has added a set -o igncr option that you can set to make it carriage-return-tolerant.

How to delete Tkinter widgets from a window?


clear_btm=Button(master,text="Clear") #this button will delete the widgets 
clear_btm["command"] = lambda one = button1, two = text1, three = entry1: clear(one,two,three) #pass the widgets
clear_btm.pack()

def clear(*widgets):
    for widget in widgets:
        widget.destroy() #finally we are deleting the widgets.

Formula px to dp, dp to px android

The answer accepted above is not fully accurate. According to information obtained by inspecting Android source code:

Resources.getDimension() and getDimensionPixelOffset()/getDimensionPixelSize() differ only in that the former returns float while the latter two return the same value rounded to int appropriatelly. For all of them, the return value is in raw pixels.

All three functions are implementedy by calling Resources.getValue() and converting thus obtained TypedValue by calling TypedValue.complexToDimension(), TypedValue.complexToDimensionPixelOffset() and TypedValue.complexToDimensionPixelSize(), respectively.

Therefore, if you want to obtain "raw" value together with the unit specified in XML source, call Resources.getValue() and use methods of the TypedValue class.

How to autosize and right-align GridViewColumn data in WPF?

If the width of the contents changes, you'll have to use this bit of code to update each column:

private void ResizeGridViewColumn(GridViewColumn column)
{
    if (double.IsNaN(column.Width))
    {
        column.Width = column.ActualWidth;
    }

    column.Width = double.NaN;
}

You'd have to fire it each time the data for that column updates.

Rails ActiveRecord date between

If you only want to get one day it would be easier this way:

Comment.all(:conditions => ["date(created_at) = ?", some_date])

How to update data in one table from corresponding data in another table in SQL Server 2005

 UPDATE Employee SET Empid=emp3.empid 
 FROM EMP_Employee AS emp3
 WHERE Employee.Empid=emp3.empid

How do I rename a Git repository?

With Github As Your Remote

Renaming the Remote Repo on Github

Regarding the remote repository, if you are using Github or Github Enterprise as the server location for saving/distributing your repository remotely, you can simply rename the repository directly in the repo settings.

From the main repo page, the settings tab is on the right, and the repo name is the first item on the page:

enter image description here

Github will redirect requests to the new URL

One very nice feature in Github when you rename a repo, is that Github will save the old repo name and all the related URLs and redirect traffic to the new URLs. Since your username/org and repo name are a part of the URL, a rename will change the URL.

Since Github saves the old repo name and redirects requests to the new URLs, if anyone uses links based on the old repo name when trying to access issues, wiki, stars, or followers they will still arrive at the new location on the Github website. Github also redirects lower level Git commands like git clone, git fetch, etc.

More information is in the Github Help for Renaming a Repo

Renaming the Local Repo Name

As others have mentioned, the local "name" of your repo is typically considered to be the root folder/directory name, and you can change that, move, or copy the folder to any location and it will not affect the repo at all.

Git is designed to only worry about files inside the root folder.

Shall we always use [unowned self] inside closure in Swift

There are some great answers here. But recent changes to how Swift implements weak references should change everyone's weak self vs. unowned self usage decisions. Previously, if you needed the best performance using unowned self was superior to weak self, as long as you could be certain that self would never be nil, because accessing unowned self is much faster than accessing weak self.

But Mike Ash has documented how Swift has updated the implementation of weak vars to use side-tables and how this substantially improves weak self performance.

https://mikeash.com/pyblog/friday-qa-2017-09-22-swift-4-weak-references.html

Now that there isn't a significant performance penalty to weak self, I believe we should default to using it going forward. The benefit of weak self is that it's an optional, which makes it far easier to write more correct code, it's basically the reason Swift is such a great language. You may think you know which situations are safe for the use of unowned self, but my experience reviewing lots of other developers code is, most don't. I've fixed lots of crashes where unowned self was deallocated, usually in situations where a background thread completes after a controller is deallocated.

Bugs and crashes are the most time-consuming, painful and expensive parts of programming. Do your best to write correct code and avoid them. I recommend making it a rule to never force unwrap optionals and never use unowned self instead of weak self. You won't lose anything missing the times force unwrapping and unowned self actually are safe. But you'll gain a lot from eliminating hard to find and debug crashes and bugs.

Structuring online documentation for a REST API

That's a very complex question for a simple answer.

You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.

Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.

At the very top level I think quality REST API docs require at least the following:

  • a list of all your API endpoints (base/relative URLs)
  • corresponding HTTP GET/POST/... method type for each endpoint
  • request/response MIME-type (how to encode params and parse replies)
  • a sample request/response, including HTTP headers
  • type and format specified for all params, including those in the URL, body and headers
  • a brief text description and important notes
  • a short code snippet showing the use of the endpoint in popular web programming languages

Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.

HTML text input field with currency symbol

None of these answers really help if you are concerned with aligning the left border with other text fields on an input form.

I'd recommend positioning the dollar sign absolutely to the left about -10px or left 5px (depending whether you want it inside or outside the input box). The inside solution requires direction:rtl on the input css.

You could also add padding to the input to avoid the direction:rtl, but that will alter the width of the input container to not match the other containers of the same width.

<div style="display:inline-block">
 <div style="position:relative">
  <div style="position:absolute; left:-10px;">$</div>
 </div>
 <input type='text' />
</div>

or

<div style="display:inline-block">
 <div style="position:relative">
  <div style="position:absolute; left:5px;">$</div>
 </div>
 <input type='text' style='direction: rtl;' />
</div>

https://i.imgur.com/ajrU0T9.png

Example: https://plnkr.co/edit/yshyuRMd06K1cuN9tFDv?p=preview

MySQL set current date in a DATETIME field on insert

Using Now() is not a good idea. It only save the current time and date. It will not update the the current date and time, when you update your data. If you want to add the time once, The default value =Now() is best option. If you want to use timestamp. and want to update the this value, each time that row is updated. Then, trigger is best option to use.

  1. http://www.mysqltutorial.org/sql-triggers.aspx
  2. http://www.tutorialspoint.com/plsql/plsql_triggers.htm

These two toturial will help to implement the trigger.

How do I iterate through the files in a directory in Java?

Using org.apache.commons.io.FileUtils

File file = new File("F:/Lines");       
Collection<File> files = FileUtils.listFiles(file, null, true);     
for(File file2 : files){
    System.out.println(file2.getName());            
} 

Use false if you do not want files from sub directories.

Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax

request parameter exist for both GET and POST ,For Get it will get appended as query string to URL but for POST it is within Request Body

List all liquibase sql types

I've found the liquibase.database.typeconversion.core.AbstractTypeConverter class. It lists all types that can be used:

protected DataType getDataType(String columnTypeString, Boolean autoIncrement, String dataTypeName, String precision, String additionalInformation) {
    // Translate type to database-specific type, if possible
    DataType returnTypeName = null;
    if (dataTypeName.equalsIgnoreCase("BIGINT")) {
        returnTypeName = getBigIntType();
    } else if (dataTypeName.equalsIgnoreCase("NUMBER") || dataTypeName.equalsIgnoreCase("NUMERIC")) {
        returnTypeName = getNumberType();
    } else if (dataTypeName.equalsIgnoreCase("BLOB")) {
        returnTypeName = getBlobType();
    } else if (dataTypeName.equalsIgnoreCase("BOOLEAN")) {
        returnTypeName = getBooleanType();
    } else if (dataTypeName.equalsIgnoreCase("CHAR")) {
        returnTypeName = getCharType();
    } else if (dataTypeName.equalsIgnoreCase("CLOB")) {
        returnTypeName = getClobType();
    } else if (dataTypeName.equalsIgnoreCase("CURRENCY")) {
        returnTypeName = getCurrencyType();
    } else if (dataTypeName.equalsIgnoreCase("DATE") || dataTypeName.equalsIgnoreCase(getDateType().getDataTypeName())) {
        returnTypeName = getDateType();
    } else if (dataTypeName.equalsIgnoreCase("DATETIME") || dataTypeName.equalsIgnoreCase(getDateTimeType().getDataTypeName())) {
        returnTypeName = getDateTimeType();
    } else if (dataTypeName.equalsIgnoreCase("DOUBLE")) {
        returnTypeName = getDoubleType();
    } else if (dataTypeName.equalsIgnoreCase("FLOAT")) {
        returnTypeName = getFloatType();
    } else if (dataTypeName.equalsIgnoreCase("INT")) {
        returnTypeName = getIntType();
    } else if (dataTypeName.equalsIgnoreCase("INTEGER")) {
        returnTypeName = getIntType();
    } else if (dataTypeName.equalsIgnoreCase("LONGBLOB")) {
        returnTypeName = getLongBlobType();
    } else if (dataTypeName.equalsIgnoreCase("LONGVARBINARY")) {
        returnTypeName = getBlobType();
    } else if (dataTypeName.equalsIgnoreCase("LONGVARCHAR")) {
        returnTypeName = getClobType();
    } else if (dataTypeName.equalsIgnoreCase("SMALLINT")) {
        returnTypeName = getSmallIntType();
    } else if (dataTypeName.equalsIgnoreCase("TEXT")) {
        returnTypeName = getClobType();
    } else if (dataTypeName.equalsIgnoreCase("TIME") || dataTypeName.equalsIgnoreCase(getTimeType().getDataTypeName())) {
        returnTypeName = getTimeType();
    } else if (dataTypeName.toUpperCase().contains("TIMESTAMP")) {
        returnTypeName = getDateTimeType();
    } else if (dataTypeName.equalsIgnoreCase("TINYINT")) {
        returnTypeName = getTinyIntType();
    } else if (dataTypeName.equalsIgnoreCase("UUID")) {
        returnTypeName = getUUIDType();
    } else if (dataTypeName.equalsIgnoreCase("VARCHAR")) {
        returnTypeName = getVarcharType();
    } else if (dataTypeName.equalsIgnoreCase("NVARCHAR")) {
        returnTypeName = getNVarcharType();
    } else {
        return new CustomType(columnTypeString,0,2);
    }

AngularJS HTTP post to PHP and undefined

It's an old question but it worth to mention that in Angular 1.4 $httpParamSerializer is added and when using $http.post, if we use $httpParamSerializer(params) to pass the parameters, everything works like a regular post request and no JSON deserializing is needed on server side.

https://docs.angularjs.org/api/ng/service/$httpParamSerializer

How to add MVC5 to Visual Studio 2013?

You can look into Windows installed folder from here of your pc path:

C:\Program Files (x86)\Microsoft ASP.NET

View of Opened file where showing installed MVC 3, MVC 4

enter image description here

Android : Fill Spinner From Java Code Programmatically

Here is an example to fully programmatically:

  • init a Spinner.
  • fill it with data via a String List.
  • resize the Spinner and add it to my View.
  • format the Spinner font (font size, colour, padding).
  • clear the Spinner.
  • add new values to the Spinner.
  • redraw the Spinner.

I am using the following class vars:

Spinner varSpinner;
List<String> varSpinnerData;

float varScaleX;
float varScaleY;    

A - Init and render the Spinner (varRoot is a pointer to my main Activity):

public void renderSpinner() {


    List<String> myArraySpinner = new ArrayList<String>();

    myArraySpinner.add("red");
    myArraySpinner.add("green");
    myArraySpinner.add("blue");     

    varSpinnerData = myArraySpinner;

    Spinner mySpinner = new Spinner(varRoot);               

    varSpinner = mySpinner;

    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, myArraySpinner);
    spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down vieww
    mySpinner.setAdapter(spinnerArrayAdapter);

B - Resize and Add the Spinner to my View:

    FrameLayout.LayoutParams myParamsLayout = new FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.MATCH_PARENT, 
            FrameLayout.LayoutParams.WRAP_CONTENT);
    myParamsLayout.gravity = Gravity.NO_GRAVITY;             

    myParamsLayout.leftMargin = (int) (100 * varScaleX);
    myParamsLayout.topMargin = (int) (350 * varScaleY);             
    myParamsLayout.width = (int) (300 * varScaleX);;
    myParamsLayout.height = (int) (60 * varScaleY);;


    varLayoutECommerce_Dialogue.addView(mySpinner, myParamsLayout);

C - Make the Click handler and use this to set the font.

    mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int myPosition, long myID) {

            Log.i("renderSpinner -> ", "onItemSelected: " + myPosition + "/" + myID);

            ((TextView) parentView.getChildAt(0)).setTextColor(Color.GREEN);
            ((TextView) parentView.getChildAt(0)).setTextSize(TypedValue.COMPLEX_UNIT_PX, (int) (varScaleY * 22.0f) );
            ((TextView) parentView.getChildAt(0)).setPadding(1,1,1,1);


        }

        @Override
        public void onNothingSelected(AdapterView<?> parentView) {
            // your code here
        }

    });

}   

D - Update the Spinner with new data:

private void updateInitSpinners(){

     String mySelected = varSpinner.getSelectedItem().toString();
     Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);


     varSpinnerData.clear();

     varSpinnerData.add("Hello World");
     varSpinnerData.add("Hello World 2");

     ((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
     varSpinner.invalidate();
     varSpinner.setSelection(1);

}

}

What I have not been able to solve in the updateInitSpinners, is to do varSpinner.setSelection(0); and have the custom font settings activated automatically.

UPDATE:

This "ugly" solution solves the varSpinner.setSelection(0); issue, but I am not very happy with it:

private void updateInitSpinners(){

    String mySelected = varSpinner.getSelectedItem().toString();
    Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);


    varSpinnerData.clear();

    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, varSpinnerData);
    spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    varSpinner.setAdapter(spinnerArrayAdapter);  


    varSpinnerData.add("Hello World");
    varSpinnerData.add("Hello World 2");

    ((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
    varSpinner.invalidate();
    varSpinner.setSelection(0);

}

}

Hope this helps......

How to vertical align an inline-block in a line of text?

_x000D_
_x000D_
code {_x000D_
    background: black;_x000D_
    color: white;_x000D_
    display: inline-block;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<p>Some text <code>A<br />B<br />C<br />D</code> continues afterward.</p>
_x000D_
_x000D_
_x000D_

Tested and works in Safari 5 and IE6+.

Allow anonymous authentication for a single folder in web.config?

To make it work I build my directory like this:

Project Public Restrict

So I edited my webconfig for my public folder:

<location path="Project/Public">
    <system.web>
      <authorization>
        <allow users="?"/>
      </authorization>
    </system.web>
  </location>

And for my Restricted folder:

 <location path="Project/Restricted">
    <system.web>
      <authorization>
        <allow users="*"/>
      </authorizatio>
    </system.web>
  </location>

See here for the spec of * and ?:

https://docs.microsoft.com/en-us/iis/configuration/system.webserver/security/authorization/add

I hope I have helped.

How to format background color using twitter bootstrap?

Bootstrap default "contextual backgrounds" helper classes to change the background color:

.bg-primary
.bg-default
.bg-info
.bg-warning
.bg-danger

If you need set custom background color then, you can write your own custom classes in style.css( a custom css file) example below

.bg-pink
{
  background-color: #CE6F9E;
}

How to search by key=>value in a multidimensional array in PHP

if (isset($array[$key]) && $array[$key] == $value)

A minor imporvement to the fast version.

vue.js 'document.getElementById' shorthand

If you're attempting to get an element you can use Vue.util.query which is really just a wrapper around document.querySelector but at 14 characters vs 22 characters (respectively) it is technically shorter. It also has some error handling in case the element you're searching for doesn't exist.

There isn't any official documentation on Vue.util, but this is the entire source of the function:

function query(el) {
  if (typeof el === 'string') {
    var selector = el;
    el = document.querySelector(el);
    if (!el) {
      ({}).NODE_ENV !== 'production' && warn('Cannot find element: ' + selector);
    }
  }
  return el;
}

Repo link: Vue.util.query

Fatal error compiling: invalid target release: 1.8 -> [Help 1]

In my case the maven "Run configuration" was using the wrong JRE (1.7). Be sure to check Run -> Run Configurations -> (Tab) JRE to be some jdk1.8.x.

How do you set a default value for a MySQL Datetime column?

Working fine with MySQL 8.x

CREATE TABLE `users` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `dateCreated` datetime DEFAULT CURRENT_TIMESTAMP,
      `dateUpdated` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`),
      UNIQUE KEY `mobile_UNIQUE` (`mobile`)
    ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

tooltips for Button

A button accepts a "title" attribute. You can then assign it the value you want to make a label appear when you hover the mouse over the button.

_x000D_
_x000D_
<button type="submit" title="Login">_x000D_
Login</button>
_x000D_
_x000D_
_x000D_

Concatenating strings doesn't work as expected

Your code, as written, works. You’re probably trying to achieve something unrelated, but similar:

std::string c = "hello" + "world";

This doesn’t work because for C++ this seems like you’re trying to add two char pointers. Instead, you need to convert at least one of the char* literals to a std::string. Either you can do what you’ve already posted in the question (as I said, this code will work) or you do the following:

std::string c = std::string("hello") + "world";

How to export query result to csv in Oracle SQL Developer?

Version I am using

alt text

Update 5th May 2012

Jeff Smith has blogged showing, what I believe is the superior method to get CSV output from SQL Developer. Jeff's method is shown as Method 1 below:

Method 1

Add the comment /*csv*/ to your SQL query and run the query as a script (using F5 or the 2nd execution button on the worksheet toolbar)

enter image description here

That's it.

Method 2

Run a query

alt text

Right click and select unload.

Update. In Sql Developer Version 3.0.04 unload has been changed to export Thanks to Janis Peisenieks for pointing this out

alt text

Revised screen shot for SQL Developer Version 3.0.04

enter image description here

From the format drop down select CSV

alt text

And follow the rest of the on screen instructions.

Given the lat/long coordinates, how can we find out the city/country?

Minimize the amount of libraries.

Get a key to use the api at their website and just get the result in a http request:

curl -i -H "key: YOUR_KEY" -X GET https://api.latlong.dev/lookup?lat=38.7447913&long=-9.1625173

Installing a specific version of angular with angular cli

If you still have problems and are using nvm make sure to set the nvm node environment.

To select the latest version installed. To see versions use nvm list.

nvm use node
sudo npm remove -g @angular/cli
sudo npm install -g @angular/cli

Or to install a specific version use:

sudo npm install -g @angular/[email protected]

If you dir permission errors use:

sudo npm install -g @angular/[email protected] --unsafe-perm

HTML img scaling

I know that this question has been asked for a long time but as of today one simple answer is:

<img src="image.png" style="width: 55vw; min-width: 330px;" />

The use of vw in here tells that the width is relative to 55% of the width of the viewport.

All the major browsers nowadays support this.

Check this link.

Drop Down Menu/Text Field in one

Option 1

Include the script from dhtmlgoodies and initialize like this:

<input type="text" name="myText" value="Norway"
       selectBoxOptions="Canada;Denmark;Finland;Germany;Mexico"> 
createEditableSelect(document.forms[0].myText);

Option 2

Here's a custom solution which combines a <select> element and <input> element, styles them, and toggles back and forth via JavaScript

<div style="position:relative;width:200px;height:25px;border:0;padding:0;margin:0;">
  <select style="position:absolute;top:0px;left:0px;width:200px; height:25px;line-height:20px;margin:0;padding:0;"
          onchange="document.getElementById('displayValue').value=this.options[this.selectedIndex].text; document.getElementById('idValue').value=this.options[this.selectedIndex].value;">
    <option></option>
    <option value="one">one</option>
    <option value="two">two</option>
    <option value="three">three</option>
  </select>
  <input type="text" name="displayValue" id="displayValue" 
         placeholder="add/select a value" onfocus="this.select()"
         style="position:absolute;top:0px;left:0px;width:183px;width:180px\9;#width:180px;height:23px; height:21px\9;#height:18px;border:1px solid #556;"  >
  <input name="idValue" id="idValue" type="hidden">
</div>

How to input a path with a white space?

You can escape the "space" char by putting a \ right before it.

Google Maps Android API v2 Authorization failure

For me, everything was working both in an emulator and on a physical device.

However, it stopped working for me when I set up a second machine to debug the same app in an emulator with a newer API level.

I did not realize that the fingerprint for that machine changed. After seeing the authentication failure error log in the Device Log I closely compared the fingerprint in my Google Developer Console with the one in the error message. That's when I saw the difference. After adding the new fingerprint to the Developer Console (in combination with the package name) my app started working as expected in the emulator on the new system.

So if you set up a new system, check your fingerprints again!

How to commit my current changes to a different branch in Git

The other answers suggesting checking out the other branch, then committing to it, only work if the checkout is possible given the local modifications. If not, you're in the most common use case for git stash:

git stash
git checkout other-branch
git stash pop

The first stash hides away your changes (basically making a temporary commit), and the subsequent stash pop re-applies them. This lets Git use its merge capabilities.

If, when you try to pop the stash, you run into merge conflicts... the next steps depend on what those conflicts are. If all the stashed changes indeed belong on that other branch, you're simply going to have to sort through them - it's a consequence of having made your changes on the wrong branch.

On the other hand, if you've really messed up, and your work tree has a mix of changes for the two branches, and the conflicts are just in the ones you want to commit back on the original branch, you can save some work. As usual, there are a lot of ways to do this. Here's one, starting from after you pop and see the conflicts:

# Unstage everything (warning: this leaves files with conflicts in your tree)
git reset

# Add the things you *do* want to commit here
git add -p     # or maybe git add -i
git commit

# The stash still exists; pop only throws it away if it applied cleanly
git checkout original-branch
git stash pop

# Add the changes meant for this branch
git add -p
git commit

# And throw away the rest
git reset --hard

Alternatively, if you realize ahead of the time that this is going to happen, simply commit the things that belong on the current branch. You can always come back and amend that commit:

git add -p
git commit
git stash
git checkout other-branch
git stash pop

And of course, remember that this all took a bit of work, and avoid it next time, perhaps by putting your current branch name in your prompt by adding $(__git_ps1) to your PS1 environment variable in your bashrc file. (See for example the Git in Bash documentation.)

How do I check in SQLite whether a table exists?

You could try:

SELECT name FROM sqlite_master WHERE name='table_name'

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

How do I print the key-value pairs of a dictionary in python

To Print key-value pair, for example:

players = {
     'lebron': 'lakers',
     'giannis':   'milwakee bucks',
     'durant':  'brooklyn nets',
     'kawhi':   'clippers',    
}

for player,club in players.items():

print(f"\n{player.title()} is the leader of {club}")

The above code, key-value pair:

 'lebron': 'lakers', - Lebron is key and lakers is value

for loop - specify key, value in dictionary.item():

Now Print (Player Name is the leader of club).

the Output is:

#Lebron is the leader of lakers
#Giannis is the leader of milwakee bucks
#Durant is the leader of brooklyn nets
#Kawhi is the leader of clippers

Setting equal heights for div's with jQuery

You can reach each separate container using .parent() API.

Like,

var highestBox = 0;
        $('.container .column').each(function(){  
                if($(this).parent().height() > highestBox){  
                highestBox = $(this).height();  
        }
    }); 

YAML equivalent of array of objects in JSON

Great answer above. Another way is to use the great yaml jq wrapper tool, yq at https://github.com/kislyuk/yq

Save your JSON example to a file, say ex.json and then

yq -y '.' ex.json

AAPL:
- shares: -75.088
  date: 11/27/2015
- shares: 75.088
  date: 11/26/2015

Variable interpolation in the shell

Use

"$filepath"_newstap.sh

or

${filepath}_newstap.sh

or

$filepath\_newstap.sh

_ is a valid character in identifiers. Dot is not, so the shell tried to interpolate $filepath_newstap.

You can use set -u to make the shell exit with an error when you reference an undefined variable.

programmatically add column & rows to WPF Datagrid

If you already have the databinding in place John Myczek answer is complete.
If not you have at least 2 options I know of if you want to specify the source of your data. (However I am not sure whether or not this is in line with most guidelines, like MVVM)

option 1: like JohnB said. But I think you should use your own defined collection instead of a weakly typed DataTable (no offense, but you can't tell from the code what each column represents)

xaml.cs

DataContext = myCollection;

//myCollection is a `ICollection<YourType>` preferably
`ObservableCollection<YourType>

 - option 2) Declare the name of the Datagrid in xaml

        <WpfToolkit:DataGrid Name=dataGrid}>

in xaml.cs

CollectionView myCollectionView = 
      (CollectionView)CollectionViewSource.GetDefaultView(yourCollection);
dataGrid.ItemsSource = myCollectionView;

If your type has a property FirstName defined, you can then do what John Myczek pointed out.

DataGridTextColumn textColumn = new DataGridTextColumn(); 
dataColumn.Header = "First Name"; 
dataColumn.Binding = new Binding("FirstName"); 
dataGrid.Columns.Add(textColumn); 

This obviously doesn't work if you don't know properties you will need to show in your dataGrid, but if that is the case you will have more problems to deal with, and I believe that's out of scope here.

How to calculate md5 hash of a file using javascript

There is a couple scripts out there on the internet to create an MD5 Hash.

The one from webtoolkit is good, http://www.webtoolkit.info/javascript-md5.html

Although, I don't believe it will have access to the local filesystem as that access is limited.

Server unable to read htaccess file, denying access to be safe

Just my solution. I had extracted a file, had some minor changes, and got the error above. Deleted everything, uploaded and extracted again, and normal business.

Force file download with php using header()

the htaccess solution

<filesmatch "\.(?i:doc|odf|pdf|cer|txt)$">
  Header set Content-Disposition attachment
</FilesMatch>

you can read this page: https://www.techmesto.com/force-files-to-download-using-htaccess/

Returning boolean if set is empty

Not as clean as bool(c) but it was an excuse to use ternary.

def myfunc(a,b):
    return True if a.intersection(b) else False

Also using a bit of the same logic there is no need to assign to c unless you are using it for something else.

def myfunc(a,b):
    return bool(a.intersection(b))

Finally, I would assume you want a True / False value because you are going to perform some sort of boolean test with it. I would recommend skipping the overhead of a function call and definition by simply testing where you need it.

Instead of:

if (myfunc(a,b)):
    # Do something

Maybe this:

if a.intersection(b):
    # Do something

How do I create a simple 'Hello World' module in Magento?

I will rather recommend Mage2Gen, this will help you generate the boilerplate and you can just focus on the core business logic. it just helps speed up the things.

Check if table exists and if it doesn't exist, create it in SQL Server 2008

Let us create a sample database with a table by the below script:

CREATE DATABASE Test
GO
USE Test
GO
CREATE TABLE dbo.tblTest (Id INT, Name NVARCHAR(50))

Approach 1: Using INFORMATION_SCHEMA.TABLES view

We can write a query like below to check if a tblTest Table exists in the current database.

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'tblTest')
BEGIN
  PRINT 'Table Exists'
END

The above query checks the existence of the tblTest table across all the schemas in the current database. Instead of this if you want to check the existence of the Table in a specified Schema and the Specified Database then we can write the above query as below:

IF EXISTS (SELECT * FROM Test.INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = N'dbo'  AND TABLE_NAME = N'tblTest')
BEGIN
  PRINT 'Table Exists'
END

Pros of this Approach: INFORMATION_SCHEMA views are portable across different RDBMS systems, so porting to different RDBMS doesn’t require any change.

Approach 2: Using OBJECT_ID() function

We can use OBJECT_ID() function like below to check if a tblTest Table exists in the current database.

IF OBJECT_ID(N'dbo.tblTest', N'U') IS NOT NULL
BEGIN
  PRINT 'Table Exists'
END

Specifying the Database Name and Schema Name parts for the Table Name is optional. But specifying Database Name and Schema Name provides an option to check the existence of the table in the specified database and within a specified schema, instead of checking in the current database across all the schemas. The below query shows that even though the current database is MASTER database, we can check the existence of the tblTest table in the dbo schema in the Test database.

USE MASTER
GO
IF OBJECT_ID(N'Test.dbo.tblTest', N'U') IS NOT NULL
BEGIN
  PRINT 'Table Exists'
END

Pros: Easy to remember. One other notable point to mention about OBJECT_ID() function is: it provides an option to check the existence of the Temporary Table which is created in the current connection context. All other Approaches checks the existence of the Temporary Table created across all the connections context instead of just the current connection context. Below query shows how to check the existence of a Temporary Table using OBJECT_ID() function:

CREATE TABLE #TempTable(ID INT)
GO
IF OBJECT_ID(N'TempDB.dbo.#TempTable', N'U') IS NOT NULL
BEGIN
  PRINT 'Table Exists'
END
GO

Approach 3: Using sys.Objects Catalog View

We can use the Sys.Objects catalog view to check the existence of the Table as shown below:

IF EXISTS(SELECT 1 FROM sys.Objects WHERE  Object_id = OBJECT_ID(N'dbo.tblTest') AND Type = N'U')
BEGIN
  PRINT 'Table Exists'
END

Approach 4: Using sys.Tables Catalog View

We can use the Sys.Tables catalog view to check the existence of the Table as shown below:

IF EXISTS(SELECT 1 FROM sys.Tables WHERE  Name = N'tblTest' AND Type = N'U')
BEGIN
  PRINT 'Table Exists'
END

Sys.Tables catalog view inherits the rows from the Sys.Objects catalog view, Sys.objects catalog view is referred to as base view where as sys.Tables is referred to as derived view. Sys.Tables will return the rows only for the Table objects whereas Sys.Object view apart from returning the rows for table objects, it returns rows for the objects like: stored procedure, views etc.

Approach 5: Avoid Using sys.sysobjects System table

We should avoid using sys.sysobjects System Table directly, direct access to it will be deprecated in some future versions of the Sql Server. As per [Microsoft BOL][1] link, Microsoft is suggesting to use the catalog views sys.objects/sys.tables instead of sys.sysobjects system table directly.

IF EXISTS(SELECT name FROM sys.sysobjects WHERE Name = N'tblTest' AND xtype = N'U')
BEGIN
  PRINT 'Table Exists'
END

Reference: http://sqlhints.com/2014/04/13/how-to-check-if-a-table-exists-in-sql-server/

Attach to a processes output for viewing

You can use reptyr:

sudo apt install reptyr
reptyr pid

How to set a JVM TimeZone Properly

Setting environment variable TZ should also works

ex: export TZ=Asia/Shanghai

Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

You need to use bitwise operators | instead of or and & instead of and in pandas, you can't simply use the bool statements from python.

For much complex filtering create a mask and apply the mask on the dataframe.
Put all your query in the mask and apply it.
Suppose,

mask = (df["col1"]>=df["col2"]) & (stock["col1"]<=df["col2"])
df_new = df[mask]

Textarea to resize based on content length

I don't think there's any way to get width of texts in variable-width fonts, especially in javascript.

The only way I can think is to make a hidden element that has variable width set by css, put text in its innerHTML, and get the width of that element. So you may be able to apply this method to cope with textarea auto-sizing problem.

How to open local file on Jupyter?

To start Jupyter Notebook in Windows:

  • open a Windows cmd (win + R and return cmd)
  • change directory to the desired file path (cd file-path)
  • give command jupyter notebook

You can further navigate from the UI of Jupyter notebook after you launch it (if you are not directly launching the right file.)
OR you can directly drag and drop the file to the cmd, to open the file.

C:\Users\kushalatreya>jupyter notebook "C:\Users\kushalatreya\Downloads\Material\PythonCourseFolder\PythonCourse-DataTypes.ipynb"

Set CFLAGS and CXXFLAGS options using CMake

The easiest solution working fine for me is this:

export CFLAGS=-ggdb
export CXXFLAGS=-ggdb

CMake will append them to all configurations' flags. Just make sure to clear CMake cache.

javascript regex for password containing at least 8 characters, 1 number, 1 upper and 1 lowercase

Using individual regular expressions to test the different parts would be considerably easier than trying to get one single regular expression to cover all of them. It also makes it easier to add or remove validation criteria.

Note, also, that your usage of .filter() was incorrect; it will always return a jQuery object (which is considered truthy in JavaScript). Personally, I'd use an .each() loop to iterate over all of the inputs, and report individual pass/fail statuses. Something like the below:

$(".buttonClick").click(function () {

    $("input[type=text]").each(function () {
        var validated =  true;
        if(this.value.length < 8)
            validated = false;
        if(!/\d/.test(this.value))
            validated = false;
        if(!/[a-z]/.test(this.value))
            validated = false;
        if(!/[A-Z]/.test(this.value))
            validated = false;
        if(/[^0-9a-zA-Z]/.test(this.value))
            validated = false;
        $('div').text(validated ? "pass" : "fail");
        // use DOM traversal to select the correct div for this input above
    });
});

Working demo

HTML5 File API read as text and binary

Note in 2018: readAsBinaryString is outdated. For use cases where previously you'd have used it, these days you'd use readAsArrayBuffer (or in some cases, readAsDataURL) instead.


readAsBinaryString says that the data must be represented as a binary string, where:

...every byte is represented by an integer in the range [0..255].

JavaScript originally didn't have a "binary" type (until ECMAScript 5's WebGL support of Typed Array* (details below) -- it has been superseded by ECMAScript 2015's ArrayBuffer) and so they went with a String with the guarantee that no character stored in the String would be outside the range 0..255. (They could have gone with an array of Numbers instead, but they didn't; perhaps large Strings are more memory-efficient than large arrays of Numbers, since Numbers are floating-point.)

If you're reading a file that's mostly text in a western script (mostly English, for instance), then that string is going to look a lot like text. If you read a file with Unicode characters in it, you should notice a difference, since JavaScript strings are UTF-16** (details below) and so some characters will have values above 255, whereas a "binary string" according to the File API spec wouldn't have any values above 255 (you'd have two individual "characters" for the two bytes of the Unicode code point).

If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between readAsText and readAsBinaryString, but with readAsBinaryString you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use readAsText, because readAsText will use an encoding determination to try to figure out what the file's encoding is and then map it to JavaScript's UTF-16 strings.

You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
    font-family: sans-serif;
}
</style>
<script type='text/javascript'>

    function loadFile() {
        var input, file, fr;

        if (typeof window.FileReader !== 'function') {
            bodyAppend("p", "The file API isn't supported on this browser yet.");
            return;
        }

        input = document.getElementById('fileinput');
        if (!input) {
            bodyAppend("p", "Um, couldn't find the fileinput element.");
        }
        else if (!input.files) {
            bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
        }
        else if (!input.files[0]) {
            bodyAppend("p", "Please select a file before clicking 'Load'");
        }
        else {
            file = input.files[0];
            fr = new FileReader();
            fr.onload = receivedText;
            fr.readAsText(file);
        }

        function receivedText() {
            showResult(fr, "Text");

            fr = new FileReader();
            fr.onload = receivedBinary;
            fr.readAsBinaryString(file);
        }

        function receivedBinary() {
            showResult(fr, "Binary");
        }
    }

    function showResult(fr, label) {
        var markup, result, n, aByte, byteStr;

        markup = [];
        result = fr.result;
        for (n = 0; n < result.length; ++n) {
            aByte = result.charCodeAt(n);
            byteStr = aByte.toString(16);
            if (byteStr.length < 2) {
                byteStr = "0" + byteStr;
            }
            markup.push(byteStr);
        }
        bodyAppend("p", label + " (" + result.length + "):");
        bodyAppend("pre", markup.join(" "));
    }

    function bodyAppend(tagName, innerHTML) {
        var elm;

        elm = document.createElement(tagName);
        elm.innerHTML = innerHTML;
        document.body.appendChild(elm);
    }

</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</form>
</body>
</html>

If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:

Text (13):

54 65 73 74 69 6e 67 20 31 20 32 20 33

Binary (28):

ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00

As you can see, readAsText interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and readAsBinaryString didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).


* XMLHttpRequest.response with responseType = "arraybuffer" is supported in HTML 5.

** "JavaScript strings are UTF-16" may seem like an odd statement; aren't they just Unicode? No, a JavaScript string is a series of UTF-16 code units; you see surrogate pairs as two individual JavaScript "characters" even though, in fact, the surrogate pair as a whole is just one character. See the link for details.

How to add New Column with Value to the Existing DataTable?

Without For loop:

Dim newColumn As New Data.DataColumn("Foo", GetType(System.String))     
newColumn.DefaultValue = "Your DropDownList value" 
table.Columns.Add(newColumn) 

C#:

System.Data.DataColumn newColumn = new System.Data.DataColumn("Foo", typeof(System.String));
newColumn.DefaultValue = "Your DropDownList value";
table.Columns.Add(newColumn);

Export javascript data to CSV file without server interaction

We can easily create and export/download the excel file with any separator (in this answer I am using the comma separator) using javascript. I am not using any external package for creating the excel file.

_x000D_
_x000D_
    var Head = [[_x000D_
        'Heading 1',_x000D_
        'Heading 2', _x000D_
        'Heading 3', _x000D_
        'Heading 4'_x000D_
    ]];_x000D_
_x000D_
    var row = [_x000D_
       {key1:1,key2:2, key3:3, key4:4},_x000D_
       {key1:2,key2:5, key3:6, key4:7},_x000D_
       {key1:3,key2:2, key3:3, key4:4},_x000D_
       {key1:4,key2:2, key3:3, key4:4},_x000D_
       {key1:5,key2:2, key3:3, key4:4}_x000D_
    ];_x000D_
_x000D_
for (var item = 0; item < row.length; ++item) {_x000D_
       Head.push([_x000D_
          row[item].key1,_x000D_
          row[item].key2,_x000D_
          row[item].key3,_x000D_
          row[item].key4_x000D_
       ]);_x000D_
}_x000D_
_x000D_
var csvRows = [];_x000D_
for (var cell = 0; cell < Head.length; ++cell) {_x000D_
       csvRows.push(Head[cell].join(','));_x000D_
}_x000D_
            _x000D_
var csvString = csvRows.join("\n");_x000D_
let csvFile = new Blob([csvString], { type: "text/csv" });_x000D_
let downloadLink = document.createElement("a");_x000D_
downloadLink.download = 'MYCSVFILE.csv';_x000D_
downloadLink.href = window.URL.createObjectURL(csvFile);_x000D_
downloadLink.style.display = "none";_x000D_
document.body.appendChild(downloadLink);_x000D_
downloadLink.click();
_x000D_
_x000D_
_x000D_

What is the difference between & and && in Java?

It depends on the type of the arguments...

For integer arguments, the single ampersand ("&")is the "bit-wise AND" operator. The double ampersand ("&&") is not defined for anything but two boolean arguments.

For boolean arguments, the single ampersand constitutes the (unconditional) "logical AND" operator while the double ampersand ("&&") is the "conditional logical AND" operator. That is to say that the single ampersand always evaluates both arguments whereas the double ampersand will only evaluate the second argument if the first argument is true.

For all other argument types and combinations, a compile-time error should occur.

how to find my angular version in my project?

For Angular 1 or 2 (but not for Angular 4+):

You can also open the console and go to the element tab on the developer tools of whatever browser you use.

Or

Type angular.version to access the Javascript object that holds angular version.

For Angular 4+ There is are the number of ways as listed below :

Write below code in the command prompt/or in the terminal in the VS Code.

  1. ng version or ng --version (See the attachment for the reference.)
  2. ng v
  3. ng -v

In the terminal you can find the angular version as shown in the attached image : enter image description here

  1. You can also open the console and go to the element tab on the developer tools of whatever browser you use. As displayed in the below image :

enter image description here

5.Find the package.json file, You will find all the installed packages and their version.

  1. declare the variable named as 'VERSION', Import the dependencies.
import { VERSION } from '@angular/core';

// To display the version in the console.

console.log(VERSION.full); 

Tomcat in Intellij Idea Community Edition

VM :-Djava.endorsed.dirs="C:/Program Files/Apache Software Foundation/Tomcat 8.0/common/endorsed" 
    -Dcatalina.base="C:/Program Files/Apache Software Foundation/Tomcat 8.0"  
    -Dcatalina.home="C:/Program Files/Apache Software Foundation/Tomcat 8.0" 
    -Djava.io.tmpdir="C:/Program Files/Apache Software Foundation/Tomcat 8.0/temp" 
    -Xmx1024M

How can I remove a pytz timezone from a datetime object?

To remove a timezone (tzinfo) from a datetime object:

# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)

If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.

# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)

Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime object to insert into the database. The solution is to convert your datetime.datetime object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime objects where one is timezone aware and another is timezone naive.

##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################

arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

arrowDt = arrowObj.to("utc").datetime

# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)

# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()

# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3

# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True

How do you exit from a void function in C++?

You mean like this?

void foo ( int i ) {
    if ( i < 0 ) return; // do nothing
    // do something
}

SHA-256 or MD5 for file integrity

Both SHA256 and MDA5 are hashing algorithms. They take your input data, in this case your file, and output a 256/128-bit number. This number is a checksum. There is no encryption taking place because an infinite number of inputs can result in the same hash value, although in reality collisions are rare.

SHA256 takes somewhat more time to calculate than MD5, according to this answer.

Offhand, I'd say that MD5 would be probably be suitable for what you need.

PHP str_replace replace spaces with underscores

Try this instead:

$journalName = str_replace(' ', '_', $journalName);

to remove white space

Requery a subform from another form?

Just a comment on the method of accomplishing this:

You're making your EntryForm permanently tied to the form you're calling it from. I think it's better to not have forms tied to context like that. I'd remove the requery from the Save/Close routine and instead open the EntryForm modally, using the acDialog switch:

  DoCmd.OpenForm "EntryForm", , ,"[ID]=" & Me!SubForm.Form!ID, , acDialog
  Me!SubForm.Form.Requery

That way, EntryForm is not tied down to use in one context. The alternative is to complicate EntryForm with something that is knowledgable of which form opened it and what needs to requeried. I think it's better to keep that kind of thing as close to the context in which it's used, and keep the called form's code as simple as possible.

Perhaps a principle here is that any time you are requerying a form using the Forms collection from another form, it's a good indication something's not right about your architecture -- that should happen seldom, in my opinion.

How to call another controller Action From a controller in Mvc

as @DLeh says Use rather

var controller = DependencyResolver.Current.GetService<ControllerB>();

But, giving the controller, a controlller context is important especially when you need to access the User object, Server object, or the HttpContext inside the 'child' controller.

I have added a line of code:

controller.ControllerContext = new ControllerContext(Request.RequestContext, controller);

or else you could have used System.Web to acces the current context too, to access Server or the early metioned objects

NB: i am targetting the framework version 4.6 (Mvc5)

What is the difference between `throw new Error` and `throw someObject`?

throw something works with both object and strings.But it is less supported than the other method.throw new Error("") Will only work with strings and turns objects into useless [Object obj] in the catch block.

Redirect echo output in shell script to logfile

You can add this line on top of your script:

#!/bin/bash
# redirect stdout/stderr to a file
exec &> logfile.txt

OR else to redirect only stdout use:

exec > logfile.txt

Adding form action in html in laravel

Laravel 5.8 Step 1: Go to the path routes/api.php add: Route::post('welcome/login', 'WelcomeController@login')->name('welcome.login'); Step2: Go to the path file view

<form method="POST" action="{{ route('welcome.login') }}">
</form>

Result html

<form method="POST" action="http://localhost/api/welcome/login">

<form>

enable/disable zoom in Android WebView

We had the same problem while working on an Android application for a customer and I managed to "hack" around this restriction.

I took a look at the Android Source code for the WebView class and spotted a updateZoomButtonsEnabled()-method which was working with an ZoomButtonsController-object to enable and disable the zoom controls depending on the current scale of the browser.

I searched for a method to return the ZoomButtonsController-instance and found the getZoomButtonsController()-method, that returned this very instance.

Although the method is declared public, it is not documented in the WebView-documentation and Eclipse couldn't find it either. So, I tried some reflection on that and created my own WebView-subclass to override the onTouchEvent()-method, which triggered the controls.

public class NoZoomControllWebView extends WebView {

    private ZoomButtonsController zoom_controll = null;

    public NoZoomControllWebView(Context context) {
        super(context);
        disableControls();
    }

    public NoZoomControllWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        disableControls();
    }

    public NoZoomControllWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        disableControls();
    }

    /**
     * Disable the controls
     */
    private void disableControls(){
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
            // Use the API 11+ calls to disable the controls
            this.getSettings().setBuiltInZoomControls(true);
            this.getSettings().setDisplayZoomControls(false);
        } else {
            // Use the reflection magic to make it work on earlier APIs
            getControlls();
        }
    }

    /**
     * This is where the magic happens :D
     */
    private void getControlls() {
        try {
            Class webview = Class.forName("android.webkit.WebView");
            Method method = webview.getMethod("getZoomButtonsController");
            zoom_controll = (ZoomButtonsController) method.invoke(this, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        super.onTouchEvent(ev);
        if (zoom_controll != null){
            // Hide the controlls AFTER they where made visible by the default implementation.
            zoom_controll.setVisible(false);
        }
        return true;
    }
}

You might want to remove the unnecessary constructors and react on probably on the exceptions.

Although this looks hacky and unreliable, it works back to API Level 4 (Android 1.6).


As @jayellos pointed out in the comments, the private getZoomButtonsController()-method is no longer existing on Android 4.0.4 and later.

However, it doesn't need to. Using conditional execution, we can check if we're on a device with API Level 11+ and use the exposed functionality (see @Yuttadhammo answer) to hide the controls.

I updated the example code above to do exactly that.

jquery function setInterval

// simple example using the concept of setInterval

$(document).ready(function(){
var g = $('.jumping');
function blink(){
  g.animate({ 'left':'50px' 
  }).animate({
     'left':'20px'
        },1000)
}
setInterval(blink,1500);
});

How to fill Dataset with multiple tables?

public DataSet GetDataSet()
    {
        try
        {
            DataSet dsReturn = new DataSet();
            using (SqlConnection myConnection = new SqlConnection(Core.con))
            {
                string query = "select * from table1;  select* from table2";
                SqlCommand cmd = new SqlCommand(query, myConnection);
                myConnection.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                dsReturn.Load(reader, LoadOption.PreserveChanges, new string[] { "tableOne", "tableTwo" });
                return dsReturn;
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

Please run `npm cache clean`

This error can be due to many many things.

The key here seems the hint about error reading. I see you are working on a flash drive or something similar? Try to run the install on a local folder owned by your current user.

You could also try with sudo, that might solve a permission problem if that's the case.

Another reason why it cannot read could be because it has not downloaded correctly, or saved correctly. A little problem in your network could have caused that, and the cache clean would remove the files and force a refetch but that does not solve your problem. That means it would be more on the save part, maybe it didn't save because of permissions, maybe it didn't not save correctly because it was lacking disk space...

How do I edit SSIS package files?

Adding to what b_levitt said, you can get the SSDT-BI plugin for Visual Studio 2013 here: http://www.microsoft.com/en-us/download/details.aspx?id=42313

How to add users to Docker container?

Ubuntu

Try the following lines in Dockerfile:

RUN useradd -rm -d /home/ubuntu -s /bin/bash -g root -G sudo -u 1001 ubuntu
USER ubuntu
WORKDIR /home/ubuntu

useradd options (see: man useradd):

  • -r, --system Create a system account. see: Implications creating system accounts
  • -m, --create-home Create the user's home directory.
  • -d, --home-dir HOME_DIR Home directory of the new account.
  • -s, --shell SHELL Login shell of the new account.
  • -g, --gid GROUP Name or ID of the primary group.
  • -G, --groups GROUPS List of supplementary groups.
  • -u, --uid UID Specify user ID. see: Understanding how uid and gid work in Docker containers
  • -p, --password PASSWORD Encrypted password of the new account (e.g. ubuntu).

Setting default user's password

To set the user password, add -p "$(openssl passwd -1 ubuntu)" to useradd command.

Alternatively add the following lines to your Dockerfile:

SHELL ["/bin/bash", "-o", "pipefail", "-c"]
RUN echo 'ubuntu:ubuntu' | chpasswd

The first shell instruction is to make sure that -o pipefail option is enabled before RUN with a pipe in it. Read more: Hadolint: Linting your Dockerfile.

How to get current time and date in C++?

There's always the __TIMESTAMP__ preprocessor macro.

#include <iostream>

using namespace std

void printBuildDateTime () {
    cout << __TIMESTAMP__ << endl;
}

int main() {
    printBuildDateTime();
}

example: Sun Apr 13 11:28:08 2014

jquery background-color change on focus and blur

#FFFFEEE is not a correct color code. Try with #FFFFEE instead.

li:before{ content: "¦"; } How to Encode this Special Character as a Bullit in an Email Stationery?

Lea's converter is no longer available. I just used this converter

Steps:

  1. Enter the Unicode decimal version such as 8226 in the tool's green input field.
  2. Press Dec code points
  3. See the result in the box Unicode U+hex notation (eg U+2022)
  4. Use it in your CSS. Eg content: '\2022'

ps. I have no connection with the web site.

How to split a list by comma not space

Using a subshell substitution to parse the words undoes all the work you are doing to put spaces together.

Try instead:

cat CSV_file | sed -n 1'p' | tr ',' '\n' | while read word; do
    echo $word
done

That also increases parallelism. Using a subshell as in your question forces the entire subshell process to finish before you can start iterating over the answers. Piping to a subshell (as in my answer) lets them work in parallel. This matters only if you have many lines in the file, of course.

Attempt to present UIViewController on UIViewController whose view is not in the window hierarchy

I've ended up with such a code that finally works to me (Swift), considering you want to display some viewController from virtually anywhere. This code will obviously crash when there is no rootViewController available, that's the open ending. It also does not include usually required switch to UI thread using

dispatch_sync(dispatch_get_main_queue(), {
    guard !NSBundle.mainBundle().bundlePath.hasSuffix(".appex") else {
       return; // skip operation when embedded to App Extension
    }

    if let delegate = UIApplication.sharedApplication().delegate {
        delegate.window!!.rootViewController?.presentViewController(viewController, animated: true, completion: { () -> Void in
            // optional completion code
        })
    }
}

Selecting a Record With MAX Value

Note: An incorrect revision of this answer was edited out. Please review all answers.

A subselect in the WHERE clause to retrieve the greatest BALANCE aggregated over all rows. If multiple ID values share that balance value, all would be returned.

SELECT 
  ID,
  BALANCE
FROM CUSTOMERS
WHERE BALANCE = (SELECT MAX(BALANCE) FROM CUSTOMERS)

How to use patterns in a case statement?

I don't think you can use braces.

According to the Bash manual about case in Conditional Constructs.

Each pattern undergoes tilde expansion, parameter expansion, command substitution, and arithmetic expansion.

Nothing about Brace Expansion unfortunately.

So you'd have to do something like this:

case $1 in
    req*)
        ...
        ;;
    met*|meet*)
        ...
        ;;
    *)
        # You should have a default one too.
esac

Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3

For me, the gem lock file was specifying an older version of cocoapods than the one I had installed. I had to re-branch and run bundle exec pod install instead of pod install

How to get first 5 characters from string

An alternative way to get only one character.

$str = 'abcdefghij';
echo $str{5};

I would particularly not use this, but for the purpose of education. We can use that to answer the question:

$newString = '';
for ($i = 0; $i < 5; $i++) {
    $newString .= $str{$i};
}
echo $newString;

For anyone using that. Bear in mind curly brace syntax for accessing array elements and string offsets is deprecated from PHP 7.4

More information: https://wiki.php.net/rfc/deprecate_curly_braces_array_access

What is the most efficient way of finding all the factors of a number in Python?

Here is another alternate without reduce that performs well with large numbers. It uses sum to flatten the list.

def factors(n):
    return set(sum([[i, n//i] for i in xrange(1, int(n**0.5)+1) if not n%i], []))

How to declare a global variable in php?

You answered this in the way you wrote the question - use 'define'. but once set, you can't change a define.

Alternatively, there are tricks with a constant in a class, such as class::constant that you can use. You can also make them variable by declaring static properties to the class, with functions to set the static property if you want to change it.

Regex to check whether a string contains only numbers

^[0-9]$ 

...is a regular expression matching any single digit, so 1 will return true but 123 will return false.

If you add the * quantifier,

^[0-9]*$

the expression will match arbitrary length strings of digits and 123 will return true. (123f will still return false).

Be aware that technically an empty string is a 0-length string of digits, and so it will return true using ^[0-9]*$ If you want to only accept strings containing 1 or more digits, use + instead of *

^[0-9]+$

As the many others have pointed out, there are more than a few ways to achieve this, but I felt like it was appropriate to point out that the code in the original question only requires a single additional character to work as intended.

How can I get the first two digits of a number?

Comparing the O(n) time solution with the "constant time" O(1) solution provided in other answers goes to show that if the O(n) algorithm is fast enough, n may have to get very large before it is slower than a slow O(1).

The strings version is approx. 60% faster than the "maths" version for numbers of 20 or fewer digits. They become closer only when then number of digits approaches 200 digits

# the "maths" version
import math

def first_n_digits1(num, n):
    return num // 10 ** (int(math.log(num, 10)) - n + 1)

%timeit first_n_digits1(34523452452, 2)
1.21 µs ± 75 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit first_n_digits1(34523452452, 8)
1.24 µs ± 47.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

# 22 digits
%timeit first_n_digits1(3423234239472523452452, 2)
1.33 µs ± 59.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit first_n_digits1(3423234239472523452452, 15)
1.23 µs ± 61.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

# 196 digits
%timeit first_n_digits1(3423234239472523409283475908723908723409872390871243908172340987123409871234012089172340987734507612340981344509873123401234670350981234098123140987314509812734091823509871345109871234098172340987125988123452452, 39)
1.86 µs ± 21.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

# The "string" verions
def first_n_digits2(num, n):
    return int(str(num)[:n])

%timeit first_n_digits2(34523452452, 2)
744 ns ± 28.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit first_n_digits2(34523452452, 8)
768 ns ± 42.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

# 22 digits
%timeit first_n_digits2(3423234239472523452452, 2)
767 ns ± 33.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit first_n_digits2(3423234239472523452452, 15)
830 ns ± 55.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

# 196 digits
%timeit first_n_digits2(3423234239472523409283475908723908723409872390871243908098712340987123401208917234098773450761234098134450987312340123467035098123409812314098734091823509871345109871234098172340987125988123452452, 39)
1.87 µs ± 140 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Factorial in numpy and scipy

You can save some homemade factorial functions on a separate module, utils.py, and then import them and compare the performance with the predefinite one, in scipy, numpy and math using timeit. In this case I used as external method the last proposed by Stefan Gruenwald:

import numpy as np


def factorial(n):
    return reduce((lambda x,y: x*y),range(1,n+1))

Main code (I used a framework proposed by JoshAdel in another post, look for how-can-i-get-an-array-of-alternating-values-in-python):

from timeit import Timer
from utils import factorial
import scipy

    n = 100

    # test the time for the factorial function obtained in different ways:

    if __name__ == '__main__':

        setupstr="""
    import scipy, numpy, math
    from utils import factorial
    n = 100
    """

        method1="""
    factorial(n)
    """

        method2="""
    scipy.math.factorial(n)  # same algo as numpy.math.factorial, math.factorial
    """

        nl = 1000
        t1 = Timer(method1, setupstr).timeit(nl)
        t2 = Timer(method2, setupstr).timeit(nl)

        print 'method1', t1
        print 'method2', t2

        print factorial(n)
        print scipy.math.factorial(n)

Which provides:

method1 0.0195569992065
method2 0.00638914108276

93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000


Process finished with exit code 0

How to view the dependency tree of a given npm module?

This site allows you to view a packages tree as a node graph in 2D or 3D.

http://npm.anvaka.com/#/view/2d/waterline

enter image description here

Great work from @Avanka!

Jquery in React is not defined

Just a note: if you use arrow functions you don't need the const that = this part. It might look like this:

fetch('http://jsonplaceholder.typicode.com/posts') 
  .then((response) => { return response.json(); }) 
  .then((myJson) => { 
     this.setState({data: myJson}); // for example
});

How to uninstall a windows service and delete its files without rebooting

I am using the InstallUtil.exe packed with .NET Framework.

The usage to uninstall is: InstallUtil '\path\to\assembly\with\the\installer\classes' /u so for example: installutil MyService.HostService.exe /u

The /u switch stands for uninstall, without it the util performs normal installation of the service. The utility stops the service if it is running and I never had problems with Windows keeping lock on the service files. You can read about other options of InstallUtil on MSDN.

P.S.:if you don't have installutil in your path variable use full path like this: C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe "C:\MyServiceFolder\MyService.HostService.exe" /u or if you need 64bit version it can be found in 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\' .The version number in path varies depending on .NET version.

apache server reached MaxClients setting, consider raising the MaxClients setting

Here's an approach that could resolve your problem, and if not would help with troubleshooting.

  1. Create a second Apache virtual server identical to the current one

  2. Send all "normal" user traffic to the original virtual server

  3. Send special or long-running traffic to the new virtual server

Special or long-running traffic could be report-generation, maintenance ops or anything else you don't expect to complete in <<1 second. This can happen serving APIs, not just web pages.

If your resource utilization is low but you still exceed MaxClients, the most likely answer is you have new connections arriving faster than they can be serviced. Putting any slow operations on a second virtual server will help prove if this is the case. Use the Apache access logs to quantify the effect.

jquery ui Dialog: cannot call methods on dialog prior to initialization

This is also some work around:

$("div[aria-describedby='divDialog'] .ui-button.ui-widget.ui-state-default.ui-corner-all.ui-button-icon-only.ui-dialog-titlebar-close").click();

Filtering Table rows using Jquery

nrodic has an amazing answer, and I just wanted to give a small update to let you know that with a small extra function you can extend the contains methid to be case insenstive:

$.expr[":"].contains = $.expr.createPseudo(function(arg) {
    return function( elem ) {
        return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
    };
});

MySQL: Error dropping database (errno 13; errno 17; errno 39)

Simply go to /opt/lampp/var/mysql

There You can find your database name. Open that folder. Remove if any files in it

Now come to phpmyadmin and drop that database

What does a Status of "Suspended" and high DiskIO means from sp_who2?

This is a very broad question, so I am going to give a broad answer.

  1. A query gets suspended when it is requesting access to a resource that is currently not available. This can be a logical resource like a locked row or a physical resource like a memory data page. The query starts running again, once the resource becomes available. 
  2. High disk IO means that a lot of data pages need to be accessed to fulfill the request.

That is all that I can tell from the above screenshot. However, if I were to speculate, you probably have an IO subsystem that is too slow to keep up with the demand. This could be caused by missing indexes or an actually too slow disk. Keep in mind, that 15000 reads for a single OLTP query is slightly high but not uncommon.

How do you Encrypt and Decrypt a PHP String?

If you don't want to use library (which you should) then use something like this (PHP 7):

function sign($message, $key) {
    return hash_hmac('sha256', $message, $key) . $message;
}

function verify($bundle, $key) {
    return hash_equals(
      hash_hmac('sha256', mb_substr($bundle, 64, null, '8bit'), $key),
      mb_substr($bundle, 0, 64, '8bit')
    );
}

function getKey($password, $keysize = 16) {
    return hash_pbkdf2('sha256',$password,'some_token',100000,$keysize,true);
}

function encrypt($message, $password) {
    $iv = random_bytes(16);
    $key = getKey($password);
    $result = sign(openssl_encrypt($message,'aes-256-ctr',$key,OPENSSL_RAW_DATA,$iv), $key);
    return bin2hex($iv).bin2hex($result);
}

function decrypt($hash, $password) {
    $iv = hex2bin(substr($hash, 0, 32));
    $data = hex2bin(substr($hash, 32));
    $key = getKey($password);
    if (!verify($data, $key)) {
      return null;
    }
    return openssl_decrypt(mb_substr($data, 64, null, '8bit'),'aes-256-ctr',$key,OPENSSL_RAW_DATA,$iv);
}

$string_to_encrypt='John Smith';
$password='password';
$encrypted_string=encrypt($string_to_encrypt, $password);
$decrypted_string=decrypt($encrypted_string, $password);

Best approach to remove time part of datetime in SQL Server

Just in case anyone is looking in here for a Sybase version since several of the versions above didn't work

CAST(CONVERT(DATE,GETDATE(),103) AS DATETIME)
  • Tested in I SQL v11 running on Adaptive Server 15.7

How to activate the Bootstrap modal-backdrop?

Pretty strange, it should work out of the box as the ".modal-backdrop" class is defined top-level in the css.

<div class="modal-backdrop"></div>

Made a small demo: http://jsfiddle.net/PfBnq/

ORACLE: Updating multiple columns at once

I guess the issue here is that you are updating INV_DISCOUNT and the INV_TOTAL uses the INV_DISCOUNT. so that is the issue here. You can use returning clause of update statement to use the new INV_DISCOUNT and use it to update INV_TOTAL.

this is a generic example let me know if this explains the point i mentioned

CREATE OR REPLACE PROCEDURE SingleRowUpdateReturn
IS
    empName VARCHAR2(50);
    empSalary NUMBER(7,2);      
BEGIN
    UPDATE emp
    SET sal = sal + 1000
    WHERE empno = 7499
    RETURNING ename, sal
    INTO empName, empSalary;

    DBMS_OUTPUT.put_line('Name of Employee: ' || empName);
    DBMS_OUTPUT.put_line('New Salary: ' || empSalary);
END;

Redirect stderr to stdout in C shell

I think this is the correct answer for csh.

xxx >/dev/stderr

Note most csh are really tcsh in modern environments:

rmockler> ls -latr /usr/bin/csh

lrwxrwxrwx 1 root root 9 2011-05-03 13:40 /usr/bin/csh -> /bin/tcsh

using a backtick embedded statement to portray this as follows:

echo "`echo 'standard out1'` `echo 'error out1' >/dev/stderr` `echo 'standard out2'`" | tee -a /tmp/test.txt ; cat /tmp/test.txt

if this works for you please bump up to 1. The other suggestions don't work for my csh environment.

split string only on first instance of specified character

With help of destructuring assignment it can be more readable:

let [first, ...rest] = "good_luck_buddy".split('_')
rest = rest.join('_')

List comprehension with if statement

If you use sufficiently big list not in b clause will do a linear search for each of the item in a. Why not use set? Set takes iterable as parameter to create a new set object.

>>> a = ["a", "b", "c", "d", "e"]
>>> b = ["c", "d", "f", "g"]
>>> set(a).intersection(set(b))
{'c', 'd'}