Programs & Examples On #Blogger

Blogger is a blog-publishing service by Google

Formatting code snippets for blogging on Blogger

To post your html, javascript,c# and java you should convert special characters to HTML code. as '<' as &lt; and '>' to &gt; and e.t.c..

Add this link Code Converter to iGoogle. This will help you to convert the special characters.

Then add SyntaxHighlighter 3.0.83 new version to customize your code in blogger. But you should know How to configure the syntaxHighlighter in your blogger template.

Android Horizontal RecyclerView scroll Direction

You can do it with just xml.

the app:reverseLayout="true" do the job!

<android.support.v7.widget.RecyclerView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:divider="@null"
                        android:orientation="horizontal"
                        app:reverseLayout="true"
                        app:layoutManager="android.support.v7.widget.LinearLayoutManager" />

How can I get the current user's username in Bash?

The current user's username can be gotten in pure Bash with the ${parameter@operator} parameter expansion (introduced in Bash 4.4):

$ : \\u
$ printf '%s\n' "${_@P}"

The : built-in (synonym of true) is used instead of a temporary variable by setting the last argument, which is stored in $_. We then expand it (\u) as if it were a prompt string with the P operator.

This is better than using $USER, as $USER is just a regular environmental variable; it can be modified, unset, etc. Even if it isn't intentionally tampered with, a common case where it's still incorrect is when the user is switched without starting a login shell (su's default).

How do I change the JAVA_HOME for ant?

There are 2 ways of changing the compiler:

  • export JAVA_HOME=/path/to/jdk before you start Ant.
  • Set <javac exectuable="/path/to/javac">

Another option would be to add a respective tools.jar to the classpath, but this is usually used if Ant is started from another tools like Maven.

For more details on these (or other) options of changing Java Compiler in Ant, see this article for example.

Python subprocess.Popen "OSError: [Errno 12] Cannot allocate memory"

swap may not be the red herring previously suggested. How big is the python process in question just before the ENOMEM?

Under kernel 2.6, /proc/sys/vm/swappiness controls how aggressively the kernel will turn to swap, and overcommit* files how much and how precisely the kernel may apportion memory with a wink and a nod. Like your facebook relationship status, it's complicated.

...but swap is actually available on demand (according to the web host)...

but not according to the output of your free(1) command, which shows no swap space recognized by your server instance. Now, your web host may certainly know much more than I about this topic, but virtual RHEL/CentOS systems I've used have reported swap available to the guest OS.

Adapting Red Hat KB Article 15252:

A Red Hat Enterprise Linux 5 system will run just fine with no swap space at all as long as the sum of anonymous memory and system V shared memory is less than about 3/4 the amount of RAM. .... Systems with 4GB of ram or less [are recommended to have] a minimum of 2GB of swap space.

Compare your /proc/sys/vm settings to a plain CentOS 5.3 installation. Add a swap file. Ratchet down swappiness and see if you live any longer.

How to set an button align-right with Bootstrap?

function Continue({show, onContinue}) {
  return(<div className="row continue">
  { show ? <div className="col-11">
    <button class="btn btn-primary btn-lg float-right" onClick= {onContinue}>Continue</button>
    </div>
    : null }
  </div>);
}

Is there a simple JavaScript slider?

There's a nice javascript slider, it's very easy to implement. You can download the zip package here: http://ruwix.com/javascript-volume-slider-control/


p.s. here the simplified version of the above script:

enter image description here

DEMO link

Add 'x' number of hours to date

I like those built-in php date expressions like +1 hour, but for some reason, they fall out of my head all of the time. Besides, none of the IDEs I'm aware of suggest auto-completion facility for that kind of stuff. And, finally, although juggling with those strtotime and date functions is no rocket science, I have to google their usage each time I need them.

That's why I like the solution that eliminates (at least mitigates) those issues. Here's how adding x hours to a date can look like:

(new Future(
    new DateTimeFromISO8601String('2014-11-21T06:04:31.321987+00:00'),
    new NHours($x)
))
    ->value();

As a nice bonus, you don't have to worry about formatting the resulting value, it's already is ISO8601 format.

This example uses meringue library, you can check out more examples here.

How to get the index with the key in Python dictionary?

Use OrderedDicts: http://docs.python.org/2/library/collections.html#collections.OrderedDict

>>> x = OrderedDict((("a", "1"), ("c", '3'), ("b", "2")))
>>> x["d"] = 4
>>> x.keys().index("d")
3
>>> x.keys().index("c")
1

For those using Python 3

>>> list(x.keys()).index("c")
1

how to make div click-able?

Give it an ID like "something", then:

var something = document.getElementById('something');

something.style.cursor = 'pointer';
something.onclick = function() {
    // do something...
};

Changing the background color (as per your updated question):

something.onmouseover = function() {
    this.style.backgroundColor = 'red';
};
something.onmouseout = function() {
    this.style.backgroundColor = '';
};

How to make an autocomplete address field with google maps api?

Like others have mentioned, the Google Places Autocomplete API is missing some important functions. Case in point, Google will not validate that the street number is real, and they also will not put it into a standardized format. So, it is the user's responsibility to enter that portion of the address correctly.

Google also won't predict PO Boxes or apartment numbers. So, if you are using their API for shipping, address cleansing or data governance, you may want one that will validate the building number, autocomplete the unit number and standardize the information.

Full Disclosure, I work for SmartyStreets

Create Table from JSON Data with angularjs and ng-repeat

To create HTML table using JSON, we will use ngRepeat directive of AngularJS.

Example

HTML

<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<table border="1">
<tr ng-repeat="x in names">
<td>{{x.Name}}</td>
<td>{{x.City}}</td>
<td>{{x.Country}}</td></tr>
</table>
</div>
</body>
</html>

JavaScript

var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope) {
    $scope.names = [
      { "Name" : "Max Joe", "City" : "Lulea", "Country" : "Sweden" },
      { "Name" : "Manish", "City" : "Delhi", "Country" : "India" },
      { "Name" : "Koniglich", "City" : "Barcelona", "Country" : "Spain" },
      { "Name" : "Wolski", "City" : "Arhus", "Country" : "Denmark" }
    ];
});

In above example I have created table from json. I have taken reference from http://www.tutsway.com/create-html-table-using-json-in-angular-js.php

Loop through columns and add string lengths as new columns

You need to use [[, the programmatic equivalent of $. Otherwise, for example, when i is col1, R will look for df$i instead of df$col1.

for(i in names(df)){
  df[[paste(i, 'length', sep="_")]] <- str_length(df[[i]])
}

How do I make Visual Studio pause after executing a console application in debug mode?

Just use a logging library, like log4net, and have it log to a file appender.

Vertical Align text in a Label

You don't have to add any padding or edit the line-height!

Instead, just make sure that when you have an HTML like this :

<label><input type="checkbox" name=""><span>Checkbox Text</span></label>

Just make sure that the input height and width are the same, and the the text has the same font size.

Then, it will look perfectly fine and looks centered.

How to find a min/max with Ruby

In addition to the provided answers, if you want to convert Enumerable#max into a max method that can call a variable number or arguments, like in some other programming languages, you could write:

def max(*values)
 values.max
end

Output:

max(7, 1234, 9, -78, 156)
=> 1234

This abuses the properties of the splat operator to create an array object containing all the arguments provided, or an empty array object if no arguments were provided. In the latter case, the method will return nil, since calling Enumerable#max on an empty array object returns nil.

If you want to define this method on the Math module, this should do the trick:

module Math
 def self.max(*values)
  values.max
 end
end

Note that Enumerable.max is, at least, two times slower compared to the ternary operator (?:). See Dave Morse's answer for a simpler and faster method.

How Many Seconds Between Two Dates?

Just subtract:

var a = new Date();
alert("Wait a few seconds, then click OK");

var b = new Date();
var difference = (b - a) / 1000;

alert("You waited: " + difference + " seconds");

python JSON only get keys in first level

As Karthik mentioned, dct.keys() will work but it will return all the keys in dict_keys type not in list type. So if you want all the keys in a list, then list(dct.keys()) will work.

Creating a new empty branch for a new project

The correct answer is to create an orphan branch. I explain how to do this in detail on my blog.(Archived link)

...

Before starting, upgrade to the latest version of GIT. To make sure you’re running the latest version, run

which git

If it spits out an old version, you may need to augment your PATH with the folder containing the version you just installed.

Ok, we’re ready. After doing a cd into the folder containing your git checkout, create an orphan branch. For this example, I’ll name the branch “mybranch”.

git checkout --orphan mybranch

Delete everything in the orphan branch

git rm -rf .

Make some changes

vi README.txt

Add and commit the changes

git add README.txt
git commit -m "Adding readme file"

That’s it. If you run

git log

you’ll notice that the commit history starts from scratch. To switch back to your master branch, just run

git checkout master

You can return to the orphan branch by running

git checkout mybranch

Get string between two strings in a string

var matches = Regex.Matches(input, @"(?<=key :)(.+?)(?=-)");

This returns only the value(s) between "key :" and the following occurance of "-"

Error:Execution failed for task ':app:processDebugResources'. > java.io.IOException: Could not delete folder "" in android studio

I have same issue. When I clean my project and rebuild it then everything works fine.

Build -> Clean Project

Progress during large file copy (Copy-Item & Write-Progress?)

Hate to be the one to bump an old subject, but I found this post extremely useful. After running performance tests on the snippets by stej and it's refinement by Graham Gold, plus the BITS suggestion by Nacht, I have decuded that:

  1. I really liked Graham's command with time estimations and speed readings.
  2. I also really liked the significant speed increase of using BITS as my transfer method.

Faced with the decision between the two... I found that Start-BitsTransfer supported Asynchronous mode. So here is the result of my merging the two.

function Copy-File {
    # ref: https://stackoverflow.com/a/55527732/3626361
    param([string]$From, [string]$To)

    try {
        $job = Start-BitsTransfer -Source $From -Destination $To `
            -Description "Moving: $From => $To" `
            -DisplayName "Backup" -Asynchronous

        # Start stopwatch
        $sw = [System.Diagnostics.Stopwatch]::StartNew()
        Write-Progress -Activity "Connecting..."

        while ($job.JobState.ToString() -ne "Transferred") {
            switch ($job.JobState.ToString()) {
                "Connecting" {
                    break
                }
                "Transferring" {
                    $pctcomp = ($job.BytesTransferred / $job.BytesTotal) * 100
                    $elapsed = ($sw.elapsedmilliseconds.ToString()) / 1000

                    if ($elapsed -eq 0) {
                        $xferrate = 0.0
                    }
                    else {
                        $xferrate = (($job.BytesTransferred / $elapsed) / 1mb);
                    }

                    if ($job.BytesTransferred % 1mb -eq 0) {
                        if ($pctcomp -gt 0) {
                            $secsleft = ((($elapsed / $pctcomp) * 100) - $elapsed)
                        }
                        else {
                            $secsleft = 0
                        }

                        Write-Progress -Activity ("Copying file '" + ($From.Split("\") | Select-Object -last 1) + "' @ " + "{0:n2}" -f $xferrate + "MB/s") `
                            -PercentComplete $pctcomp `
                            -SecondsRemaining $secsleft
                    }
                    break
                }
                "Transferred" {
                    break
                }
                Default {
                    throw $job.JobState.ToString() + " unexpected BITS state."
                }
            }
        }

        $sw.Stop()
        $sw.Reset()
    }
    finally {
        Complete-BitsTransfer -BitsJob $job
        Write-Progress -Activity "Completed" -Completed
    }
}

How do I format XML in Notepad++?

Plugins -> XML Tools -> Pretty Print (libXML) or Ctrl+Alt+Shift+B

You probably need to install the plugin:

Plugins > Plugins Manager > Show Plugins Manager

If you are behind a proxy, download it from here.

Then copy XMLTools.dll to the plugins directory and external libraries (four dlls) into the root Notepad++ directory.

What's the difference between git clone --mirror and git clone --bare

The difference is that when using --mirror, all refs are copied as-is. This means everything: remote-tracking branches, notes, refs/originals/* (backups from filter-branch). The cloned repo has it all. It's also set up so that a remote update will re-fetch everything from the origin (overwriting the copied refs). The idea is really to mirror the repository, to have a total copy, so that you could for example host your central repo in multiple places, or back it up. Think of just straight-up copying the repo, except in a much more elegant git way.

The new documentation pretty much says all this:

--mirror

Set up a mirror of the source repository. This implies --bare. Compared to --bare, --mirror not only maps local branches of the source to local branches of the target, it maps all refs (including remote branches, notes etc.) and sets up a refspec configuration such that all these refs are overwritten by a git remote update in the target repository.

My original answer also noted the differences between a bare clone and a normal (non-bare) clone - the non-bare clone sets up remote tracking branches, only creating a local branch for HEAD, while the bare clone copies the branches directly.

Suppose origin has a few branches (master (HEAD), next, pu, and maint), some tags (v1, v2, v3), some remote branches (devA/master, devB/master), and some other refs (refs/foo/bar, refs/foo/baz, which might be notes, stashes, other devs' namespaces, who knows).

  • git clone origin-url (non-bare): You will get all of the tags copied, a local branch master (HEAD) tracking a remote branch origin/master, and remote branches origin/next, origin/pu, and origin/maint. The tracking branches are set up so that if you do something like git fetch origin, they'll be fetched as you expect. Any remote branches (in the cloned remote) and other refs are completely ignored.

  • git clone --bare origin-url: You will get all of the tags copied, local branches master (HEAD), next, pu, and maint, no remote tracking branches. That is, all branches are copied as is, and it's set up completely independent, with no expectation of fetching again. Any remote branches (in the cloned remote) and other refs are completely ignored.

  • git clone --mirror origin-url: Every last one of those refs will be copied as-is. You'll get all the tags, local branches master (HEAD), next, pu, and maint, remote branches devA/master and devB/master, other refs refs/foo/bar and refs/foo/baz. Everything is exactly as it was in the cloned remote. Remote tracking is set up so that if you run git remote update all refs will be overwritten from origin, as if you'd just deleted the mirror and recloned it. As the docs originally said, it's a mirror. It's supposed to be a functionally identical copy, interchangeable with the original.

Responsive design with media query : screen size?

The screen widths Bootstrap v3.x uses are as follows:

  • Extra small devices Phones (<768px) / .col-xs-
  • Small devices Tablets (=768px) / .col-sm-
  • Medium devices Desktops (=992px) / .col-md-
  • Large devices Desktops (=1200px) / .col-lg-

So, these are good to use and work well in practice.

What is the proper declaration of main in C++?

Details on return values and their meaning

Per 3.6.1 ([basic.start.main]):

A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling std::exit with the return value as the argument. If control reaches the end of main without encountering a return statement, the effect is that of executing

return 0;

The behavior of std::exit is detailed in section 18.5 ([support.start.term]), and describes the status code:

Finally, control is returned to the host environment. If status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.

How to send a POST request with BODY in swift

You're close. The parameters dictionary formatting doesn't look correct. You should try the following:

let parameters: [String: AnyObject] = [
    "IdQuiz" : 102,
    "IdUser" : "iosclient",
    "User" : "iosclient",
    "List": [
        [
            "IdQuestion" : 5,
            "IdProposition": 2,
            "Time" : 32
        ],
        [
            "IdQuestion" : 4,
            "IdProposition": 3,
            "Time" : 9
        ]
    ]
]

Alamofire.request(.POST, "http://myserver.com", parameters: parameters, encoding: .JSON)
    .responseJSON { request, response, JSON, error in
        print(response)
        print(JSON)
        print(error)
    }

Hopefully that fixed your issue. If it doesn't, please reply and I'll adjust my answer accordingly.

PHP FPM - check if running

in case it helps someone, on amilinux, with php5.6 and php-fpm installed, it's:

sudo /etc/init.d/php-fpm-5.6 status

Reversing an Array in Java

I like to keep the original array and return a copy. This is a generic version:

public static <T> T[] reverse(T[] array) {
    T[] copy = array.clone();
    Collections.reverse(Arrays.asList(copy));
    return copy;
}

without keeping the original array:

public static <T> void reverse(T[] array) {
    Collections.reverse(Arrays.asList(array));
}

How do I center text horizontally and vertically in a TextView?

android:gravity="centre" 

This would help you to centre the textview.

How do I force a DIV block to extend to the bottom of a page even if it has no content?

Try playing around with the following css rule:

#content {
    min-height: 600px;
    height: auto !important;
    height: 600px;
}

Change the height to suit your page. height is mentioned twice for cross browser compatibility.

using extern template (C++11)

You should only use extern template to force the compiler to not instantiate a template when you know that it will be instantiated somewhere else. It is used to reduce compile time and object file size.

For example:

// header.h

template<typename T>
void ReallyBigFunction()
{
    // Body
}

// source1.cpp

#include "header.h"
void something1()
{
    ReallyBigFunction<int>();
}

// source2.cpp

#include "header.h"
void something2()
{
    ReallyBigFunction<int>();
}

This will result in the following object files:

source1.o
    void something1()
    void ReallyBigFunction<int>()    // Compiled first time

source2.o
    void something2()
    void ReallyBigFunction<int>()    // Compiled second time

If both files are linked together, one void ReallyBigFunction<int>() will be discarded, resulting in wasted compile time and object file size.

To not waste compile time and object file size, there is an extern keyword which makes the compiler not compile a template function. You should use this if and only if you know it is used in the same binary somewhere else.

Changing source2.cpp to:

// source2.cpp

#include "header.h"
extern template void ReallyBigFunction<int>();
void something2()
{
    ReallyBigFunction<int>();
}

Will result in the following object files:

source1.o
    void something1()
    void ReallyBigFunction<int>() // compiled just one time

source2.o
    void something2()
    // No ReallyBigFunction<int> here because of the extern

When both of these will be linked together, the second object file will just use the symbol from the first object file. No need for discard and no wasted compile time and object file size.

This should only be used within a project, like in times when you use a template like vector<int> multiple times, you should use extern in all but one source file.

This also applies to classes and function as one, and even template member functions.

Android: remove left margin from actionbar's custom layout

Create toolbar like this:

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/menuToolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="0dp"
android:background="@color/white"
android:contentInsetLeft="10dp"
android:contentInsetRight="10dp"
android:contentInsetStart="10dp"
android:minHeight="?attr/actionBarSize"
android:padding="0dp"
app:contentInsetLeft="10dp"
app:contentInsetRight="10dp"
app:contentInsetStart="10dp"></android.support.v7.widget.Toolbar>

please follow this link for more - Android Tips

How to make space between LinearLayout children?

Since API Level 14 you can just add a (transparent) divider drawable:

android:divider="@drawable/divider"
android:showDividers="middle"

and it will handle the rest for you!

How can I convert a string with dot and comma into a float in Python

Better solution for different currency formats:

def text_currency_to_float(text):
  t = text
  dot_pos = t.rfind('.')
  comma_pos = t.rfind(',')
  if comma_pos > dot_pos:
    t = t.replace(".", "")
    t = t.replace(",", ".")
  else:
    t = t.replace(",", "")

  return(float(t))

Which SchemaType in Mongoose is Best for Timestamp?

Edit - 20 March 2016

Mongoose now support timestamps for collections.

Please consider the answer of @bobbyz below. Maybe this is what you are looking for.

Original answer

Mongoose supports a Date type (which is basically a timestamp):

time : { type : Date, default: Date.now }

With the above field definition, any time you save a document with an unset time field, Mongoose will fill in this field with the current time.

Source: http://mongoosejs.com/docs/guide.html

SQL join: selecting the last records in a one-to-many relationship

Tested on SQLite:

SELECT c.*, p.*, max(p.date)
FROM customer c
LEFT OUTER JOIN purchase p
ON c.id = p.customer_id
GROUP BY c.id

The max() aggregate function will make sure that the latest purchase is selected from each group (but assumes that the date column is in a format whereby max() gives the latest - which is normally the case). If you want to handle purchases with the same date then you can use max(p.date, p.id).

In terms of indexes, I would use an index on purchase with (customer_id, date, [any other purchase columns you want to return in your select]).

The LEFT OUTER JOIN (as opposed to INNER JOIN) will make sure that customers that have never made a purchase are also included.

The openssl extension is required for SSL/TLS protection

For me on Windows 10 none of those worked ... I had changed my local server from WAMP to Laragon and had to add the new path to the php.ini in the Environment Variables under:

Control Panel --> Advanced System Settings --> Environment Variables --> Path (double click) --> Browse... then navigate to the php.ini and click ok.

After that a reboot was needed and now composer works like a charm!

How to add 10 minutes to my (String) time?

I would recommend storing the time as integers and regulate it through the division and modulo operators, once that is done convert the integers into the string format you require.

Android OnClickListener - identify a button

Button mybutton = new Button(ViewPagerSample.this);
mybutton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
            // TODO Auto-generated method stub
    }
});

How to use a App.config file in WPF applications?

You have to add the reference to System.configuration in your solution. Also, include using System.Configuration;. Once you do that, you'll have access to all the configuration settings.

What are the differences between Visual Studio Code and Visual Studio?

One huge difference (for me) is that Visual Studio Code is one monitor only. With Visual Studio you can use multi-screen setups.

Difference between clean, gradlew clean

You should use this one too:

./gradlew :app:dependencies (Mac and Linux) -With ./

gradlew :app:dependencies (Windows) -Without ./

The libs you are using internally using any other versions of google play service.If yes then remove or update those libs.

Get and set position with jQuery .offset()

//Get
var p = $("#elementId");
var offset = p.offset();

//set
$("#secondElementId").offset({ top: offset.top, left: offset.left});

Assign a login to a user created without login (SQL Server)

I found that this question was still relevant but not clearly answered in my case.

Using SQL Server 2012 with an orphaned SQL_USER this was the fix;

USE databasename                      -- The database I had recently attached
EXEC sp_change_users_login 'Report'   -- Display orphaned users
EXEC sp_change_users_login 'Auto_Fix', 'UserName', NULL, 'Password'

How do I type a TAB character in PowerShell?

Test with [char]9, such as:

$Tab = [char]9
Write-Output "$Tab hello"

Output:

     hello

Check that a input to UITextField is numeric only

Not so elegant, but simple :)

- (BOOL) isNumber: (NSString*)input
{
    return [input doubleValue] != 0 || [input isEqualToString:@"0"] || [input isEqualToString:@"0.0"];
}

Using other keys for the waitKey() function of opencv

If you want to pause the program to take screenshots of the progress

(shown in let's say cv2.imshow)

cv2.waitKey(0) would continue after pressing "Scr" button (or its combination), but you can try this

cv2.waitKey(0)
input('')

cv2.waitkey(0) to give the program enough time to process everything you want to see in the imshow and input('')

to make it wait for you to press Enter in the console window

this works on python 3

Inline instantiation of a constant List

You'll need to use a static readonly list instead. And if you want the list to be immutable then you might want to consider using ReadOnlyCollection<T> rather than List<T>.

private static readonly ReadOnlyCollection<string> _metrics =
    new ReadOnlyCollection<string>(new[]
        {
            SourceFile.LOC,
            SourceFile.MCCABE,
            SourceFile.NOM,
            SourceFile.NOA,
            SourceFile.FANOUT,
            SourceFile.FANIN,
            SourceFile.NOPAR,
            SourceFile.NDC,
            SourceFile.CALLS
        });

public static ReadOnlyCollection<string> Metrics
{
    get { return _metrics; }
}

How to read a CSV file from a URL with Python?

I am also using this approach for csv files (Python 3.6.9):

import csv
import io
import requests

r = requests.get(url)
buff = io.StringIO(r.text)
dr = csv.DictReader(buff)
for row in dr:
    print(row)

Why is super.super.method(); not allowed in Java?

I think if you overwrite a method and want to all the super-class version of it (like, say for equals), then you virtually always want to call the direct superclass version first, which one will call its superclass version in turn if it wants.

I think it only makes rarely sense (if at all. i can't think of a case where it does) to call some arbitrary superclass' version of a method. I don't know if that is possible at all in Java. It can be done in C++:

this->ReallyTheBase::foo();

Pausing a batch file for amount of time

If choice is available, use this:

choice /C X /T 10 /D X > nul

where /T 10 is the number of seconds to delay. Note the syntax can vary depending on your Windows version, so use CHOICE /? to be sure.

Deny all, allow only one IP through htaccess

This can be improved by using the directive designed for that task.

ErrorDocument 403 /specific_page.html
Order Allow,Deny
Allow from 111.222.333.444

Where 111.222.333.444 is your static IP address.

When using the "Order Allow,Deny" directive the requests must match either Allow or Deny, if neither is met, the request is denied.

http://httpd.apache.org/docs/2.2/mod/mod_authz_host.html#order

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

Since you've included the C++ tag, you could use the {fmt} library and avoid the PRIu64 macro and other printf issues altogether:

#include <fmt/core.h>

int main() {
  uint64_t ui64 = 90;
  fmt::print("test uint64_t : {}\n", ui64);
}

The formatting facility based on this library is proposed for standardization in C++20: P0645.

Disclaimer: I'm the author of {fmt}.

IN Clause with NULL or IS NULL

Note: Since someone claimed that the external link is dead in Sushant Butta's answer I've posted the content here as a separate answer.

Beware of NULLS.

Today I came across a very strange behaviour of query while using IN and NOT IN operators. Actually I wanted to compare two tables and find out whether a value from table b existed in table a or not and find out its behavior if the column containsnull values. So I just created an environment to test this behavior.

We will create table table_a.

SQL> create table table_a ( a number);
Table created.

We will create table table_b.

SQL> create table table_b ( b number);
Table created.

Insert some values into table_a.

SQL> insert into table_a values (1);
1 row created.

SQL> insert into table_a values (2);
1 row created.

SQL> insert into table_a values (3);
1 row created.

Insert some values into table_b.

SQL> insert into table_b values(4);
1 row created.

SQL> insert into table_b values(3);
1 row created.

Now we will execute a query to check the existence of a value in table_a by checking its value from table_b using IN operator.

SQL> select * from table_a where a in (select * from table_b);
         A
----------
         3

Execute below query to check the non existence.

SQL> select * from table_a where a not in (select * from table_b);
         A
----------
         1
         2

The output came as expected. Now we will insert a null value in the table table_b and see how the above two queries behave.

SQL> insert into table_b values(null);
1 row created.

SQL> select * from table_a where a in (select * from table_b);
         A
----------
         3

SQL> select * from table_a where a not in (select * from table_b);

no rows selected

The first query behaved as expected but what happened to the second query? Why didn't we get any output, what should have happened? Is there any difference in the query? No.

The change is in the data of table table_b. We have introduced a null value in the table. But how come it's behaving like this? Let's split the two queries into "AND" and "OR" operator.

First Query:

The first query will be handled internally something like this. So a null will not create a problem here as my first two operands will either evaluate to true or false. But my third operand a = null will neither evaluate to true nor false. It will evaluate to null only.

select * from table_a whara a = 3 or a = 4 or a = null;

a = 3  is either true or false
a = 4  is either true or false
a = null is null

Second Query:

The second query will be handled as below. Since we are using an "AND" operator and anything other than true in any of the operand will not give me any output.

select * from table_a whara a <> 3 and a <> 4 and a <> null;

a <> 3 is either true or false
a <> 4 is either true or false
a <> null is null

So how do we handle this? We will pick all the not null values from table table_b while using NOT IN operator.

SQL> select * from table_a where a not in (select * from table_b where b is not null);

         A
----------
         1
         2

So always be careful about NULL values in the column while using NOT IN operator.

Beware of NULL!!

How to uninstall Apache with command line

sc delete Apache2.4

Remove service in windows

Android Starting Service at Boot Time , How to restart service class after device Reboot?

Most the solutions posted here are missing an important piece: doing it without a wake lock runs the risk of your Service getting killed before it is finished processing. Saw this solution in another thread, answering here as well.

Since WakefulBroadcastReceiver is deprecated in api 26 it is recommended for API Levels below 26

You need to obtain a wake lock . Luckily, the Support library gives us a class to do this:

public class SimpleWakefulReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // This is the Intent to deliver to our service.
        Intent service = new Intent(context, SimpleWakefulService.class);

        // Start the service, keeping the device awake while it is launching.
        Log.i("SimpleWakefulReceiver", "Starting service @ " + SystemClock.elapsedRealtime());
        startWakefulService(context, service);
    }
}

then, in your Service, make sure to release the wake lock:

    @Override
    protected void onHandleIntent(Intent intent) {
        // At this point SimpleWakefulReceiver is still holding a wake lock
        // for us.  We can do whatever we need to here and then tell it that
        // it can release the wakelock.

...
        Log.i("SimpleWakefulReceiver", "Completed service @ " + SystemClock.elapsedRealtime());
        SimpleWakefulReceiver.completeWakefulIntent(intent);
    }

Don't forget to add the WAKE_LOCK permission and register your receiver in the manifest:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

...

<service android:name=".SimpleWakefulReceiver">
    <intent-filter>
        <action android:name="com.example.SimpleWakefulReceiver"/>
    </intent-filter>
</service>

Unknown URL content://downloads/my_downloads

The exception is caused by disabled Download Manager. And there is no way to activate/deactivate Download Manager directly, since it's system application and we don't have access to it.

Only alternative way is redirect user to settings of Download Manager Application.

try {
     //Open the specific App Info page:
     Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
     intent.setData(Uri.parse("package:" + "com.android.providers.downloads"));
     startActivity(intent);

} catch ( ActivityNotFoundException e ) {
     e.printStackTrace();

     //Open the generic Apps page:
     Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
     startActivity(intent);
}

How do I combine two data-frames based on two columns?

You can also use the join command (dplyr).

For example:

new_dataset <- dataset1 %>% right_join(dataset2, by=c("column1","column2"))

Android background music service

way too late for the party here but i will still add my $0.02, Google has released a free sample called universal music player with which you can learn to stream music across all android platforms(auto, watch,mobile,tv..) it uses service to play music in the background, do check it out very helpful. here's the link to the project
https://github.com/googlesamples/android-UniversalMusicPlayer

Login failed for user 'IIS APPPOOL\ASP.NET v4.0'

I had to create a user `IIS APPPOOL\DefaultAppPool' as shown below in SQL Server. Security > Login > Right click and press 'New Login'. You only enter the username as show in red in the screen.

enter image description here

Then go into that new user properties, check the database this user will access (marked in blue below) and select db_owner as well. I had to select because although connection was working but subsequent SELECT queries didn't had the access if this was not selected.

enter image description here

These two should do it. Basically you are making the new user owner for the database so it has full access.

You don't need to restart SQL Server or anything, should work.

All shards failed

first thing first, all shards failed exception is not as dramatic as it sounds, it means shards were failed while serving a request(query or index), and there could be multiple reasons for it like

  1. Shards are actually in non-recoverable state, if your cluster and index state are in Yellow and RED, then it is one of the reason.
  2. Due to some shard recovery happening in background, shards didn't respond.
  3. Due to bad syntax of your query, ES responds in all shards failed.

In order to fix the issue, you need to filter it in one of the above category and based on that appropriate fix is required.

The one mentioned in the question, is clearly in the first bucket as cluster health is RED, means one or more primary shards are missing, and my this SO answer will help you fix RED cluster issue, which will fix the all shards exception in this case.

Using an authorization header with Fetch in React Native

It turns out, I was using the fetch method incorrectly.

fetch expects two parameters: an endpoint to the API, and an optional object which can contain body and headers.

I was wrapping the intended object within a second object, which did not get me any desired result.

Here's how it looks on a high level:

fetch('API_ENDPOINT', OBJECT)  
  .then(function(res) {
    return res.json();
   })
  .then(function(resJson) {
    return resJson;
   })

I structured my object as such:

var obj = {  
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Origin': '',
    'Host': 'api.producthunt.com'
  },
  body: JSON.stringify({
    'client_id': '(API KEY)',
    'client_secret': '(API SECRET)',
    'grant_type': 'client_credentials'
  })

How to check empty DataTable

Don't use rows.Count. That's asking for how many rows exist. If there are many, it will take some time to count them. All you really want to know is "is there at least one?" You don't care if there are 10 or 1000 or a billion. You just want to know if there is at least one. If I give you a box and ask you if there are any marbles in it, will you dump the box on the table and start counting? Of course not. Using LINQ, you might think that this would work:

bool hasRows = dataTable1.Rows.Any()

But unfortunately, DataRowCollection does not implement IEnumerable. So instead, try this:

bool hasRows = dataTable1.Rows.GetEnumerator().MoveNext()

You will of course need to check if the dataTable1 is null first. if it's not, this will tell you if there are any rows without enumerating the whole lot.

Twitter bootstrap 3 two columns full height

Try this

<div class="row row-offcanvas row-offcanvas-right">
<div class="col-xs-6 col-sm-3 sidebar-offcanvas" id="sidebar" role="navigation">Nav     Content</div>
<div class="col-xs-12 col-sm-9">Content goes here</div>
</div>

This uses Bootstrap 3 so no need for extra CSS etc...

How can I set a custom date time format in Oracle SQL Developer?

When i copied the date format for timestamp and used that for date, it did not work. But changing the date format to this (DD-MON-YY HH12:MI:SS AM) worked for me.

The change has to be made in Tools->Preferences-> search for NLS

Chrome Fullscreen API

Here are some functions I created for working with fullscreen in the browser.

They provide both enter/exit fullscreen across most major browsers.

function isFullScreen()
{
    return (document.fullScreenElement && document.fullScreenElement !== null)
         || document.mozFullScreen
         || document.webkitIsFullScreen;
}


function requestFullScreen(element)
{
    if (element.requestFullscreen)
        element.requestFullscreen();
    else if (element.msRequestFullscreen)
        element.msRequestFullscreen();
    else if (element.mozRequestFullScreen)
        element.mozRequestFullScreen();
    else if (element.webkitRequestFullscreen)
        element.webkitRequestFullscreen();
}

function exitFullScreen()
{
    if (document.exitFullscreen)
        document.exitFullscreen();
    else if (document.msExitFullscreen)
        document.msExitFullscreen();
    else if (document.mozCancelFullScreen)
        document.mozCancelFullScreen();
    else if (document.webkitExitFullscreen)
        document.webkitExitFullscreen();
}

function toggleFullScreen(element)
{
    if (isFullScreen())
        exitFullScreen();
    else
        requestFullScreen(element || document.documentElement);
}

opening html from google drive

Found method to see your own html file (from here (scroll down to answer from prac): https://productforums.google.com/forum/#!topic/drive/YY_fou2vo0A)

-- use Get Link to get URL with id=... substring -- put uc instead of open in URL

Gcc error: gcc: error trying to exec 'cc1': execvp: No such file or directory

What helped for me was to use llvm-gcc instead:

ln -s $(which llvm-gcc) /usr/local/bin/gcc

git push rejected: error: failed to push some refs

What I did to solve the problem was:

git pull origin [branch]
git push origin [branch]

Also make sure that you are pointing to the right branch by running:

git remote set-url origin [url]

Filter an array using a formula (without VBA)

Today, in Office 365, Excel has so called 'array functions'. The filter function does exactly what you want. No need to use CTRL+SHIFT+ENTER anymore, a simple enter will suffice.

In Office 365, your problem would be simply solved by using:

=VLOOKUP(A3, FILTER(A2:C6, B2:B6="B"), 3, FALSE)

PHP add elements to multidimensional array with array_push

I know the topic is old, but I just fell on it after a google search so... here is another solution:

$array_merged = array_merge($array_going_first, $array_going_second);

This one seems pretty clean to me, it works just fine!

How to get row count in sqlite using Android?

I know it is been answered long time ago, but i would like to share this also:

This code works very well:

SQLiteDatabase db = this.getReadableDatabase();
long taskCount = DatabaseUtils.queryNumEntries(db, TABLE_TODOTASK);

BUT what if i dont want to count all rows and i have a condition to apply?

DatabaseUtils have another function for this: DatabaseUtils.longForQuery

long taskCount = DatabaseUtils.longForQuery(db, "SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?",
         new String[] { String.valueOf(tasklist_Id) });

The longForQuery documentation says:

Utility method to run the query on the db and return the value in the first column of the first row.

public static long longForQuery(SQLiteDatabase db, String query, String[] selectionArgs)

It is performance friendly and save you some time and boilerplate code

Hope this will help somebody someday :)

Java better way to delete file if exists

if you have the file inside a dirrectory called uploads in your project. bellow code can be used.

Path root = Paths.get("uploads");
File existingFile = new File(this.root.resolve("img.png").toUri());

if (existingFile.exists() && existingFile.isFile()) {
     existingFile.delete();
   }

OR

If it is inside a different directory this solution can be used.

File existingFile = new File("D:\\<path>\\img.png");

if (existingFile.exists() && existingFile.isFile()) {
    existingFile.delete();
  }

How can I programmatically get the MAC address of an iphone

This looks like a pretty clean solution: UIDevice BIdentifier

// Return the local MAC addy
// Courtesy of FreeBSD hackers email list
// Accidentally munged during previous update. Fixed thanks to erica sadun & mlamb.
- (NSString *) macaddress{

    int                 mib[6];
    size_t              len;
    char                *buf;
    unsigned char       *ptr;
    struct if_msghdr    *ifm;
    struct sockaddr_dl  *sdl;

    mib[0] = CTL_NET;
    mib[1] = AF_ROUTE;
    mib[2] = 0;
    mib[3] = AF_LINK;
    mib[4] = NET_RT_IFLIST;

    if ((mib[5] = if_nametoindex("en0")) == 0) {
        printf("Error: if_nametoindex error\n");
        return NULL;
    }

    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 1\n");
        return NULL;
    }

    if ((buf = malloc(len)) == NULL) {
        printf("Could not allocate memory. error!\n");
        return NULL;
    }

    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 2");
        free(buf);
        return NULL;
    }

    ifm = (struct if_msghdr *)buf;
    sdl = (struct sockaddr_dl *)(ifm + 1);
    ptr = (unsigned char *)LLADDR(sdl);
    NSString *outstring = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X", 
                           *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    free(buf);

    return outstring;
}

How to search for a string in cell array in MATLAB?

I guess the following code could do the trick:

strs = {'HA' 'KU' 'LA' 'MA' 'TATA'}
ind=find(ismember(strs,'KU'))

This returns

ans = 
     2

find all unchecked checkbox in jquery

Also it can be achieved with pure js in such a way:

var matches = document.querySelectorAll('input[type="checkbox"]:not(:checked)');

Difference between 'struct' and 'typedef struct' in C++?

An important difference between a 'typedef struct' and a 'struct' in C++ is that inline member initialisation in 'typedef structs' will not work.

// the 'x' in this struct will NOT be initialised to zero
typedef struct { int x = 0; } Foo;

// the 'x' in this struct WILL be initialised to zero
struct Foo { int x = 0; };

Upload Image using POST form data in Python-requests

In case if you were to pass the image as part of JSON along with other attributes, you can use the below snippet.
client.py

import base64
import json                    

import requests

api = 'http://localhost:8080/test'
image_file = 'sample_image.png'

with open(image_file, "rb") as f:
    im_bytes = f.read()        
im_b64 = base64.b64encode(im_bytes).decode("utf8")

headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
  
payload = json.dumps({"image": im_b64, "other_key": "value"})
response = requests.post(api, data=payload, headers=headers)
try:
    data = response.json()     
    print(data)                
except requests.exceptions.RequestException:
    print(response.text)

server.py

import io
import json                    
import base64                  
import logging             
import numpy as np
from PIL import Image

from flask import Flask, request, jsonify, abort

app = Flask(__name__)          
app.logger.setLevel(logging.DEBUG)
  
  
@app.route("/test", methods=['POST'])
def test_method():         
    # print(request.json)      
    if not request.json or 'image' not in request.json: 
        abort(400)
             
    # get the base64 encoded string
    im_b64 = request.json['image']

    # convert it into bytes  
    img_bytes = base64.b64decode(im_b64.encode('utf-8'))

    # convert bytes data to PIL Image object
    img = Image.open(io.BytesIO(img_bytes))

    # PIL image object to numpy array
    img_arr = np.asarray(img)      
    print('img shape', img_arr.shape)

    # process your img_arr here    
    
    # access other keys of json
    # print(request.json['other_key'])

    result_dict = {'output': 'output_key'}
    return result_dict
  
  
def run_server_api():
    app.run(host='0.0.0.0', port=8080)
  
  
if __name__ == "__main__":     
    run_server_api()

Cannot find "Package Explorer" view in Eclipse

Not all view are listed directly in every perspective ... choose:

Window->Show View->Other...->Java->Package Explorer

LinkButton Send Value to Code Behind OnClick

Add a CommandName attribute, and optionally a CommandArgument attribute, to your LinkButton control. Then set the OnCommand attribute to the name of your Command event handler.

<asp:LinkButton ID="ENameLinkBtn" runat="server" CommandName="MyValueGoesHere" CommandArgument="OtherValueHere" 
          style="font-weight: 700; font-size: 8pt;" OnCommand="ENameLinkBtn_Command" ><%# Eval("EName") %></asp:LinkButton>

<asp:Label id="Label1" runat="server"/>

Then it will be available when in your handler:

protected void ENameLinkBtn_Command (object sender, CommandEventArgs e)
{
   Label1.Text = "You chose: " + e.CommandName + " Item " + e.CommandArgument;
}

More info on MSDN

Maximum Java heap size of a 32-bit JVM on a 64-bit OS

I have tried setting the heap size upto 2200M on 32bit Linux machine and JVM worked fine. The JVM didnt start when I set it to 2300M.

Auto-increment on partial primary key with Entity Framework Core

To anyone who came across this question who are using SQL Server Database and still having an exception thrown even after adding the following annotation on the int primary key

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

Please check your SQL, make sure your the primary key has 'IDENTITY(startValue, increment)' next to it,

CREATE TABLE [dbo].[User]
(
    [Id] INT IDENTITY(1,1) NOT NULL PRIMARY KEY
)

This will make the database increments the id every time a new row is added, with a starting value of 1 and increments of 1.

I accidentally overlooked that in my SQL which cost me an hour of my life, so hopefully this helps someone!!!

Execute curl command within a Python script

You could use urllib as @roippi said:

import urllib2
data = '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}'
url = 'http://localhost:8080/firewall/rules/0000000000000001'
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
for x in f:
    print(x)
f.close()

jQuery: If this HREF contains

Try this:

$("a").each(function() {
    if ($('[href$="?"]', this).length()) {
        alert("Contains questionmark");
    }
});

How to use matplotlib tight layout with Figure?

Just call fig.tight_layout() as you normally would. (pyplot is just a convenience wrapper. In most cases, you only use it to quickly generate figure and axes objects and then call their methods directly.)

There shouldn't be a difference between the QtAgg backend and the default backend (or if there is, it's a bug).

E.g.

import matplotlib.pyplot as plt

#-- In your case, you'd do something more like:
# from matplotlib.figure import Figure
# fig = Figure()
#-- ...but we want to use it interactive for a quick example, so 
#--    we'll do it this way
fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

plt.show()

Before Tight Layout

enter image description here

After Tight Layout

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

fig.tight_layout()

plt.show()

enter image description here

How to write some data to excel file(.xlsx)

You can use ClosedXML for this.

Store your table in a DataTable and you can export the table to excel by this simple snippet:

XLWorkbook workbook = new XLWorkbook();
DataTable table = GetYourTable();
workbook.Worksheets.Add(table );

You can read the documentation of ClosedXML to learn more. Hope this helps!

How to use ESLint with Jest

In your .eslintignore file add the following value:

**/__tests__/

This should ignore all instances of the __tests__ directory and their children.

T-SQL query to show table definition?

Since SQL 2012 you can run the following statement:

Exec sp_describe_first_result_set @tsql= N'Select * from <yourtable>'

If you enter a complex select statement (joins, subselects, etc), it will give you the definition of the result set. This is very handy, if you need to create a new table (or temp table) and you don't want to check every single field definition manually.

https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-describe-first-result-set-transact-sql

Swift how to sort array of custom objects by property value

Nearly everyone gives how directly, let me show the evolvement:

you can use the instance methods of Array:

// general form of closure
images.sortInPlace({ (image1: imageFile, image2: imageFile) -> Bool in return image1.fileID > image2.fileID })

// types of closure's parameters and return value can be inferred by Swift, so they are omitted along with the return arrow (->)
images.sortInPlace({ image1, image2 in return image1.fileID > image2.fileID })

// Single-expression closures can implicitly return the result of their single expression by omitting the "return" keyword
images.sortInPlace({ image1, image2 in image1.fileID > image2.fileID })

// closure's argument list along with "in" keyword can be omitted, $0, $1, $2, and so on are used to refer the closure's first, second, third arguments and so on
images.sortInPlace({ $0.fileID > $1.fileID })

// the simplification of the closure is the same
images = images.sort({ (image1: imageFile, image2: imageFile) -> Bool in return image1.fileID > image2.fileID })
images = images.sort({ image1, image2 in return image1.fileID > image2.fileID })
images = images.sort({ image1, image2 in image1.fileID > image2.fileID })
images = images.sort({ $0.fileID > $1.fileID })

For elaborate explanation about the working principle of sort, see The Sorted Function.

Get list of all input objects using JavaScript, without accessing a form object

querySelectorAll returns a NodeList which has its own forEach method:

document.querySelectorAll('input').forEach( input => {
  // ...
});

getElementsByTagName now returns an HTMLCollection instead of a NodeList. So you would first need to convert it to an array to have access to methods like map and forEach:

Array.from(document.getElementsByTagName('input')).forEach( input => {
  // ...
});

How can I get column names from a table in SQL Server?

--This is another variation used to document a large database for conversion (Edited to --remove static columns)

SELECT o.Name                   as Table_Name
     , c.Name                   as Field_Name
     , t.Name                   as Data_Type
     , t.length                 as Length_Size
     , t.prec                   as Precision_
FROM syscolumns c 
     INNER JOIN sysobjects o ON o.id = c.id
     LEFT JOIN  systypes t on t.xtype = c.xtype  
WHERE o.type = 'U' 
ORDER BY o.Name, c.Name

--In the left join, c.type is replaced by c.xtype to get varchar types

pandas dataframe convert column type to string or categorical

You need astype:

df['zipcode'] = df.zipcode.astype(str)
#df.zipcode = df.zipcode.astype(str)

For converting to categorical:

df['zipcode'] = df.zipcode.astype('category')
#df.zipcode = df.zipcode.astype('category')

Another solution is Categorical:

df['zipcode'] = pd.Categorical(df.zipcode)

Sample with data:

import pandas as pd

df = pd.DataFrame({'zipcode': {17384: 98125, 2680: 98107, 722: 98005, 18754: 98109, 14554: 98155}, 'bathrooms': {17384: 1.5, 2680: 0.75, 722: 3.25, 18754: 1.0, 14554: 2.5}, 'sqft_lot': {17384: 1650, 2680: 3700, 722: 51836, 18754: 2640, 14554: 9603}, 'bedrooms': {17384: 2, 2680: 2, 722: 4, 18754: 2, 14554: 4}, 'sqft_living': {17384: 1430, 2680: 1440, 722: 4670, 18754: 1130, 14554: 3180}, 'floors': {17384: 3.0, 2680: 1.0, 722: 2.0, 18754: 1.0, 14554: 2.0}})
print (df)
       bathrooms  bedrooms  floors  sqft_living  sqft_lot  zipcode
722         3.25         4     2.0         4670     51836    98005
2680        0.75         2     1.0         1440      3700    98107
14554       2.50         4     2.0         3180      9603    98155
17384       1.50         2     3.0         1430      1650    98125
18754       1.00         2     1.0         1130      2640    98109

print (df.dtypes)
bathrooms      float64
bedrooms         int64
floors         float64
sqft_living      int64
sqft_lot         int64
zipcode          int64
dtype: object

df['zipcode'] = df.zipcode.astype('category')

print (df)
       bathrooms  bedrooms  floors  sqft_living  sqft_lot zipcode
722         3.25         4     2.0         4670     51836   98005
2680        0.75         2     1.0         1440      3700   98107
14554       2.50         4     2.0         3180      9603   98155
17384       1.50         2     3.0         1430      1650   98125
18754       1.00         2     1.0         1130      2640   98109

print (df.dtypes)
bathrooms       float64
bedrooms          int64
floors          float64
sqft_living       int64
sqft_lot          int64
zipcode        category
dtype: object

What's sizeof(size_t) on 32-bit vs the various 64-bit data models?

size_t is 64 bit normally on 64 bit machine

How do I disable and re-enable a button in with javascript?

you can try with

document.getElementById('btn').disabled = !this.checked"

_x000D_
_x000D_
<input type="submit" name="btn"  id="btn" value="submit" disabled/>_x000D_
_x000D_
<input type="checkbox"  onchange="document.getElementById('btn').disabled = !this.checked"/>
_x000D_
_x000D_
_x000D_

How to set a cron job to run at a exact time?

My use case is that I'm on a metered account. Data transfer is limited on weekdays, Mon - Fri, from 6am - 6pm. I am using bandwidth limiting, but somehow, data still slips through, about 1GB per day!

I strongly suspected it's sickrage or sickbeard, doing a high amount of searches. My download machine is called "download." The following was my solution, using the above,for starting, and stopping the download VM, using KVM:

# Stop download Mon-Fri, 6am
0 6 * * 1,2,3,4,5 root          virsh shutdown download
# Start download Mon-Fri, 6pm
0 18 * * 1,2,3,4,5 root         virsh start download

I think this is correct, and hope it helps someone else too.

nvarchar(max) still being truncated

Print truncates the varchar(MAX) to 8000, nvarchar(MAX) to 4000 chars.

But;

PRINT CAST(@query AS NTEXT)

will print the whole query.

Good Patterns For VBA Error Handling

Professional Excel Development has a pretty good error handling scheme. If you're going to spend any time in VBA, it's probably worth getting the book. There are a number of areas where VBA is lacking and this book has good suggestions for managing those areas.

PED describes two error handling methods. The main one is a system where all entry point procedures are subprocedures and all other procedures are functions that return Booleans.

The entry point procedure use On Error statements to capture errors pretty much as designed. The non-entry point procedures return True if there were no errors and False if there were errors. Non-entry point procedures also use On Error.

Both types of procedures use a central error handling procedure to keep the error in state and to log the error.

Change fill color on vector asset in Android Studio

If the vectors are not showing individually set colors using fillColor then they may be being set to a default widget parameter.

Try adding app:itemIconTint="@color/lime" to activity_main.xml to set a default color type for the widget icons.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:itemIconTint="@color/lime"
        app:menu="@menu/activity_main_drawer" />

</android.support.v4.widget.DrawerLayout>

VectorDrawable @ developers.android

How to get current route

You can use in the .ts file

import { Route, Router, NavigationStart } from '@angular/router';

constructor(private router: Router) {}

this.router.events.subscribe(value => {
      if (value instanceof NavigationStart) {
        console.log(value) // your current route
      }
    });

How to stop mysqld

When mysql was installed with Homebrew, the following command did the trick for me:

brew services stop mysql

Get path to execution directory of Windows Forms application

This could help;

Path.GetDirectoryName(Application.ExecutablePath);

also here is the reference

GROUP BY and COUNT in PostgreSQL

WITH uniq AS (
        SELECT DISTINCT posts.id as post_id
        FROM posts
        JOIN votes ON votes.post_id = posts.id
        -- GROUP BY not needed anymore
        -- GROUP BY posts.id
        )
SELECT COUNT(*)
FROM uniq;

Wrapping long text without white space inside of a div

white-space: pre-wrap

is what worked for me for <span> and <div>.

How do you split a list into evenly sized chunks?

Use list comprehensions:

l = [1,2,3,4,5,6,7,8,9,10,11,12]
k = 5 #chunk size
print [tuple(l[x:y]) for (x, y) in [(x, x+k) for x in range(0, len(l), k)]]

Java List.add() UnsupportedOperationException

Many of the List implementation support limited support to add/remove, and Arrays.asList(membersArray) is one of that. You need to insert the record in java.util.ArrayList or use the below approach to convert into ArrayList.

With the minimal change in your code, you can do below to convert a list to ArrayList. The first solution is having a minimum change in your solution, but the second one is more optimized, I guess.

    String[] membersArray = request.getParameterValues('members');
    ArrayList<String> membersList = new ArrayList<>(Arrays.asList(membersArray));

OR

    String[] membersArray = request.getParameterValues('members');
    ArrayList<String> membersList = Stream.of(membersArray).collect(Collectors.toCollection(ArrayList::new));

Where does Oracle SQL Developer store connections?

I found mine in

C:\Users\<user>\AppData\Roaming\SQL Developer\system2.1.1.64.45\o.jdeveloper.db.connection.11.1.1.2.36.55.30\connections.xml

How many bits is a "word"?

"most convenient block of data" probably refers to the width (in bits) of the WORD, in correspondance to the system bus width, or whatever underlying "bandwidth" is available. On a 16 bit system, with WORD being defined as 16 bits wide, moving data around in chunks the size of a WORD will be the most efficient way. (On hardware or "system" level.)

With Java being more or less platform independant, it just defines a "WORD" as the next size from a "BYTE", meaning "full bandwidth". I guess any platform that's able to run Java will use 32 bits for a WORD.

:before and background-image... should it work?

 color: transparent; 

make the tricks for me

#videos-part:before{
    font-size: 35px;
    line-height: 33px;
    width: 16px;
    color: transparent;
    content: 'AS YOU LIKE';
    background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjwhRE9DVFlQRSBzdmcgIFBVQkxJQyAnLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4nICAnaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkJz48c3ZnIGVuYWJsZS1iYWNrZ3JvdW5kPSJuZXcgMCAwIDUwIDUwIiBoZWlnaHQ9IjUwcHgiIGlkPSJMYXllcl8xIiB2ZXJzaW9uPSIxLjEiIHZpZXdCb3g9IjAgMCA1MCA1MCIgd2lkdGg9IjUwcHgiIHhtbDpzcGFjZT0icHJlc2VydmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxwYXRoIGQ9Ik04LDE0TDQsNDloNDJsLTQtMzVIOHoiIGZpbGw9Im5vbmUiIHN0cm9rZT0iIzAwMDAwMCIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbWl0ZXJsaW1pdD0iMTAiIHN0cm9rZS13aWR0aD0iMiIvPjxyZWN0IGZpbGw9Im5vbmUiIGhlaWdodD0iNTAiIHdpZHRoPSI1MCIvPjxwYXRoIGQ9Ik0zNCwxOWMwLTEuMjQxLDAtNi43NTksMC04ICBjMC00Ljk3MS00LjAyOS05LTktOXMtOSw0LjAyOS05LDljMCwxLjI0MSwwLDYuNzU5LDAsOCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjMDAwMDAwIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1taXRlcmxpbWl0PSIxMCIgc3Ryb2tlLXdpZHRoPSIyIi8+PGNpcmNsZSBjeD0iMzQiIGN5PSIxOSIgcj0iMiIvPjxjaXJjbGUgY3g9IjE2IiBjeT0iMTkiIHI9IjIiLz48L3N2Zz4=');
    background-size: 25px;
    background-repeat: no-repeat;
    }

How to apply CSS page-break to print a table with lots of rows?

Here is an example:

Via css:

<style>
  .my-table {
    page-break-before: always;
    page-break-after: always;
  }
  .my-table tr {
    page-break-inside: avoid;
  }
</style>

or directly on the element:

<table style="page-break-before: always; page-break-after: always;">
  <tr style="page-break-inside: avoid;">
    ..
  </tr>
</table>

Adding elements to an xml file in C#

Id be inclined to create classes that match the structure and add an instance to a collection then serialise and deserialise the collection to load and save the document.

jQuery on window resize

jQuery has a resize event handler which you can attach to the window, .resize(). So, if you put $(window).resize(function(){/* YOUR CODE HERE */}) then your code will be run every time the window is resized.

So, what you want is to run the code after the first page load and whenever the window is resized. Therefore you should pull the code into its own function and run that function in both instances.

// This function positions the footer based on window size
function positionFooter(){
    var $containerHeight = $(window).height();
    if ($containerHeight <= 818) {
        $('.footer').css({
            position: 'static',
            bottom: 'auto',
            left: 'auto'
        });
    }
    else {
        $('.footer').css({
            position: 'absolute',
            bottom: '3px',
            left: '0px'
        });
    } 
}

$(document).ready(function () {
    positionFooter();//run when page first loads
});

$(window).resize(function () {
    positionFooter();//run on every window resize
});

See: Cross-browser window resize event - JavaScript / jQuery

Ignore mapping one property with Automapper

From Jimmy Bogard: CreateMap<Foo, Bar>().ForMember(x => x.Blarg, opt => opt.Ignore());

It's in one of the comments at his blog.

How to solve "Could not establish trust relationship for the SSL/TLS secure channel with authority"

Add this to your client code :

ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(
    delegate
    {
        return true;
    });

Run "mvn clean install" in Eclipse

If you want to open command prompt inside your eclipse, this can be a useful approach to link cmd with eclipse.

You can follow this link to get the steps in detail with screenshots. How to use cmd prompt inside Eclipse ?

I'm quoting the steps here:

Step 1: Setup a new External Configuration Tool

In the Eclipse tool go to Run -> External Tools -> External Tools Configurations option.

Step 2: Click New Launch Configuration option in Create, manage and run configuration screen

Step 3: New Configuration screen for configuring the command prompt

Step 4: Provide configuration details of the Command Prompt in the Main tab

Name: Give any name to your configuration (Here it is Command_Prompt)
Location: Location of the CMD.exe in your Windows
Working Directory: Any directory where you want to point the Command prompt

Step 5: Tick the check box Allocate console This will ensure the eclipse console is being used as the command prompt for any input or output.

Step 6: Click Run and you are there!! You will land up in the C: directory as a working directory

php convert datetime to UTC

I sometime use this method:

// It is not importnat what timezone your system is set to.
// Get the UTC offset in seconds:
$offset = date("Z");

// Then subtract if from your original timestamp:
$utc_time = date("Y-m-d H:i:s", strtotime($original_time." -".$offset." Seconds"));

Works all MOST of the time.

Are (non-void) self-closing tags valid in HTML5?

I would be very careful with self closing tags as this example demonstrates:

var a = '<span/><span/>';
var d = document.createElement('div');
d.innerHTML = a
console.log(d.innerHTML) // "<span><span></span></span>"

My gut feeling would have been <span></span><span></span> instead

UTL_FILE.FOPEN() procedure not accepting path for directory?

Since Oracle 9i there are two ways or declaring a directory for use with UTL_FILE.

The older way is to set the INIT.ORA parameter UTL_FILE_DIR. We have to restart the database for a change to take affect. The value can like any other PATH variable; it accepts wildcards. Using this approach means passing the directory path...

UTL_FILE.FOPEN('c:\temp', 'vineet.txt', 'W');

The alternative approach is to declare a directory object.

create or replace directory temp_dir as 'C:\temp'
/

grant read, write on directory temp_dir to vineet
/

Directory objects require the exact file path, and don't accept wildcards. In this approach we pass the directory object name...

UTL_FILE.FOPEN('TEMP_DIR', 'vineet.txt', 'W');

The UTL_FILE_DIR is deprecated because it is inherently insecure - all users have access to all the OS directories specified in the path, whereas read and write privileges can de granted discretely to individual users. Also, with Directory objects we can be add, remove or change directories without bouncing the database.

In either case, the oracle OS user must have read and/or write privileges on the OS directory. In case it isn't obvious, this means the directory must be visible from the database server. So we cannot use either approach to expose a directory on our local PC to a process running on a remote database server. Files must be uploaded to the database server, or a shared network drive.


If the oracle OS user does not have the appropriate privileges on the OS directory, or if the path specified in the database does not match to an actual path, the program will hurl this exception:

ORA-29283: invalid file operation
ORA-06512: at "SYS.UTL_FILE", line 536
ORA-29283: invalid file operation
ORA-06512: at line 7

The OERR text for this error is pretty clear:

29283 -  "invalid file operation"
*Cause:    An attempt was made to read from a file or directory that does
           not exist, or file or directory access was denied by the
           operating system.
*Action:   Verify file and directory access privileges on the file system,
           and if reading, verify that the file exists.

How I can get and use the header file <graphics.h> in my C++ program?

<graphics.h> is very old library. It's better to use something that is new

Here are some 2D libraries (platform independent) for C/C++

SDL

GTK+

Qt

Also there is a free very powerful 3D open source graphics library for C++

OGRE

jQuery: keyPress Backspace won't fire?

I came across this myself. I used .on so it looks a bit different but I did this:

 $('#element').on('keypress', function() {
   //code to be executed
 }).on('keydown', function(e) {
   if (e.keyCode==8)
     $('element').trigger('keypress');
 });

Adding my Work Around here. I needed to delete ssn typed by user so i did this in jQuery

  $(this).bind("keydown", function (event) {
        // Allow: backspace, delete
        if (event.keyCode == 46 || event.keyCode == 8) 
        {
            var tempField = $(this).attr('name');
            var hiddenID = tempField.substr(tempField.indexOf('_') + 1);
            $('#' + hiddenID).val('');
            $(this).val('')
            return;
        }  // Allow: tab, escape, and enter
        else if (event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
        // Allow: Ctrl+A
        (event.keyCode == 65 && event.ctrlKey === true) ||
        // Allow: home, end, left, right
        (event.keyCode >= 35 && event.keyCode <= 39)) {
            // let it happen, don't do anything
            return;
        }
        else 
        {
            // Ensure that it is a number and stop the keypress
            if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) &&       (event.keyCode < 96 || event.keyCode > 105)) 
            {
                event.preventDefault();
            }
        }
    });

iOS Detection of Screenshot?

Swift 4+

NotificationCenter.default.addObserver(forName: UIApplication.userDidTakeScreenshotNotification, object: nil, queue: OperationQueue.main) { notification in
           //you can do anything you want here. 
        }

by using this observer you can find out when user takes a screenshot, but you can not prevent him.

Nginx serves .php files as downloads, instead of executing them

If anything else doesn't help you. And maybe earlier you installed apache2 with info.php test file. Just clear App Data (cache,cookie) for localhost.

Saving a high resolution image in R

You can do the following. Add your ggplot code after the first line of code and end with dev.off().

tiff("test.tiff", units="in", width=5, height=5, res=300)
# insert ggplot code
dev.off()

res=300 specifies that you need a figure with a resolution of 300 dpi. The figure file named 'test.tiff' is saved in your working directory.

Change width and height in the code above depending on the desired output.

Note that this also works for other R plots including plot, image, and pheatmap.

Other file formats

In addition to TIFF, you can easily use other image file formats including JPEG, BMP, and PNG. Some of these formats require less memory for saving.

LPCSTR, LPCTSTR and LPTSTR

Adding to John and Tim's answer.

Unless you are coding for Win98, there are only two of the 6+ string types you should be using in your application

  • LPWSTR
  • LPCWSTR

The rest are meant to support ANSI platforms or dual compilations. Those are not as relevant today as they used to be.

How to remove entry from $PATH on mac

when you login, or start a bash shell, environment variables are loaded/configured according to .bashrc, or .bash_profile. Whatever export you are doing, it's valid only for current session. so export PATH=/Applications/SenchaSDKTools-2.0.0-beta3:$PATH this command is getting executed each time you are opening a shell, you can override it, but again that's for the current session only. edit the .bashrc file to suite your need. If it's saying permission denied, perhaps the file is write-protected, a link to some other file (many organisations keep a master .bashrc file and gives each user a link of it to their home dir, you can copy the file instead of link and the start adding content to it)

What's the difference between a temp table and table variable in SQL Server?

  1. Temp table: A Temp table is easy to create and back up data.

    Table variable: But the table variable involves the effort when we usually create the normal tables.

  2. Temp table: Temp table result can be used by multiple users.

    Table variable: But the table variable can be used by the current user only. 

  3. Temp table: Temp table will be stored in the tempdb. It will make network traffic. When we have large data in the temp table then it has to work across the database. A Performance issue will exist.

    Table variable: But a table variable will store in the physical memory for some of the data, then later when the size increases it will be moved to the tempdb.

  4. Temp table: Temp table can do all the DDL operations. It allows creating the indexes, dropping, altering, etc..,

    Table variable: Whereas table variable won't allow doing the DDL operations. But the table variable allows us to create the clustered index only.

  5. Temp table: Temp table can be used for the current session or global. So that a multiple user session can utilize the results in the table.

    Table variable: But the table variable can be used up to that program. (Stored procedure)

  6. Temp table: Temp variable cannot use the transactions. When we do the DML operations with the temp table then it can be rollback or commit the transactions.

    Table variable: But we cannot do it for table variable.

  7. Temp table: Functions cannot use the temp variable. More over we cannot do the DML operation in the functions .

    Table variable: But the function allows us to use the table variable. But using the table variable we can do that.

  8. Temp table: The stored procedure will do the recompilation (can't use same execution plan) when we use the temp variable for every sub sequent calls.

    Table variable: Whereas the table variable won't do like that.

how do you insert null values into sql server

If you're using SSMS (or old school Enterprise Manager) to edit the table directly, press CTRL+0 to add a null.

SQL Server: How to use UNION with two queries that BOTH have a WHERE clause?

select * from 
(
    select top 2 t1.ID, t1.ReceivedDate
    from Table t1
    where t1.Type = 'TYPE_1'
    order by t1.ReceivedDate de
) t1
union
select * from 
(
    select top 2 t2.ID
    from Table t2
    where t2.Type = 'TYPE_2'
    order by t2.ReceivedDate desc
) t2

or using CTE (SQL Server 2005+)

;with One as
(
    select top 2 t1.ID, t1.ReceivedDate
    from Table t1
    where t1.Type = 'TYPE_1'
    order by t1.ReceivedDate de
)
,Two as
(
    select top 2 t2.ID
    from Table t2
    where t2.Type = 'TYPE_2'
    order by t2.ReceivedDate desc
)
select * from One
union
select * from Two

Passing arguments forward to another javascript function

If you want to only pass certain arguments, you can do so like this:

Foo.bar(TheClass, 'theMethod', 'arg1', 'arg2')

Foo.js

bar (obj, method, ...args) {
  obj[method](...args)
}

obj and method are used by the bar() method, while the rest of args are passed to the actual call.

PL/SQL, how to escape single quote in a string?

Here's a blog post that should help with escaping ticks in strings.

Here's the simplest method from said post:

The most simple and most used way is to use a single quotation mark with two single >quotation marks in both sides.

SELECT 'test single quote''' from dual;

The output of the above statement would be:

test single quote'

Simply stating you require an additional single quote character to print a single quote >character. That is if you put two single quote characters Oracle will print one. The first >one acts like an escape character.

This is the simplest way to print single quotation marks in Oracle. But it will get >complex when you have to print a set of quotation marks instead of just one. In this >situation the following method works fine. But it requires some more typing labour.

Creating a procedure in mySql with parameters

(IN @brugernavn varchar(64)**)**,IN @password varchar(64))

The problem is the )

How to show PIL images on the screen?

You can display an image in your own window using Tkinter, w/o depending on image viewers installed in your system:

import Tkinter as tk
from PIL import Image, ImageTk  # Place this at the end (to avoid any conflicts/errors)

window = tk.Tk()
#window.geometry("500x500") # (optional)    
imagefile = {path_to_your_image_file}
img = ImageTk.PhotoImage(Image.open(imagefile))
lbl = tk.Label(window, image = img).pack()
window.mainloop()

For Python 3, replace import Tkinter as tk with import tkinter as tk.

How do I make a matrix from a list of vectors in R?

Not straightforward, but it works:

> t(sapply(a, unlist))
      [,1] [,2] [,3] [,4] [,5] [,6]
 [1,]    1    1    2    3    4    5
 [2,]    2    1    2    3    4    5
 [3,]    3    1    2    3    4    5
 [4,]    4    1    2    3    4    5
 [5,]    5    1    2    3    4    5
 [6,]    6    1    2    3    4    5
 [7,]    7    1    2    3    4    5
 [8,]    8    1    2    3    4    5
 [9,]    9    1    2    3    4    5
[10,]   10    1    2    3    4    5

Python: Importing urllib.quote

If you need to handle both Python 2.x and 3.x you can catch the exception and load the alternative.

try:
    from urllib import quote  # Python 2.X
except ImportError:
    from urllib.parse import quote  # Python 3+

You could also use the python compatibility wrapper six to handle this.

from six.moves.urllib.parse import quote

Difference between Fact table and Dimension table?

This is to answer the part:

I was trying to understand whether dimension tables can be fact table as well or not?

The short answer (INMO) is No.That is because the 2 types of tables are created for different reasons. However, from a database design perspective, a dimension table could have a parent table as the case with the fact table which always has a dimension table (or more) as a parent. Also, fact tables may be aggregated, whereas Dimension tables are not aggregated. Another reason is that fact tables are not supposed to be updated in place whereas Dimension tables could be updated in place in some cases.

More details:

Fact and dimension tables appear in a what is commonly known as a Star Schema. A primary purpose of star schema is to simplify a complex normalized set of tables and consolidate data (possibly from different systems) into one database structure that can be queried in a very efficient way.

On its simplest form, it contains a fact table (Example: StoreSales) and a one or more dimension tables. Each Dimension entry has 0,1 or more fact tables associated with it (Example of dimension tables: Geography, Item, Supplier, Customer, Time, etc.). It would be valid also for the dimension to have a parent, in which case the model is of type "Snow Flake". However, designers attempt to avoid this kind of design since it causes more joins that slow performance. In the example of StoreSales, The Geography dimension could be composed of the columns (GeoID, ContenentName, CountryName, StateProvName, CityName, StartDate, EndDate)

In a Snow Flakes model, you could have 2 normalized tables for Geo information, namely: Content Table, Country Table.

You can find plenty of examples on Star Schema. Also, check this out to see an alternative view on the star schema model Inmon vs. Kimball. Kimbal has a good forum you may also want to check out here: Kimball Forum.

Edit: To answer comment about examples for 4NF:

  • Example for a fact table violating 4NF:

Sales Fact (ID, BranchID, SalesPersonID, ItemID, Amount, TimeID)

  • Example for a fact table not violating 4NF:

AggregatedSales (BranchID, TotalAmount)

Here the relation is in 4NF

The last example is rather uncommon.

libaio.so.1: cannot open shared object file

It looks like a 32/64 bit mismatch. The ldd output shows that mainly libraries from /lib64 are chosen. That would indicate that you have installed a 64 bit version of the Oracle client and have created a 64 bit executable. But libaio.so is probably a 32 bit library and cannot be used for your application.

So you either need a 64 bit version of libaio or you create a 32 bit version of your application.

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

How do I resolve `The following packages have unmet dependencies`

Installing nodejs will install npm ... so just remove nodejs then reinstall it: $ sudo apt-get remove nodejs

$ sudo apt-get --purge remove nodejs node npm
$ sudo apt-get clean
$ sudo apt-get autoclean
$ sudo apt-get -f install
$ sudo apt-get autoremove

How to sort a file in-place

To sort file in place, try:

echo "$(sort your_file)" > your_file

As explained in other answers, you cannot directly redirect the output back to the input file. But you can evaluate the sort command first and then redirect it back to the original file. In this way you can implement in-place sort.

Similarly, you can also apply this trick to other command like paste to implement row-wise appending.

Count occurrences of a char in a string using Bash

I Would suggest the following:

var="any given string"
N=${#var}
G=${var//g/}
G=${#G}
(( G = N - G ))
echo "$G"

No call to any other program

Difference between JPanel, JFrame, JComponent, and JApplet

JFrame and JApplet are top level containers. If you wish to create a desktop application, you will use JFrame and if you plan to host your application in browser you will use JApplet.

JComponent is an abstract class for all Swing components and you can use it as the base class for your new component. JPanel is a simple usable component you can use for almost anything.

Since this is for a fun project, the simplest way for you is to work with JPanel and then host it inside JFrame or JApplet. Netbeans has a visual designer for Swing with simple examples.

How can I use a JavaScript variable as a PHP variable?

You can do what you want, but not like that. What you need to do is make an AJAX request from JavaScript back to the server where a separate PHP script can do the database operation.

Changing the image source using jQuery

You should add id attribute to your image tag, like this:

<div id="d1">
   <div class="c1">
            <a href="#"><img id="img1" src="img1_on.gif"></a>
            <a href="#"><img id="img2" src="img2_on.gif"></a>
   </div>
</div>

then you can use this code to change the source of images:

 $(document).ready(function () {
        $("#img1").attr({ "src": "logo-ex-7.png" });
        $("#img2").attr({ "src": "logo-ex-8.png" });
    });

jQuery remove options from select

It works on either option tag or text field:

$("#idname option[value='option1']").remove();

How to get a json string from url?

AFAIK JSON.Net does not provide functionality for reading from a URL. So you need to do this in two steps:

using (var webClient = new System.Net.WebClient()) {
    var json = webClient.DownloadString(URL);
    // Now parse with JSON.Net
}

A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations

declare @cur cursor
declare @idx int       
declare @Approval_No varchar(50) 

declare @ReqNo varchar(100)
declare @M_Id  varchar(100)
declare @Mail_ID varchar(100)
declare @temp  table
(
val varchar(100)
)
declare @temp2  table
(
appno varchar(100),
mailid varchar(100),
userod varchar(100)
)


    declare @slice varchar(8000)       
    declare @String varchar(100)
    --set @String = '1200096,1200095,1200094,1200093,1200092,1200092'
set @String = '20131'


    select @idx = 1       
        if len(@String)<1 or @String is null  return       

    while @idx!= 0       
    begin       
        set @idx = charindex(',',@String)       
        if @idx!=0       
            set @slice = left(@String,@idx - 1)       
        else       
            set @slice = @String

            --select @slice       
            insert into @temp values(@slice)
        set @String = right(@String,len(@String) - @idx)       
        if len(@String) = 0 break


    end
    -- select distinct(val) from @temp


SET @cur = CURSOR FOR select distinct(val) from @temp


--open cursor    
OPEN @cur    
--fetchng id into variable    
FETCH NEXT    
    FROM @cur into @Approval_No 

      --
    --loop still the end    
     while @@FETCH_STATUS = 0  
    BEGIN   


select distinct(Approval_Sr_No) as asd, @ReqNo=Approval_Sr_No,@M_Id=AM_ID,@Mail_ID=Mail_ID from WFMS_PRAO,WFMS_USERMASTER where  WFMS_PRAO.AM_ID=WFMS_USERMASTER.User_ID
and Approval_Sr_No=@Approval_No

   insert into @temp2 values(@ReqNo,@M_Id,@Mail_ID)  

FETCH NEXT    
      FROM @cur into @Approval_No    
 end  
    --close cursor    
    CLOSE @cur    

select * from @tem

document.body.appendChild(i)

You can appendChild to document.body but not if the document hasn't been loaded. So you should put everything in:

window.onload=function(){
    //your code
}

This works or you can make appendChild to be dependent on something else like another event for eg.

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_doc_body_append

As a matter of fact you can try changing the innerHTML of the document.body it works...!

Can you use if/else conditions in CSS?

Not in the traditional sense, but you can use classes for this, if you have access to the HTML. Consider this:

<p class="normal">Text</p>

<p class="active">Text</p>

and in your CSS file:

p.normal {
  background-position : 150px 8px;
}
p.active {
  background-position : 4px 8px;
}

That's the CSS way to do it.


Then there are CSS preprocessors like Sass. You can use conditionals there, which'd look like this:

$type: monster;
p {
  @if $type == ocean {
    color: blue;
  } @else if $type == matador {
    color: red;
  } @else if $type == monster {
    color: green;
  } @else {
    color: black;
  }
}

Disadvantages are, that you're bound to pre-process your stylesheets, and that the condition is evaluated at compile time, not run time.


A newer feature of CSS proper are custom properties (a.k.a. CSS variables). They are evaluated at run time (in browsers supporting them).

With them you could do something along the line:

:root {
  --main-bg-color: brown;
}

.one {
  background-color: var(--main-bg-color);
}

.two {
  background-color: black;
}

Finally, you can preprocess your stylesheet with your favourite server-side language. If you're using PHP, serve a style.css.php file, that looks something like this:

p {
  background-position: <?php echo (@$_GET['foo'] == 'bar')? "150" : "4"; ?>px 8px;
}

In this case, you will however have a performance impact, since caching such a stylesheet will be difficult.

What are these attributes: `aria-labelledby` and `aria-hidden`

aria-hidden="true" will hide decorative items like glyphicon icons from screen readers, which doesn't have meaningful pronunciation so as not to cause confusions. It's a nice thing do as matter of good practice.

"The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine" Error in importing process of xlsx to a sql server

I had no luck until I installed the 2010 version link here: https://www.microsoft.com/en-us/download/details.aspx?id=13255

I tried installing the 32 bit version, it still errored, so I uninstalled it and installed the 64 bit version and it started working.

Pass a JavaScript function as parameter

To pass the function as parameter, simply remove the brackets!

function ToBeCalled(){
  alert("I was called");
}

function iNeedParameter( paramFunc) {
   //it is a good idea to check if the parameter is actually not null
   //and that it is a function
   if (paramFunc && (typeof paramFunc == "function")) {
      paramFunc();   
   }
}

//this calls iNeedParameter and sends the other function to it
iNeedParameter(ToBeCalled); 

The idea behind this is that a function is quite similar to a variable. Instead of writing

function ToBeCalled() { /* something */ }

you might as well write

var ToBeCalledVariable = function () { /* something */ }

There are minor differences between the two, but anyway - both of them are valid ways to define a function. Now, if you define a function and explicitly assign it to a variable, it seems quite logical, that you can pass it as parameter to another function, and you don't need brackets:

anotherFunction(ToBeCalledVariable);

Pass by Reference / Value in C++

As I parse it, those words are wrong. It should read "If the function modifies that value, the modifications appear also within the scope of the calling function when passing by reference, but not when passing by value."

How to stick <footer> element at the bottom of the page (HTML5 and CSS3)?

Here is an example using css3:

CSS:

html, body {
    height: 100%;
    margin: 0;
}
#wrap {
    padding: 10px;
    min-height: -webkit-calc(100% - 100px);     /* Chrome */
    min-height: -moz-calc(100% - 100px);     /* Firefox */
    min-height: calc(100% - 100px);     /* native */
}
.footer {
    position: relative;
    clear:both;
}

HTML:

<div id="wrap">
    body content....
</div>
<footer class="footer">
    footer content....
</footer>

jsfiddle

Update
As @Martin pointed, the ´position: relative´ is not mandatory on the .footer element, the same for clear:both. These properties are only there as an example. So, the minimum css necessary to stick the footer on the bottom should be:

html, body {
    height: 100%;
    margin: 0;
}
#wrap {
    min-height: -webkit-calc(100% - 100px);     /* Chrome */
    min-height: -moz-calc(100% - 100px);     /* Firefox */
    min-height: calc(100% - 100px);     /* native */
}

Also, there is an excellent article at css-tricks showing different ways to do this: https://css-tricks.com/couple-takes-sticky-footer/

Moment JS start and end of given month

When you use .endOf() you are mutating the object it's called on, so startDate becomes Sep 30

You should use .clone() to make a copy of it instead of changing it

var startDate = moment(year + '-' + month + '-' + 01 + ' 00:00:00');
            var endDate = startDate.clone().endOf('month');
            console.log(startDate.toDate());
            console.log(endDate.toDate());

Mon Sep 01 2014 00:00:00 GMT+0700 (ICT) 
Tue Sep 30 2014 23:59:59 GMT+0700 (ICT) 

Clicking a checkbox with ng-click does not update the model

The order in which ng-click and ng-model will be executed is ambiguous (since neither explicitly set their priority). The most stable solution to this would be to avoid using them on the same element.

Also, you probably do not want the behavior that the examples show; you want the checkbox to respond to clicks on the complete label text, not only the checkbox. Hence, the cleanest solution would be to wrap the input (with ng-model) inside a label (with ng-click):

<label ng-click="onCompleteTodo(todo)">
  <input type='checkbox' ng-model="todo.done">
  {{todo.text}}
</label>

Working example: http://jsfiddle.net/b3NLH/1/

What does the "@" symbol do in Powershell?

PowerShell will actually treat any comma-separated list as an array:

"server1","server2"

So the @ is optional in those cases. However, for associative arrays, the @ is required:

@{"Key"="Value";"Key2"="Value2"}

Officially, @ is the "array operator." You can read more about it in the documentation that installed along with PowerShell, or in a book like "Windows PowerShell: TFM," which I co-authored.

How to access accelerometer/gyroscope data from Javascript?

Usefull fallback here: https://developer.mozilla.org/en-US/docs/Web/Events/MozOrientation

function orientationhandler(evt){


  // For FF3.6+
  if (!evt.gamma && !evt.beta) {
    evt.gamma = -(evt.x * (180 / Math.PI));
    evt.beta = -(evt.y * (180 / Math.PI));
  }

  // use evt.gamma, evt.beta, and evt.alpha 
  // according to dev.w3.org/geo/api/spec-source-orientation


}

window.addEventListener('deviceorientation',  orientationhandler, false);
window.addEventListener('MozOrientation',     orientationhandler, false);

How to convert seconds to time format?

just one small additional example

requested time in miliseconds

    // ms2time( (microtime(true) - ( time() - rand(0,1000000) ) ) );
    // return array
    function ms2time($ms){
        $return = array();
        // ms
        $return['ms'] = (int) number_format( ($ms - (int) $ms), 2, '', '');
        $seconds = (int) $ms;
        unset($ms);

        if ($seconds%60 > 0){
            $return['s'] = $seconds%60;
        } else {
            $return['s'] = 0;
        }

        if ( ($minutes = intval($seconds/60))){
            $return['m'] = $minutes;
        }

        if (isset($return['m'])){
            $return['h'] = intval($return['m'] / 60);
            $return['m']  = $return['m'] % 60; 
        }


        if (isset($return['h'])){
            $return['d'] = intval($return['h'] / 24);
            $return['h']  = $return['h'] % 24; 
        }

        if (isset($return['d']))
            $return['mo'] = intval($return['d'] / 30);

        foreach($return as $k=>$v){
            if ($v == 0)
                unset($return[$k]);
        }

        return $return;
    }

    // ms2time2string( (microtime(true) - ( time() - rand(0,1000000) ) ) );
    // return array     
    function ms2time2string($ms){
        $array = array(
            'ms' => 'ms',
            's'  => 'seconds',
            'm'  => 'minutes',
            'h'  => 'hours',
            'd'  => 'days',
            'mo' => 'month',
        );


        if ( ( $return = ms2time($ms) )  && count($ms) > 0){

            foreach($return as $key=>$data){
                $return[$key] = $data .' '.$array[$key];
            }

        }
        return implode(" ", array_reverse($return));
    }

How to get file_get_contents() to work with HTTPS?

In my case, the issue was due to WAMP using a different php.ini for CLI than Apache, so your settings made through the WAMP menu don't apply to CLI. Just modify the CLI php.ini and it works.

bootstrap 4 responsive utilities visible / hidden xs sm lg not working

Screen Size Class

-

  1. Hidden on all .d-none

  2. Hidden only on xs .d-none .d-sm-block

  3. Hidden only on sm .d-sm-none .d-md-block

  4. Hidden only on md .d-md-none .d-lg-block

  5. Hidden only on lg .d-lg-none .d-xl-block

  6. Hidden only on xl .d-xl-none

  7. Visible on all .d-block

  8. Visible only on xs .d-block .d-sm-none

  9. Visible only on sm .d-none .d-sm-block .d-md-none

  10. Visible only on md .d-none .d-md-block .d-lg-none

  11. Visible only on lg .d-none .d-lg-block .d-xl-none

  12. Visible only on xl .d-none .d-xl-block

Refer this link http://getbootstrap.com/docs/4.0/utilities/display/#hiding-elements

4.5 link: https://getbootstrap.com/docs/4.5/utilities/display/#hiding-elements

Display Image On Text Link Hover CSS Only

I did something like that:

HTML:

<p class='parent'>text text text</p>
<img class='child' src='idk.png'>

CSS:

.child {
    visibility: hidden;
}

.parent:hover .child {
    visibility: visible;
}

jQuery Ajax File Upload

Using FormData is the way to go as indicated by many answers. here is a bit of code that works great for this purpose. I also agree with the comment of nesting ajax blocks to complete complex circumstances. By including e.PreventDefault(); in my experience makes the code more cross browser compatible.

    $('#UploadB1').click(function(e){        
    e.preventDefault();

    if (!fileupload.valid()) {
        return false;            
    }

    var myformData = new FormData();        
    myformData.append('file', $('#uploadFile')[0].files[0]);

    $("#UpdateMessage5").html("Uploading file ....");
    $("#UpdateMessage5").css("background","url(../include/images/loaderIcon.gif) no-repeat right");

    myformData.append('mode', 'fileUpload');
    myformData.append('myid', $('#myid').val());
    myformData.append('type', $('#fileType').val());
    //formData.append('myfile', file, file.name); 

    $.ajax({
        url: 'include/fetch.php',
        method: 'post',
        processData: false,
        contentType: false,
        cache: false,
        data: myformData,
        enctype: 'multipart/form-data',
        success: function(response){
            $("#UpdateMessage5").html(response); //.delay(2000).hide(1); 
            $("#UpdateMessage5").css("background","");

            console.log("file successfully submitted");
        },error: function(){
            console.log("not okay");
        }
    });
});

How do I compare two Integers?

if (x.equals(y))

This looks like an expensive operation. Are there any hash codes calculated this way?

It is not an expensive operation and no hash codes are calculated. Java does not magically calculate hash codes, equals(...) is just a method call, not different from any other method call.

The JVM will most likely even optimize the method call away (inlining the comparison that takes place inside the method), so this call is not much more expensive than using == on two primitive int values.

Note: Don't prematurely apply micro-optimizations; your assumptions like "this must be slow" are most likely wrong or don't matter, because the code isn't a performance bottleneck.

Fastest way to determine if an integer's square root is an integer

If you do a binary chop to try to find the "right" square root, you can fairly easily detect if the value you've got is close enough to tell:

(n+1)^2 = n^2 + 2n + 1
(n-1)^2 = n^2 - 2n + 1

So having calculated n^2, the options are:

  • n^2 = target: done, return true
  • n^2 + 2n + 1 > target > n^2 : you're close, but it's not perfect: return false
  • n^2 - 2n + 1 < target < n^2 : ditto
  • target < n^2 - 2n + 1 : binary chop on a lower n
  • target > n^2 + 2n + 1 : binary chop on a higher n

(Sorry, this uses n as your current guess, and target for the parameter. Apologise for the confusion!)

I don't know whether this will be faster or not, but it's worth a try.

EDIT: The binary chop doesn't have to take in the whole range of integers, either (2^x)^2 = 2^(2x), so once you've found the top set bit in your target (which can be done with a bit-twiddling trick; I forget exactly how) you can quickly get a range of potential answers. Mind you, a naive binary chop is still only going to take up to 31 or 32 iterations.

How do I navigate to a parent route from a child route?

constructor(private router: Router) {}

navigateOnParent() {
  this.router.navigate(['../some-path-on-parent']);
}

The router supports

  • absolute paths /xxx - started on the router of the root component
  • relative paths xxx - started on the router of the current component
  • relative paths ../xxx - started on the parent router of the current component

Are iframes considered 'bad practice'?

I have seen IFRAMEs applied very successfully as an easy way to make dynamic context menus, but the target audience of that web-app was only Internet Explorer users.

I would say that it all depends on your requirements. If you wish to make sure your page works equally well on every browser, avoid IFRAMEs. If you are targeting a narrow and well-known audience (eg. on the local Intranet) and you see a benefit in using IFRAMEs then I would say it's OK to do so.

Difference between chr(13) and chr(10)

Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


Historically, Line Feed would move down a line but not return to column 1:

This  
    is  
        a  
            test.

Similarly Carriage Return would return to column 1 but not move down a line:

This  
is  
a  
test.

Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

Floating point exception( core dump

Floating Point Exception happens because of an unexpected infinity or NaN. You can track that using gdb, which allows you to see what is going on inside your C program while it runs. For more details: https://www.cs.swarthmore.edu/~newhall/unixhelp/howto_gdb.php

In a nutshell, these commands might be useful...

gcc -g myprog.c

gdb a.out

gdb core a.out

ddd a.out

See full command of running/stopped container in Docker

Use:

docker inspect -f "{{.Name}} {{.Config.Cmd}}" $(docker ps -a -q)

... it does a "docker inspect" for all containers.

What is the Gradle artifact dependency graph command?

If you want to see dependencies on project and all subprojects use in your top-level build.gradle:

subprojects {
    task listAllDependencies(type: DependencyReportTask) {}
}

Then call gradle:

gradle listAllDependencies

how to check the version of jar file?

It can be checked with a command java -jar jarname

Changing capitalization of filenames in Git

To bulk git mv files to lowercase on macOS:

for f in *; do git mv "$f" "`echo $f | tr "[:upper:]" "[:lower:]"`"; done

It will lowercase all files in a folder.

Express.js: how to get remote client address

var ip = req.connection.remoteAddress;

ip = ip.split(':')[3];

JNZ & CMP Assembly Instructions

At first it seems as if JNZ means jump if not Zero (0), as in jump if zero flag is 1/set.

But in reality it means Jump (if) not Zero (is set).

If 0 = not set and 1 = set then just remember:
JNZ Jumps if the zero flag is not set (0)

React Native - Image Require Module using Dynamic Names

I know this is old but I'm going to add this here as I've found this question, whilst searching for a solution. The docs allow for a uri: 'Network Image'

https://facebook.github.io/react-native/docs/images#network-images

For me I got images working dynamically with this

<Image source={{uri: image}} />

Is Django for the frontend or backend?

(a) Django is a framework, not a language

(b) I'm not sure what you're missing - there is no reason why you can't have business logic in a web application. In Django, you would normally expect presentation logic to be separated from business logic. Just because it is hosted in the same application server, it doesn't follow that the two layers are entangled.

(c) Django does provide templating, but it doesn't provide rich libraries for generating client-side content.

Generate a random letter in Python

You can use this to get one or more random letter(s)

import random
import string
random.seed(10)
letters = string.ascii_lowercase
rand_letters = random.choices(letters,k=5) # where k is the number of required rand_letters

print(rand_letters)

['o', 'l', 'p', 'f', 'v']

How to print variables without spaces between values

To build off what Martjin was saying. I'd use string interpolation/formatting.

In Python 2.x which seems to be what you're using due to the lack of parenthesis around the print function you do:

print 'Value is "%d"' % value

In Python 3.x you'd use the format method instead, so you're code would look like this.

message = 'Value is "{}"'
print(message.format(value))

SQL Server Express 2008 Install Side-by-side w/ SQL 2005 Express Fails

I also had to remove the SMSS before it would get past that step.

How to prevent favicon.ico requests?

I believe I've seen this (I haven't tested it or used it personally though):

<link rel="shortcut icon" href="#" />

Anyone had similar experience?

EDIT:

I just tested the above snippet and on a forced full refresh, no favicon requests were seen in Fiddler. I tested against IE8 (Compat mode as IE7 standards) and FF 3.6.

Copying a local file from Windows to a remote server using scp

Drive letters can be used in the target like

scp some_file user@host:/c/temp

where c is the drive letter. It's treated like a directory.

Maybe this works on the source, too.

Installing Homebrew on OS X

If you still get error after running,

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Then try to download and install command line tool from https://developer.apple.com/download/more/ for your particular Mac os and Xcode version.

Then try to run,

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

and then

brew install node

Android studio: emulator is running but not showing up in Run App "choose a running device"

in your device you want to run app on Go to settings About device >> Build number triple clicks or more and back to settings you will found "Developer options" appear go to and click on "USB debugging" Done

How do I POST a x-www-form-urlencoded request using Fetch?

Even simpler:

body: new URLSearchParams({
      'userName': '[email protected]',
      'password': 'Password!',
      'grant_type': 'password'
    }),

Docs: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch

Row names & column names in R

I think that using colnames and rownames makes the most sense; here's why.

Using names has several disadvantages. You have to remember that it means "column names", and it only works with data frame, so you'll need to call colnames whenever you use matrices. By calling colnames, you only have to remember one function. Finally, if you look at the code for colnames, you will see that it calls names in the case of a data frame anyway, so the output is identical.

rownames and row.names return the same values for data frame and matrices; the only difference that I have spotted is that where there aren't any names, rownames will print "NULL" (as does colnames), but row.names returns it invisibly. Since there isn't much to choose between the two functions, rownames wins on the grounds of aesthetics, since it pairs more prettily withcolnames. (Also, for the lazy programmer, you save a character of typing.)

How does cellForRowAtIndexPath work?

I'll try and break it down (example from documention)

/* 
 *   The cellForRowAtIndexPath takes for argument the tableView (so if the same object
 *   is delegate for several tableViews it can identify which one is asking for a cell),
 *   and an indexPath which determines which row and section the cell is returned for. 
 */ 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    /*
     *   This is an important bit, it asks the table view if it has any available cells
     *   already created which it is not using (if they are offScreen), so that it can
     *   reuse them (saving the time of alloc/init/load from xib a new cell ).
     *   The identifier is there to differentiate between different types of cells
     *   (you can display different types of cells in the same table view)
     */

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];

    /*
     *   If the cell is nil it means no cell was available for reuse and that we should
     *   create a new one.
     */
    if (cell == nil) {

        /* 
         *   Actually create a new cell (with an identifier so that it can be dequeued). 
         */

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"] autorelease];

        cell.selectionStyle = UITableViewCellSelectionStyleNone;

    }

    /*
     *   Now that we have a cell we can configure it to display the data corresponding to
     *   this row/section
     */

    NSDictionary *item = (NSDictionary *)[self.content objectAtIndex:indexPath.row];
    cell.textLabel.text = [item objectForKey:@"mainTitleKey"];
    cell.detailTextLabel.text = [item objectForKey:@"secondaryTitleKey"];
    NSString *path = [[NSBundle mainBundle] pathForResource:[item objectForKey:@"imageKey"] ofType:@"png"];
    UIImage *theImage = [UIImage imageWithContentsOfFile:path];
    cell.imageView.image = theImage;

    /* Now that the cell is configured we return it to the table view so that it can display it */

    return cell;

}

This is a DataSource method so it will be called on whichever object has declared itself as the DataSource of the UITableView. It is called when the table view actually needs to display the cell onscreen, based on the number of rows and sections (which you specify in other DataSource methods).

Reading Excel files from C#

You can try using this open source solution that makes dealing with Excel a lot more cleaner.

http://excelwrapperdotnet.codeplex.com/

Checking if a variable is not nil and not zero in ruby

unless [nil, 0].include?(discount) 
  # ...
end

Using Panel or PlaceHolder

I weird bug* in visual studio 2010, if you put controls inside a Placeholder it does not render them in design view mode.

This is especially true for Hidenfields and Empty labels.

I would love to use placeholders instead of panels but I hate the fact I cant put other controls inside placeholders at design time in the GUI.

What are DDL and DML?

SQL command can be divided into three subgroups, DDL, DML and DCL

The following is adapted from here MySQL What is DDL, DML and DCL?:

DDL

DDL is short name of Data Definition Language, which deals with database schemas and descriptions, of how the data should reside in the database.

  • CREATE – to create database and its objects like (table, index, views, store procedure, function and triggers).
  • ALTER – alters the structure of the existing database.
  • DROP – delete objects from the database.
  • TRUNCATE – remove all records from a table; also, all spaces allocated for the records are removed.
  • COMMENT – add comments to the data dictionary.
  • RENAME – rename an object.

DML

DML is short name of Data Manipulation Language which deals with data manipulation, and includes most common SQL statements such SELECT, INSERT, UPDATE, DELETE etc, and it is used to store, modify, retrieve, delete and update data in database.

  • SELECT – retrieve data from one or more tables.
  • INSERT – insert data into a table.
  • UPDATE – updates existing data within a table.
  • DELETE – delete all records from a table.
  • MERGE – UPSERT operation (insert or update)
  • CALL – call a PL/SQL or Java subprogram.
  • EXPLAIN PLAN – interpretation of the data access path.
  • LOCK TABLE – concurrency control.

DCL

DCL is short name of Data Control Language which includes commands such as GRANT, and mostly concerned with rights, permissions and other controls of the database system.

  • GRANT – allow users access privileges to database.
  • REVOKE – withdraw users access privileges given by using the GRANT command.

TCL

TCL is short name of Transaction Control Language which deals with transaction within a database.

  • COMMIT – commits a transaction.
  • ROLLBACK – rollback a transaction in case of any error occurs.
  • SAVEPOINT – a point inside a transaction that allows rollback state to what it was at the time of the savepoint.
  • SET TRANSACTION – specify characteristics for the transaction.

Hive External Table Skip First Row

I also struggled with this and found no way to tell hive to skip first row, like there is e.g. in Greenplum. So finally I had to remove it from the files. e.g. "cat File.csv | grep -v RecordId > File_no_header.csv"

Read data from a text file using Java

Simple code for reading file in JAVA:

import java.io.*;

class ReadData
{
    public static void main(String args[])
    {
        FileReader fr = new FileReader(new File("<put your file path here>"));
        while(true)
        {
            int n=fr.read();
            if(n>-1)
            {
                char ch=(char)fr.read();
                System.out.print(ch);
            }
        }
    }
}

How to convert int to QString?

Just for completeness, you can use the standard library and do QString qstr = QString::fromStdString(std::to_string(42));

MySQL Orderby a number, Nulls last

You can swap out instances of NULL with a different value to sort them first (like 0 or -1) or last (a large number or a letter)...

SELECT field1, IF(field2 IS NULL, 9999, field2) as ordered_field2
  FROM tablename
 WHERE visible = 1
 ORDER BY ordered_field2 ASC, id DESC

Alternative to iFrames with HTML5

You can use an XMLHttpRequest to load a page into a div (or any other element of your page really). An exemple function would be:

function loadPage(){
if (window.XMLHttpRequest){
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
}else{
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
        document.getElementById("ID OF ELEMENT YOU WANT TO LOAD PAGE IN").innerHTML=xmlhttp.responseText;
    }
}

xmlhttp.open("POST","WEBPAGE YOU WANT TO LOAD",true);
xmlhttp.send();
}

If your sever is capable, you could also use PHP to do this, but since you're asking for an HTML5 method, this should be all you need.

Merge PDF files

Is it possible, using Python, to merge seperate PDF files?

Yes.

The following example merges all files in one folder to a single new PDF file:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from argparse import ArgumentParser
from glob import glob
from pyPdf import PdfFileReader, PdfFileWriter
import os

def merge(path, output_filename):
    output = PdfFileWriter()

    for pdffile in glob(path + os.sep + '*.pdf'):
        if pdffile == output_filename:
            continue
        print("Parse '%s'" % pdffile)
        document = PdfFileReader(open(pdffile, 'rb'))
        for i in range(document.getNumPages()):
            output.addPage(document.getPage(i))

    print("Start writing '%s'" % output_filename)
    with open(output_filename, "wb") as f:
        output.write(f)

if __name__ == "__main__":
    parser = ArgumentParser()

    # Add more options if you like
    parser.add_argument("-o", "--output",
                        dest="output_filename",
                        default="merged.pdf",
                        help="write merged PDF to FILE",
                        metavar="FILE")
    parser.add_argument("-p", "--path",
                        dest="path",
                        default=".",
                        help="path of source PDF files")

    args = parser.parse_args()
    merge(args.path, args.output_filename)