Programs & Examples On #Preemptive


Calculating Waiting Time and Turnaround Time in (non-preemptive) FCFS queue

For non-preemptive system,

waitingTime = startTime - arrivalTime

turnaroundTime = burstTime + waitingTime = finishTime- arrivalTime

startTime = Time at which the process started executing

finishTime = Time at which the process finished executing

You can keep track of the current time elapsed in the system(timeElapsed). Assign all processors to a process in the beginning, and execute until the shortest process is done executing. Then assign this processor which is free to the next process in the queue. Do this until the queue is empty and all processes are done executing. Also, whenever a process starts executing, recored its startTime, when finishes, record its finishTime (both same as timeElapsed). That way you can calculate what you need.

"Active Directory Users and Computers" MMC snap-in for Windows 7?

You have to enable the features in Add/Remove Programs section of your Control Panel. Select "Turn Windows features on or off"

split string only on first instance of specified character

A simple ES6 way to get both the first key and remaining parts in a string would be:

 const [key,] = "good_luck_buddy".split('_')
 const value = rest.join('_')
 console.log(key, value) // good, luck_buddy

How to get index of object by its property in JavaScript?

This might be useful

function showProps(obj, objName) {  
  var result = "";  
  for (var i in obj)  
    result += objName + "." + i + " = " + obj[i] + "\n";  
  return result;  

Copied this from

Connect to SQL Server Database from PowerShell

Integrated Security and User ID \ Password authentication are mutually exclusive. To connect to SQL Server as the user running the code, remove User ID and Password from your connection string:

$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True;"

To connect with specific credentials, remove Integrated Security:

$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; User ID = $uid; Password = $pwd;"

if block inside echo statement?

You will want to use the a ternary operator which acts as a shortened IF/Else statement:

echo '<option value="'.$value.'" '.(($value=='United States')?'selected="selected"':"").'>'.$value.'</option>';


Dim o
Set o = CreateObject("MSXML2.XMLHTTP") "GET", "", False
' o.responseText now holds the response as a string.

Best way to list files in Java, sorted by Date Modified?

Elegant solution since Java 8:

File[] files = directory.listFiles();
Arrays.sort(files, Comparator.comparingLong(File::lastModified));

Or, if you want it in descending order, just reverse it:

File[] files = directory.listFiles();
Arrays.sort(files, Comparator.comparingLong(File::lastModified).reversed());

jQuery .val() vs .attr("value")

The proper way to set and get the value of a form field is using .val() method.

$('#field').val('test'); // Set
var value = $('#field').val(); // Get

With jQuery 1.6 there is a new method called .prop().

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. In addition, .attr() should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop() method.

Excluding Maven dependencies

You can utilize the dependency management mechanism.

If you create entries in the <dependencyManagement> section of your pom for spring-security-web and spring-web with the desired 3.1.0 version set the managed version of the artifact will override those specified in the transitive dependency tree.

I'm not sure if that really saves you any code, but it is a cleaner solution IMO.

Create session factory in Hibernate 4

Even there is an update in 4.3.0 API. ServiceRegistryBuilder is also deprecated in 4.3.0 and replaced with the StandardServiceRegistryBuilder. Now the actual code for creating the session factory would look this example on creating session factory.

How to call a method daily, at specific time, in C#?

I just recently wrote a c# app that had to restart daily. I realize this question is old but I don't think it hurts to add another possible solution. This is how I handled daily restarts at a specified time.

public void RestartApp()
  AppRestart = AppRestart.AddHours(5);
  AppRestart = AppRestart.AddMinutes(30);
  DateTime current = DateTime.Now;
  if (current > AppRestart) { AppRestart = AppRestart.AddDays(1); }

  TimeSpan UntilRestart = AppRestart - current;
  int MSUntilRestart = Convert.ToInt32(UntilRestart.TotalMilliseconds);

  tmrRestart.Interval = MSUntilRestart;
  tmrRestart.Elapsed += tmrRestart_Elapsed;

To ensure your timer is kept in scope I recommend creating it outside of the method using System.Timers.Timer tmrRestart = new System.Timers.Timer() method. Put the method RestartApp() in your form load event. When the application launches it will set the values for AppRestart if current is greater than the restart time we add 1 day to AppRestart to ensure the restart happens on time and that we don't get an exception for putting a negative value into the timer. In the tmrRestart_Elapsed event run whatever code you need ran at that specific time. If your application restarts on it's own you don't necessarily have to stop the timer but it doesn't hurt either, If the application does not restart simply call the RestartApp() method again and you will be good to go.

Printing list elements on separated lines in Python

Another good option for handling this kind of option is the pprint module, which (among other things) pretty prints long lists with one element per line:

>>> import sys
>>> import pprint
>>> pprint.pprint(sys.path)

Can a foreign key refer to a primary key in the same table?

Other answers have given clear enough examples of a record referencing another record in the same table.

There are even valid use cases for a record referencing itself in the same table. For example, a point of sale system accepting many tenders may need to know which tender to use for change when the payment is not the exact value of the sale. For many tenders that's the same tender, for others that's domestic cash, for yet other tenders, no form of change is allowed.

All this can be pretty elegantly represented with a single tender attribute which is a foreign key referencing the primary key of the same table, and whose values sometimes match the respective primary key of same record. In this example, the absence of value (also known as NULL value) might be needed to represent an unrelated meaning: this tender can only be used at its full value.

Popular relational database management systems support this use case smoothly.


  1. When inserting a record, the foreign key reference is verified to be present after the insert, rather than before the insert.

  2. When inserting multiple records with a single statement, the order in which the records are inserted matters. The constraints are checked for each record separately.

  3. Certain other data patterns, such as those involving circular dependences on record level going through two or more tables, cannot be purely inserted at all, or at least not with all the foreign keys enabled, and they have to be established using a combination of inserts and updates (if they are truly necessary).

How to store NULL values in datetime fields in MySQL?

For what it is worth: I was experiencing a similar issue trying to update a MySQL table via Perl. The update would fail when an empty string value (translated from a null value from a read from another platform) was passed to the date column ('dtcol' in the code sample below). I was finally successful getting the data updated by using an IF statement embedded in my update statement:

    my $stmnt='update tbl set colA=?,dtcol=if(?="",null,?) where colC=?';
    my $status=$dbh->do($stmt,undef,$iref[1],$iref[2],$iref[2],$ref[0]);

How to import a bak file into SQL Server Express

Using management studio the procedure can be done as follows

  1. right click on the Databases container within object explorer
  2. from context menu select Restore database
  3. Specify To Database as either a new or existing database
  4. Specify Source for restore as from device
  5. Select Backup media as File
  6. Click the Add button and browse to the location of the BAK file


You'll need to specify the WITH REPLACE option to overwrite the existing adventure_second database with a backup taken from a different database.

Click option menu and tick Overwrite the existing database(With replace)


Maven dependency update on commandline

If you just want to re-load/update dependencies (I assume, with constantly changing you mean either SNAPSHOTS or local dependencies you update yourself), you can use

mvn dependency:resolve

Hashing with SHA1 Algorithm in C#

This is what I went with. For those of you who want to optimize, check out

    public static string Hash(string stringToHash)
        using (var sha1 = new SHA1Managed())
            return BitConverter.ToString(sha1.ComputeHash(Encoding.UTF8.GetBytes(stringToHash)));

How to force table cell <td> content to wrap?

If you want fix the column you should set width. For example:

<td style="width:100px;">some data</td>

increment date by one month

function dayOfWeek($date){
    return DateTime::createFromFormat('Y-m-d', $date)->format('N');

Usage examples:

echo dayOfWeek(2016-12-22);
// "4"
echo dayOfWeek(date('Y-m-d'));
// "4"

Bash ignoring error for a particular command

Just add || true after the command where you want to ignore the error.

sudo: port: command not found

if you use zsh.please add flowing string to the line 'export PATH="..."' in file '~/.zshrc'


What is the Sign Off feature in Git for?

Sign-off is a requirement for getting patches into the Linux kernel and a few other projects, but most projects don't actually use it.

It was introduced in the wake of the SCO lawsuit, (and other accusations of copyright infringement from SCO, most of which they never actually took to court), as a Developers Certificate of Origin. It is used to say that you certify that you have created the patch in question, or that you certify that to the best of your knowledge, it was created under an appropriate open-source license, or that it has been provided to you by someone else under those terms. This can help establish a chain of people who take responsibility for the copyright status of the code in question, to help ensure that copyrighted code not released under an appropriate free software (open source) license is not included in the kernel.

Phone: numeric keyboard for text input

You can try like this:

<input type="number" name="input">
<input type="submit" value="Next" formnovalidate="formnovalidate">

But be careful: If your input contains something other than a number, it will not be transmitted to the server.

How to resolve a Java Rounding Double issue

As the previous answers stated, this is a consequence of doing floating point arithmetic.

As a previous poster suggested, When you are doing numeric calculations, use java.math.BigDecimal.

However, there is a gotcha to using BigDecimal. When you are converting from the double value to a BigDecimal, you have a choice of using a new BigDecimal(double) constructor or the BigDecimal.valueOf(double) static factory method. Use the static factory method.

The double constructor converts the entire precision of the double to a BigDecimal while the static factory effectively converts it to a String, then converts that to a BigDecimal.

This becomes relevant when you are running into those subtle rounding errors. A number might display as .585, but internally its value is '0.58499999999999996447286321199499070644378662109375'. If you used the BigDecimal constructor, you would get the number that is NOT equal to 0.585, while the static method would give you a value equal to 0.585.

double value = 0.585;
System.out.println(new BigDecimal(value));

on my system gives


How to paste text to end of every line? Sublime 2

Yeah Regex is cool, but there are other alternative.

  • Select all the lines you want to prefix or suffix
  • Goto menu Selection -> Split into Lines (Cmd/Ctrl + Shift + L)

This allows you to edit multiple lines at once. Now you can add *Quotes (") or anything * at start and end of each lines.

SQL Server 2008 Row Insert and Update timestamps


CREATE TABLE [dbo].[Names]
    [Name] [nvarchar](64) NOT NULL,
    [UpdateTS] [smalldatetime] NOT NULL


PS I think a smalldatetime is good enough. You may decide differently.

Can you not do this at the "moment of impact" ?

In Sql Server, this is common:

Update dbo.MyTable 

ColA = @SomeValue , 

Sql Server has a "timestamp" datatype.

But it may not be what you think.

Here is a reference:

Here is a little RowVersion (synonym for timestamp) example:

CREATE TABLE [dbo].[Names]
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [UpdateTS] [datetime] NOT NULL


INSERT INTO dbo.Names (Name,UpdateTS)

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Maybe a complete working example:

DROP TABLE [dbo].[Names]

CREATE TABLE [dbo].[Names]
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [UpdateTS] [datetime] NOT NULL



CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names


Update dbo.Names Set UpdateTS = CURRENT_TIMESTAMP from dbo.Names myAlias , inserted triggerInsertedTable where 
triggerInsertedTable.Name = myAlias.Name



INSERT INTO dbo.Names (Name,UpdateTS)

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Matching on the "Name" value is probably not wise.

Try this more mainstream example with a SurrogateKey

DROP TABLE [dbo].[Names]

CREATE TABLE [dbo].[Names]
    SurrogateKey int not null Primary Key Identity (1001,1),
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [UpdateTS] [datetime] NOT NULL



CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names


   UPDATE dbo.Names
    From  dbo.Names myAlias
    WHERE exists ( select null from inserted triggerInsertedTable where myAlias.SurrogateKey = triggerInsertedTable.SurrogateKey)



INSERT INTO dbo.Names (Name,UpdateTS)

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Loop backwards using indices in Python?

In my opinion, this is the most readable:

for i in reversed(xrange(101)):
    print i,

Passing command line arguments to R CMD BATCH

Here's another way to process command line args, using R CMD BATCH. My approach, which builds on an earlier answer here, lets you specify arguments at the command line and, in your R script, give some or all of them default values.

Here's an R file, which I name test.R:

defaults <- list(a=1, b=c(1,1,1)) ## default values of any arguments we might pass

## parse each command arg, loading it into global environment
for (arg in commandArgs(TRUE))

## if any variable named in defaults doesn't exist, then create it
## with value from defaults
for (nm in names(defaults))
  assign(nm, mget(nm, ifnotfound=list(defaults[[nm]]))[[1]])


At the command line, if I type

R CMD BATCH --no-save --no-restore '--args a=2 b=c(2,5,6)' test.R

then within R we'll have a = 2 and b = c(2,5,6). But I could, say, omit b, and add in another argument c:

R CMD BATCH --no-save --no-restore '--args a=2 c="hello"' test.R

Then in R we'll have a = 2, b = c(1,1,1) (the default), and c = "hello".

Finally, for convenience we can wrap the R code in a function, as long as we're careful about the environment:

## defaults should be either NULL or a named list
parseCommandArgs <- function(defaults=NULL, envir=globalenv()) {
  for (arg in commandArgs(TRUE))
    eval(parse(text=arg), envir=envir)

  for (nm in names(defaults))
    assign(nm, mget(nm, ifnotfound=list(defaults[[nm]]), envir=envir)[[1]], pos=envir)

## example usage:
parseCommandArgs(list(a=1, b=c(1,1,1)))

Switch statement with returns -- code correctness

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

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

So get rid of the break following a return.

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

running a command as a super user from a python script

I used this for python 3.5. I did it using subprocess module.Using the password like this is very insecure.

The subprocess module takes command as a list of strings so either create a list beforehand using split() or pass the whole list later. Read the documentation for more information.

What we are doing here is echoing the password and then using pipe we pass it on to the sudo through '-S' argument.

#!/usr/bin/env python
import subprocess

sudo_password = 'mysecretpass'
command = 'apach2ctl restart'
command = command.split()

cmd1 = subprocess.Popen(['echo',sudo_password], stdout=subprocess.PIPE)
cmd2 = subprocess.Popen(['sudo','-S'] + command, stdin=cmd1.stdout, stdout=subprocess.PIPE)

output = 

jQuery datepicker to prevent past date

var givenStartDate = $('#startDate').val();
        alert('START DATE'+givenStartDate);
        var givenEndDate = $('#endDate').val();
        alert('END DATE'+givenEndDate);
        var date = new Date();
        var month = date.getMonth()+1;
        var day = date.getDate();
        var currentDate = date.getFullYear() + '-' +
            (month<10 ? '0' : '') + month + '-' +
            (day<10 ? '0' : '') + day;
        if(givenStartDate < currentDate || givenEndDate < currentDate)
         if(givenStartDate < currentDate && givenEndDate > currentDate)
         if(givenStartDate > currentDate || givenEndDate > currentDate) { 

Try this. If any mistake, please correct me :) Thanks all.

How can I convert an Int to a CString?

If you want something more similar to your example try _itot_s. On Microsoft compilers _itot_s points to _itoa_s or _itow_s depending on your Unicode setting:

CString str;
_itot_s( 15, str.GetBufferSetLength( 40 ), 40, 10 );

it should be slightly faster since it doesn't need to parse an input format.

Converting Hexadecimal String to Decimal Integer

It looks like there's an extra space character in your string. You can use trim() to remove leading and trailing whitespaces:

temp1 = Integer.parseInt(display.getText().trim(), 16 );

Or if you think the presence of a space means there's something else wrong, you'll have to look into it yourself, since we don't have the rest of your code.

How to style icon color, size, and shadow of Font Awesome Icons

In FontAwesome 4.0, the classes change to 'fa-2x', 'fa-3x'.

MySQL IF ELSEIF in select query

For your question :

   IF(qty_1 <= '23', price,
   IF(('23' > qty_1 && qty_2 <= '23'), price_2,
   IF(('23' > qty_2 && qty_3 <= '23'), price_3,
   IF(('23' > qty_2 && qty_3<='23'), price_3,
   IF('23' > qty_3, price_4, 1))))) as total 
FROM product;

You can use the if - else control structure or the IF function in MySQL.


Splitting a string at every n-th character

You could do it like this:

String s = "1234567890";

which produces:

[123, 456, 789, 0]

The regex (?<=\G...) matches an empty string that has the last match (\G) followed by three characters (...) before it ((?<= ))

What is /dev/null 2>&1?

Edit /etc/conf.apf. Set DEVEL_MODE="0". DEVEL_MODE set to 1 will add a cron job to stop apf after 5 minutes.

SQL Server - Convert varchar to another collation (code page) to fix character encoding

We may need more information. Here is what I did to reproduce on SQL Server 2008:

    NAME = N'Test'
    , FILENAME = N'...Test.mdf' 
    , SIZE = 3072KB 
    , FILEGROWTH = 1024KB 
    LOG ON 
    NAME = N'Test_log'
    , FILENAME = N'...Test_log.ldf' 
    , SIZE = 1024KB 
    , FILEGROWTH = 10%
    COLLATE SQL_Latin1_General_CP850_BIN2
CREATE TABLE [dbo].[MyTable]
    [SomeCol] [varchar](50) NULL
    ) ON [PRIMARY]
Insert MyTable( SomeCol )
Select '±' Collate SQL_Latin1_General_CP1_CI_AS
Select SomeCol, SomeCol Collate SQL_Latin1_General_CP1_CI_AS
From MyTable

Results show the original character. Declaring collation in the query should return the proper character from SQL Server's perspective however it may be the case that the presentation layer is then converting to something yet different like UTF-8.

SOAP-UI - How to pass xml inside parameter

To send CDATA in a request object use the SoapObject.setInnerText("..."); method.

Richtextbox wpf binding

There is a much easier way!

You can easily create an attached DocumentXaml (or DocumentRTF) property which will allow you to bind the RichTextBox's document. It is used like this, where Autobiography is a string property in your data model:

<TextBox Text="{Binding FirstName}" />
<TextBox Text="{Binding LastName}" />
<RichTextBox local:RichTextBoxHelper.DocumentXaml="{Binding Autobiography}" />

Voila! Fully bindable RichTextBox data!

The implementation of this property is quite simple: When the property is set, load the XAML (or RTF) into a new FlowDocument. When the FlowDocument changes, update the property value.

This code should do the trick:

using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
public class RichTextBoxHelper : DependencyObject
    public static string GetDocumentXaml(DependencyObject obj)
        return (string)obj.GetValue(DocumentXamlProperty);

    public static void SetDocumentXaml(DependencyObject obj, string value)
        obj.SetValue(DocumentXamlProperty, value);

    public static readonly DependencyProperty DocumentXamlProperty =
            new FrameworkPropertyMetadata
                BindsTwoWayByDefault = true,
                PropertyChangedCallback = (obj, e) =>
                    var richTextBox = (RichTextBox)obj;

                    // Parse the XAML to a document (or use XamlReader.Parse())
                    var xaml = GetDocumentXaml(richTextBox);
                    var doc = new FlowDocument();
                    var range = new TextRange(doc.ContentStart, doc.ContentEnd);

                    range.Load(new MemoryStream(Encoding.UTF8.GetBytes(xaml)),

                    // Set the document
                    richTextBox.Document = doc;

                    // When the document changes update the source
                    range.Changed += (obj2, e2) =>
                        if (richTextBox.Document == doc)
                            MemoryStream buffer = new MemoryStream();
                            range.Save(buffer, DataFormats.Xaml);

The same code could be used for TextFormats.RTF or TextFormats.XamlPackage. For XamlPackage you would have a property of type byte[] instead of string.

The XamlPackage format has several advantages over plain XAML, especially the ability to include resources such as images, and it is more flexible and easier to work with than RTF.

It is hard to believe this question sat for 15 months without anyone pointing out the easy way to do this.

Changing PowerShell's default output encoding to UTF-8

To be short, use:

write-output "your text" | out-file -append -encoding utf8 "filename"

Sniffing/logging your own Android Bluetooth traffic

Also, this might help finding the actual location the btsnoop_hci.log is being saved:

adb shell "cat /etc/bluetooth/bt_stack.conf | grep FileName"

How to change font size on part of the page in LaTeX?

To add exact fontsize you can use following. Worked for me since in my case predefined ranges (Large, tiny) are not match with the font size required to me.

\fontsize{10}{12}\selectfont This is the text you need to be in 10px

More info:

Get selected option text with JavaScript

I just copy all "select list", you can see demo from following image.gif link.

see demo now

I love "select/option" css style and javascript tricks...

try it now....

/***javascript code***/
  document.querySelector("#mySelect").addEventListener("click", () => {
    var x = document.querySelector("#mySelect").selectedIndex;
    let optionText = document.getElementsByTagName("option")[x].innerText;
    document.querySelector(".nav-search-label").innerText = optionText;
  .nav-left {
    display: -webkit-box;
    display: -moz-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    position: static;
    float: none;
  .nav-search-scope {
    display: -webkit-box;
    display: -moz-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    position: relative;
    float: none;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
  .nav-search-facade {
    position: relative;
    float: left;
    cursor: default;
    overflow: hidden;
    top: 3px;
  .nav-search-label {
    display: block;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    color: #555;
    font-size: 12px;
    line-height: 33px;
    margin-right: 21px;
    margin-left: 5px;
    min-width: 19px;
  .nav-icon {
    position: absolute;
    top: 14px;
    right: 8px;
    border-style: solid;
    _border-style: dashed;
    border-width: 4px;
    border-color: transparent;
    border-top: 4px solid #666;
    border-bottom-width: 0;
    width: 0;
    height: 0;
    font-size: 0;
    line-height: 0;
  .nav-search-dropdown {
    position: absolute;
    display: block;
    top: -1px;
    left: 0;
    height: 35px;
    width: auto;
    font-family: inherit;
    outline: 0;
    margin: 0;
    padding: 0;
    cursor: pointer;
    opacity: 0;
    filter: alpha(opacity=0);
    visibility: visible;
    border: 0;
    line-height: 35px;
<!--html code-->
<div class="nav-left">
  <div id="nav-search-dropdown-card">
    <div class="nav-search-scope nav-sprite">
      <div class="nav-search-facade">
        <span class="nav-search-label" style="width: auto">All</span>
        <i class="nav-icon"></i>

        class="nav-search-dropdown searchSelect"
        style="display: block; top: 3px"
        title="Search in"
        <option>All Departments</option>
        <option>Arts &amp; Crafts</option>
        <option>Beauty &amp; Personal Care</option>
        <option>Digital Music</option>
        <option>Kindle Store</option>
        <option>Prime Video</option>
        <option>Women's Fashion</option>
        <option>Men's Fashion</option>
        <option>Girls' Fashion</option>
        <option>Boys' Fashion</option>
        <option>Health &amp; Household</option>
        <option>Home &amp; Kitchen</option>
        <option>Industrial &amp; Scientific</option>
        <option>Movies &amp; TV</option>
        <option>Music, CDs &amp; Vinyl</option>
        <option>Pet Supplies</option>
        <option>Sports &amp; Outdoors</option>
        <option>Tools &amp; Home Improvement</option>
        <option>Toys &amp; Games</option>
        <option>Video Games</option>

Convert a list of characters into a string

If your Python interpreter is old (1.5.2, for example, which is common on some older Linux distributions), you may not have join() available as a method on any old string object, and you will instead need to use the string module. Example:

a = ['a', 'b', 'c', 'd']

    b = ''.join(a)

except AttributeError:
    import string
    b = string.join(a, '')

The string b will be 'abcd'.

How to place two forms on the same page?

Give the submit buttons for both forms different names and use PHP to check which button has submitted data.

Form one button - btn1 Form two button -btn2

PHP Code:


How do I print colored output to the terminal in Python?

I suggest sty. It's similar to colorama, but less verbose and it supports 8bit and 24bit colors. You can also extend the color register with your own colors.


from sty import fg, bg, ef, rs

foo = + 'This is red text!' +
bar = + 'This has a blue background!' +
baz = ef.italic + 'This is italic text' + rs.italic
qux = fg(201) + 'This is pink text using 8bit colors' +
qui = fg(255, 10, 10) + 'This is red text using 24bit colors.' +

# Add custom colors:

from sty import Style, RgbFg = Style(RgbFg(255, 150, 50))

buf = + 'Yay, Im orange.' +

print(foo, bar, baz, qux, qui, buf, sep='\n')

enter image description here


enter image description here

Static Block in Java

It's a block of code which is executed when the class gets loaded by a classloader. It is meant to do initialization of static members of the class.

It is also possible to write non-static initializers, which look even stranger:

public class Foo {
        // This code will be executed before every constructor
        // but after the call to super()

    Foo() {


How to install pip with Python 3?

This is what I did on OS X Mavericks to get this to work.

Firstly, have brew installed

Install python 3.4

brew install python3

Then I get the latest version of distribute:


cd distribute-0.7.3
sudo install
sudo easy_install-3.4 pip
sudo pip3.4 install virtualenv
sudo pip3.4 install virtualenvwrapper

mkvirtualenv py3 

python --version
Python 3.4.1

I hope this helps.

CSS Selector for <input type="?"

You can do this with jQuery. Using their selectors, you can select by attributes, such as type. This does, however, require that your users have Javascript turned on, and an additional file to download, but if it works...

Difference between text and varchar (character varying)

On PostgreSQL manual

There is no performance difference among these three types, apart from increased storage space when using the blank-padded type, and a few extra CPU cycles to check the length when storing into a length-constrained column. While character(n) has performance advantages in some other database systems, there is no such advantage in PostgreSQL; in fact character(n) is usually the slowest of the three because of its additional storage costs. In most situations text or character varying should be used instead.

I usually use text


How is the default submit button on an HTML form determined?

HTML 4 does not make it explicit. The current HTML5 working draft specifies that the first submit button must be the default:

A form element's default button is the first submit button in tree order whose form owner is that form element.

If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button.

How to programmatically set the Image source

Use asp:image

<asp:Image id="Image1" runat="server"
           AlternateText="Image text"

and codebehind to change image url

Image1.ImageUrl = "/MyProject;component/Images/down.png"; 

What's the best mock framework for Java?

We are heavily using EasyMock and EasyMock Class Extension at work and are pretty happy with it. It basically gives you everything you need. Take a look at the documentation, there's a very nice example which shows you all the features of EasyMock.

How to download a folder from github?

Use GitZip online tool. It allows to download a sub-directory of a github repository as a zip file. No git commands needed!

Share application "link" in Android

To be more exact

   Intent intent = new Intent(Intent.ACTION_VIEW);

or if you want to share your other apps from your dev. account you can do something like this

Intent intent = new Intent(Intent.ACTION_VIEW);

Ruby Arrays: select(), collect(), and map()

EDIT: I just realized you want to filter details, which is an array of hashes. In that case you could do

details.reject { |item| item[:qty].empty? }

The inner data structure itself is not an Array, but a Hash. You can also use select here, but the block is given the key and value in this case:

irb(main):001:0> h = {:sku=>"507772-B21", :desc=>"HP 1TB 3G SATA 7.2K RPM LFF (3 .", :qty=>"", :qty2=>"1", :price=>"5,204.34 P"}
irb(main):002:0> { |key, value| !value.empty? }
=> {:sku=>"507772-B21", :desc=>"HP 1TB 3G SATA 7.2K RPM LFF (3 .", 
    :qty2=>"1", :price=>"5,204.34 P"}

Or using reject, which is the inverse of select (excludes all items for which the given condition holds):

h.reject { |key, value| value.empty? }

Note that this is Ruby 1.9. If you have to maintain compatibility with 1.8, you could do:

Hash[h.reject { |key, value| value.empty? }]

How do I test if a variable is a number in Bash?

To catch negative numbers:

if [[ $1 == ?(-)+([0-9.]) ]]
    echo number
    echo not a number

Write to CSV file and export it?

Here's a very simple free open-source CsvExport class for C#. There's an ASP.NET MVC example at the bottom.

It takes care about line-breaks, commas, escaping quotes, MS Excel compatibilty... Just add one short .cs file to your project and you're good to go.

(disclaimer: I'm one of the contributors)

Deploy a project using Git push

I found this script on this site and it seems to work quite well.

  1. Copy over your .git directory to your web server
  2. On your local copy, modify your .git/config file and add your web server as a remote:

    [remote "production"]
        url = username@webserver:/path/to/htdocs/.git
  3. On the server, replace .git/hooks/post-update with this file (in the answer below)

  4. Add execute access to the file (again, on the server):

    chmod +x .git/hooks/post-update
  5. Now, just locally push to your web server and it should automatically update the working copy:

    git push production

Can I set state inside a useEffect hook

? 1. Can I set state inside a useEffect hook?

In principle, you can set state freely where you need it - including inside useEffect and even during rendering. Just make sure to avoid infinite loops by settting Hook deps properly and/or state conditionally.

? 2. Lets say I have some state that is dependent on some other state. Is it appropriate to create a hook that observes A and sets B inside the useEffect hook?

You just described the classic use case for useReducer:

useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one. (React docs)

When setting a state variable depends on the current value of another state variable, you might want to try replacing them both with useReducer. [...] When you find yourself writing setSomething(something => ...), it’s a good time to consider using a reducer instead. (Dan Abramov, Overreacted blog)

let MyComponent = () => {_x000D_
  let [state, dispatch] = useReducer(reducer, { a: 1, b: 2 });_x000D_
  useEffect(() => {_x000D_
    console.log("Some effect with B");_x000D_
  }, [state.b]);_x000D_
  return (_x000D_
      <p>A: {state.a}, B: {state.b}</p>_x000D_
      <button onClick={() => dispatch({ type: "SET_A", payload: 5 })}>_x000D_
        Set A to 5 and Check B_x000D_
      <button onClick={() => dispatch({ type: "INCREMENT_B" })}>_x000D_
        Increment B_x000D_
// B depends on A. If B >= A, then reset B to 1._x000D_
function reducer(state, { type, payload }) {_x000D_
  const someCondition = state.b >= state.a;_x000D_
  if (type === "SET_A")_x000D_
    return someCondition ? { a: payload, b: 1 } : { ...state, a: payload };_x000D_
  else if (type === "INCREMENT_B") return { ...state, b: state.b + 1 };_x000D_
  return state;_x000D_
ReactDOM.render(<MyComponent />, document.getElementById("root"));
<script src="" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>_x000D_
<script src="" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>_x000D_
<div id="root"></div>_x000D_
<script>var { useReducer, useEffect } = React</script>

? 3. Will the effects cascade such that, when I click the button, the first effect will fire, causing b to change, causing the second effect to fire, before the next render?

useEffect always runs after the render is committed and DOM changes are applied. The first effect fires, changes b and causes a re-render. After this render has completed, second effect will run due to b changes.

let MyComponent = props => {_x000D_
  let [a, setA] = useState(1);_x000D_
  let [b, setB] = useState(2);_x000D_
  let isFirstRender = useRef(true);_x000D_
  useEffect(() => {_x000D_
    console.log("useEffect a, value:", a);_x000D_
    if (isFirstRender.current) isFirstRender.current = false;_x000D_
    else setB(3);_x000D_
    return () => {_x000D_
      console.log("unmount useEffect a, value:", a);_x000D_
  }, [a]);_x000D_
  useEffect(() => {_x000D_
    console.log("useEffect b, value:", b);_x000D_
    return () => {_x000D_
      console.log("unmount useEffect b, value:", b);_x000D_
  }, [b]);_x000D_
  return (_x000D_
      <p>a: {a}, b: {b}</p>_x000D_
        onClick={() => {_x000D_
        click me_x000D_
ReactDOM.render(<MyComponent />, document.getElementById("root"));
<script src="" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>_x000D_
<script src="" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>_x000D_
<div id="root"></div>_x000D_
<script>var { useReducer, useEffect, useState, useRef } = React</script>

? 4. Are there any performance downsides to structuring code like this?

Yes. By wrapping the state change of b in a separate useEffect for a, the browser has an additional layout/paint phase - these effects are potentially visible for the user. If there is no way you want give useReducer a try, you could change b state together with a directly:

let MyComponent = () => {_x000D_
  let [a, setA] = useState(1);_x000D_
  let [b, setB] = useState(2);_x000D_
  useEffect(() => {_x000D_
    console.log("useEffect b, value:", b);_x000D_
    return () => {_x000D_
      console.log("unmount useEffect b, value:", b);_x000D_
  }, [b]);_x000D_
  const handleClick = () => {_x000D_
    b >= 5 ? setB(1) : setB(b + 1);_x000D_
  return (_x000D_
        a: {a}, b: {b}_x000D_
      <button onClick={handleClick}>click me</button>_x000D_
ReactDOM.render(<MyComponent />, document.getElementById("root"));
<script src="" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>_x000D_
<script src="" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>_x000D_
<div id="root"></div>_x000D_
<script>var { useReducer, useEffect, useState, useRef } = React</script>

Why can't I find SQL Server Management Studio after installation?

It appears that SQL Server 2008 R2 can be downloaded with or without the management tools. I honestly have NO IDEA why someone would not want the management tools. But either way, the options are here:

and the one for 64 bit WITH the management tools (management studio) is here:

From the first link I presented, the 3rd and 4th include the management studio for 32 and 64 bit respectively.

Best way to check for null values in Java?

if you do not have an access to the commons apache library, the following probably will work ok

if(null != foo && {
//do something

connect to host localhost port 22: Connection refused

you need to check the configuration in sshd_config ListenAddress update this and restart the sshd service that will resolve the issue.

Replace first occurrence of string in Python

Use re.sub directly, this allows you to specify a count:

regex.sub('', url, 1)

(Note that the order of arguments is replacement, original not the opposite, as might be suspected.)

How To Get Selected Value From UIPickerView

       NSInteger SelectedRow;
                   SelectedRow = [yourPickerView selectedRowInComponent:0];
                   selectedPickerString = [YourPickerArray objectAtIndex:SelectedRow];
                   self.YourTextField.text= selectedPickerString;

    // if  you want to move pickerview to selected row then 
 for (int i = 0; I<YourPickerArray.count; i++) {
  if ([[YourPickerArray objectAtIndex:i] isEqualToString:self.YourTextField.text]) { 
[yourPickerView selectRow:i inComponent:0 animated:NO];

Swift: Determine iOS Screen size

In Swift 3.0

let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

In older swift: Do something like this:

let screenSize: CGRect = UIScreen.mainScreen().bounds

then you can access the width and height like this:

let screenWidth = screenSize.width
let screenHeight = screenSize.height

if you want 75% of your screen's width you can go:

let screenWidth = screenSize.width * 0.75

Swift 4.0

// Screen width.
public var screenWidth: CGFloat {
    return UIScreen.main.bounds.width

// Screen height.
public var screenHeight: CGFloat {
    return UIScreen.main.bounds.height

In Swift 5.0

let screenSize: CGRect = UIScreen.main.bounds

Writing a dictionary to a text file?

First of all you are opening file in read mode and trying to write into it. Consult - IO modes python

Secondly, you can only write a string to a file. If you want to write a dictionary object, you either need to convert it into string or serialize it.

import json

# as requested in comment
exDict = {'exDict': exDict}

with open('file.txt', 'w') as file:
     file.write(json.dumps(exDict)) # use `json.loads` to do the reverse

In case of serialization

import cPickle as pickle

with open('file.txt', 'w') as file:
     file.write(pickle.dumps(exDict)) # use `pickle.loads` to do the reverse

For python 3.x pickle package import would be different

import _pickle as pickle

Is there a way to comment out markup in an .ASPX page?

Yes, there are special server side comments:

<%-- Text not sent to client  --%>

How to draw border on just one side of a linear layout?

Easy as pie, allowing a transparent bg:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android=""
        android:centerX="0.01" />

Change the angle to change border location:

  • 0 = left
  • 90 = bottom
  • 180 = right
  • 270 = top

Select the values of one property on all objects of an array in PowerShell

To complement the preexisting, helpful answers with guidance of when to use which approach and a performance comparison.

  • Outside of a pipeline[1], use (PSv3+):

    as demonstrated in rageandqq's answer, which is both syntactically simpler and much faster.

    • Accessing a property at the collection level to get its members' values as an array is called member enumeration and is a PSv3+ feature.

    • Alternatively, in PSv2, use the foreach statement, whose output you can also assign directly to a variable:

      $results = foreach ($obj in $objects) { $obj.Name }

    • If collecting all output from a (pipeline) command in memory first is feasible, you can also combine pipelines with member enumeration; e.g.:

       (Get-ChildItem -File | Where-Object Length -lt 1gb).Name
    • Tradeoffs:

      • Both the input collection and output array must fit into memory as a whole.
      • If the input collection is itself the result of a command (pipeline) (e.g., (Get-ChildItem).Name), that command must first run to completion before the resulting array's elements can be accessed.
  • In a pipeline, in case you must pass the results to another command, notably if the original input doesn't fit into memory as a whole, use:

    $objects | Select-Object -ExpandProperty Name

    • The need for -ExpandProperty is explained in Scott Saad's answer (you need it to get only the property value).
    • You get the usual pipeline benefits of the pipeline's streaming behavior, i.e. one-by-one object processing, which typically produces output right away and keeps memory use constant (unless you ultimately collect the results in memory anyway).
    • Tradeoff:
      • Use of the pipeline is comparatively slow.

For small input collections (arrays), you probably won't notice the difference, and, especially on the command line, sometimes being able to type the command easily is more important.

Here is an easy-to-type alternative, which, however is the slowest approach; it uses simplified ForEach-Object syntax called an operation statement (again, PSv3+): ; e.g., the following PSv3+ solution is easy to append to an existing command:

$objects | % Name      # short for: $objects | ForEach-Object -Process { $_.Name }

The PSv4+ .ForEach() array method, more comprehensively discussed in this article, is yet another, well-performing alternative, but note that it requires collecting all input in memory first, just like member enumeration:

# By property name (string):

# By script block (more flexibility; like ForEach-Object)
$objects.ForEach({ $_.Name })
  • This approach is similar to member enumeration, with the same tradeoffs, except that pipeline logic is not applied; it is marginally slower than member enumeration, though still noticeably faster than the pipeline.

  • For extracting a single property value by name (string argument), this solution is on par with member enumeration (though the latter is syntactically simpler).

  • The script-block variant ({ ... }) allows arbitrary transformations; it is a faster - all-in-memory-at-once - alternative to the pipeline-based ForEach-Object cmdlet (%).

Note: The .ForEach() array method, like its .Where() sibling (the in-memory equivalent of Where-Object), always returns a collection (an instance of [System.Collections.ObjectModel.Collection[psobject]]), even if only one output object is produced.
By contrast, member enumeration, Select-Object, ForEach-Object and Where-Object return a single output object as-is, without wrapping it in a collection (array).

Comparing the performance of the various approaches

Here are sample timings for the various approaches, based on an input collection of 10,000 objects, averaged across 10 runs; the absolute numbers aren't important and vary based on many factors, but it should give you a sense of relative performance (the timings come from a single-core Windows 10 VM:


  • The relative performance varies based on whether the input objects are instances of regular .NET Types (e.g., as output by Get-ChildItem) or [pscustomobject] instances (e.g., as output by Convert-FromCsv).
    The reason is that [pscustomobject] properties are dynamically managed by PowerShell, and it can access them more quickly than the regular properties of a (statically defined) regular .NET type. Both scenarios are covered below.

  • The tests use already-in-memory-in-full collections as input, so as to focus on the pure property extraction performance. With a streaming cmdlet / function call as the input, performance differences will generally be much less pronounced, as the time spent inside that call may account for the majority of the time spent.

  • For brevity, alias % is used for the ForEach-Object cmdlet.

General conclusions, applicable to both regular .NET type and [pscustomobject] input:

  • The member-enumeration ($collection.Name) and foreach ($obj in $collection) solutions are by far the fastest, by a factor of 10 or more faster than the fastest pipeline-based solution.

  • Surprisingly, % Name performs much worse than % { $_.Name } - see this GitHub issue.

  • PowerShell Core consistently outperforms Windows Powershell here.

Timings with regular .NET types:

  • PowerShell Core v7.0.0-preview.3
Factor Command                                       Secs (10-run avg.)
------ -------                                       ------------------
1.00   $objects.Name                                 0.005
1.06   foreach($o in $objects) { $o.Name }           0.005
6.25   $objects.ForEach('Name')                      0.028
10.22  $objects.ForEach({ $_.Name })                 0.046
17.52  $objects | % { $_.Name }                      0.079
30.97  $objects | Select-Object -ExpandProperty Name 0.140
32.76  $objects | % Name                             0.148
  • Windows PowerShell v5.1.18362.145
Factor Command                                       Secs (10-run avg.)
------ -------                                       ------------------
1.00   $objects.Name                                 0.012
1.32   foreach($o in $objects) { $o.Name }           0.015
9.07   $objects.ForEach({ $_.Name })                 0.105
10.30  $objects.ForEach('Name')                      0.119
12.70  $objects | % { $_.Name }                      0.147
27.04  $objects | % Name                             0.312
29.70  $objects | Select-Object -ExpandProperty Name 0.343


  • In PowerShell Core, .ForEach('Name') clearly outperforms .ForEach({ $_.Name }). In Windows PowerShell, curiously, the latter is faster, albeit only marginally so.

Timings with [pscustomobject] instances:

  • PowerShell Core v7.0.0-preview.3
Factor Command                                       Secs (10-run avg.)
------ -------                                       ------------------
1.00   $objects.Name                                 0.006
1.11   foreach($o in $objects) { $o.Name }           0.007
1.52   $objects.ForEach('Name')                      0.009
6.11   $objects.ForEach({ $_.Name })                 0.038
9.47   $objects | Select-Object -ExpandProperty Name 0.058
10.29  $objects | % { $_.Name }                      0.063
29.77  $objects | % Name                             0.184
  • Windows PowerShell v5.1.18362.145
Factor Command                                       Secs (10-run avg.)
------ -------                                       ------------------
1.00   $objects.Name                                 0.008
1.14   foreach($o in $objects) { $o.Name }           0.009
1.76   $objects.ForEach('Name')                      0.015
10.36  $objects | Select-Object -ExpandProperty Name 0.085
11.18  $objects.ForEach({ $_.Name })                 0.092
16.79  $objects | % { $_.Name }                      0.138
61.14  $objects | % Name                             0.503


  • Note how with [pscustomobject] input .ForEach('Name') by far outperforms the script-block based variant, .ForEach({ $_.Name }).

  • Similarly, [pscustomobject] input makes the pipeline-based Select-Object -ExpandProperty Name faster, in Windows PowerShell virtually on par with .ForEach({ $_.Name }), but in PowerShell Core still about 50% slower.

  • In short: With the odd exception of % Name, with [pscustomobject] the string-based methods of referencing the properties outperform the scriptblock-based ones.

Source code for the tests:


  • Download function Time-Command from this Gist to run these tests.

    • Assuming you have looked at the linked code to ensure that it is safe (which I can personally assure you of, but you should always check), you can install it directly as follows:

      irm | iex
  • Set $useCustomObjectInput to $true to measure with [pscustomobject] instances instead.

$count = 1e4 # max. input object count == 10,000
$runs  = 10  # number of runs to average 

# Note: Using [pscustomobject] instances rather than instances of 
#       regular .NET types changes the performance characteristics.
# Set this to $true to test with [pscustomobject] instances below.
$useCustomObjectInput = $false

# Create sample input objects.
if ($useCustomObjectInput) {
  # Use [pscustomobject] instances.
  $objects = 1..$count | % { [pscustomobject] @{ Name = "$foobar_$_"; Other1 = 1; Other2 = 2; Other3 = 3; Other4 = 4 } }
} else {
  # Use instances of a regular .NET type.
  # Note: The actual count of files and folders in your file-system
  #       may be less than $count
  $objects = Get-ChildItem / -Recurse -ErrorAction Ignore | Select-Object -First $count

Write-Host "Comparing property-value extraction methods with $($objects.Count) input objects, averaged over $runs runs..."

# An array of script blocks with the various approaches.
$approaches = { $objects | Select-Object -ExpandProperty Name },
              { $objects | % Name },
              { $objects | % { $_.Name } },
              { $objects.ForEach('Name') },
              { $objects.ForEach({ $_.Name }) },
              { $objects.Name },
              { foreach($o in $objects) { $o.Name } }

# Time the approaches and sort them by execution time (fastest first):
Time-Command $approaches -Count $runs | Select Factor, Command, Secs*

[1] Technically, even a command without |, the pipeline operator, uses a pipeline behind the scenes, but for the purpose of this discussion using the pipeline refers only to commands that do use | and therefore involve multiple commands connected by a pipeline.

JavaScript window resize event

var EM = new events_managment();

EM.addEvent(window, 'resize', function(win,doc, event_){
    //EM.removeEvent(win,doc, event_);

function events_managment(){ = {};
    this.addEvent = function(node, event_, func){
            if(event_ in{
                node.addEventListener(event_, function(){
                    func(node, event_);
          [event_](win_doc, event_);
                }, true);
                node.addEventListener(event_, function(){
                    func(node, event_);
                }, true);
  [event_] = func;
        }else if(node.attachEvent){

            var ie_event = 'on' + event_;
            if(ie_event in{
                node.attachEvent(ie_event, function(){
                    func(node, ie_event);
                node.attachEvent(ie_event, function(){
                    func(node, ie_event);
  [ie_event] = func;
    this.removeEvent = function(node, event_){
            node.removeEventListener(event_,[event_], true);
  [event_] = null;
        }else if(node.detachEvent){
  [event_] = null;

Apply function to each column in a data frame observing each columns existing data type

The reason that max works with apply is that apply is coercing your data frame to a matrix first, and a matrix can only hold one data type. So you end up with a matrix of characters. sapply is just a wrapper for lapply, so it is not surprising that both yield the same error.

The default behavior when you create a data frame is for categorical columns to be stored as factors. Unless you specify that it is an ordered factor, operations like max and min will be undefined, since R is assuming that you've created an unordered factor.

You can change this behavior by specifying options(stringsAsFactors = FALSE), which will change the default for the entire session, or you can pass stringsAsFactors = FALSE in the data.frame() construction call itself. Note that this just means that min and max will assume "alphabetical" ordering by default.

Or you can manually specify an ordering for each factor, although I doubt that's what you want to do.

Regardless, sapply will generally yield an atomic vector, which will entail converting everything to characters in many cases. One way around this is as follows:

#Some test data
d <- data.frame(v1 = runif(10), v2 = letters[1:10], 
                v3 = rnorm(10), v4 = LETTERS[1:10],stringsAsFactors = TRUE)

d[4,] <- NA

#Similar function to DWin's answer          
fun <- function(x){
    if(is.numeric(x)){max(x,na.rm = 1)}

#Use colwise from plyr package
         v1 v2       v3 v4
1 0.8478983  j 1.999435  J

jQuery attr() change img src

You remove the original image here:

newImg.animate(css, SPEED, function() {
    (callback || function() {})();

And all that's left behind is newImg. Then you reset link references the image using #rocket:

$("#rocket").attr('src', ...

But your newImg doesn't have an id attribute let alone an id of rocket.

To fix this, you need to remove img and then set the id attribute of newImg to rocket:

newImg.animate(css, SPEED, function() {
    var old_id = img.attr('id');
    newImg.attr('id', old_id);
    (callback || function() {})();

And then you'll get the shiny black rocket back again:

UPDATE: A better approach (as noted by mellamokb) would be to hide the original image and then show it again when you hit the reset button. First, change the reset action to something like this:

    $("#wrapper").css('top', '250px');
    $('.throbber, .morpher').remove(); // Clear out the new stuff.
    $("#rocket").show();               // Bring the original back.

And in the newImg.load function, grab the images original size:

var orig = {
    width: img.width(),
    height: img.height()

And finally, the callback for finishing the morphing animation becomes this:

newImg.animate(css, SPEED, function() {
    (callback || function() {})();

New and improved:

The leaking of $('.throbber, .morpher') outside the plugin isn't the best thing ever but it isn't a big deal as long as it is documented.

Not Equal to This OR That in Lua

x ~= 0 or 1 is the same as ((x ~= 0) or 1)

x ~=(0 or 1) is the same as (x ~= 0).

try something like this instead.

function isNot0Or1(x)
    return (x ~= 0 and x ~= 1)

print( isNot0Or1(-1) == true )
print( isNot0Or1(0) == false )
print( isNot0Or1(1) == false )

How to add/update child entities when updating a parent entity in EF

public async Task<IHttpActionResult> PutParent(int id, Parent parent)
            if (!ModelState.IsValid)
                return BadRequest(ModelState);

            if (id != parent.Id)
                return BadRequest();

            db.Entry(parent).State = EntityState.Modified;

            foreach (Child child in parent.Children)
                db.Entry(child).State = child.Id == 0 ? EntityState.Added : EntityState.Modified;

                await db.SaveChangesAsync();
            catch (DbUpdateConcurrencyException)
                if (!ParentExists(id))
                    return NotFound();

            return Ok(db.Parents.Find(id));

This is how I solved this problem. This way, EF knows which to add which to update.

How to increment a datetime by one day?

date = datetime.datetime(2003,8,1,12,4,5)
for i in range(5): 
    date += datetime.timedelta(days=1)

How can I ping a server port with PHP?

You can use exec function

 exec("ping ".$ip);

here an example

How to remove \xa0 from string in Python?

It's the equivalent of a space character, so strip it

print(string.strip()) # no more xa0

Do we need type="text/css" for <link> in HTML5

Don’t need to specify a type value of “text/css”

Every time you link to a CSS file:

<link rel="stylesheet" type="text/css" href="file.css">

You can simply write:

<link rel="stylesheet" href="file.css">

Why would a " Connection timed out" exception occur when URL is up?

If the URL works fine in the web browser on the same machine, it might be that the Java code isn't using the HTTP proxy the browser is using for connecting to the URL.

What's the difference between a single precision and double precision floating point operation?

All have explained in great detail and nothing I could add further. Though I would like to explain it in Layman's Terms or plain ENGLISH

1.9 is less precise than 1.99
1.99 is less precise than 1.999
1.999 is less precise than 1.9999


A variable, able to store or represent "1.9" provides less precision than the one able to hold or represent 1.9999. These Fraction can amount to a huge difference in large calculations.

Make a directory and copy a file

Use the FileSystemObject object, namely, its CreateFolder and CopyFile methods. Basically, this is what your script will look like:

Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")

' Create a new folder
oFSO.CreateFolder "C:\MyFolder"

' Copy a file into the new folder
' Note that the destination folder path must end with a path separator (\)
oFSO.CopyFile "\\server\folder\file.ext", "C:\MyFolder\"

You may also want to add additional logic, like checking whether the folder you want to create already exists (because CreateFolder raises an error in this case) or specifying whether or not to overwrite the file being copied. So, you can end up with this:

Const strFolder = "C:\MyFolder\", strFile = "\\server\folder\file.ext"
Const Overwrite = True
Dim oFSO

Set oFSO = CreateObject("Scripting.FileSystemObject")

If Not oFSO.FolderExists(strFolder) Then
  oFSO.CreateFolder strFolder
End If

oFSO.CopyFile strFile, strFolder, Overwrite

What's is the difference between include and extend in use case diagram?

I often use this to remember the two:

My use case: I am going to the city.

includes -> drive the car

extends -> fill the petrol

"Fill the petrol" may not be required at all times, but may optionally be required based on the amount of petrol left in the car. "Drive the car" is a prerequisite hence I am including.

Where does Chrome store extensions?

Storage Location for Unpacked Extensions

Extension engine does not explicitly change their location or add a reference to its local paths, they are left in the place where there are selected from in all Operating Systems.

Ex: If i load a unpacked Extension from E:\Chrome Extension the unpacked Extension is still in the same location

Storage Location for Packed Extensions

Navigate to chrome://version/ and look for Profile Path, it is your default directory and Extensions Folder is where all the extensions, apps, themes are stored



If my Profile Path is %userprofile%\AppData\Local\Google\Chrome\User Data\Default then my storage directory is:

C:\Users\<Your_User_Name>\AppData\Local\Google\Chrome\User Data\Default\Extensions 




~/Library/Application\ Support/Google/Chrome/Default/Extensions



How do I create a file and write to it?

A very simple way to create and write to a file in Java:


public class CreateFiles {

    public static void main(String[] args) {
            // Create new file
            String content = "This is the content to write into create file";
            String path="D:\\a\\hi.txt";
            File file = new File(path);

            // If file doesn't exists, then create it
            if (!file.exists()) {

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);

            // Write in file

            // Close connection
        catch(Exception e){

How to set up ES cluster?

I tried the steps that @KannarKK suggested on ES 2.0.2, however, I could not bring the cluster up and running. Evidently, I figured out something, as I had set tcp port number on Master, on the Slave configuration needs Master's port number along with IP address ( tcp port number ) for discovery. So when I try following configuration it works for me.

Node 1 mycluster "node1"
node.master: true true
http.port : 9200
tcp.port : 9300 false
# I think on master is redundant. [""]

Node 2 mycluster "node2"
node.master: false true
http.port : 9201
tcp.port : 9301 false
# The port number of Node 1 [""]

How do I open phone settings when a button is clicked?

App-Prefs:root=Privacy&path=LOCATION worked for me for getting to general location settings. Note: only works on a device.

How can I capture packets in Android?

It's probably worth mentioning that for http/https some people proxy their browser traffic through Burp/ZAP or another intercepting "attack proxy". A thread that covers options for this on Android devices can be found here:

ValueError when checking if variable is None or numpy.array

If you are trying to do something very similar: a is not None, the same issue comes up. That is, Numpy complains that one must use a.any or a.all.

A workaround is to do:

if not (a is None):

Not too pretty, but it does the job.

Hexadecimal To Decimal in Shell Script

To convert from hex to decimal, there are many ways to do it in the shell or with an external program:

With :

$ echo $((16#FF))

with :

$ echo "ibase=16; FF" | bc

with :

$ perl -le 'print hex("FF");'

with :

$ printf "%d\n" 0xFF

with :

$ python -c 'print(int("FF", 16))'

with :

$ ruby -e 'p "FF".to_i(16)'

with :

$ nodejs <<< "console.log(parseInt('FF', 16))"

with :

$ rhino<<EOF
print(parseInt('FF', 16))

with :

$ groovy -e 'println Integer.parseInt("FF",16)'

Where can I download english dictionary database in a text format?

I dont know if its too late, but i thought it would help someone else.

I wanted the same badly...found it eventually.

Maybe its not perfect,but to me its adequate(for my little dictionary app).

Its not a dump file, but a MYSQL .sql script file

The words are in WN_SYNSET table and the glossary/meaning in the WN_GLOSS table

How do I get the base URL with PHP?

You can do it like this, but sorry my english is not good enough.

First, get home base url with this simple code..

I've tested this code on my local server and public and the result is good.


function home_base_url(){   

// first get http protocol if http or https

$base_url = (isset($_SERVER['HTTPS']) &&

$_SERVER['HTTPS']!='off') ? 'https://' : 'http://';

// get default website root directory

$tmpURL = dirname(__FILE__);

// when use dirname(__FILE__) will return value like this "C:\xampp\htdocs\my_website",

//convert value to http url use string replace, 

// replace any backslashes to slash in this case use chr value "92"

$tmpURL = str_replace(chr(92),'/',$tmpURL);

// now replace any same string in $tmpURL value to null or ''

// and will return value like /localhost/my_website/ or just /my_website/

$tmpURL = str_replace($_SERVER['DOCUMENT_ROOT'],'',$tmpURL);

// delete any slash character in first and last of value

$tmpURL = ltrim($tmpURL,'/');

$tmpURL = rtrim($tmpURL, '/');

// check again if we find any slash string in value then we can assume its local machine

    if (strpos($tmpURL,'/')){

// explode that value and take only first value

       $tmpURL = explode('/',$tmpURL);

       $tmpURL = $tmpURL[0];


// now last steps

// assign protocol in first value

   if ($tmpURL !== $_SERVER['HTTP_HOST'])

// if protocol its http then like this

      $base_url .= $_SERVER['HTTP_HOST'].'/'.$tmpURL.'/';


// else if protocol is https

      $base_url .= $tmpURL.'/';

// give return value

return $base_url; 



// and test it

echo home_base_url();

output will like this :

local machine : http://localhost/my_website/ or https://myhost/my_website 

public : or

use home_base_url function at index.php of your website and define it

and then you can use this function to load scripts, css and content via url like


echo '<script type="text/javascript" src="'.home_base_url().'js/script.js"></script>'."\n";


will create output like this :

<script type="text/javascript" src=""></script>

and if this script works fine,,!

Foreach in a Foreach in MVC View

You have:

foreach (var category in Model.Categories)

and then

@foreach (var product in Model)

Based on that view and model it seems that Model is of type Product if yes then the second foreach is not valid. Actually the first one could be the one that is invalid if you return a collection of Product.


You are right, I am returning the model of type Product. Also, I do understand what is wrong now that you've pointed it out. How am I supposed to do what I'm trying to do then if I can't do it this way?

I'm surprised your code compiles when you said you are returning a model of Product type. Here's how you can do it:

@foreach (var category in Model)

            @foreach (var product in category.Products)
                    put the rest of your code

That suggest that instead of returning a Product, you return a collection of Category with Products. Something like this in EF:

// I am typing it here directly 
// so I'm not sure if this is the correct syntax.
// I assume you know how to do this,
// anyway this should give you an idea.

notifyDataSetChanged example

You can use the runOnUiThread() method as follows. If you're not using a ListActivity, just adapt the code to get a reference to your ArrayAdapter.

final ArrayAdapter adapter = ((ArrayAdapter)getListAdapter());
runOnUiThread(new Runnable() {
    public void run() {

Using Oracle to_date function for date string with milliseconds

TO_DATE supports conversion to DATE datatype, which doesn't support milliseconds. If you want millisecond support in Oracle, you should look at TIMESTAMP datatype and TO_TIMESTAMP function.

Hope that helps.

How can I rollback a git repository to a specific commit?

Another way:

Checkout the branch you want to revert, then reset your local working copy back to the commit that you want to be the latest one on the remote server (everything after it will go bye-bye). To do this, in SourceTree, I right-clicked on the and selected "Reset BRANCHNAME to this commit".

Then navigate to your repository's local directory and run this command:

git -c diff.mnemonicprefix=false -c core.quotepath=false push -v -f -- tags REPOSITORY_NAME BRANCHNAME:BRANCHNAME 

This will erase all commits after the current one in your local repository but only for that one branch.

Difference between hamiltonian path and euler path

They are related but are neither dependent nor mutually exclusive. If a graph has an Eurler cycle, it may or may not also have a Hamiltonian cyle and vice versa.

Euler cycles visit every edge in the graph exactly once. If there are vertices in the graph with more than two edges, then by definition, the cycle will pass through those vertices more than once. As a result, vertices can be repeated but edges cannot.

Hamiltonian cycles visit every vertex in the graph exactly once (similar to the travelling salesman problem). As a result, neither edges nor vertices can be repeated.

Git Diff with Beyond Compare

Here is my config file. It took some wrestling but now it is working. I am using windows server, msysgit and beyond compare 3 (apparently an x86 version). Youll notice that I dont need to specify any arguments, and I use "path" instead of "cmd".

        name = PeteW
        email = [email protected]
        tool = bc3
        prompt = false
[difftool "bc3"]
        path = /c/Program Files (x86)/Beyond Compare 3/BComp.exe
        tool = bc3
        prompt = false
        keepBackup = false
[mergetool "bc3"]
        path = /c/Program Files (x86)/Beyond Compare 3/BComp.exe
        trustExitCode = true
        dt = difftool
        mt = mergetool

Internet Access in Ubuntu on VirtualBox

I could get away with the following solution (works with Ubuntu 14 guest VM on Windows 7 host or Ubuntu 9.10 Casper guest VM on host Windows XP x86):

  1. Go to network connections -> Virtual Box Host-Only Network -> Select "Properties"
  2. Check VirtualBox Bridged Networking Driver
  3. Come to VirtualBox Manager, choose the network adapter as Bridged Adapter and Name to the device in Step #1.
  4. Restart the VM.

write newline into a file

Or you could use something like the following. Pay attention to "\n":

 * Created by mona on 3/26/16.
public class FileExample {

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

        File newFile = new File("tweet.txt");
        FileWriter fileWriter = new FileWriter(newFile);
        fileWriter.write("Mona Jalal");
        fileWriter.append("\nMona Mona");
        FileReader fileReader = new FileReader(newFile);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String line;
        while ((line = bufferedReader.readLine()) != null) {


How to update Identity Column in SQL Server?

INSERT INTO dbo.TableName 
    TableId, ColumnName1, ColumnName2, ColumnName3
    TableId_Value, ColumnName1_Value, ColumnName2_Value, ColumnName3_Value


When using Identity_Insert don't forget to include the column names because sql will not allow you to insert without specifying them

Difference between staticmethod and classmethod

staticmethod has no access to attibutes of the object, of the class, or of parent classes in the inheritance hierarchy. It can be called at the class directly (without creating an object).

classmethod has no access to attributes of the object. It however can access attributes of the class and of parent classes in the inheritance hierarchy. It can be called at the class directly (without creating an object). If called at the object then it is the same as normal method which doesn't access self.<attribute(s)> and accesses self.__class__.<attribute(s)> only.

Think we have a class with b=2, we will create an object and re-set this to b=4 in it. Staticmethod cannot access nothing from previous. Classmethod can access .b==2 only, via cls.b. Normal method can access both: .b==4 via self.b and .b==2 via self.__class__.b.

We could follow the KISS style (keep it simple, stupid): Don't use staticmethods and classmethods, don't use classes without instantiating them, access only the object's attributes self.attribute(s). There are languages where the OOP is implemented that way and I think it is not bad idea. :)

How to extend / inherit components?

if you read through the CDK libraries and the material libraries, they're using inheritance but not so much for components themselves, content projection is king IMO. see this link where it says "the key problem with this design"

I know this doesn't answer your question but I really think inheriting / extending components should be avoided. Here's my reasoning:

If the abstract class extended by two or more components contains shared logic: use a service or even create a new typescript class that can be shared between the two components.

If the abstract class... contains shared variables or onClicketc functions, Then there will be duplication between the html of the two extending components views. This is bad practice & that shared html needs to be broken into Component(s). These Component(s) (parts) can be shared between the two components.

Am I missing other reasons for having an abstract class for components?

An example I saw recently was components extending AutoUnsubscribe:

import { Subscription } from 'rxjs';
import { OnDestroy } from '@angular/core';
export abstract class AutoUnsubscribeComponent implements OnDestroy {
  protected infiniteSubscriptions: Array<Subscription>;

  constructor() {
    this.infiniteSubscriptions = [];

  ngOnDestroy() {
    this.infiniteSubscriptions.forEach((subscription) => {

this was bas because throughout a large codebase, infiniteSubscriptions.push() was only used 10 times. Also importing & extending AutoUnsubscribe actually takes more code than just adding mySubscription.unsubscribe() in the ngOnDestroy() method of the component itself, which required additional logic anyway.

Sorting a vector in descending order


Use any. They are almost the same.

Boring answer

As usual, there are pros and cons.

Use std::reverse_iterator:

  • When you are sorting custom types and you don't want to implement operator>()
  • When you are too lazy to type std::greater<int>()

Use std::greater when:

  • When you want to have more explicit code
  • When you want to avoid using obscure reverse iterators

As for performance, both methods are equally efficient. I tried the following benchmark:

#include <algorithm>
#include <chrono>
#include <iostream>
#include <fstream>
#include <vector>

using namespace std::chrono;

/* 64 Megabytes. */
#define VECTOR_SIZE (((1 << 20) * 64) / sizeof(int))
/* Number of elements to sort. */
#define SORT_SIZE 100000

int main(int argc, char **argv) {
    std::vector<int> vec;

    /* We generate more data here, so the first SORT_SIZE elements are evicted
       from the cache. */
    std::ifstream urandom("/dev/urandom", std::ios::in | std::ifstream::binary);*), vec.size() * sizeof(int));

    auto start = steady_clock::now();
    auto it_rbegin = vec.rend() - SORT_SIZE;
    std::sort(it_rbegin, vec.rend());
    auto it_end = vec.begin() + SORT_SIZE;
    std::sort(vec.begin(), it_end, std::greater<int>());
    auto stop = steady_clock::now();

    std::cout << "Sorting time: "
          << duration_cast<microseconds>(stop - start).count()
          << "us" << std::endl;
    return 0;

With this command line:

g++ -g -DUSE_REVERSE_ITER=0 -std=c++11 -O3 main.cpp \
    && valgrind --cachegrind-out-file=cachegrind.out --tool=cachegrind ./a.out \
    && cg_annotate cachegrind.out
g++ -g -DUSE_REVERSE_ITER=1 -std=c++11 -O3 main.cpp \
    && valgrind --cachegrind-out-file=cachegrind.out --tool=cachegrind ./a.out \
    && cg_annotate cachegrind.out

std::greater demo std::reverse_iterator demo

Timings are same. Valgrind reports the same number of cache misses.

Python: Is there an equivalent of mid, right, and left from BASIC?

This is Andy's solution. I just addressed User2357112's concern and gave it meaningful variable names. I'm a Python rookie and preferred these functions.

def left(aString, howMany):
    if howMany <1:
        return ''
        return aString[:howMany]

def right(aString, howMany):
    if howMany <1:
        return ''
        return aString[-howMany:]

def mid(aString, startChar, howMany):
    if howMany < 1:
        return ''
        return aString[startChar:startChar+howMany]

Using jQuery how to get click coordinates on the target element

Are you trying to get the position of mouse pointer relative to element ( or ) simply the mouse pointer location

Try this Demo :

Edit :

1) event.pageX, event.pageY gives you the mouse position relative document !

Ref :

2) offset() : It gives the offset position of an element

Ref :

3) position() : It gives you the relative Position of an element i.e.,

consider an element is embedded inside another element

example :

<div id="imParent">
   <div id="imchild" />

Ref :


   <div id="A" style="left:100px;"> Default    <br /> mouse<br/>position </div>
   <div id="B" style="left:300px;"> offset()   <br /> mouse<br/>position </div>
   <div id="C" style="left:500px;"> position() <br /> mouse<br/>position </div>


$(document).ready(function (e) {

    $('#A').click(function (e) { //Default mouse Position 
        alert(e.pageX + ' , ' + e.pageY);

    $('#B').click(function (e) { //Offset mouse Position
        var posX = $(this).offset().left,
            posY = $(this).offset().top;
        alert((e.pageX - posX) + ' , ' + (e.pageY - posY));

    $('#C').click(function (e) { //Relative ( to its parent) mouse position 
        var posX = $(this).position().left,
            posY = $(this).position().top;
        alert((e.pageX - posX) + ' , ' + (e.pageY - posY));

Confusion: @NotNull vs. @Column(nullable = false) with JPA and Hibernate

Interesting to note, all sources emphasize that @Column(nullable=false) is used only for DDL generation.

However, even if there is no @NotNull annotation, and hibernate.check_nullability option is set to true, Hibernate will perform validation of entities to be persisted.

It will throw PropertyValueException saying that "not-null property references a null or transient value", if nullable=false attributes do not have values, even if such restrictions are not implemented in the database layer.

More information about hibernate.check_nullability option is available here:

How to convert a byte array to a hex string in Java?

Converts bytes data to hex characters

@param bytes byte array to be converted to hex string
@return byte String in hex format

private static String bytesToHex(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    int v;
    for (int j = 0; j < bytes.length; j++) {
        v = bytes[j] & 0xFF;
        hexChars[j * 2] = HEX_ARRAY[v >>> 4];
        hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
    return new String(hexChars);

What do curly braces mean in Verilog?

The curly braces mean concatenation, from most significant bit (MSB) on the left down to the least significant bit (LSB) on the right. You are creating a 32-bit bus (result) whose 16 most significant bits consist of 16 copies of bit 15 (the MSB) of the a bus, and whose 16 least significant bits consist of just the a bus (this particular construction is known as sign extension, which is needed e.g. to right-shift a negative number in two's complement form and keep it negative rather than introduce zeros into the MSBits).

There is a tutorial here*, but it doesn't explain too much more than the above paragraph.

For what it's worth, the nested curly braces around a[15:0] are superfluous.

*Beware: the example within the tutorial link contains a typo when demonstrating multiple concatenations - the (2{C}} should be a {2{2}}.

How to force deletion of a python object?

Perhaps you are looking for a context manager?

>>> class Foo(object):
...   def __init__(self):
... = None
...   def __enter__(self):
...     if != 'open':
...       print 'opening the bar'
... = 'open'
...   def __exit__(self, type_, value, traceback):
...     if != 'closed':
...       print 'closing the bar', type_, value, traceback
... = 'close'
>>> with Foo() as f:
...     # oh no something crashes the program
...     sys.exit(0)
opening the bar
closing the bar <type 'exceptions.SystemExit'> 0 <traceback object at 0xb7720cfc>

How to get Java Decompiler / JD / JD-Eclipse running in Eclipse Helios

After testing on Juno, Kepler and Luna, I found JD only works for *.class files on build path.

  1. Adding the jar as a lib of an existing project
  2. Go to Preferences->General->Editors->File Associations, set *.class without source to Class File Editor with a cup icon

Declare a dictionary inside a static class

You can use the static/class constructor to initialize your dictionary:

public static class ErrorCode
    public const IDictionary<string, string> ErrorCodeDic;
    public static ErrorCode()
        ErrorCodeDic = new Dictionary<string, string>()
            { {"1", "User name or password problem"} };

Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g

You need to merge the remote branch into your current branch by running git pull.

If your local branch is already up-to-date, you may also need to run git pull --rebase.

A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.

How to add an item to a drop down list in ASP.NET?

Which specific index? If you want 'Add New' to be first on the dropdownlist you can add it though the code like this:

<asp:DropDownList ID="DropDownList1" AppendDataBoundItems="true" runat="server">
     <asp:ListItem Text="Add New" Value="0" />

If you want to add it at a different index, maybe the last then try:

ListItem lst = new ListItem ( "Add New" , "0" );

DropDownList1.Items.Insert( DropDownList1.Items.Count-1 ,lst);

How to write a CSS hack for IE 11?

You can use js and add a class in html to maintain the standard of conditional comments:

  var ua = navigator.userAgent,
      doc = document.documentElement;

  if ((ua.match(/MSIE 10.0/i))) {
    doc.className = doc.className + " ie10";

  } else if((ua.match(/rv:11.0/i))){
    doc.className = doc.className + " ie11";

Or use a lib like bowser:

Or modernizr for feature detection:

Command-line tool for finding out who is locking a file

I have used Unlocker for years and really like it. It not only will identify programs and offer to unlock the folder\file, it will allow you to kill the processing that has the lock as well.

Additionally, it offers actions to do to the locked file in question such as deleting it.

Unlocker helps delete locked files with error messages including "cannot delete file," and "access is denied." Video tutorial available.

Some errors you might get that Unlocker can help with include:

  • Cannot delete file: Access is denied.
  • There has been a sharing violation.
  • The source or destination file may be in use.
  • The file is in use by another program or user.
  • Make sure the disk is not full or write-protected and that the file is not currently in use.

How to make an unaware datetime timezone aware in python

quite new to Python and I encountered the same issue. I find this solution quite simple and for me it works fine (Python 3.6):

unaware=parser.parse("2020-05-01 0:00:00")

Arrays in unix shell?

The Bourne shell and C shell don't have arrays, IIRC.

In addition to what others have said, in Bash you can get the number of elements in an array as follows:


and do slice-style operations:

arrayname=(apple banana cherry)
echo ${arrayname[@]:1}                   # yields "banana cherry"
echo ${arrayname[@]: -1}                 # yields "cherry"
echo ${arrayname[${#arrayname[@]}-1]}    # yields "cherry"
echo ${arrayname[@]:0:2}                 # yields "apple banana"
echo ${arrayname[@]:1:1}                 # yields "banana"

ES6 class variable alternatives

Since your issue is mostly stylistic (not wanting to fill up the constructor with a bunch of declarations) it can be solved stylistically as well.

The way I view it, many class based languages have the constructor be a function named after the class name itself. Stylistically we could use that that to make an ES6 class that stylistically still makes sense but does not group the typical actions taking place in the constructor with all the property declarations we're doing. We simply use the actual JS constructor as the "declaration area", then make a class named function that we otherwise treat as the "other constructor stuff" area, calling it at the end of the true constructor.

"use strict";

class MyClass
    // only declare your properties and then call this.ClassName(); from here
        this.prop1 = 'blah 1';
        this.prop2 = 'blah 2';
        this.prop3 = 'blah 3';

    // all sorts of other "constructor" stuff, no longer jumbled with declarations
    MyClass() {

Both will be called as the new instance is constructed.

Sorta like having 2 constructors where you separate out the declarations and the other constructor actions you want to take, and stylistically makes it not too hard to understand that's what is going on too.

I find it's a nice style to use when dealing with a lot of declarations and/or a lot of actions needing to happen on instantiation and wanting to keep the two ideas distinct from each other.

NOTE: I very purposefully do not use the typical idiomatic ideas of "initializing" (like an init() or initialize() method) because those are often used differently. There is a sort of presumed difference between the idea of constructing and initializing. Working with constructors people know that they're called automatically as part of instantiation. Seeing an init method many people are going to assume without a second glance that they need to be doing something along the form of var mc = MyClass(); mc.init();, because that's how you typically initialize. I'm not trying to add an initialization process for the user of the class, I'm trying to add to the construction process of the class itself.

While some people may do a double-take for a moment, that's actually the bit of the point: it communicates to them that the intent is part of construction, even if that makes them do a bit of a double take and go "that's not how ES6 constructors work" and take a second looking at the actual constructor to go "oh, they call it at the bottom, I see", that's far better than NOT communicating that intent (or incorrectly communicating it) and probably getting a lot of people using it wrong, trying to initialize it from the outside and junk. That's very much intentional to the pattern I suggest.

For those that don't want to follow that pattern, the exact opposite can work too. Farm the declarations out to another function at the beginning. Maybe name it "properties" or "publicProperties" or something. Then put the rest of the stuff in the normal constructor.

"use strict";

class MyClass
    properties() {
        this.prop1 = 'blah 1';
        this.prop2 = 'blah 2';
        this.prop3 = 'blah 3';

    constructor() {;

Note that this second method may look cleaner but it also has an inherent problem where properties gets overridden as one class using this method extends another. You'd have to give more unique names to properties to avoid that. My first method does not have this problem because its fake half of the constructor is uniquely named after the class.

Detect when a window is resized using JavaScript ?

This can be achieved with the onresize property of the GlobalEventHandlers interface in JavaScript, by assigning a function to the onresize property, like so:

window.onresize = functionRef;

The following code snippet demonstrates this, by console logging the innerWidth and innerHeight of the window whenever it's resized. (The resize event fires after the window has been resized)

function resize() {_x000D_
  console.log("height: ", window.innerHeight, "px");_x000D_
  console.log("width: ", window.innerWidth, "px");_x000D_
window.onresize = resize;
<p>In order for this code snippet to work as intended, you will need to either shrink your browser window down to the size of this code snippet, or fullscreen this code snippet and resize from there.</p>

Html.DropdownListFor selected value not being set

Make sure that you have trim the selected value before you assigning.


public class SelectType
    public string Text { get; set; }
    public string Value { get; set; }


var types = new List<SelectType>();
types.Add(new SelectType() { Value =  0, Text = "Select a Type" });
types.Add(new SelectType() { Value =  1, Text = "Family Trust" });
types.Add(new SelectType() { Value =  2, Text = "Unit Trust"});
ViewBag.PartialTypes = types;


@Html.DropDownListFor(m => m.PartialType, new SelectList(ViewBag.PartialTypes, "Value", "Text"), new { id = "Type" })

Refused to load the font 'data:font/woff.....'it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src'

From personal experience, it is always a best, first step to run your site in Incognito (Chrome), Private Browsing (Firefox), and InPrivate (IE11 && Edge) to remove the interference of add-ons/extensions. These can still interfere with testing in this mode if they are enabled explicitly in their settings. However, it is an easy first step to troubleshooting an issue.

The reason I am here, was due to Web of Trust (WoT) adding content to my page, and my page having had very strict Content Security Policy:

Header set Content-Security-Policy "default-src 'none'; font-src 'self' data:; style-src 'self' 'unsafe-inline' data:; img-src 'self' data:; script-src 'self' 'unsafe-inline'; connect-src 'self';"

This caused many errors. I was looking more for an answer on how to tell the extension to not try and run on this site programatically. This way when people have extensions, they just won't run on my site. I imagine if this were possible, ad blockers would have been banned on sites long ago. So my research is a bit naive. Hope this helps anyone else trying to diagnose an issue that is not specifically tied to the handful of mentioned extensions in other answers.

Better way to cast object to int

You can first cast object to string and then cast the string to int; for example:

string str_myobject = myobject.ToString();
int int_myobject = int.Parse(str_myobject);

this worked for me.

Error: unexpected symbol/input/string constant/numeric constant/SPECIAL in my code

These errors mean that the R code you are trying to run or source is not syntactically correct. That is, you have a typo.

To fix the problem, read the error message carefully. The code provided in the error message shows where R thinks that the problem is. Find that line in your original code, and look for the typo.

Prophylactic measures to prevent you getting the error again

The best way to avoid syntactic errors is to write stylish code. That way, when you mistype things, the problem will be easier to spot. There are many R style guides linked from the SO R tag info page. You can also use the formatR package to automatically format your code into something more readable. In RStudio, the keyboard shortcut CTRL + SHIFT + A will reformat your code.

Consider using an IDE or text editor that highlights matching parentheses and braces, and shows strings and numbers in different colours.

Common syntactic mistakes that generate these errors

Mismatched parentheses, braces or brackets

If you have nested parentheses, braces or brackets it is very easy to close them one too many or too few times.

## Error: unexpected '}' in "{}}"
{{}} # OK

Missing * when doing multiplication

This is a common mistake by mathematicians.

Error: unexpected symbol in "5x"
5*x # OK

Not wrapping if, for, or return values in parentheses

This is a common mistake by MATLAB users. In R, if, for, return, etc., are functions, so you need to wrap their contents in parentheses.

if x > 0 {}
## Error: unexpected symbol in "if x"
if(x > 0) {} # OK

Not using multiple lines for code

Trying to write multiple expressions on a single line, without separating them by semicolons causes R to fail, as well as making your code harder to read.

x + 2 y * 3
## Error: unexpected symbol in "x + 2 y"
x + 2; y * 3 # OK

else starting on a new line

In an if-else statement, the keyword else must appear on the same line as the end of the if block.

if(TRUE) 1
else 2
## Error: unexpected 'else' in "else"    
if(TRUE) 1 else 2 # OK
} else            # also OK

= instead of ==

= is used for assignment and giving values to function arguments. == tests two values for equality.

if(x = 0) {}
## Error: unexpected '=' in "if(x ="    
if(x == 0) {} # OK

Missing commas between arguments

When calling a function, each argument must be separated by a comma.

c(1 2)
## Error: unexpected numeric constant in "c(1 2"
c(1, 2) # OK

Not quoting file paths

File paths are just strings. They need to be wrapped in double or single quotes.

## Error: unexpected ')' in "path.expand(~)"
path.expand("~") # OK

Quotes inside strings

This is a common problem when trying to pass quoted values to the shell via system, or creating quoted xPath or sql queries.

Double quotes inside a double quoted string need to be escaped. Likewise, single quotes inside a single quoted string need to be escaped. Alternatively, you can use single quotes inside a double quoted string without escaping, and vice versa.

## Error: unexpected symbol in ""x"y"   
"x\"y" # OK
'x"y'  # OK  

Using curly quotes

So-called "smart" quotes are not so smart for R programming.

## Error: unexpected input in "path.expand(“"    
path.expand("~") # OK

Using non-standard variable names without backquotes

?make.names describes what constitutes a valid variable name. If you create a non-valid variable name (using assign, perhaps), then you need to access it with backquotes,

assign("x y", 0)
x y
## Error: unexpected symbol in "x y"
`x y` # OK

This also applies to column names in data frames created with check.names = FALSE.

dfr <- data.frame("x y" = 1:5, check.names = FALSE)
dfr$x y
## Error: unexpected symbol in "dfr$x y"
dfr[,"x y"] # OK
dfr$`x y`   # also OK

It also applies when passing operators and other special values to functions. For example, looking up help on %in%.

## Error: unexpected SPECIAL in "?%in%"
?`%in%` # OK

Sourcing non-R code

The source function runs R code from a file. It will break if you try to use it to read in your data. Probably you want read.table.

source(textConnection("x y"))
## Error in source(textConnection("x y")) : 
##   textConnection("x y"):1:3: unexpected symbol
## 1: x y
##       ^

Corrupted RStudio desktop file

RStudio users have reported erroneous source errors due to a corrupted .rstudio-desktop file. These reports only occurred around March 2014, so it is possibly an issue with a specific version of the IDE. RStudio can be reset using the instructions on the support page.

Using expression without paste in mathematical plot annotations

When trying to create mathematical labels or titles in plots, the expression created must be a syntactically valid mathematical expression as described on the ?plotmath page. Otherwise the contents should be contained inside a call to paste.

plot(rnorm(10), ylab = expression(alpha ^ *)))
## Error: unexpected '*' in "plot(rnorm(10), ylab = expression(alpha ^ *"
plot(rnorm(10), ylab = expression(paste(alpha ^ phantom(0), "*"))) # OK

Checking if a string is empty or null in Java

You can leverage Apache Commons StringUtils.isEmpty(str), which checks for empty strings and handles null gracefully.


System.out.println(StringUtils.isEmpty("")); // true
System.out.println(StringUtils.isEmpty(null)); // true

Google Guava also provides a similar, probably easier-to-read method: Strings.isNullOrEmpty(str).


System.out.println(Strings.isNullOrEmpty("")); // true
System.out.println(Strings.isNullOrEmpty(null)); // true

Using IF ELSE in Oracle

IF is a PL/SQL construct. If you are executing a query, you are using SQL not PL/SQL.

In SQL, you can use a CASE statement in the query itself

                (CASE WHEN b.salesman = 'VIKKIE'
                      THEN 'ICKY'
                      ELSE b.salesman
                NVL(a.manufacturer,'Not Set') Manufacturer
  FROM inv_items a, 
       arv_sales b
 WHERE = '100'
   AND =
   AND A.ITEM_KEY = b.item_key   
   AND a.item LIKE 'BX%'
   AND b.salesman in ('01','15')
   AND trans_date BETWEEN to_date('010113','mmddrr')
                      and to_date('011713','mmddrr')
ORDER BY a.item

Since you aren't doing any aggregation, you don't want a GROUP BY in your query. Are you really sure that you need the DISTINCT? People often throw that in haphazardly or add it when they are missing a join condition rather than considering whether it is really necessary to do the extra work to identify and remove duplicates.

How can you search Google Programmatically Java API

Just an alternative. Searching google and parsing the results can also be done in a generic way using any HTML Parser such as Jsoup in Java. Following is the link to the mentioned example.

Update: Link no longer works. Please look for any other example.

React Native fixed footer

You get the Dimension first and then manipulate it through flex style

var Dimensions = require('Dimensions')
var {width, height} = Dimensions.get('window')

In render

<View style={{flex: 1}}>
    <View style={{width: width, height: height - 200}}>main</View>
    <View style={{width: width, height: 200}}>footer</View>

The other method is to use flex

<View style={{flex: 1}}>
    <View style={{flex: .8}}>main</View>
    <View style={{flex: .2}}>footer</View>

ASP.NET Button to redirect to another page

<button type ="button" onclick="location.href='@Url.Action("viewname","Controllername")'"> Button name</button>

for e.g ,

<button type="button" onclick="location.href='@Url.Action("register","Home")'">Register</button>

Convert JSON String to JSON Object c#

if you don't want or need a typed object try:

using Newtonsoft.Json;
// ...   
dynamic json  = JsonConvert.DeserializeObject(str);

or try for a typed object try:

Foo json  = JsonConvert.DeserializeObject<Foo>(str)

CSS: background image on background color

You need to use the full property name for each:

background-color: #6DB3F2;
background-image: url('images/checked.png');

Or, you can use the background shorthand and specify it all in one line:

background: url('images/checked.png'), #6DB3F2;

How to search and replace text in a file?

I have worked this out as an exercise of a course: open file, find and replace string and write to a new file.

class Letter:

    def __init__(self):

        with open("./Input/Names/invited_names.txt", "r") as file:
            # read the list of names
            list_names = [line.rstrip() for line in file]
            with open("./Input/Letters/starting_letter.docx", "r") as f:
                # read letter
                file_source =
            for name in list_names:
                with open(f"./Output/ReadyToSend/LetterTo{name}.docx", "w") as f:
                    # replace [name] with name of the list in the file
                    replace_string = file_source.replace('[name]', name)
                    # write to a new file

brief = Letter()

If hasClass then addClass to parent

The reason that does not work is because this has no specific meaning inside of an if statement, you will have to go back to a level of scope where this is defined (a function).

For example:

$('#element1').click(function() {
    console.log($(this).attr('id')); // logs "element1"

    if ($('#element2').hasClass('class')) {
        console.log($(this).attr('id')); // still logs "element1"

How to get length of a string using strlen function

using namespace std;
int main()

    char str[80];

    int i;

    cout<<"\n enter string:";


    int n=strlen(str);

    cout<<"\n lenght is:"<<n;


    return 0;


This is the program if you want to use strlen . Hope this helps!

How to import multiple .csv files at once?

It was requested that I add this functionality to the stackoverflow R package. Given that it is a tinyverse package (and can't depend on third party packages), here is what I came up with:

#' Bulk import data files 
#' Read in each file at a path and then unnest them. Defaults to csv format.
#' @param path        a character vector of full path names
#' @param pattern     an optional \link[=regex]{regular expression}. Only file names which match the regular expression will be returned.
#' @param reader      a function that can read data from a file name.
#' @param ...         optional arguments to pass to the reader function (eg \code{stringsAsFactors}).
#' @param reducer     a function to unnest the individual data files. Use I to retain the nested structure. 
#' @param recursive     logical. Should the listing recurse into directories?
#' @author Neal Fultz
#' @references \url{}
#' @importFrom utils read.csv
#' @export <- function(path='.', pattern=NULL, reader=read.csv, ..., 
                           reducer=function(dfs), dfs), recursive=FALSE) {
  files <- list.files(path, pattern, full.names = TRUE, recursive = recursive)

  reducer(lapply(files, reader, ...))

By parameterizing the reader and reducer function, people can use data.table or dplyr if they so choose, or just use the base R functions that are fine for smaller data sets.

Unity Scripts edited in Visual studio don't provide autocomplete

Try pressing Ctrl + Alt + Space (which toggles between suggestion and standard completion modes)

When restoring a backup, how do I disconnect all active connections?

SQL Server Management Studio 2005

When you right click on a database and click Tasks and then click Detach Database, it brings up a dialog with the active connections.

Detach Screen

By clicking on the hyperlink under "Messages" you can kill the active connections.

You can then kill those connections without detaching the database.

More information here.

SQL Server Management Studio 2008

The interface has changed for SQL Server Management studio 2008, here are the steps (via: Tim Leung)

  1. Right-click the server in Object Explorer and select 'Activity Monitor'.
  2. When this opens, expand the Processes group.
  3. Now use the drop-down to filter the results by database name.
  4. Kill off the server connections by selecting the right-click 'Kill Process' option.

Change the background color of CardView programmatically



android use ARGB colors. you can use like this (0xFF + RGB COLOR)--Hard-coded color.

Openssl is not recognized as an internal or external command

I used this code:

This is worked for me successfully.

"C:\Program Files\Java\jdk1.6.0_26\bin\keytool.exe" -exportcert -alias sociallisting -
keystore "D:\keystore\SocialListing" | "C:\cygwin\bin\openssl.exe" sha1 -binary | 
"C:\cygwin\bin\openssl.exe" base64

String comparison in bash. [[: not found

[[ is a bash-builtin. Your /bin/bash doesn't seem to be an actual bash.

From a comment:

Add #!/bin/bash at the top of file

How can I hide/show a div when a button is clicked?

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Show and hide div with JavaScript</title>

    var button_beg = '<button id="button" onclick="showhide()">', button_end = '</button>';
    var show_button = 'Show', hide_button = 'Hide';
    function showhide() {
        var div = document.getElementById( "hide_show" );
        var showhide = document.getElementById( "showhide" );
        if ( !== "none" ) {
   = "none";
            button = show_button;
            showhide.innerHTML = button_beg + button + button_end;
        } else {
   = "block";
            button = hide_button;
            showhide.innerHTML = button_beg + button + button_end;
    function setup_button( status ) {
        if ( status == 'show' ) {
            button = hide_button;
        } else {
            button = show_button;
        var showhide = document.getElementById( "showhide" );
        showhide.innerHTML = button_beg + button + button_end;
    window.onload = function () {
        setup_button( 'hide' );
        showhide(); // if setup_button is set to 'show' comment this line
    <div id="showhide"></div>
    <div id="hide_show">
        <p>This div will be show and hide on button click</p>

How to switch activity without animation in Android?

This is not an example use or an explanation of how to use FLAG_ACTIVITY_NO_ANIMATION, however it does answer how to disable the Activity switching animation, as asked in the question title:

Android, how to disable the 'wipe' effect when starting a new activity?

Can I use Twitter Bootstrap and jQuery UI at the same time?

The data-role="none" is the key to make them work together. You can apply to the elements you want bootstrap to touch but jquery mobile to ignore. like this input type="text" class="form-control" placeholder="Search" data-role="none"

Make a number a percentage

Most answers suggest appending '%' at the end. I would rather prefer Intl.NumberFormat() with { style: 'percent'}

var num = 25;_x000D_
var option = {_x000D_
  style: 'percent'_x000D_
var formatter = new Intl.NumberFormat("en-US", option);_x000D_
var percentFormat = formatter.format(num / 100);_x000D_

html div onclick event

The problem was that clicking the anchor still triggered a click in your <div>. That's called "event bubbling".

In fact, there are multiple solutions:

  • Checking in the DIV click event handler whether the actual target element was the anchor
    → jsFiddle

    $('.expandable-panel-heading').click(function (evt) {
        if ( != "A") {
        // Also possible if conditions:
        // - != "ancherComplaint"
        // - !$("#ancherComplaint")
    $("#ancherComplaint").click(function () {
  • Stopping the event propagation from the anchor click listener
    → jsFiddle

    $("#ancherComplaint").click(function (evt) {

As you may have noticed, I have removed the following selector part from my examples:


This was unnecessary because there is no element with the class .expandable-panel-heading which also have #ancherComplaint as its ID.

I assume that you wanted to suppress the event for the anchor. That cannot work in that manner because both selectors (yours and mine) select the exact same DIV. The selector has no influence on the listener when it is called; it only sets the list of elements to which the listeners should be registered. Since this list is the same in both versions, there exists no difference.

Why is it important to override GetHashCode when Equals method is overridden?

You should always guarantee that if two objects are equal, as defined by Equals(), they should return the same hash code. As some of the other comments state, in theory this is not mandatory if the object will never be used in a hash based container like HashSet or Dictionary. I would advice you to always follow this rule though. The reason is simply because it is way too easy for someone to change a collection from one type to another with the good intention of actually improving the performance or just conveying the code semantics in a better way.

For example, suppose we keep some objects in a List. Sometime later someone actually realizes that a HashSet is a much better alternative because of the better search characteristics for example. This is when we can get into trouble. List would internally use the default equality comparer for the type which means Equals in your case while HashSet makes use of GetHashCode(). If the two behave differently, so will your program. And bear in mind that such issues are not the easiest to troubleshoot.

I've summarized this behavior with some other GetHashCode() pitfalls in a blog post where you can find further examples and explanations.

How do I break out of a loop in Perl?

Additional data (in case you have more questions):

FOO: {
       for my $i ( @listone ){
          for my $j ( @listtwo ){
                 if ( cond( $i,$j ) ){

                    last FOO;  # --->
                                   # |
                 }                 # |
          }                        # |
       }                           # |
 } # <-------------------------------

Parsing HTTP Response in Python

When I printed I noticed that b was preprended to the string (e.g. b'{"a":1,..). The "b" stands for bytes and serves as a declaration for the type of the object you're handling. Since, I knew that a string could be converted to a dict by using json.loads('string'), I just had to convert the byte type to a string type. I did this by decoding the response to utf-8 decode('utf-8'). Once it was in a string type my problem was solved and I was easily able to iterate over the dict.

I don't know if this is the fastest or most 'pythonic' way of writing this but it works and theres always time later of optimization and improvement! Full code for my solution:

from urllib.request import urlopen
import json

# Get the dataset
url = ''
response = urlopen(url)

# Convert bytes to string type and string type to dict
string ='utf-8')
json_obj = json.loads(string)

print(json_obj['source_name']) # prints the string with 'source_name' key

How do I remove blue "selected" outline on buttons?

You can remove the blue outline by using outline: none.

However, I would highly recommend styling your focus states too. This is to help users who are visually impaired.

Check out: More reading here:

jQuery see if any or no checkboxes are selected

This is the best way to solve this problem.


  // Do something here /////



The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).

WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.

For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:

enter image description here Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the MVC.

Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.

In the scenarios listed below you should go for WCF:

  1. If you need to send data on protocols like TCP, MSMQ or MIME
  2. If the consuming client just knows how to consume SOAP messages

WEB API is a framework for developing RESTful/HTTP services.

There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.

HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.

Get TimeZone offset value from TimeZone without TimeZone name

We can easily get the millisecond offset of a TimeZone with only a TimeZone instance and System.currentTimeMillis(). Then we can convert from milliseconds to any time unit of choice using the TimeUnit class.

Like so:

public static int getOffsetHours(TimeZone timeZone) {
    return (int) TimeUnit.MILLISECONDS.toHours(timeZone.getOffset(System.currentTimeMillis()));

Or if you prefer the new Java 8 time API

public static ZoneOffset getOffset(TimeZone timeZone) { //for using ZoneOffsett class
    ZoneId zi = timeZone.toZoneId();
    ZoneRules zr = zi.getRules();
    return zr.getOffset(;

public static int getOffsetHours(TimeZone timeZone) { //just hour offset
    ZoneOffset zo = getOffset(timeZone);

C# code to validate email address

In case you are using FluentValidation you could write something as simple as this:

public cass User
    public string Email { get; set; }

public class UserValidator : AbstractValidator<User>
    public UserValidator()
        RuleFor(x => x.Email).EmailAddress().WithMessage("The text entered is not a valid email address.");

// Validates an user. 
var validationResult = new UserValidator().Validate(new User { Email = "açflkdj" });

// This will return false, since the user email is not valid.
bool userIsValid = validationResult.IsValid;

How to Find App Pool Recycles in Event Log

It seemed quite hard to find this information, but eventually, I came across this question
You have to look at the 'System' event log, and filter by the WAS source.
Here is more info about the WAS (Windows Process Activation Service)

Optional query string parameters in ASP.NET Web API

This issue has been fixed in the regular release of MVC4. Now you can do:

public string GetFindBooks(string author="", string title="", string isbn="", string  somethingelse="", DateTime? date= null) 
    // ...

and everything will work out of the box.

How do I create a comma-separated list from an array in PHP?

Another way could be like this:

$letters = array("a", "b", "c", "d", "e", "f", "g");

$result = substr(implode(", ", $letters), 0, -3);

Output of $result is a nicely formatted comma-separated list.

a, b, c, d, e, f, g

java.lang.NoClassDefFoundError: Could not initialize class XXX

Just several days ago, I met the same question just like yours. All code runs well on my local machine, but turns out error(noclassdeffound&initialize). So I post my solution, but I don't know why, I merely advance a possibility. I hope someone know will explain this.@John Vint Firstly, I'll show you my problem. My code has static variable and static block both. When I first met this problem, I tried John Vint's solution, and tried to catch the exception. However, I caught nothing. So I thought it is because the static variable(but now I know they are the same thing) and still found nothing. So, I try to find the difference between the linux machine and my computer. Then I found that this problem happens only when several threads run in one process(By the way, the linux machine has double cores and double processes). That means if there are two tasks(both uses the code which has static block or variables) run in the same process, it goes wrong, but if they run in different processes, both of them are ok. In the Linux machine, I use

mvn -U clean  test -Dtest=path 

to run a task, and because my static variable is to start a container(or maybe you initialize a new classloader), so it will stay until the jvm stop, and the jvm stops only when all the tasks in one process stop. Every task will start a new container(or classloader) and it makes the jvm confused. As a result, the error happens. So, how to solve it? My solution is to add a new command to the maven command, and make every task go to the same container.

-Dxxx.version=xxxxx #sorry can't post more

Maybe you have already solved this problem, but still hope it will help others who meet the same problem.

what's the easiest way to put space between 2 side-by-side buttons in

create a divider class as follows:


Then attach this to a div between the two buttons

<div style="text-align: center"> 
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" Width="89px" OnClick="btnSubmit_Click" />
    <div class="divider"/>
    <asp:Button ID="btnClear" runat="server" Text="Clear" Width="89px" OnClick="btnClear_Click" />

This is the best way as it avoids the box model, which can be a pain on older browsers, and doesn't add any extra characters that would be picked up by a screen reader, so it is better for readability.

It's good to have a number of these types of divs for certain scenarios (my most used one is vert5spacer, similar to this but puts a block div with height 5 and width auto for spacing out items in a form etc.


Using array formula.



Troubleshooting misplaced .git directory (nothing to commit)

if .git is already there in your dir, then follow:

  1. rm -rf .git/
  2. git init
  3. git remote add origin http://xyzremotedir/xyzgitproject.git
  4. git commit -m "do commit"
  5. git push origin master

How to display data from database into textbox, and update it

Wrap your all statements in !IsPostBack condition on page load.

protected void Page_Load(object sender, EventArgs e)
      // all statements

This will fix your issue.

How to set the environmental variable LD_LIBRARY_PATH in linux

  1. Go to the home folder and edit .profile
  2. Place the following line at the end

    export LD_LIBRARY_PATH=<your path>

  3. Save and Exit.

  4. Execute this command

    sudo ldconfig

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:

<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;
<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.");

        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;

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

            fr = new FileReader();
            fr.onload = receivedBinary;

        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;
        bodyAppend("p", label + " (" + result.length + "):");
        bodyAppend("pre", markup.join(" "));

    function bodyAppend(tagName, innerHTML) {
        var elm;

        elm = document.createElement(tagName);
        elm.innerHTML = innerHTML;

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

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 right-align form input boxes?

input { float: right; clear: both; }

Terminating idle mysql connections

I don't see any problem, unless you are not managing them using a connection pool.

If you use connection pool, these connections are re-used instead of initiating new connections. so basically, leaving open connections and re-use them it is less problematic than re-creating them each time.

Hidden TextArea

Set CSS display to none for textarea

<textarea name="hide" style="display:none;"></textarea>

Converting a string to JSON object

Let's us consider you have string like

example : "name:lucy,age:21,gender:female"

function getJsonData(query){_x000D_
    let arrayOfKeyValues = query.split(',');_x000D_
    let modifiedArray =  new Array();_x000D_
    for(let i=0;i< arrayOfKeyValues.length;i++){_x000D_
        let arrayValues = arrayOfKeyValues[i].split(':');_x000D_
        let arrayString ='"'+arrayValues[0]+'"'+':'+'"'+arrayValues[1]+'"';_x000D_
    let jsonDataString = '{'+modifiedArray.toString()+'}';_x000D_
    let jsonData = JSON.parse(jsonDataString);_x000D_
    console.log(typeof jsonData);_x000D_
    return jsonData;_x000D_
let query = "name:lucy,age:21,gender:female";_x000D_
let response = getJsonData(query);_x000D_


CSS3 scrollbar styling on a div

The problem with the css3 scroll bars is that, interaction can only be performed on the content. we can't interact with the scroll bar on touch devices.

single line comment in HTML

No, you have to close the comment with -->.

2D array values C++

Just want to point out you do not need to specify all dimensions of the array.

The leftmost dimension can be 'guessed' by the compiler.

#include <stdio.h>
int main(void) {
  int arr[][5] = {{1,2,3,4,5}, {5,6,7,8,9}, {6,5,4,3,2}};
  printf("sizeof arr is %d bytes\n", (int)sizeof arr);
  printf("number of elements: %d\n", (int)(sizeof arr/sizeof arr[0]));
  return 0;

What’s the best way to load a JSONObject from a json text file?

try this:

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

    public class JsonParsing {

        public static void main(String[] args) throws Exception {
            InputStream is = 
                    JsonParsing.class.getResourceAsStream( "sample-json.txt");
            String jsonTxt = IOUtils.toString( is );

            JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt );        
            double coolness = json.getDouble( "coolness" );
            int altitude = json.getInt( "altitude" );
            JSONObject pilot = json.getJSONObject("pilot");
            String firstName = pilot.getString("firstName");
            String lastName = pilot.getString("lastName");

            System.out.println( "Coolness: " + coolness );
            System.out.println( "Altitude: " + altitude );
            System.out.println( "Pilot: " + lastName );

and this is your sample-json.txt , should be in json format

 'mission':'apollo 11'

SQL Server Case Statement when IS NULL

  case isnull(B.[stat],0)
  when 0 then dateadd(dd,10,(c.[Eventdate]))

you can add in else statement if you want to add 30 days to the same .

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

For Windows/WSL/Cygwin etc users:

Make sure that your line endings are standard Unix line feeds, i.e. \n (LF) only.

Using Windows line endings \r\n (CRLF) line endings will break the command line break.

This is because having \ at the end of a line with Windows line ending translates to \ \r \n.
As Mark correctly explains above:

The line-continuation will fail if you have whitespace after the backslash and before the newline.

This includes not just space () or tabs (\t) but also the carriage return (\r).

SOAP request to WebService with java

A SOAP request is an XML file consisting of the parameters you are sending to the server.

The SOAP response is equally an XML file, but now with everything the service wants to give you.

Basically the WSDL is a XML file that explains the structure of those two XML.

To implement simple SOAP clients in Java, you can use the SAAJ framework (it is shipped with JSE 1.6 and above):

SOAP with Attachments API for Java (SAAJ) is mainly used for dealing directly with SOAP Request/Response messages which happens behind the scenes in any Web Service API. It allows the developers to directly send and receive soap messages instead of using JAX-WS.

See below a working example (run it!) of a SOAP web service call using SAAJ. It calls this web service.

import javax.xml.soap.*;

public class SOAPClientSAAJ {

    // SAAJ - SOAP Client Testing
    public static void main(String args[]) {
            The example below requests from the Web Service at:

            To call other WS, change the parameters below, which are:
             - the SOAP Endpoint URL (that is, where the service is responding from)
             - the SOAP Action

            Also change the contents of the method createSoapEnvelope() in this class. It constructs
             the inner part of the SOAP envelope that is actually sent.
        String soapEndpointUrl = "";
        String soapAction = "http://www.webserviceX.NET/GetInfoByCity";

        callSoapWebService(soapEndpointUrl, soapAction);

    private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
        SOAPPart soapPart = soapMessage.getSOAPPart();

        String myNamespace = "myNamespace";
        String myNamespaceURI = "http://www.webserviceX.NET";

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);

            Constructed SOAP Request Message:
            <SOAP-ENV:Envelope xmlns:SOAP-ENV="" xmlns:myNamespace="http://www.webserviceX.NET">
                        <myNamespace:USCity>New York</myNamespace:USCity>

        // SOAP Body
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyElem = soapBody.addChildElement("GetInfoByCity", myNamespace);
        SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("USCity", myNamespace);
        soapBodyElem1.addTextNode("New York");

    private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
        try {
            // Create SOAP Connection
            SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection soapConnection = soapConnectionFactory.createConnection();

            // Send SOAP Message to SOAP Server
            SOAPMessage soapResponse =, soapEndpointUrl);

            // Print the SOAP Response
            System.out.println("Response SOAP Message:");

        } catch (Exception e) {
            System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n");

    private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();


        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", soapAction);


        /* Print the request message, just for debugging purposes */
        System.out.println("Request SOAP Message:");

        return soapMessage;


How to convert JSON data into a Python object

dacite may also be a solution for you, it supports following features:

  • nested structures
  • (basic) types checking
  • optional fields (i.e. typing.Optional)
  • unions
  • forward references
  • collections
  • custom type hooks

from dataclasses import dataclass
from dacite import from_dict

class User:
    name: str
    age: int
    is_active: bool

data = {
    'name': 'John',
    'age': 30,
    'is_active': True,

user = from_dict(data_class=User, data=data)

assert user == User(name='John', age=30, is_active=True)

Find the most frequent number in a NumPy array

Here is a general solution that may be applied along an axis, regardless of values, using purely numpy. I've also found that this is much faster than scipy.stats.mode if there are a lot of unique values.

import numpy

def mode(ndarray, axis=0):
    # Check inputs
    ndarray = numpy.asarray(ndarray)
    ndim = ndarray.ndim
    if ndarray.size == 1:
        return (ndarray[0], 1)
    elif ndarray.size == 0:
        raise Exception('Cannot compute mode on empty array')
        axis = range(ndarray.ndim)[axis]
        raise Exception('Axis "{}" incompatible with the {}-dimension array'.format(axis, ndim))

    # If array is 1-D and numpy version is > 1.9 numpy.unique will suffice
    if all([ndim == 1,
            int(numpy.__version__.split('.')[0]) >= 1,
            int(numpy.__version__.split('.')[1]) >= 9]):
        modals, counts = numpy.unique(ndarray, return_counts=True)
        index = numpy.argmax(counts)
        return modals[index], counts[index]

    # Sort array
    sort = numpy.sort(ndarray, axis=axis)
    # Create array to transpose along the axis and get padding shape
    transpose = numpy.roll(numpy.arange(ndim)[::-1], axis)
    shape = list(sort.shape)
    shape[axis] = 1
    # Create a boolean array along strides of unique values
    strides = numpy.concatenate([numpy.zeros(shape=shape, dtype='bool'),
                                 numpy.diff(sort, axis=axis) == 0,
                                 numpy.zeros(shape=shape, dtype='bool')],
    # Count the stride lengths
    counts = numpy.cumsum(strides)
    counts[~strides] = numpy.concatenate([[0], numpy.diff(counts[~strides])])
    counts[strides] = 0
    # Get shape of padded counts and slice to return to the original shape
    shape = numpy.array(sort.shape)
    shape[axis] += 1
    shape = shape[transpose]
    slices = [slice(None)] * ndim
    slices[axis] = slice(1, None)
    # Reshape and compute final counts
    counts = counts.reshape(shape).transpose(transpose)[slices] + 1

    # Find maximum counts and return modals/counts
    slices = [slice(None, i) for i in sort.shape]
    del slices[axis]
    index = numpy.ogrid[slices]
    index.insert(axis, numpy.argmax(counts, axis=axis))
    return sort[index], counts[index]

Why is Github asking for username/password when following the instructions on screen and pushing a new repo?

Here is an official answer to this:

If Git prompts you for a username and password every time you try to interact with GitHub, you're probably using the HTTPS clone URL for your repository.

Using an HTTPS remote URL has some advantages: it's easier to set up than SSH, and usually works through strict firewalls and proxies. However, it also prompts you to enter your GitHub credentials every time you pull or push a repository.

You can configure Git to store your password for you. If you'd like to set that up, read all about setting up password caching.

jQuery load first 3 elements, click "load more" to display next 5 elements

The expression $(document).ready(function() deprecated in jQuery3.

See working fiddle with jQuery 3 here

Take into account I didn't include the showless button.

Here's the code:


$(function () {
    $('#myList li').slice(0, 3).show();
    $('#loadMore').on('click', function (e) {
        x = x+5;
        $('#myList li').slice(0, x).slideDown();


#myList li{display:none;
#loadMore {
#loadMore:hover {

Response to preflight request doesn't pass access control check

In AspNetCore web api, this issue got fixed by adding "Microsoft.AspNetCore.Cors" (ver 1.1.1) and adding the below changes on Startup.cs.

public void ConfigureServices(IServiceCollection services)
    services.AddCors(options =>
                builder =>


public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

    // Shows UseCors with named policy.

and putting [EnableCors("AllowAllHeaders")] on the controller.

Can ordered list produce result that looks like 1.1, 1.2, 1.3 (instead of just 1, 2, 3, ...) with css?

Note: Use CSS counters to create nested numbering in a modern browser. See the accepted answer. The following is for historical interest only.

If the browser supports content and counter,

.foo {_x000D_
  counter-reset: foo;_x000D_
.foo li {_x000D_
  list-style-type: none;_x000D_
.foo li::before {_x000D_
  counter-increment: foo;_x000D_
  content: "1." counter(foo) " ";_x000D_
<ol class="foo">_x000D_

Timing Delays in VBA

On Windows timer returns hundredths of a second... Most people just use seconds because on the Macintosh platform timer returns whole numbers.

multi line comment in Visual studio 2010

Highlight block of text, then:

Comment Block: Ctrl + K + C

Uncomment Block: Ctrl + K + U

Tested in Visual Studio 2012

How do I get the total Json record count using JQuery?

What you're looking for is


The d is the key. At least it is in my case, I'm using a .NET webservice.

            type: "POST",
            url: "CantTellU.asmx",
            data: "{'userID' : " + parseInt($.query.get('ID')) + " }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg, status) {

Pandas DataFrame: replace all values in a column, based on condition

You need to select that column:

In [41]:
df.loc[df['First Season'] > 1990, 'First Season'] = 1

                 Team  First Season  Total Games
0      Dallas Cowboys          1960          894
1       Chicago Bears          1920         1357
2   Green Bay Packers          1921         1339
3      Miami Dolphins          1966          792
4    Baltimore Ravens             1          326
5  San Franciso 49ers          1950         1003

So the syntax here is:

df.loc[<mask>(here mask is generating the labels to index) , <optional column(s)> ]

You can check the docs and also the 10 minutes to pandas which shows the semantics


If you want to generate a boolean indicator then you can just use the boolean condition to generate a boolean Series and cast the dtype to int this will convert True and False to 1 and 0 respectively:

In [43]:
df['First Season'] = (df['First Season'] > 1990).astype(int)

                 Team  First Season  Total Games
0      Dallas Cowboys             0          894
1       Chicago Bears             0         1357
2   Green Bay Packers             0         1339
3      Miami Dolphins             0          792
4    Baltimore Ravens             1          326
5  San Franciso 49ers             0         1003

Pass row number as variable in excel sheet

An alternative is to use OFFSET:

Assuming the column value is stored in B1, you can use the following

C1 = OFFSET(A1, 0, B1 - 1)

This works by:

a) taking a base cell (A1)
b) adding 0 to the row (keeping it as A)
c) adding (A5 - 1) to the column

You can also use another value instead of 0 if you want to change the row value too.

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

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

I found this nice quick tutorial for how to setup a bookmark on mobile safari that will automatically open the view source of a page:

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

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

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

Stop form from submitting , Using Jquery

A different approach could be

    <script type="text/javascript">
    function CheckData() {
    //you may want to check something here and based on that wanna return true and false from the         function.
     return true;//will cause form to postback to server.
      return false;//will cause form Not to postback to server
    @using (Html.BeginForm("SaveEmployee", "Employees", FormMethod.Post, new { id = "EmployeeDetailsForm" }))
    <input type="submit" value= "Save Employee" onclick="return CheckData();"/>

What exactly is nullptr?

From nullptr: A Type-safe and Clear-Cut Null Pointer:

The new C++09 nullptr keyword designates an rvalue constant that serves as a universal null pointer literal, replacing the buggy and weakly-typed literal 0 and the infamous NULL macro. nullptr thus puts an end to more than 30 years of embarrassment, ambiguity, and bugs. The following sections present the nullptr facility and show how it can remedy the ailments of NULL and 0.

Other references:

Plotting categorical data with pandas and matplotlib

To plot multiple categorical features as bar charts on the same plot, I would suggest:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(
        "colour": ["red", "blue", "green", "red", "red", "yellow", "blue"],
        "direction": ["up", "up", "down", "left", "right", "down", "down"],

categorical_features = ["colour", "direction"]
fig, ax = plt.subplots(1, len(categorical_features))
for i, categorical_feature in enumerate(df[categorical_features]):
    df[categorical_feature].value_counts().plot("bar", ax=ax[i]).set_title(categorical_feature)

enter image description here

Simplest way to do grouped barplot

There are several ways to do plots in R; lattice is one of them, and always a reasonable solution, +1 to @agstudy. If you want to do this in base graphics, you could try the following:

Reasonstats <- read.table(text="Category         Reason  Species
                                 Decline        Genuine       24
                                Improved        Genuine       16
                                Improved  Misclassified       85
                                 Decline  Misclassified       41
                                 Decline      Taxonomic        2
                                Improved      Taxonomic        7
                                 Decline        Unclear       41
                                Improved        Unclear      117", header=T)

ReasonstatsDec <- Reasonstats[which(Reasonstats$Category=="Decline"),]
ReasonstatsImp <- Reasonstats[which(Reasonstats$Category=="Improved"),]
Reasonstats3   <- cbind(ReasonstatsImp[,3], ReasonstatsDec[,3])
colnames(Reasonstats3) <- c("Improved", "Decline")
rownames(Reasonstats3) <- ReasonstatsImp$Reason

  barplot(t(Reasonstats3), beside=TRUE, ylab="number of species", 
          cex.names=0.8, las=2, ylim=c(0,120), col=c("darkblue","red"))

enter image description here

Here's what I did: I created a matrix with two columns (because your data were in columns) where the columns were the species counts for Decline and for Improved. Then I made those categories the column names. I also made the Reasons the row names. The barplot() function can operate over this matrix, but wants the data in rows rather than columns, so I fed it a transposed version of the matrix. Lastly, I deleted some of your arguments to your barplot() function call that were no longer needed. In other words, the problem was that your data weren't set up the way barplot() wants for your intended output.

Video file formats supported in iPhone

Quoting the iPhone OS Technology Overview:

iPhone OS provides support for full-screen video playback through the Media Player framework (MediaPlayer.framework). This framework supports the playback of movie files with the .mov, .mp4, .m4v, and .3gp filename extensions and using the following compression standards:

  • H.264 video, up to 1.5 Mbps, 640 by 480 pixels, 30 frames per second, Low-Complexity version of the H.264 Baseline Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
  • H.264 video, up to 768 Kbps, 320 by 240 pixels, 30 frames per second, Baseline Profile up to Level 1.3 with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
  • MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second, Simple Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
  • Numerous audio formats, including the ones listed in “Audio Technologies”

For information about the classes of the Media Player framework, see Media Player Framework Reference.

CSS3's border-radius property and border-collapse:collapse don't mix. How can I use border-radius to create a collapsed table with rounded corners?

The given answers only work when there are no borders around the table, which is very limiting!

I have a macro in SASS to do this, which fully supports external and internal borders, achieving the same styling as border-collapse: collapse without actually specifying it.

Tested in FF/IE8/Safari/Chrome.

Gives nice rounded borders in pure CSS in all browsers but IE8 (degrades gracefully) since IE8 doesn't support border-radius :(

Some older browsers may require vendor prefixes to work with border-radius, so feel free to add those prefixes to your code as necessary.

This answer is not the shortest - but it works.

.roundedTable {
  border-radius: 20px / 20px;
  border: 1px solid #333333;
  border-spacing: 0px;
.roundedTable th {
  padding: 4px;
  background: #ffcc11;
  border-left: 1px solid #333333;
.roundedTable th:first-child {
  border-left: none;
  border-top-left-radius: 20px;
.roundedTable th:last-child {
  border-top-right-radius: 20px;
.roundedTable tr td {
  border: 1px solid #333333;
  border-right: none;
  border-bottom: none;
  padding: 4px;
.roundedTable tr td:first-child {
  border-left: none;

To apply this style simply change your


tag to the following:

<table class="roundedTable">

and be sure to include the above CSS styles in your HTML.

Hope this helps.

Default optional parameter in Swift function

If you want to be able to call the func with or without the parameter you can create a second func of the same name which calls the other.

func test(firstThing: Int?) {
    if firstThing != nil {

func test() {
    test(firstThing: nil)

now you can call a function named test without or without the parameter.

// both work
test(firstThing: 5)

What is the minimum length of a valid international phone number?

The minimum length is 4 for Saint Helena (Format: +290 XXXX) and Niue (Format: +683 XXXX).

How to select specific columns in laravel eloquent

From laravel 5.3 only using get() method you can get specific columns of your table:

YouModelName::get(['id', 'name']);

Or from laravel 5.4 you can also use all() method for getting the fields of your choice:

YourModelName::all('id', 'name');

with both of above method get() or all() you can also use where() but syntax is different for both:


YourModelName::all('id', 'name')->where('id',1);


YourModelName::where('id',1)->get(['id', 'name']);

How to set all elements of an array to zero or any same value?

If your array is static or global it's initialized to zero before main() starts. That would be the most efficient option.

In python, what is the difference between random.uniform() and random.random()?

In random.random() the output lies between 0 & 1 , and it takes no input parameters

Whereas random.uniform() takes parameters , wherein you can submit the range of the random number. e.g.
import random as ra print ra.random() print ra.uniform(5,10)

0.672485369423 7.9237539416