Programs & Examples On #Acceleration

ambiguous tag: avoid

How to tell if tensorflow is using gpu acceleration from inside python shell?

Tensorflow 2.1

A simple calculation that can be verified with nvidia-smi for memory usage on the GPU.

import tensorflow as tf 

c1 = []
n = 10

def matpow(M, n):
    if n < 1: #Abstract cases where n < 1
        return M
        return tf.matmul(M, matpow(M, n-1))

with tf.device('/gpu:0'):
    a = tf.Variable(tf.random.uniform(shape=(10000, 10000)), name="a")
    b = tf.Variable(tf.random.uniform(shape=(10000, 10000)), name="b")
    c1.append(matpow(a, n))
    c1.append(matpow(b, n))

Emulator: ERROR: x86 emulation currently requires hardware acceleration

I already had HAXM installed, but it was an older version. Then I updated from SDK manager, then emulator worked!

HAX kernel module is not installed

Since most modern CPUs support virtualization natively, the reason you received such message can be because virtualization is turned off on your machine. For example, that was the case on my HP laptop - the factory setting for hardware virtualization was "Disabled". So, go to your machine's BIOS and enable virtualization.

Intel X86 emulator accelerator (HAXM installer) VT/NX not enabled

For IntelHAXM to install you have to activate Intel Virtual Technology.

To activate it, you have to restart your PC and go to BIOS. There is an option called Intel Virtual Technology that you have to enable to activate it.

After enabling it, reinstall IntelHAXM. That should solve the problem.

How can I run Android emulator for Intel x86 Atom without hardware acceleration on Windows 8 for API 21 and 19?

Same issue as in Error in launching AVD:

1) Install the Intel x86 Emulator Accelerator (HAXM installer) from the Android SDK Manager;

enter image description here

2) Run (for Windows):


or (for OSX):


3) Start the emulator.

Error in launching AVD with AMD processor

First of all you should have Virtualization Enabled and you can do it from BIOS setting.

After that go to Control Panel\Programs and Click on "Turn Windows features on or off" option.

You will now have a pop up window, spot "Windows Hypervisor Platform" and enable it by checking the check box.

enter image description here Restart your PC and now AVD should work without any issue.

Converting String to Int with Swift

Basic Idea, note that this only works in Swift 1.x (check out ParaSara's answer to see how it works in Swift 2.x):

    // toInt returns optional that's why we used a:Int?
    let a:Int? = firstText.text.toInt() // firstText is UITextField
    let b:Int? = secondText.text.toInt() // secondText is UITextField

    // check a and b before unwrapping using !
    if a && b {
        var ans = a! + b!
        answerLabel.text = "Answer is \(ans)" // answerLabel ie UILabel
    } else {
        answerLabel.text = "Input values are not numeric"

Update for Swift 4

let a:Int? = Int(firstText.text) // firstText is UITextField
let b:Int? = Int(secondText.text) // secondText is UITextField

How can I parse a local JSON file from assets folder into a ListView?

{ // json object node
    "formules": [ // json array formules
    { // json object 
      "formule": "Linear Motion", // string
      "url": "qp1"

What you are doing

  Context context = null; // context is null 
    try {
        String jsonLocation = AssetJSONFile("formules.json", context);

So change to

   try {
        String jsonLocation = AssetJSONFile("formules.json", CatList.this);

To parse

I believe you get the string from the assests folder.

String jsonLocation = AssetJSONFile("formules.json", context);
JSONObject jsonobject = new JSONObject(jsonLocation);
JSONArray jarray = (JSONArray) jsonobject.getJSONArray("formules");
for(int i=0;i<jarray.length();i++)
JSONObject jb =(JSONObject) jarray.get(i);
String formula = jb.getString("formule");
String url = jb.getString("url");
} catch (IOException e) {
} catch (JSONException e) {

Disable vertical sync for glxgears

I found a solution that works in the intel card and in the nvidia card using Bumblebee.

> export vblank_mode=0
optirun glxgears
export vblank_mode=1

How do you make an array of structs in C?

So to put it all together by using malloc():

int main(int argc, char** argv) {
    typedef struct{
        char* firstName;
        char* lastName;
        int day;
        int month;
        int year;


    int numStudents=3;
    int x;
    STUDENT* students = malloc(numStudents * sizeof *students);
    for (x = 0; x < numStudents; x++){

    for (x = 0; x < numStudents; x++)
        printf("first name: %s, surname: %s, day: %d, month: %d, year: %d\n",students[x].firstName,students[x].lastName,students[x].day,students[x].month,students[x].year);

    return (EXIT_SUCCESS);

"Bitmap too large to be uploaded into a texture"

Changing the image file to drawable-nodpi folder from drawable folder worked for me.

Python function overloading

The @overload decorator was added with type hints (PEP 484).

While this doesn't change the behaviour of Python, it does make it easier to understand what is going on, and for mypy to detect errors.

See: Type hints and PEP 484

Fastest method of screen capturing on Windows

With Windows 8, Microsoft introduced the Windows Desktop Duplication API. That is the officially recommended way of doing it. One nice feature it has for screencasting is that it detects window movement, so you can transmit block deltas when windows get moved around, instead of raw pixels. Also, it tells you which rectangles have changed, from one frame to the next.

The Microsoft example code is pretty complex, but the API is actually simple and easy to use. I've put together an example project which is much simpler than the official example:


Microsoft official example code:

How can I send a file document to the printer and have it print?

    public static void PrintFileToDefaultPrinter(string FilePath)
            var file = File.ReadAllBytes(FilePath);
            var printQueue = LocalPrintServer.GetDefaultPrintQueue();

            using (var job = printQueue.AddJob())
            using (var stream = job.JobStream)
                stream.Write(file, 0, file.Length);
        catch (Exception)


CSS height 100% percent not working

I believe you need to make sure that all the container div tags above the 100% height div also has 100% height set on them including the body tag and html.

Android Studio not showing modules in project structure

Update 19 March 2019

A new experience someone has just faced recently even though he/she did add a library module in app module, and include in Setting gradle as described below. One more thing worth trying is to make sure your app module and your library module have the same compileSdkVersion (which is in each its gradle)!

Please follow this link for more details.

Ref: Imported module in Android Studio can't find imported class

Original answer

Sometimes you use import module function, then the module does appear in Project mode but not in Android mode

enter image description here

enter image description here So the thing works for me is to go to Setting gradle, add my module manually, and sync a gradle again:

enter image description here

Best way to copy a database (SQL Server 2008)

Easiest way is actually a script.

Run this on production:


TO DISK = 'C:\temp\MyDatabase1.bak' -- some writeable folder. 

This one command makes a complete backup copy of the database onto a single file, without interfering with production availability or backup schedule, etc.

To restore, just run this on your dev or test SQL Server:


FROM DISK = 'C:\temp\MyDatabase1.bak'
MOVE 'MyDatabase'   TO 'C:\Sql\MyDatabase.mdf', -- or wherever these live on target
MOVE 'MyDatabase_log'   TO 'C:\Sql\MyDatabase_log.ldf',

Then save these scripts on each server. One-click convenience.

if you get an error when restoring that the logical names don't match, you can get them like this:

FROM disk = 'C:\temp\MyDatabaseName1.bak'

If you use SQL Server logins (not windows authentication) you can run this after restoring each time (on the dev/test machine):

use MyDatabaseName;
sp_change_users_login 'Auto_Fix', 'userloginname', null, 'userpassword';

How to change the current URL in javascript?

Your example wasn't working because you are trying to add 1 to a string that looks like this: "1.html". That will just get you this "1.html1" which is not what you want. You have to isolate the numeric part of the string and then convert it to an actual number before you can do math on it. After getting it to an actual number, you can then increase its value and then combine it back with the rest of the string.

You can use a custom replace function like this to isolate the various pieces of the original URL and replace the number with an incremented number:

function nextImage() {
    return(window.location.href.replace(/(\d+)(\.html)$/, function(str, p1, p2) {
        return((Number(p1) + 1) + p2);

You can then call it like this:

window.location.href = nextImage();

Demo here:

This will work for any URL that ends in some series of digits followed by .html and if you needed a slightly different URL form, you could just tweak the regular expression.

A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war

You should add maven-resources-plugin in your pom.xml file. Deleting ~/.m2/repository does not work always.


Now build your project again. It should be successful!

How to change the font color in the textbox in C#?

Assuming WinForms, the ForeColor property allows to change all the text in the TextBox (not just what you're about to add):

TextBox.ForeColor = Color.Red;

To only change the color of certain words, look at RichTextBox.

jquery variable syntax

The dollarsign as a prefix in the var name is a usage from the concept of the hungarian notation.

TortoiseSVN icons not showing up under Windows 7

Halt ye!

Before doing anything to your registry or similar procedures listed in Kris Erickson's (excellent) answer or the ones below, there's something to consider...

Are you on a network drive?

If so, go to Tortoise SVN settings (right click any folder > TortoiseSVN > Settings), then go to 'Icon Overlays'

Make sure you've checked 'Network Drives' as pictured:

alt text

By default on a fresh Tortoise install, network drives don't have the icons added.

This solved the problem for us. If this fails for you then obviously you can go through the (slightly) more involved solutions listed here.

Add image to left of text via css

Very simple method:

.create:before {
content: url(image.png);

Works in all modern browsers and IE8+.


Don't use this on large sites though. The :before pseudo-element is horrible in terms of performance.

Could not load the Tomcat server configuration

I solved this problem. DON'T USE THE .exe Unistall Tomcat and download the .zip from Tomcat's web site. Then unpack and put it in C:\Program Files. Open Eclipse and set the server. it will work.

Java regex email

Thanks to @Jason Buberel's answer, I think lowercase letters must be validated by the RegEX. So the following is correct:


Now, both [email protected] and [email protected] are valid!
Note that \. should be \\. to escape . and have \. itself. Since, . is a meaningful character in java RegEX means all characters.

How to add an Android Studio project to GitHub

If you are using the latest version of Android studio. then you don't need to install additional software for Git other than GIT itself -


  1. Create an account on Github -
  2. Install Git
  3. Open your working project in Android studio
  4. GoTo - File -> Settings -> Version Controll -> GitHub
  5. Enter Login and Password which you have created just on Git Account and click on test
  6. Once all credentials are true - it shows Success message. o.w Invalid Cred.
  7. Now click on VCS in android studio menu bar
  8. Select Import into Version Control -> Share Project on GitHub
  9. The popup dialog will occure contains all your files with check mark, do ok or commit all
  10. At next time whenever you want to push your project just click on VCS - > Commit Changes -> Commmit and Push.

That's it. You can find your project on your github now

Android: I am unable to have ViewPager WRAP_CONTENT

All answers do not work perfectly. So I created one. Below class would request layout when a new page was selected to make viewPager 's height is the current child view's height.

class WrapContentViewPager : ViewPager {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)

    private var curPos = 0

    init {
        addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {}

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {}

            override fun onPageSelected(position: Int) {
                curPos = position

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        if (childCount == 0) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        measureChildren(widthMeasureSpec, heightMeasureSpec)
        setMeasuredDimension(measuredWidth, getChildAt(curPos).measuredHeight)

How can I declare optional function parameters in JavaScript?

With ES6: This is now part of the language:

function myFunc(a, b = 0) {
   // function body

Please keep in mind that ES6 checks the values against undefined and not against truthy-ness (so only real undefined values get the default value - falsy values like null will not default).

With ES5:

function myFunc(a,b) {
  b = b || 0;

  // b will be set either to b or to 0.

This works as long as all values you explicitly pass in are truthy. Values that are not truthy as per MiniGod's comment: null, undefined, 0, false, ''

It's pretty common to see JavaScript libraries to do a bunch of checks on optional inputs before the function actually starts.

How to open a new tab using Selenium WebDriver

The same example for Node.js:

var webdriver = require('selenium-webdriver');
driver = new webdriver.Builder().
driver.findElement(webdriver.By.tagName("body")).sendKeys(webdriver.Key.COMMAND + "t");

How to post a file from a form with Axios

This works for me, I hope helps to someone.

var frm = $('#frm');
let formData = new FormData(frm[0]);'your-url', formData)
    .then(res => {
    }).catch(err => {

dd: How to calculate optimal blocksize?

  • for better performace use the biggest blocksize you RAM can accomodate (will send less I/O calls to the OS)
  • for better accurancy and data recovery set the blocksize to the native sector size of the input

As dd copies data with the conv=noerror,sync option, any errors it encounters will result in the remainder of the block being replaced with zero-bytes. Larger block sizes will copy more quickly, but each time an error is encountered the remainder of the block is ignored.


What is the difference between POST and GET?

If you are working RESTfully, GET should be used for requests where you are only getting data, and POST should be used for requests where you are making something happen.

Some examples:

  • GET the page showing a particular SO question

  • POST a comment

  • Send a POST request by clicking the "Add to cart" button.

Error: org.testng.TestNGException: Cannot find class in classpath: EmpClass

I also had this issue. I'm using IntelliJ IDEA. I was using src/main/java for configuration files and src/test/java for test files.
Because of this testNG couldn't find the class path. To prevent getting that error need to move all the files from src/main/java to src/test/java or vice versa.

MongoDB and "joins"

It's no join since the relationship will only be evaluated when needed. A join (in a SQL database) on the other hand will resolve relationships and return them as if they were a single table (you "join two tables into one").

You can read more about DBRef here:

There are two possible solutions for resolving references. One is to do it manually, as you have almost described. Just save a document's _id in another document's other_id, then write your own function to resolve the relationship. The other solution is to use DBRefs as described on the manual page above, which will make MongoDB resolve the relationship client-side on demand. Which solution you choose does not matter so much because both methods will resolve the relationship client-side (note that a SQL database resolves joins on the server-side).

svn : how to create a branch from certain revision of trunk

append the revision using an "@" character:

svn copy http://src@REV http://dev

Or, use the -r [--revision] command line argument.

How can you run a command in bash over and over until success?

You need to test $? instead, which is the exit status of the previous command. passwd exits with 0 if everything worked ok, and non-zero if the passwd change failed (wrong password, password mismatch, etc...)

while [ $? -ne 0 ]; do

With your backtick version, you're comparing passwd's output, which would be stuff like Enter password and confirm password and the like.

<strong> vs. font-weight:bold & <em> vs. font-style:italic

<strong> and <em> - unlike <b> and <i> - have clear purpose for web browsers for the blind.

A blind person doesn't browse the web visually, but by sound such as text readers. <strong> and <em>, in addition to encouraging something to be bold or italic, also convey loudness or stressing syllables respectively (OH MY! & Ooooooh Myyyyyyy!). Audio-only browsers are unpredictable when it comes to <b> and <i>... they may make them loud or stress them or they may not... you never can be sure unless you use <strong> and <em>.

How to close activity and go back to previous activity in android

on onCreate method of your activity write the following code.


Then override the onOptionsItem selected method of your activity as follows

public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
    return super.onOptionsItemSelected(item);

And you are good to go.

Is it possible to modify a registry entry via a .bat/.cmd script?

In addition to reg.exe, I highly recommend that you also check out powershell, its vastly more capable in its registry handling.

"Conversion to Dalvik format failed with error 1" on external JAR

EDIT (new solution):

It looks like the previous solution is only a bypass. I managed to finally fix the problem permanently: In my case there was a mismatch in android-support-v4 files in my project and in the Facebook project that is referenced in my project.

I found this error by performing Lint Check (Android Tools / Run Lint: Check for Common Errors)

My previous solution:

I've tried any possible solution on this site - nothing helped!!!

Finally I've found an answer here:!topic/actionbarsherlock/drzI7pEvKd4

Easy steps:

Go to Project -> uncheck Build Automatically

Go to Project -> Clean... , clean both the library project and your app project

Export your app as a signed APK while Build Automatically is still disabled

How ViewBag in ASP.NET MVC works

ViewBag is of type dynamic. More, you cannot do ViewBag["Foo"]. You will get exception - Cannot apply indexing with [] to an expression of type 'System.Dynamic.DynamicObject'.

Internal implementation of ViewBag actually stores Foo into ViewData["Foo"] (type of ViewDataDictionary), so those 2 are interchangeable. ViewData["Foo"] and ViewBag.Foo.

And scope. ViewBag and ViewData are ment to pass data between Controller's Actions and View it renders.

Apache Tomcat Connection refused

Not sure if your issue was fixed and how. But I faced the same issue while trying to make a tomcat instance running.

  • The port was not in use.
  • There was no firewall issue.
  • Tomcat instance was starting up fine.

I changed the custom shutdown script and this issue was fixed. Old Script:-

export CATALINA_HOME=/home/lrsprod/ELA/tomcat6/apache-tomcat-6.0.35 $CATALINA_HOME/bin/ stop

Added catalina base to it.

export CATALINA_BASE=/home/lrsprod/ELA/tomcat6/ela_instance export CATALINA_HOME=/home/lrsprod/ELA/tomcat6/apache-tomcat-6.0.35 $CATALINA_HOME/bin/ stop

That did the trick.

RVM is not a function, selecting rubies with 'rvm use ...' will not work

Your console is not running as a login shell and hence have no access to rvm function. If you are running Ubuntu, you can:

  1. Open console
  2. Select Edit -> Profile Preferences
  3. Select tab: Title and Command
  4. Check box 'Run command as a login shell'
  5. Restart terminal

Reason to Pass a Pointer by Reference in C++?

You would want to pass a pointer by reference if you have a need to modify the pointer rather than the object that the pointer is pointing to.

This is similar to why double pointers are used; using a reference to a pointer is slightly safer than using pointers.

What is the difference between encode/decode?

mybytestring.encode(somecodec) is meaningful for these values of somecodec:

  • base64
  • bz2
  • zlib
  • hex
  • quopri
  • rot13
  • string_escape
  • uu

I am not sure what decoding an already decoded unicode text is good for. Trying that with any encoding seems to always try to encode with the system's default encoding first.

React Native Error: ENOSPC: System limit for number of file watchers reached

  1. Firstly you can run every time with root privileges

    sudo npm start

  2. Or you can delete node_modules folder and use npm install to install again

  3. or you can get permanent solution

    echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

How to prevent a click on a '#' link from jumping to top of page?

You could just pass an anchor tag without an href property, and use jQuery to do the required action:

<a class="foo">bar</a>

Asp.Net MVC with Drop Down List, and SelectListItem Assistance

Step-1: Your Model class

public class RechargeMobileViewModel
        public string CustomerFullName { get; set; }
        public string TelecomSubscriber { get; set; }
        public int TotalAmount { get; set; }
        public string MobileNumber { get; set; }
        public int Month { get; set; }
        public List<SelectListItem> getAllDaysList { get; set; }

        // Define the list which you have to show in Drop down List
        public List<SelectListItem> getAllWeekDaysList()
            List<SelectListItem> myList = new List<SelectListItem>();
            var data = new[]{
                 new SelectListItem{ Value="1",Text="Monday"},
                 new SelectListItem{ Value="2",Text="Tuesday"},
                 new SelectListItem{ Value="3",Text="Wednesday"},
                 new SelectListItem{ Value="4",Text="Thrusday"},
                 new SelectListItem{ Value="5",Text="Friday"},
                 new SelectListItem{ Value="6",Text="Saturday"},
                 new SelectListItem{ Value="7",Text="Sunday"},
            myList = data.ToList();
            return myList;

Step-2: Call this method to fill Drop down in your controller Action

namespace MvcVariousApplication.Controllers
        public class HomeController : Controller
            public ActionResult Index()
              RechargeMobileViewModel objModel = new RechargeMobileViewModel();
                objModel.getAllDaysList = objModel.getAllWeekDaysList();  
                return View(objModel);

Step-3: Fill your Drop-Down List of View as follows

 @model MvcVariousApplication.Models.RechargeMobileViewModel
        ViewBag.Title = "Contact";
    @Html.LabelFor(model=> model.CustomerFullName)
    @Html.TextBoxFor(model => model.CustomerFullName)

    @Html.LabelFor(model => model.MobileNumber)
    @Html.TextBoxFor(model => model.MobileNumber)

    @Html.LabelFor(model => model.TelecomSubscriber)
    @Html.TextBoxFor(model => model.TelecomSubscriber)

    @Html.LabelFor(model => model.TotalAmount)
    @Html.TextBoxFor(model => model.TotalAmount)

    @Html.LabelFor(model => model.Month)
    @Html.DropDownListFor(model => model.Month, new SelectList(Model.getAllDaysList, "Value", "Text"), "-Select Day-")

Rotate label text in seaborn factorplot

This is still a matplotlib object. Try this:

# <your code here>
locs, labels = plt.xticks()
plt.setp(labels, rotation=45)

How to upload a file in Django?

You can refer to server examples in Fine Uploader, which has django version.

It's very elegant and most important of all, it provides featured js lib. Template is not included in server-examples, but you can find demo on its website. Fine Uploader:


UploadView dispatches post and delete request to respective handlers.

class UploadView(View):

    def dispatch(self, *args, **kwargs):
        return super(UploadView, self).dispatch(*args, **kwargs)

    def post(self, request, *args, **kwargs):
        """A POST request. Validate the form and then handle the upload
        based ont the POSTed data. Does not handle extra parameters yet.
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_upload(request.FILES['qqfile'], form.cleaned_data)
            return make_response(content=json.dumps({ 'success': True }))
            return make_response(status=400,
                    'success': False,
                    'error': '%s' % repr(form.errors)

    def delete(self, request, *args, **kwargs):
        """A DELETE request. If found, deletes a file with the corresponding
        UUID from the server's filesystem.
        qquuid = kwargs.get('qquuid', '')
        if qquuid:
                return make_response(content=json.dumps({ 'success': True }))
            except Exception, e:
                return make_response(status=400,
                        'success': False,
                        'error': '%s' % repr(e)
        return make_response(status=404,
                'success': False,
                'error': 'File not present'

class UploadFileForm(forms.Form):

    """ This form represents a basic request from Fine Uploader.
    The required fields will **always** be sent, the other fields are optional
    based on your setup.
    Edit this if you want to add custom parameters in the body of the POST
    qqfile = forms.FileField()
    qquuid = forms.CharField()
    qqfilename = forms.CharField()
    qqpartindex = forms.IntegerField(required=False)
    qqchunksize = forms.IntegerField(required=False)
    qqpartbyteoffset = forms.IntegerField(required=False)
    qqtotalfilesize = forms.IntegerField(required=False)
    qqtotalparts = forms.IntegerField(required=False)

How to add a column in TSQL after a specific column?

/* Script to change the column order of a table
Note this will create a new table to replace the original table
HOWEVER it doesn't copy the triggers or other table properties - just the data

Generate a new table with the columns in the order that you require

Select Column2, Column1, Column3 Into NewTable from OldTable

Delete the original table

Drop Table OldTable;

Rename the new table

EXEC sp_rename 'NewTable', 'OldTable';

SSL handshake fails with - a verisign chain certificate - that contains two CA signed certificates and one self-signed certificate

It sounds like the intermediate certificate is missing. As of April 2006, all SSL certificates issued by VeriSign require the installation of an Intermediate CA Certificate.

It could be that you don't have the entire certificate chain loaded on your server. Some businesses do not allow their computers to download additional certificates, causing a failure to complete an SSL handshake.

Here is some information on intermediate chains:

Intermediate CA Certificates

Get the cell value of a GridView row

Expanding on Dennis R answer above ... This will get the value based on the Heading Text (so you don't need to know what column...especially if its dynamic changing).

Example setting a session variable on SelectedIndexChange.

    protected void gvCustomer_SelectedIndexChanged(object sender, EventArgs e)
        int iCustomerID = Convert.ToInt32(Library.gvGetVal(gvCustomer, "CustomerID"));
        Session[SSS.CustomerID] = iCustomerID;

public class Library
    public static string gvGetVal(GridView gvGrid, string sHeaderText)
        string sRetVal = string.Empty;
        if (gvGrid.Rows.Count > 0)
            if (gvGrid.SelectedRow != null)
                GridViewRow row = gvGrid.SelectedRow;
                int iCol = gvGetColumn(gvGrid, sHeaderText);
                if (iCol > -1)
                    sRetVal = row.Cells[iCol].Text;
        return sRetVal;

    private static int gvGetColumn(GridView gvGrid, string sHeaderText)
        int iRetVal = -1;
        for (int i = 0; i < gvGrid.Columns.Count; i++)
            if (gvGrid.Columns[i].HeaderText.ToLower().Trim() == sHeaderText.ToLower().Trim())
                iRetVal = i;
        return iRetVal;

C# equivalent of the IsNull() function in SQL Server

    public static T IsNull<T>(this T DefaultValue, T InsteadValue)

        object obj="kk";

        if((object) DefaultValue == DBNull.Value)
            obj = null;

        if (obj==null || DefaultValue==null || DefaultValue.ToString()=="")
            return InsteadValue;
            return DefaultValue;


//This method can work with DBNull and null value. This method is question's answer

Problem with converting int to string in Linq to entities

I solved a similar problem by placing the conversion of the integer to string out of the query. This can be achieved by putting the query into an object.

var items = from c in contacts
            select new 
                Value = c.ContactId,
                Text = c.Name
var itemList = new SelectList();
foreach (var item in items)
    itemList.Add(new SelectListItem{ Value = item.ContactId, Text = item.Name });

JavaScript get clipboard data on paste event (Cross browser)

Just let the browser paste as usual in its content editable div and then after the paste swap any span elements used for custom text styles with the text itself. This seems to work okay in internet explorer and the other browsers I tried...

$('[contenteditable]').on('paste', function (e) {
    setTimeout(function () {
        $('span').each(function () {
    }, 0);

This solution assumes that you are running jQuery and that you don't want text formatting in any of your content editable divs.

The plus side is that it's super simple.

How to check version of a CocoaPods framework

To check version of cocoapods from terminal:

For Sudoless:

gem which cocoapods

For Sudo:

sudo gem which cocoapods

Also note: If you want to edit podfile or podfile.lock don't edit it in editors. Open only with XCode.

How to select only the first rows for each unique value of a column?

You can use row_number() to get the row number of the row. It uses the over command - the partition by clause specifies when to restart the numbering and the order by selects what to order the row number on. Even if you added an order by to the end of your query, it would preserve the ordering in the over command when numbering.

select *
from mytable
where row_number() over(partition by Name order by AddressLine) = 1

If else on WHERE clause

try this ,hope it helps

select user_display_image as user_image,
user_display_name as user_name,
    WHEN invitee_status=1 THEN "attending" 
    WHEN invitee_status=2 THEN "unsure" 
    WHEN invitee_status=3 THEN "declined" 
    WHEN invitee_status=0 THEN "notreviwed" END
) AS  invitee_status
 FROM your_tbl

How do you read a CSV file and display the results in a grid in Visual Basic 2010?

This is how you can read data from .csv file using OLEDB provider.

  If OpenFileDialog1.ShowDialog(Me) = DialogResult.OK Then
            Dim fi As New FileInfo(OpenFileDialog1.FileName)
            Dim sConnectionStringz As String = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Text;Data Source=" & fi.DirectoryName
            Dim objConn As New OleDbConnection(sConnectionStringz)
            'DataGridView1.TabIndex = 1
            Dim objCmdSelect As New OleDbCommand("SELECT * FROM " & fi.Name, objConn)
            Dim objAdapter1 As New OleDbDataAdapter
            objAdapter1.SelectCommand = objCmdSelect
            Dim objDataset1 As New DataSet

            '--objAdapter1.Update(objDataset1) '--updating
            DataGridView1.DataSource = objDataset1.Tables(0).DefaultView
        Catch ex as Exception
           MsgBox("Error: " + ex.Message)
        End Try
    End If

Iterate over the lines of a string

I suppose you could roll your own:

def parse(string):
    retval = ''
    for char in string:
        retval += char if not char == '\n' else ''
        if char == '\n':
            yield retval
            retval = ''
    if retval:
        yield retval

I'm not sure how efficient this implementation is, but that will only iterate over your string once.

Mmm, generators.


Of course you'll also want to add in whatever type of parsing actions you want to take, but that's pretty simple.

Exclude subpackages from Spring autowiring?

You can also include specific package and excludes them like :

Include and exclude (both)

                scanBasePackages = {
                exclude = {org.springframework.boot.sample.class}

JUST Exclude

@SpringBootApplication(exclude= {com.package1.class})
public class MySpringConfiguration {}

Convert String value format of YYYYMMDDHHMMSS to C# DateTime

class Program
    static void Main(string[] args)

        int transactionDate = 20201010;
        int? transactionTime = 210000;

        var agreementDate = DateTime.Today;
        var previousDate = agreementDate.AddDays(-1);

        var agreementHour = 22;
        var agreementMinute = 0;
        var agreementSecond = 0;

        var startDate = new DateTime(previousDate.Year, previousDate.Month, previousDate.Day, agreementHour, agreementMinute, agreementSecond);
        var endDate = new DateTime(agreementDate.Year, agreementDate.Month, agreementDate.Day, agreementHour, agreementMinute, agreementSecond);

        DateTime selectedDate = Convert.ToDateTime(transactionDate.ToString().Substring(6, 2) + "/" + transactionDate.ToString().Substring(4, 2) + "/" + transactionDate.ToString().Substring(0, 4) + " " + string.Format("{0:00:00:00}", transactionTime));

        Console.WriteLine("Selected Date : " + selectedDate.ToString());
        Console.WriteLine("Start Date : " + startDate.ToString());
        Console.WriteLine("End Date : " + endDate.ToString());

        if (selectedDate > startDate && selectedDate <= endDate)
            Console.WriteLine("Between two dates..");
        else if (selectedDate <= startDate)
            Console.WriteLine("Less than or equal to the start date!");
        else if (selectedDate > endDate)
            Console.WriteLine("Greater than end date!");
            Console.WriteLine("Out of date ranges!");

iOS app 'The application could not be verified' only on one device

Had the same issue on my iPad running 8.1.3 Deleting the app and installing again fixed the issue. I use two different provisioning profiles on two different machines and that could have caused this issue.

CSS div 100% height

I have another suggestion. When you want myDiv to have a height of 100%, use these extra 3 attributes on your div:

myDiv {
    min-height: 100%;
    overflow-y: hidden;
    position: relative;

That should do the job!

Binary Data Posting with curl

You don't need --header "Content-Length: $LENGTH".

curl --request POST --data-binary "@template_entry.xml" $URL

Note that GET request does not support content body widely.

Also remember that POST request have 2 different coding schema. This is first form:

  $ nc -l -p 6666 &
  $ curl  --request POST --data-binary "@README" http://localhost:6666

User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/ libidn/1.15 libssh2/1.2.6
Host: localhost:6666
Accept: */*
Content-Length: 9309
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

.. -*- mode: rst; coding: cp1251; fill-column: 80 -*-
.. contents::

You probably request this:

-F/--form name=content
           (HTTP) This lets curl emulate a filled-in form in
              which a user has pressed the submit button. This
              causes curl to POST data using the Content- Type
              multipart/form-data according to RFC2388. This
              enables uploading of binary files etc. To force the
              'content' part to be a file, prefix the file name
              with an @ sign. To just get the content part from a
              file, prefix the file name with the symbol <. The
              difference between @ and < is then that @ makes a
              file get attached in the post as a file upload,
              while the < makes a text field and just get the
              contents for that text field from a file.

Regular expression for first and last name

For first and last names theres are really only 2 things you should be looking for:

  1. Length
  2. Content

Here is my regular expression:

var regex = /^[A-Za-z-,]{3,20}?=.*\d)/

1. Length

Here the {3,20} constrains the length of the string to be between 3 and 20 characters.

2. Content

The information between the square brackets [A-Za-z] allows uppercase and lowercase characters. All subsequent symbols (-,.) are also allowed.

CSS: Position text in the middle of the page

Try this CSS:

h1 {
    left: 0;
    line-height: 200px;
    margin-top: -100px;
    position: absolute;
    text-align: center;
    top: 50%;
    width: 100%;


webpack: Module not found: Error: Can't resolve (with relative path)

I met this problem with typescript but forgot to add ts and tsx suffix to resolve entry.

module.exports = {
  resolve: {
    extensions: ['.js', '.jsx', '.ts', '.tsx'],

This does the job for me

Iterate through a HashMap

Depends. If you know you're going to need both the key and the value of every entry, then go through the entrySet. If you just need the values, then there's the values() method. And if you just need the keys, then use keyset().

A bad practice would be to iterate through all of the keys, and then within the loop, always do map.get(key) to get the value. If you're doing that, then the first option I wrote is for you.

How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?

One more method is to Define the Layout inside the View:

    Layout = "~/Views/Shared/_MyAdminLayout.cshtml";

More Ways to do, can be found here, hope this helps someone.

How do you enable mod_rewrite on any OS?

if it related to hosting site then ask to your hosting or if you want to enable it in local machine then check this youtube step by step tutorial related to enabling rewrite module in wamp apache
Wamp server icon -> Apache -> Apache Modules and check the rewrite module option it should be checked but after that wamp require restart all services

How to execute INSERT statement using JdbcTemplate class from Spring Framework

You can alternatively use NamedParameterJdbcTemplate (naming can be useful when you have many parameters)

Map<String, Object> params = new HashMap<>();
    "INSERT INTO schema.tableName (column1, column2) VALUES (:var1, :var2)",

How to call a Parent Class's method from Child Class in Python?

Use the super() function:

class Foo(Bar):
    def baz(self, arg):
        return super().baz(arg)

For Python < 3, you must explicitly opt in to using new-style classes and use:

class Foo(Bar):
    def baz(self, arg):
        return super(Foo, self).baz(arg)

Get response from PHP file using AJAX

in your PHP file, when you echo your data use json_encode (


//plum or data...
$output = array("data","plum");

echo json_encode($output);


in your javascript code, when your ajax completes the json encoded response data can be turned into an js array like this:

                type: "POST",
                url: "process.php",
                data: somedata;
                success function(json_data){
                    var data_array = $.parseJSON(json_data);

                    //access your data like this:
                    var plum_or_whatever = data_array['output'];.
                    //continue from here...

How to create a file on Android Internal Storage?

I was getting the same exact error as well. Here is the fix. When you are specifying where to write to, Android will automatically resolve your path into either /data/ or /mnt/sdcard/. Let me explain.

If you execute the following statement:

File resolveMe = new File("/data/myPackage/files/media/qmhUZU.jpg");

It will resolve the path to the root /data/ somewhere higher up in Android.

I figured this out, because after I executed the following code, it was placed automatically in the root /mnt/ without me translating anything on my own.

File resolveMeSDCard = new File("/sdcard/myPackage/files/media/qmhUZU.jpg");

A quick fix would be to change your following code:

File f = new File(getLocalPath().replace("/data/data/", "/"));

Hope this helps

How to load a model from an HDF5 file in Keras?

See the following sample code on how to Build a basic Keras Neural Net Model, save Model (JSON) & Weights (HDF5) and load them:

# create model
model = Sequential()
model.add(Dense(X.shape[1], input_dim=X.shape[1], activation='relu')) #Input Layer
model.add(Dense(X.shape[1], activation='relu')) #Hidden Layer
model.add(Dense(output_dim, activation='softmax')) #Output Layer

# Compile & Fit model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']),Y,nb_epoch=5,batch_size=100,verbose=1)    

# serialize model to JSON
model_json = model.to_json()
with open("Data/model.json", "w") as json_file:
    json_file.write(simplejson.dumps(simplejson.loads(model_json), indent=4))

# serialize weights to HDF5
print("Saved model to disk")

# load json and create model
json_file = open('Data/model.json', 'r')
loaded_model_json =
loaded_model = model_from_json(loaded_model_json)

# load weights into new model
print("Loaded model from disk")

# evaluate loaded model on test data 
# Define X_test & Y_test data first
loaded_model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
score = loaded_model.evaluate(X_test, Y_test, verbose=0)
print ("%s: %.2f%%" % (loaded_model.metrics_names[1], score[1]*100))

How can you use optional parameters in C#?

For just in case if someone wants to pass a callback (or delegate) as an optional parameter, can do it this way.

Optional Callback parameter:

public static bool IsOnlyOneElement(this IList lst, Action callbackOnTrue = (Action)((null)), Action callbackOnFalse = (Action)((null)))
    var isOnlyOne = lst.Count == 1;
    if (isOnlyOne && callbackOnTrue != null) callbackOnTrue();
    if (!isOnlyOne && callbackOnFalse != null) callbackOnFalse();
    return isOnlyOne;

Send an Array with an HTTP Get

I know this post is really old, but I have to reply because although BalusC's answer is marked as correct, it's not completely correct.

You have to write the query adding "[]" to foo like this:


Postgres integer arrays as parameters?

Full Coding Structure

postgresql function

CREATE OR REPLACE FUNCTION admin.usp_itemdisplayid_byitemhead_select(
    item_head_list int[])
    RETURNS TABLE(item_display_id integer) 
    LANGUAGE 'sql'

    COST 100
    ROWS 1000
        SELECT vii.item_display_id from admin.view_item_information as vii
where vii.item_head_id = ANY(item_head_list);


public class CampaignCreator
        public int item_display_id { get; set; }
        public List<int> pitem_head_id { get; set; }

.NET CORE function

DynamicParameters _parameter = new DynamicParameters();
                string sql = "select * from admin.usp_itemdisplayid_byitemhead_select(@item_head_list)";
       = await _connection.QueryAsync<CampaignCreator>(sql, _parameter);

Python - Create list with numbers between 2 values?

If you are looking for range like function which works for float type, then here is a very good article.

def frange(start, stop, step=1.0):
    ''' "range()" like function which accept float type''' 
    i = start
    while i < stop:
        yield i
        i += step
# Generate one element at a time.
# Preferred when you don't need all generated elements at the same time. 
# This will save memory.
for i in frange(1.0, 2.0, 0.5):
    print i   # Use generated element.
# Generate all elements at once.
# Preferred when generated list ought to be small.
print list(frange(1.0, 10.0, 0.5))    


[1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5]

django admin - add custom form fields that are not part of the model

Django 2.1.1 The primary answer got me halfway to answering my question. It did not help me save the result to a field in my actual model. In my case I wanted a textfield that a user could enter data into, then when a save occurred the data would be processed and the result put into a field in the model and saved. While the original answer showed how to get the value from the extra field, it did not show how to save it back to the model at least in Django 2.1.1

This takes the value from an unbound custom field, processes, and saves it into my real description field:

class WidgetForm(forms.ModelForm):
    extra_field = forms.CharField(required=False)

    def processData(self, input):
        # example of error handling
        if False:
            raise forms.ValidationError('Processing failed!')

        return input + " has been processed"

    def save(self, commit=True):
        extra_field = self.cleaned_data.get('extra_field', None)

        # self.description = "my result" note that this does not work

        # Get the form instance so I can write to its fields
        instance = super(WidgetForm, self).save(commit=commit)

        # this writes the processed data to the description field
        instance.description = self.processData(extra_field)

        if commit:

        return instance

    class Meta:
        model = Widget
        fields = "__all__"

Python ImportError: No module named wx

I had the same error today but I tried something and surprisingly it worked. In the site packages folder there will be a file named wx.pth. Open it using notepad and its contents would be like "wx-2.8-msw-unicode"

It is basically the name of the folder containing wxpython. Delete this using Ctrl + A and copy the name of the folder from the site packages and paste it here even if it is the same.

Sounds weird but maybe the original file contained a hidden character...

What does -save-dev mean in npm install grunt --save-dev

When you use the parameter "--save" your dependency will go inside the #1 below in package.json. When you use the parameter "--save-dev" your dependency will go inside the #2 below in package.json.

#1. "dependencies": these packages are required by your application in production.

#2. "devDependencies": these packages are only needed for development and testing

Which programming language for cloud computing?

As for what programming languages, any browser-based or server-based language is likely to be used. Javascript, PHP, ASP, AJAX, Perl, Java, SQL.

Let's say you need to implement a new programming language and BCL designed specifically for operating in the cloud (it won't be used on client machines ever). It should be optimized for cloud computing; easy to learn, fast, efficient, powerful, modern.

The biggest way i’ve seen cloud hosting products help out developers is the ability to launch and increase the size of a server, without having any kind of delay. Developers are able to create the application in a completely customized environment, and then expand it into a production machine with a significant hassle. If things don’t work as wanted, they can then destroy that machine with relative ease.

Most of the Cloud Computing Providers used JAVA and C-Sharp, to make cloud server.

Redis: How to access Redis log file

vi /usr/local/etc/redis.conf

Look for dir, logfile

# The working directory.
# The DB will be written inside this directory, with the filename specified
# above using the 'dbfilename' configuration directive.
# The Append Only File will also be created inside this directory.
# Note that you must specify a directory here, not a file name.
dir /usr/local/var/db/redis/

# Specify the log file name. Also the empty string can be used to force
# Redis to log on the standard output. Note that if you use standard
# output for logging but daemonize, logs will be sent to /dev/null 
logfile "redis_log"

So the log file is created at /usr/local/var/db/redis/redis_log with the name redis_log

You can also try MONITOR command from redis-cli to review the number of commands executed.

Why use pip over easy_install?

pip won't install binary packages and isn't well tested on Windows.

As Windows doesn't come with a compiler by default pip often can't be used there. easy_install can install binary packages for Windows.

message box in jquery

Try this plugin JQuery UI Message box. He uses jQuery UI Dialog.

PHP - auto refreshing page

This works with Firefox Quantum 60+ and Chrome v72 (2019)

//set a header to instruct the browser to call the page every 30 sec
header("Refresh: 30;");

It does not seem to be NECESSARY to pass the page url as well as the refresh period in order to (re)call the same page. I haven't tried this with Safari/Opera or IE/Edge.

How do you import classes in JSP?

Use the following import statement to import java.util.List:

<%@ page import="java.util.List" %>

BTW, to import more than one class, use the following format:

<%@ page import="package1.myClass1,package2.myClass2,....,packageN.myClassN" %>

diff to output only the file names

You can also use rsync

rsync -rv --size-only --dry-run /my/source/ /my/dest/ > diff.out

Is there a way to perform "if" in python's lambda

Lambdas in Python are fairly restrictive with regard to what you're allowed to use. Specifically, you can't have any keywords (except for operators like and, not, or, etc) in their body.

So, there's no way you could use a lambda for your example (because you can't use raise), but if you're willing to concede on that… You could use:

f = lambda x: x == 2 and x or None

What is the Ruby <=> (spaceship) operator?

What is <=> ( The 'Spaceship' Operator )

According to the RFC that introduced the operator, $a <=> $b

 -  0 if $a == $b
 - -1 if $a < $b
 -  1 if $a > $b

 - Return 0 if values on either side are equal
 - Return 1 if value on the left is greater
 - Return -1 if the value on the right is greater


//Comparing Integers

echo 1 <=> 1; //ouputs 0
echo 3 <=> 4; //outputs -1
echo 4 <=> 3; //outputs 1

//String Comparison

echo "x" <=> "x"; // 0
echo "x" <=> "y"; //-1
echo "y" <=> "x"; //1


// Integers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1

// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1

// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1

echo "a" <=> "aa"; // -1
echo "zz" <=> "aa"; // 1

// Arrays
echo [] <=> []; // 0
echo [1, 2, 3] <=> [1, 2, 3]; // 0
echo [1, 2, 3] <=> []; // 1
echo [1, 2, 3] <=> [1, 2, 1]; // 1
echo [1, 2, 3] <=> [1, 2, 4]; // -1

// Objects
$a = (object) ["a" => "b"]; 
$b = (object) ["a" => "b"]; 
echo $a <=> $b; // 0

Joining Spark dataframes on the key

Let me explain with an example

  1. create emp DataFrame

    import spark.sqlContext.implicits._ val emp = Seq((1,"Smith",-1,"2018","10","M",3000), (2,"Rose",1,"2010","20","M",4000), (3,"Williams",1,"2010","10","M",1000), (4,"Jones",2,"2005","10","F",2000), (5,"Brown",2,"2010","40","",-1), (6,"Brown",2,"2010","50","",-1) ) val empColumns = Seq("emp_id","name","superior_emp_id","year_joined", "emp_dept_id","gender","salary")

    val empDF = emp.toDF(empColumns:_*)

  2. Create dept DataFrame

    val dept = Seq(("Finance",10), ("Marketing",20), ("Sales",30), ("IT",40) )

    val deptColumns = Seq("dept_name","dept_id") val deptDF = dept.toDF(deptColumns:_*)

Now let's join emp.emp_dept_id with dept.dept_id

empDF.join(deptDF,empDF("emp_dept_id") ===  deptDF("dept_id"),"inner")

This results below

|emp_id|name    |superior_emp_id|year_joined|emp_dept_id|gender|salary|dept_name|dept_id|
|1     |Smith   |-1             |2018       |10         |M     |3000  |Finance  |10     |
|2     |Rose    |1              |2010       |20         |M     |4000  |Marketing|20     |
|3     |Williams|1              |2010       |10         |M     |1000  |Finance  |10     |
|4     |Jones   |2              |2005       |10         |F     |2000  |Finance  |10     |
|5     |Brown   |2              |2010       |40         |      |-1    |IT       |40     |

If you are looking in python PySpark Join with example and also find the complete Scala example at Spark Join

Docker: unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx

I also faced the same issues and it was resolved when i created file named with DockerFile and mentioned all the command which wanted to get executed while creation of any image.

Clearing content of text file using php

To add button you may use either jQuery libraries or simple Javascript script as shown below:

HTML link or button:

<a href="#" onClick="goclear()" id="button">click event</a>


<script type="text/javascript">
var btn = document.getElementById('button');
function goclear() { 
alert("Handler called. Page will redirect to clear.php");
document.location.href = "clear.php";

Use PHP to clear a file content. For instance you can use the fseek($fp, 0); or ftruncate ( resource $file , int $size ) as below:

//open file to write
$fp = fopen("/tmp/file.txt", "r+");
// clear content to 0 bits
ftruncate($fp, 0);
//close file

Redirect PHP - you can use header ( string $string [, bool $replace = true [, int $http_response_code ]] )

header('Location: getbacktoindex.html');

I hope it's help.

How can I use threading in Python?

Like others mentioned, CPython can use threads only for I/O waits due to GIL.

If you want to benefit from multiple cores for CPU-bound tasks, use multiprocessing:

from multiprocessing import Process

def f(name):
    print 'hello', name

if __name__ == '__main__':
    p = Process(target=f, args=('bob',))

Smart cast to 'Type' is impossible, because 'variable' is a mutable property that could have been changed by this time

Do this:

var left: Node? = null

fun show() {
     val left = left
     if (left != null) {
         queue.add(left) // safe cast succeeds

Which seems to be the first option provided by the accepted answer, but that's what you're looking for.

CSS vertical alignment text inside li

line-height is how you vertically align text. It is pretty standard and I don't consider it a "hack". Just add line-height: 100px to your ul.catBlock li and it will be fine.

In this case you may have to add it to ul.catBlock li a instead since all of the text inside the li is also inside of an a. I have seen some weird things happen when you do this, so try both and see which one works.

How does Python manage int and long?

Interesting. On my 64-bit (i7 Ubuntu) box:

>>> print type(0x7FFFFFFF)
<type 'int'>
>>> print type(0x7FFFFFFF+1)
<type 'int'>

Guess it steps up to 64 bit ints on a larger machine.

error: expected class-name before ‘{’ token


#include "Landing.h"


class Landing;

If you still get errors, also post Item.h, Flight.h and common.h

EDIT: In response to comment.

You will need to e.g. #include "Landing.h" from Event.cpp in order to actually use the class. You just cannot include it from Event.h

How to parse JSON in Java

If you have some Java class(say Message) representing the JSON string(jsonString), you can use Jackson JSON library with:

Message message= new ObjectMapper().readValue(jsonString, Message.class);

and from message object you can fetch any of its attribute.

Jenkins Slave port number for firewall

A slave isn't a server, it's a client type application. Network clients (almost) never use a specific port. Instead, they ask the OS for a random free port. This works much better since you usually run clients on many machines where the current configuration isn't known in advance. This prevents thousands of "client wouldn't start because port is already in use" bug reports every day.

You need to tell the security department that the slave isn't a server but a client which connects to the server and you absolutely need to have a rule which says client:ANY -> server:FIXED. The client port number should be >= 1024 (ports 1 to 1023 need special permissions) but I'm not sure if you actually gain anything by adding a rule for this - if an attacker can open privileged ports, they basically already own the machine.

If they argue, then ask them why they don't require the same rule for all the web browsers which people use in your company.

How to change the style of the title attribute inside an anchor tag?

You can't style an actual title attribute

How the text in the title attribute is displayed is defined by the browser and varies from browser to browser. It's not possible for a webpage to apply any style to the tooltip that the browser displays based on the title attribute.

However, you can create something very similar using other attributes.

You can make a pseudo-tooltip with CSS and a custom attribute (e.g. data-title)

For this, I'd use a data-title attribute. data-* attributes are a method to store custom data in DOM elements/HTML. There are multiple ways of accessing them. Importantly, they can be selected by CSS.

Given that you can use CSS to select elements with data-title attributes, you can then use CSS to create :after (or :before) content that contains the value of the attribute using attr().

Styled tooltip Examples

Bigger and with a different background color (per question's request):

[data-title]:hover:after {_x000D_
    opacity: 1;_x000D_
    transition: all 0.1s ease 0.5s;_x000D_
    visibility: visible;_x000D_
[data-title]:after {_x000D_
    content: attr(data-title);_x000D_
    background-color: #00FF00;_x000D_
    color: #111;_x000D_
    font-size: 150%;_x000D_
    position: absolute;_x000D_
    padding: 1px 5px 2px 5px;_x000D_
    bottom: -1.6em;_x000D_
    left: 100%;_x000D_
    white-space: nowrap;_x000D_
    box-shadow: 1px 1px 3px #222222;_x000D_
    opacity: 0;_x000D_
    border: 1px solid #111111;_x000D_
    z-index: 99999;_x000D_
    visibility: hidden;_x000D_
[data-title] {_x000D_
    position: relative;_x000D_
<a href="" data-title="My site"> Link </a> with styled tooltip (bigger and with a different background color, as requested in the question)<br/>_x000D_
<a href="" title="My site"> Link </a> with normal tooltip

More elaborate styling (adapted from this blog post):

[data-title]:hover:after {_x000D_
    opacity: 1;_x000D_
    transition: all 0.1s ease 0.5s;_x000D_
    visibility: visible;_x000D_
[data-title]:after {_x000D_
    content: attr(data-title);_x000D_
    position: absolute;_x000D_
    bottom: -1.6em;_x000D_
    left: 100%;_x000D_
    padding: 4px 4px 4px 8px;_x000D_
    color: #222;_x000D_
    white-space: nowrap; _x000D_
    -moz-border-radius: 5px; _x000D_
    -webkit-border-radius: 5px;  _x000D_
    border-radius: 5px;  _x000D_
    -moz-box-shadow: 0px 0px 4px #222;  _x000D_
    -webkit-box-shadow: 0px 0px 4px #222;  _x000D_
    box-shadow: 0px 0px 4px #222;  _x000D_
    background-image: -moz-linear-gradient(top, #f8f8f8, #cccccc);  _x000D_
    background-image: -webkit-gradient(linear,left top,left bottom,color-stop(0, #f8f8f8),color-stop(1, #cccccc));_x000D_
    background-image: -webkit-linear-gradient(top, #f8f8f8, #cccccc);  _x000D_
    background-image: -moz-linear-gradient(top, #f8f8f8, #cccccc);  _x000D_
    background-image: -ms-linear-gradient(top, #f8f8f8, #cccccc);  _x000D_
    background-image: -o-linear-gradient(top, #f8f8f8, #cccccc);_x000D_
    opacity: 0;_x000D_
    z-index: 99999;_x000D_
    visibility: hidden;_x000D_
[data-title] {_x000D_
    position: relative;_x000D_
<a href="" data-title="My site"> Link </a> with styled tooltip<br/>_x000D_
<a href="" title="My site"> Link </a> with normal tooltip

Known issues

Unlike a real title tooltip, the tooltip produced by the above CSS is not, necessarily, guaranteed to be visible on the page (i.e. it might be outside the visible area). On the other hand, it is guaranteed to be within the current window, which is not the case for an actual tooltip.

In addition, the pseudo-tooltip is positioned relative to the element that has the pseudo-tooltip rather than relative to where the mouse is on that element. You may want to fine-tune where the pseudo-tooltip is displayed. Having it appear in a known location relative to the element can be a benefit or a drawback, depending on the situation.

You can't use :before or :after on elements which are not containers

There's a good explanation in this answer to "Can I use a :before or :after pseudo-element on an input field?"

Effectively, this means that you can't use this method directly on elements like <input type="text"/>, <textarea/>, <img>, etc. The easy solution is to wrap the element that's not a container in a <span> or <div> and have the pseudo-tooltip on the container.

Examples of using a pseudo-tooltip on a <span> wrapping a non-container element:

[data-title]:hover:after {_x000D_
    opacity: 1;_x000D_
    transition: all 0.1s ease 0.5s;_x000D_
    visibility: visible;_x000D_
[data-title]:after {_x000D_
    content: attr(data-title);_x000D_
    background-color: #00FF00;_x000D_
    color: #111;_x000D_
    font-size: 150%;_x000D_
    position: absolute;_x000D_
    padding: 1px 5px 2px 5px;_x000D_
    bottom: -1.6em;_x000D_
    left: 100%;_x000D_
    white-space: nowrap;_x000D_
    box-shadow: 1px 1px 3px #222222;_x000D_
    opacity: 0;_x000D_
    border: 1px solid #111111;_x000D_
    z-index: 99999;_x000D_
    visibility: hidden;_x000D_
[data-title] {_x000D_
    position: relative;_x000D_
.pseudo-tooltip-wrapper {_x000D_
    /*This causes the wrapping element to be the same size as what it contains.*/_x000D_
    display: inline-block;_x000D_
Text input with a pseudo-tooltip:<br/>_x000D_
<span class="pseudo-tooltip-wrapper" data-title="input type=&quot;text&quot;"><input type='text'></span><br/><br/><br/>_x000D_
Textarea with a pseudo-tooltip:<br/>_x000D_
<span class="pseudo-tooltip-wrapper" data-title="this is a textarea"><textarea data-title="this is a textarea"></textarea></span><br/>

From the code on the blog post linked above (which I first saw in an answer here that plagiarized it), it appeared obvious to me to use a data-* attribute instead of the title attribute. Doing so was also suggested in a comment by snostorm on that (now deleted) answer.

Keyboard shortcuts with jQuery

Since this question was originally asked, John Resig (the primary author of jQuery) has forked and improved the js-hotkeys project. His version is available at:

jQuery AJAX single file upload

A. Grab file data from the file field

The first thing to do is bind a function to the change event on your file field and a function for grabbing the file data:

// Variable to store your files
var files;

// Add events
$('input[type=file]').on('change', prepareUpload);

// Grab the files and set them to our variable
function prepareUpload(event)
  files =;

This saves the file data to a file variable for later use.

B. Handle the file upload on submit

When the form is submitted you need to handle the file upload in its own AJAX request. Add the following binding and function:

$('form').on('submit', uploadFiles);

// Catch the form submit and upload the files
function uploadFiles(event)
  event.stopPropagation(); // Stop stuff happening
    event.preventDefault(); // Totally stop stuff happening


// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
    data.append(key, value);

    url: 'submit.php?files',
    type: 'POST',
    data: data,
    cache: false,
    dataType: 'json',
    processData: false, // Don't process the files
    contentType: false, // Set content type to false as jQuery will tell the server its a query string request
    success: function(data, textStatus, jqXHR)
        if(typeof data.error === 'undefined')
            // Success so call function to process the form
            submitForm(event, data);
            // Handle errors here
            console.log('ERRORS: ' + data.error);
    error: function(jqXHR, textStatus, errorThrown)
        // Handle errors here
        console.log('ERRORS: ' + textStatus);

What this function does is create a new formData object and appends each file to it. It then passes that data as a request to the server. 2 attributes need to be set to false:

  • processData - Because jQuery will convert the files arrays into strings and the server can't pick it up.
  • contentType - Set this to false because jQuery defaults to application/x-www-form-urlencoded and doesn't send the files. Also setting it to multipart/form-data doesn't seem to work either.

C. Upload the files

Quick and dirty php script to upload the files and pass back some info:

<?php // You need to add server side validation and better error handling here

$data = array();

$error = false;
$files = array();

$uploaddir = './uploads/';
foreach($_FILES as $file)
    if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
        $files[] = $uploaddir .$file['name'];
        $error = true;
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
    $data = array('success' => 'Form was submitted', 'formData' => $_POST);

echo json_encode($data);


IMP: Don't use this, write your own.

D. Handle the form submit

The success method of the upload function passes the data sent back from the server to the submit function. You can then pass that to the server as part of your post:

function submitForm(event, data)
  // Create a jQuery object from the form
$form = $(;

// Serialize the form data
var formData = $form.serialize();

// You should sterilise the file names
$.each(data.files, function(key, value)
    formData = formData + '&filenames[]=' + value;

    url: 'submit.php',
    type: 'POST',
    data: formData,
    cache: false,
    dataType: 'json',
    success: function(data, textStatus, jqXHR)
        if(typeof data.error === 'undefined')
            // Success so call function to process the form
            console.log('SUCCESS: ' + data.success);
            // Handle errors here
            console.log('ERRORS: ' + data.error);
    error: function(jqXHR, textStatus, errorThrown)
        // Handle errors here
        console.log('ERRORS: ' + textStatus);
    complete: function()

Final note

This script is an example only, you'll need to handle both server and client side validation and some way to notify users that the file upload is happening. I made a project for it on Github if you want to see it working.

Referenced From

Temporary tables in stored procedures

According SQL Server 2008 Books You can create local and global temporary tables. Local temporary tables are visible only in the current session, and global temporary tables are visible to all sessions.



If a local temporary table is created in a stored procedure or application that can be executed at the same time by several users, the Database Engine must be able to distinguish the tables created by the different users. The Database Engine does this by internally appending a numeric suffix to each local temporary table name.

Then there occurs no problem.

How to set default value for column of new created table from select statement in 11g

The reason is that CTAS (Create table as select) does not copy any metadata from the source to the target table, namely

  • no primary key
  • no foreign keys
  • no grants
  • no indexes
  • ...

To achieve what you want, I'd either

  • use dbms_metadata.get_ddl to get the complete table structure, replace the table name with the new name, execute this statement, and do an INSERT afterward to copy the data
  • or keep using CTAS, extract the not null constraints for the source table from user_constraints and add them to the target table afterwards

How do you detect the clearing of a "search" HTML5 input?

It made sense to me that clicking the X should count as a change event. I already had the onChange event all setup to do what I needed it to do. So for me, the fix was to simply do this jQuery line:

$('#search').click(function(){ $(this).change(); });


REST is tightly coupled with HTTP, so if you only expose your API over HTTP then REST is more appropriate for most (but not all) situations. However, if you need to expose your API over other transports like messaging or web sockets then REST is just not applicable.

Text size and different android screen sizes

You can also use weightSum and layout_weight property to adjust your different screen.

For that, you have to make android:layout_width = 0dp, and android:layout_width = (whatever you want);

How to convert string to XML using C#

// using System.Xml;

String rawXml =
          <person firstname=""Riley"" lastname=""Scott"" />
          <person firstname=""Thomas"" lastname=""Scott"" />

XmlDocument xmlDoc = new XmlDocument();

I think this should work.

Open Jquery modal dialog on click event

Try adding this line before your dialog line.

$( "#dialog" ).dialog( "open" );

This method worked for me. It seems that the "close" command messes up the dialog opening again with only the .dialog() .

Using your code as an example, it would go in like this (note that you may need to add more to your code for it to make sense):

    <script type="text/javascript">
$(document).ready(function() {
    $('#dialog_link').click(function() {
$( "#dialog" ).dialog( "open" );        
        return false;
   <div id="dialog" title="Dialog Title" style="display:none"> Some text</div>  
   <p id="dialog_link">Open Dialog</p>  

How to delete/truncate tables from Hadoop-Hive?

You can use drop command to delete meta data and actual data from HDFS.

And just to delete data and keep the table structure, use truncate command.

For further help regarding hive ql, check language manual of hive.

Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)

This is a simple way from XML only

spanCount for number of columns

layoutManager for making it grid or linear(Vertical or Horizontal)

        app:layout_constraintTop_toTopOf="parent" />

Change the borderColor of the TextBox

You can handle WM_NCPAINT message of TextBox and draw a border on the non-client area of control if the control has focus. You can use any color to draw border:

using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class ExTextBox : TextBox
    private static extern IntPtr GetWindowDC(IntPtr hwnd);
    private const int WM_NCPAINT = 0x85;
    protected override void WndProc(ref Message m)
        base.WndProc(ref m);
        if (m.Msg == WM_NCPAINT && this.Focused)
            var dc = GetWindowDC(Handle);
            using (Graphics g = Graphics.FromHdc(dc))
                g.DrawRectangle(Pens.Red, 0, 0, Width - 1, Height - 1);


The painting of borders while the control is focused is completely flicker-free:

Change TextBox border color on focus

BorderColor property for TextBox

In the current post I just change the border color on focus. You can also add a BorderColor property to the control. Then you can change border-color based on your requirement at design-time or run-time. I've posted a more completed version of TextBox which has BorderColor property: in the following post:

Change Textbox border color

Select count(*) from multiple tables

        SELECT COUNT(*)
        FROM   tab1
        ) AS count1,
        SELECT COUNT(*)
        FROM   tab2
        ) AS count2
FROM    dual

JOIN queries vs multiple queries

Whether you should use a join is first and foremost about whether a join makes sense. Only at that point is performance even something to be considered, as nearly all other cases will result in significantly worse performance.

Performance differences will largely be tied to how related the info you're querying for is. Joins work, and they're fast when the data is related and you index stuff correctly, but they do often result in some redundancy and sometimes more results than needed. And if your data sets are not directly related, sticking them in a single query will result in what's called a Cartesian product (basically, all possible combinations of rows), which is almost never what you want.

This is often caused by many-to-one-to-many relationships. For example, HoldOffHunger's answer mentioned a single query for posts, tags, and comments. Comments are related to a post, as are tags...but tags are unrelated to comments.

+------------+     +---------+     +---------+
|  comment   |     |   post  |     |  tag    |
|------------|*   1|---------|1   *|---------|
| post_id    |-----| post_id |-----| post_id |
| comment_id |     | ...     |     | tag_id  |
| user_id    |     |         |     | ...     |
| ...        |     |         |     | ...     |
+------------+     +---------+     +---------+

In this case, it is unambiguously better for this to be at least two separate queries. If you try to join tags and comments, because there's no direct relation between the two, you end up with every possible combination of tag and comment. many * many == manymany. Aside from that, since posts and tags are unrelated, you can do those two queries in parallel, leading to potential gain.

Let's consider a different scenario, though: You want the comments attached to a post, and the commenters' contact info.

 +----------+     +------------+     +---------+
 |   user   |     |  comment   |     |   post  |
 |----------|1   *|------------|*   1|---------|
 | user_id  |-----| post_id    |-----| post_id |
 | username |     | user_id    |     | ...     |
 | ...      |     | ...        |     +---------+
 +----------+     +------------+

This is where you should consider a join. Aside from being a much more natural query, most database systems (including MySQL) have lots of smart people put lots of hard work into optimizing queries just like it. For separate queries, since each query depends on the results of the previous one, the queries can't be done in parallel, and the total time becomes not just the actual execute time of the queries, but also the time spent fetching results, sifting through them for IDs for the next query, linking rows together, etc.

How do you debug MySQL stored procedures?

I do something very similar to you.

I'll usually include a DEBUG param that defaults to false and I can set to true at run time. Then wrap the debug statements into an "If DEBUG" block.

I also use a logging table with many of my jobs so that I can review processes and timing. My Debug code gets output there as well. I include the calling param name, a brief description, row counts affected (if appropriate), a comments field and a time stamp.

Good debugging tools is one of the sad failings of all SQL platforms.

PG COPY error: invalid input syntax for integer

I think it's better to change your csv file like:


It's also possible to define your table like

  age        varchar(20),
  first_name varchar(20),
  last_name  varchar(20)

and after copy, you can convert empty strings:

select nullif(age, '')::int as age, first_name, last_name
from people

Create an array of strings

one of the simplest ways to create a string matrix is as follow :

x = [ {'first string'} {'Second parameter} {'Third text'} {'Fourth component'} ]

How to get single value from this multi-dimensional PHP array

You can also use array_column(). It's available from PHP 5.5:

It returns the values from a single column of the array, identified by the column_key. Optionally, you may provide an index_key to index the values in the returned array by the values from the index_key column in the input array.

print_r(array_column($myarray, 'email'));

Bootstrap modal: close current, open new


// same as above button id
$('#Modal_id_You_Want_to_Show').modal({backdrop: 'static', keyboard: false})});

Update statement with inner join on Oracle

Using description instead of desc for table2,

  value = (select code from table2 where description = table1.value)
  exists (select 1 from table2 where description = table1.value)
  table1.updatetype = 'blah'

Angular and Typescript: Can't find names - Error: cannot find name

Angular 2 RC1 renamed the node_modules/angular2 directory to node_modules/angular.

If you're using a gulpfile to copy files to an output directory you probably still have node_modules/angular sitting in there which may be getting picked up by the compiler and confusing the hell out of itself.

So (carefully) wipe out what you have in node_modules that is for the beta versions, and also delete any old typings and re-run typings install.

PHP + MySQL transactions examples


// trans.php
function begin(){

function commit(){

function rollback(){

mysql_connect("localhost","Dude1", "SuperSecret") or die(mysql_error());

mysql_select_db("bedrock") or die(mysql_error());

$query = "INSERT INTO employee (ssn,name,phone) values ('123-45-6789','Matt','1-800-555-1212')";

begin(); // transaction begins

$result = mysql_query($query);

    rollback(); // transaction rolls back
    echo "transaction rolled back";
    commit(); // transaction is committed
    echo "Database transaction was successful";


How to pass a datetime parameter?

This is a solution and a model for possible solutions. Use Moment.js in your client to format dates, convert to unix time.


Setup your route parameters to be long.

public async Task<object[]> Get(long? startDate)
    DateTime? sDate = new DateTime();

        if (startDate != null)
            sDate = new DateTime().FromUnixTime(startDate.Value); 
            sDate = null;
         ... your code here!

Create an extension method for Unix time. Unix DateTime Method

How to dynamically create a class?

Yes, you can use System.Reflection.Emit namespace for this. It is not straight forward if you have no experience with it, but it is certainly possible.

Edit: This code might be flawed, but it will give you the general idea and hopefully off to a good start towards the goal.

using System;
using System.Reflection;
using System.Reflection.Emit;

namespace TypeBuilderNamespace
    public static class MyTypeBuilder
        public static void CreateNewObject()
            var myType = CompileResultType();
            var myObject = Activator.CreateInstance(myType);
        public static Type CompileResultType()
            TypeBuilder tb = GetTypeBuilder();
            ConstructorBuilder constructor = tb.DefineDefaultConstructor(MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);

            // NOTE: assuming your list contains Field objects with fields FieldName(string) and FieldType(Type)
            foreach (var field in yourListOfFields)
                CreateProperty(tb, field.FieldName, field.FieldType);

            Type objectType = tb.CreateType();
            return objectType;

        private static TypeBuilder GetTypeBuilder()
            var typeSignature = "MyDynamicType";
            var an = new AssemblyName(typeSignature);
            AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run);
            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule");
            TypeBuilder tb = moduleBuilder.DefineType(typeSignature,
                    TypeAttributes.Public |
                    TypeAttributes.Class |
                    TypeAttributes.AutoClass |
                    TypeAttributes.AnsiClass |
                    TypeAttributes.BeforeFieldInit |
            return tb;

        private static void CreateProperty(TypeBuilder tb, string propertyName, Type propertyType)
            FieldBuilder fieldBuilder = tb.DefineField("_" + propertyName, propertyType, FieldAttributes.Private);

            PropertyBuilder propertyBuilder = tb.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null);
            MethodBuilder getPropMthdBldr = tb.DefineMethod("get_" + propertyName, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, propertyType, Type.EmptyTypes);
            ILGenerator getIl = getPropMthdBldr.GetILGenerator();

            getIl.Emit(OpCodes.Ldfld, fieldBuilder);

            MethodBuilder setPropMthdBldr =
                tb.DefineMethod("set_" + propertyName,
                  MethodAttributes.Public |
                  MethodAttributes.SpecialName |
                  null, new[] { propertyType });

            ILGenerator setIl = setPropMthdBldr.GetILGenerator();
            Label modifyProperty = setIl.DefineLabel();
            Label exitSet = setIl.DefineLabel();

            setIl.Emit(OpCodes.Stfld, fieldBuilder);



Is there a way to access an iteration-counter in Java's for-each loop?

The best and optimized solution is to do the following thing:

int i=0;

for(Type t: types) {

Where Type can be any data type and types is the variable on which you are applying for a loop.

Import Maven dependencies in IntelliJ IDEA

I had the similar issue with my macbook, just did a small change in pom.xml and it started downloading all dependencies:

Earlier dependencies were written as below for my windows machine:


I just removed the <dependencies> and </dependencies> tags and it started downloading all the dependencies:


I am not sure it will work for you or not.. but worked fine for me.


Why is there no SortedList in Java?

For any newcomers, as of April 2015, Android now has a SortedList class in the support library, designed specifically to work with RecyclerView. Here's the blog post about it.

How to set time to midnight for current day?

You can use the Date property of the DateTime object - eg

DateTime midnight = DateTime.Now.Date;

So your code example becomes

private DateTime _Begin = DateTime.Now.Date;
public DateTime Begin { get { return _Begin; } set { _Begin = value; } }

PS. going back to your original code setting the hours to 12 will give you time of noon for the current day, so instead you could have used 0...

var now = DateTime.Now;
new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);

"static const" vs "#define" vs "enum"

In C, specifically? In C the correct answer is: use #define (or, if appropriate, enum)

While it is beneficial to have the scoping and typing properties of a const object, in reality const objects in C (as opposed to C++) are not true constants and therefore are usually useless in most practical cases.

So, in C the choice should be determined by how you plan to use your constant. For example, you can't use a const int object as a case label (while a macro will work). You can't use a const int object as a bit-field width (while a macro will work). In C89/90 you can't use a const object to specify an array size (while a macro will work). Even in C99 you can't use a const object to specify an array size when you need a non-VLA array.

If this is important for you then it will determine your choice. Most of the time, you'll have no choice but to use #define in C. And don't forget another alternative, that produces true constants in C - enum.

In C++ const objects are true constants, so in C++ it is almost always better to prefer the const variant (no need for explicit static in C++ though).

Docker official registry (Docker Hub) URL

For those wanting to explicitly declare they are pulling from dockerhub when using fabric8 maven plugin, add a new property: <docker.pull.registry></docker.pull.registry>

I arrived on this page trying to solve problem of pulling from my AWS ECR registry when building Docker images using fabric8.

how to sort an ArrayList in ascending order using Collections and Comparator

Use the default version:


Of course this requires that your Elements implement Comparable, but the same holds true for the version you mentioned.

BTW: you should use generics in your code, that way you get compile-time errors if your class doesn't implement Comparable. And compile-time errors are much better than the runtime errors you'll get otherwise.

List<MyClass> list = new ArrayList<MyClass>();
// now fill up the list

// compile error here unless MyClass implements Comparable

Spring cannot find bean xml configuration file when it does exist

I was experiencing this issue and it was driving me nuts; I ultimately found the following lying in my POM.xml, which was the cause of the problem:


Detect if a browser in a mobile device (iOS/Android phone/tablet) is used

Don't detect mobile devices, go for stationary ones instead.

Nowadays (2016) there is a way to detect dots per inch/cm/px that seems to work in most modern browsers (see I needed a method to distinguish between a relatively small screen, orientation didn't matter, and a stationary computer monitor.

Because many mobile browsers don't support this, one can write the general css code for all cases and use this exception for large screens:

@media (max-resolution: 1dppx) {
    /* ... */

Both Windows XP and 7 have the default setting of 1 dot per pixel (or 96dpi). I don't know about other operating systems, but this works really well for my needs.

Edit: dppx doesn't seem to work in Internet Explorer.. use (96)dpi instead.

How to use a WSDL file to create a WCF service (not make a call)

There are good resources out there if you know what to search for. Try "Contract First" and WCF. or "WSDL First" and WCF.

Here is a selection:

Which Eclipse version should I use for an Android app?

I would recommend at least Eclipse Indigo (v 3.7) for Android Development because even though a minimum of Helios (v 3.6) is required for ADT 22.0.1 as explained here...

... Indigo is required for Android NDK development using CDT, as explained here:

How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?

Action Filters, jquery stringify, bleh...

Peter, this functionality is native to MVC. That's one of things that makes MVC so great.

$.post('SomeController/Batch', { 'ids': ['1', '2', '3']}, function (r) {

And in the action,

public ActionResult Batch(string[] ids)

Works like a charm:

enter image description here

If you're using jQuery 1.4+, then you want to look into setting traditional mode:

jQuery.ajaxSettings.traditional = true;

As described here:

This even works for complex objects. If you're interested, you should look into the MVC documentation about Model Binding:

Reading a file character by character in C

Here's one simple way to ignore everything but valid brainfuck characters:

#define BF_VALID "+-><[].,"

if (strchr(BF_VALID, c))
    code[n++] = c;

Why does the 260 character path length limit exist in Windows?

Quoting this article

Maximum Path Length Limitation

In the Windows API (with some exceptions discussed in the following paragraphs), the maximum length for a path is MAX_PATH, which is defined as 260 characters. A local path is structured in the following order: drive letter, colon, backslash, name components separated by backslashes, and a terminating null character. For example, the maximum path on drive D is "D:\some 256-character path string<NUL>" where "<NUL>" represents the invisible terminating null character for the current system codepage. (The characters < > are used here for visual clarity and cannot be part of a valid path string.)

Now we see that it is 1+2+256+1 or [drive][:\][path][null] = 260. One could assume that 256 is a reasonable fixed string length from the DOS days. And going back to the DOS APIs we realize that the system tracked the current path per drive, and we have 26 (32 with symbols) maximum drives (and current directories).

The INT 0x21 AH=0x47 says “This function returns the path description without the drive letter and the initial backslash.” So we see that the system stores the CWD as a pair (drive, path) and you ask for the path by specifying the drive (1=A, 2=B, …), if you specify a 0 then it assumes the path for the drive returned by INT 0x21 AH=0x15 AL=0x19. So now we know why it is 260 and not 256, because those 4 bytes are not stored in the path string.

Why a 256 byte path string, because 640K is enough RAM.

show loading icon until the page is load?

firstly, in your main page use a loading icon

then, delete your </body> and </HTML> from your main page and replace it by

<?php include('footer.php');?>

in the footer.php file type :

    $iconPath="myIcon.ico" // myIcon is the final icon
    echo '<script>changeIcon($iconPath)</script>'; // where changeIcon is a javascript function whiwh change your icon.
    echo '</body>';
    echo '</HTML>';


Exchange rate from Euro to NOK on the first of January 2016:


The INDEX() function is used because GOOGLEFINANCE() function actually prints out in 4 separate cells (2x2) when you call it with these arguments, with it the result will only be one cell.

Toggle input disabled attribute using jQuery

$('#el').prop('disabled', function(i, v) { return !v; });

The .prop() method accepts two arguments:

  • Property name (disabled, checked, selected) anything that is either true or false
  • Property value, can be:
    • (empty) - returns the current value.
    • boolean (true/false) - sets the property value.
    • function - Is executed for each found element, the returned value is used to set the property. There are two arguments passed; the first argument is the index (0, 1, 2, increases for each found element). The second argument is the current value of the element (true/false).

So in this case, I used a function that supplied me the index (i) and the current value (v), then I returned the opposite of the current value, so the property state is reversed.

How do you perform a left outer join using linq extension methods

For a (left outer) join of a table Bar with a table Foo on Foo.Foo_Id = Bar.Foo_Id in lambda notation:

var qry = Foo.GroupJoin(
          foo => foo.Foo_Id,
          bar => bar.Foo_Id,
          (x,y) => new { Foo = x, Bars = y })
           x => x.Bars.DefaultIfEmpty(),
           (x,y) => new { Foo=x.Foo, Bar=y});

How can I detect if this dictionary key exists in C#?

I use a Dictionary and because of the repetetiveness and possible missing keys, I quickly patched together a small method:

 private static string GetKey(IReadOnlyDictionary<string, string> dictValues, string keyValue)
     return dictValues.ContainsKey(keyValue) ? dictValues[keyValue] : "";

Calling it:

var entry = GetKey(dictList,"KeyValue1");

Gets the job done.

jquery multiple checkboxes array

If you have a class for each of your input box, then you can do it as

        var checked = []
        $('input.Booking').each(function ()

Email validation using jQuery

A very simple solution is to use html5 validation:

  <input type="email" required pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}">

  <input type="submit">

Slide right to left Android Animations

For sliding both activity (old and new) same direction:


<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android=""


<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android=""


<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android=""
    android:toXDelta="-100%" />


<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android=""
    android:toXDelta="100%" />

startActivity transition:

overridePendingTransition(R.anim.right_in, R.anim.left_out);

onBackPressed transition:

overridePendingTransition(R.anim.left_in, R.anim.right_out);

Difference between virtual and abstract methods

First of all you should know the difference between a virtual and abstract method.

Abstract Method

  • Abstract Method resides in abstract class and it has no body.
  • Abstract Method must be overridden in non-abstract child class.

Virtual Method

  • Virtual Method can reside in abstract and non-abstract class.
  • It is not necessary to override virtual method in derived but it can be.
  • Virtual method must have body ....can be overridden by "override keyword".....

find -exec with multiple commands

I don't know if you can do this with find, but an alternate solution would be to create a shell script and to run this with find.

echo $(tail -1 $1),$1

Make the script executable

chmod +x

Use find:

find . -name "*.txt" -exec ./ {} \;

Finding what methods a Python object has

You can make use of dir() which is pre-defined in Python.

import module_name

You can also pass an object to dir() as


If the object is an object of a pre-defined class such as int, str, etc. it displays the methods in it (you may know those methods as built in functions). If that object is created for a user-defined class, it displays all the methods given in that class.

Increase max execution time for php

There's probably a limit set in your webserver. Some browsers/proxies will also implement a timeout. Invoking long running processes via an HTTP request is just plain silly. The right way to solve the problem (assuming you can't make the processing any faster) is to use the HTTP request to trigger processing outside of the webserver session group then poll the status via HTTP until you've got a result set.

Converting VS2012 Solution to VS2010

Simple solution which worked for me.

  1. Install Vim editor for windows.
  2. Open VS 2012 project solution using Vim editor and modify the version targetting Visual studio solution 10.
  3. Open solution with Visual studio 2010.. and continue with your work ;)

Why is Java Vector (and Stack) class considered obsolete or deprecated?

Vector synchronizes on each individual operation. That's almost never what you want to do.

Generally you want to synchronize a whole sequence of operations. Synchronizing individual operations is both less safe (if you iterate over a Vector, for instance, you still need to take out a lock to avoid anyone else changing the collection at the same time, which would cause a ConcurrentModificationException in the iterating thread) but also slower (why take out a lock repeatedly when once will be enough)?

Of course, it also has the overhead of locking even when you don't need to.

Basically, it's a very flawed approach to synchronization in most situations. As Mr Brian Henk pointed out, you can decorate a collection using the calls such as Collections.synchronizedList - the fact that Vector combines both the "resized array" collection implementation with the "synchronize every operation" bit is another example of poor design; the decoration approach gives cleaner separation of concerns.

As for a Stack equivalent - I'd look at Deque/ArrayDeque to start with.

How to parse XML and count instances of a particular node attribute?

There are many options out there. cElementTree looks excellent if speed and memory usage are an issue. It has very little overhead compared to simply reading in the file using readlines.

The relevant metrics can be found in the table below, copied from the cElementTree website:

library                         time    space
xml.dom.minidom (Python 2.1)    6.3 s   80000K
gnosis.objectify                2.0 s   22000k
xml.dom.minidom (Python 2.4)    1.4 s   53000k
ElementTree 1.2                 1.6 s   14500k  
ElementTree 1.2.4/1.3           1.1 s   14500k  
cDomlette (C extension)         0.540 s 20500k
PyRXPU (C extension)            0.175 s 10850k
libxml2 (C extension)           0.098 s 16000k
readlines (read as utf-8)       0.093 s 8850k
cElementTree (C extension)  --> 0.047 s 4900K <--
readlines (read as ascii)       0.032 s 5050k   

As pointed out by @jfs, cElementTree comes bundled with Python:

  • Python 2: from xml.etree import cElementTree as ElementTree.
  • Python 3: from xml.etree import ElementTree (the accelerated C version is used automatically).

Get value from a string after a special character

Assuming you have your hidden input in a jQuery object $myHidden, you then use JavaScript (not jQuery) to get the part after ?:

var myVal = $myHidden.val ();
var tmp = myVal.substr ( myVal.indexOf ( '?' ) + 1 ); // tmp now contains whatever is after ?

Custom bullet symbol for <li> elements in <ul> that is a regular character, and not an image

Font-awesome provides a great solution out of the box:

<link href="" rel="stylesheet" />_x000D_
<ul class='fa-ul'>_x000D_
  <li><i class="fa-li fa fa-plus"></i> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam</li>_x000D_
  <li><i class="fa-li fa fa-plus"></i> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam</li>_x000D_

How to remove the left part of a string?

The pop version wasn't quite right. I think you want:

>>> print('foofoobar'.split('foo', 1).pop())

PHP code to convert a MySQL query to CSV

Look at the documentation regarding the SELECT ... INTO OUTFILE syntax.

SELECT a,b,a+b INTO OUTFILE '/tmp/result.txt'
  FROM test_table;

Split string based on a regular expression

Its very simple actually. Try this:

str1="a    b     c      d"
splitStr1 = str1.split()
print splitStr1

Linq to Entities join vs groupjoin


Suppose you have two lists:

Id  Value
1   A
2   B
3   C

Id  ChildValue
1   a1
1   a2
1   a3
2   b1
2   b2

When you Join the two lists on the Id field the result will be:

Value ChildValue
A     a1
A     a2
A     a3
B     b1
B     b2

When you GroupJoin the two lists on the Id field the result will be:

Value  ChildValues
A      [a1, a2, a3]
B      [b1, b2]
C      []

So Join produces a flat (tabular) result of parent and child values.
GroupJoin produces a list of entries in the first list, each with a group of joined entries in the second list.

That's why Join is the equivalent of INNER JOIN in SQL: there are no entries for C. While GroupJoin is the equivalent of OUTER JOIN: C is in the result set, but with an empty list of related entries (in an SQL result set there would be a row C - null).


So let the two lists be IEnumerable<Parent> and IEnumerable<Child> respectively. (In case of Linq to Entities: IQueryable<T>).

Join syntax would be

from p in Parent
join c in Child on p.Id equals c.Id
select new { p.Value, c.ChildValue }

returning an IEnumerable<X> where X is an anonymous type with two properties, Value and ChildValue. This query syntax uses the Join method under the hood.

GroupJoin syntax would be

from p in Parent
join c in Child on p.Id equals c.Id into g
select new { Parent = p, Children = g }

returning an IEnumerable<Y> where Y is an anonymous type consisting of one property of type Parent and a property of type IEnumerable<Child>. This query syntax uses the GroupJoin method under the hood.

We could just do select g in the latter query, which would select an IEnumerable<IEnumerable<Child>>, say a list of lists. In many cases the select with the parent included is more useful.

Some use cases

1. Producing a flat outer join.

As said, the statement ...

from p in Parent
join c in Child on p.Id equals c.Id into g
select new { Parent = p, Children = g }

... produces a list of parents with child groups. This can be turned into a flat list of parent-child pairs by two small additions:

from p in parents
join c in children on p.Id equals c.Id into g // <= into
from c in g.DefaultIfEmpty()               // <= flattens the groups
select new { Parent = p.Value, Child = c?.ChildValue }

The result is similar to

Value Child
A     a1
A     a2
A     a3
B     b1
B     b2
C     (null)

Note that the range variable c is reused in the above statement. Doing this, any join statement can simply be converted to an outer join by adding the equivalent of into g from c in g.DefaultIfEmpty() to an existing join statement.

This is where query (or comprehensive) syntax shines. Method (or fluent) syntax shows what really happens, but it's hard to write:

parents.GroupJoin(children, p => p.Id, c => c.Id, (p, c) => new { p, c })
       .SelectMany(x => x.c.DefaultIfEmpty(), (x,c) => new { x.p.Value, c?.ChildValue } )

So a flat outer join in LINQ is a GroupJoin, flattened by SelectMany.

2. Preserving order

Suppose the list of parents is a bit longer. Some UI produces a list of selected parents as Id values in a fixed order. Let's use:

var ids = new[] { 3,7,2,4 };

Now the selected parents must be filtered from the parents list in this exact order.

If we do ...

var result = parents.Where(p => ids.Contains(p.Id));

... the order of parents will determine the result. If the parents are ordered by Id, the result will be parents 2, 3, 4, 7. Not good. However, we can also use join to filter the list. And by using ids as first list, the order will be preserved:

from id in ids
join p in parents on id equals p.Id
select p

The result is parents 3, 7, 2, 4.

MySQL convert date string to Unix timestamp

Here's an example of how to convert DATETIME to UNIX timestamp:
SELECT UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p'))

Here's an example of how to change date format:
SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p')),'%m-%d-%Y %h:%i:%p')


Querying date field in MongoDB with Mongoose

{ "date" : "1000000" } in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }

It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback) and if that works, you have a typing issue.

Make a UIButton programmatically in Swift

Swift 4.2 - XCode 10.1

Using a closure

let button: UIButton = {
  let button = UIButton(type: .system)
  button.titleLabel?.font = UIFont.systemFont(ofSize: 20)
  return button

Simple JavaScript login form validation

Here is some useful links with example Login form Validation in javascript

function validate() {
        var username = document.getElementById("username").value;
        var password = document.getElementById("password").value;
        if (username == null || username == "") {
            alert("Please enter the username.");
            return false;
        if (password == null || password == "") {
            alert("Please enter the password.");
            return false;
        alert('Login successful');


  <input type="text" name="username" id="username" />
  <input type="password" name="password" id="password" />
  <input type="button" value="Login" id="submit" onclick="validate();" />

How to Get a Sublist in C#

Use the Where clause from LINQ:

List<object> x = new List<object>();

var z = x.Where(p => p == "A");
z = x.Where(p => p == "B");

In the statements above "p" is the object that is in the list. So if you used a data object, i.e.:

public class Client
    public string Name { get; set; }

then your linq would look like this:

List<Client> x = new List<Client>();
x.Add(new Client() { Name = "A" });
x.Add(new Client() { Name = "B" });
x.Add(new Client() { Name = "C" });
x.Add(new Client() { Name = "D" });
x.Add(new Client() { Name = "B" });

var z = x.Where(p => p.Name == "A");
z = x.Where(p => p.Name == "B");

Why can't I do <img src="C:/localfile.jpg">?

IE 9 : If you want that the user takes a look at image before he posts it to the server : The user should ADD the website to "trusted Website list".

Is there a rule-of-thumb for how to divide a dataset into training and validation sets?

Perhaps a 63.2% / 36.8% is a reasonable choice. The reason would be that if you had a total sample size n and wanted to randomly sample with replacement (a.k.a. re-sample, as in the statistical bootstrap) n cases out of the initial n, the probability of an individual case being selected in the re-sample would be approximately 0.632, provided that n is not too small, as explained here:

For a sample of n=250, the probability of an individual case being selected for a re-sample to 4 digits is 0.6329. For a sample of n=20000, the probability is 0.6321.

How to find out what character key is pressed?

There are a million duplicates of this question on here, but here goes again anyway:

document.onkeypress = function(evt) {
    evt = evt || window.event;
    var charCode = evt.keyCode || evt.which;
    var charStr = String.fromCharCode(charCode);

The best reference on key events I've seen is

How to align checkboxes and their labels consistently cross-browsers

So I know this has been answered many times, but I feel I have a way more elegant solution than those that have been provided already. And not only 1 elegant solution, but 2 separate solutions to tickle your fancy. With that said, everything you need to know and see are contained in 2 JS Fiddle's, with comments.

Solution #1 relies on the native "Checkbox" of the given browser, though with a twist... Its contained in a div which is easier to position cross-browser, with an overflow: hidden to chop the excess of a 1px stretched checkbox (this is so you cant see the ugly borders of FF)

Simple HTML: (follow the link to review the css with comments, code block is to satisfy stackoverflow)

<label><div class="checkbox"><input type="checkbox" /></div> Label text</label>

Solution #2 uses the "Checkbox Toggle Hack" to toggle the CSS state of a DIV, which has been properly positioned across browser, and setup with a simple sprite for the checkbox unchecked and checked states. All that is needed is to adjust the background-position with said Checkbox Toggle Hack. This, in my opinion, is the more elegant solution as you have more control over your checkboxes & radios, and can guarantee they look the same across browser.

Simple HTML: (follow the link to review the CSS with comments, code block is to satisfy StackOverflow)

<label><input type="checkbox" /><div class="checkbox"></div>Label text</label>

If anyone disagree's with these methods, please leave me a comment, I would love to hear some feedback on why others have not come across these solutions, or if they have, why I see no answers here regarding them? If anyone sees one of these methods fail, it would be nice to see that too, but these have been tested in the latest browsers and rely on HTML / CSS methods that are quite old, and universal as far as I have seen.

Apache VirtualHost 403 Forbidden

I just spent several hours on this stupid problem

First, change permissions using this in terminal

find htdocs -type f -exec chmod 664 {} + -o -type d -exec chmod 775 {} +

I don't know what the difference is between 664 and 775 I did both 775 like this Also htdocs needs the directory path for instance for me it was


find htdocs -type f -exec chmod 775 {} + -o -type d -exec chmod 775 {} +

This is the other dumb thing too

make sure that your image src link is your domain name for instance


Be sure to have

EnableSendfile off in httpd.conf file
EnableMMAP off in httpd.conf file

You edit those using pico in terminal

I also created a directory for images specifically so that when you type in the browser address bar, you will get a list of photos which can be downloaded and need to be downloaded successfully to indicate image files that are working properly

<Directory /usr/local/apache2/htdocs/images>
AddType images/png .png

And those are the solutions I have tried, now I have functioning images... yay!!!

Onto the next problem(s)

How to concatenate two strings to build a complete path

Won't simply concatenating the part of your path accomplish what you want?

$ base="/home/user1/MyFolder/"
$ subdir="subFold1"
$ new_path=$base$subdir
$ echo $new_path

You can then create the folders/directories as needed.

One convention is to end directory paths with / (e.g. /home/) because paths starting with a / could be confused with the root directory. If a double slash (//) is used in a path, it is also still correct. But, if no slash is used on either variable, it would be incorrect (e.g. /home/user1/MyFoldersubFold1).

How can I reuse a navigation bar on multiple pages?

You can use php for making multi-page website.

  • Create a header.php in which you should put all your html code for menu's and social media etc
  • Insert header.php in your index.php using following code

<? php include 'header.php'; ?>

(Above code will dump all html code before this)Your site body content.

  • Similarly you can create footer and other elements with ease. PHP built-in support html code in their extensions. So, better learn this easy fix.

How to show all of columns name on pandas dataframe?

To obtain all the column names of a DataFrame, df_data in this example, you just need to use the command df_data.columns.values. This will show you a list with all the Column names of your Dataframe




['PassengerId' 'Survived' 'Pclass' 'Name' 'Sex' 'Age' 'SibSp' 'Parch' 'Ticket' 'Fare' 'Cabin' 'Embarked']

This certificate has an invalid issuer Apple Push Services

This is not actually a development issue. It happens due to expiration of the Apple Worldwide Developer Relations Intermediate Certificate issued by Apple Worldwide Developer Relations Certificate Authority. WWDRCA issues the certificate to sign your software for Apple devices, allowing our systems to confirm that your software is delivered to users as intended and has not been modified.

To resolve this issue, you have to follow the below steps:

  1. Open Keychain Access
  2. Go to View -> Show Expired Certificates

Enter image description here

  1. Go to System in Keychain Enter image description here

  2. Here you find that "Apple Worldwide Developer Relations Certificate Authority" is marked as expired. So delete it. Also check under Login Tab and delete expired WWDRCA.

  3. Download new WWDR Intermediate Certificate from here(The renewed Apple Worldwide Developer Relations Certification Intermediate Certificate will expire on February 7, 2023).

  4. Install it by double clicking on it.

If you still face any issue with your iOS apps, Mac apps, Safari extensions, Apple Wallet and Safari push notifications, then please follow this link of expiration.

The Apple Worldwide Developer Relations Certification Intermediate Certificate expires soon and we've issued a renewed certificate that must be included when signing all new Apple Wallet Passes, push packages for Safari Push Notifications, and Safari Extensions starting February 14, 2016.

While most developers and users will not be affected by the certificate change, we recommend that all developers download and install the renewed certificate on their development systems and servers as a best practice. All apps will remain available on the App Store for iOS, Mac, and Apple TV.

How to Convert string "07:35" (HH:MM) to TimeSpan

While correct that this will work:

TimeSpan time = TimeSpan.Parse("07:35");

And if you are using it for validation...

TimeSpan time;
if (!TimeSpan.TryParse("07:35", out time))
    // handle validation error

Consider that TimeSpan is primarily intended to work with elapsed time, rather than time-of-day. It will accept values larger than 24 hours, and will accept negative values also.

If you need to validate that the input string is a valid time-of-day (>= 00:00 and < 24:00), then you should consider this instead:

DateTime dt;
if (!DateTime.TryParseExact("07:35", "HH:mm", CultureInfo.InvariantCulture, 
                                              DateTimeStyles.None, out dt))
    // handle validation error
TimeSpan time = dt.TimeOfDay;

As an added benefit, this will also parse 12-hour formatted times when an AM or PM is included, as long as you provide the appropriate format string, such as "h:mm tt".

Set opacity of background image without affecting child elements

#footer ul li
    #footer ul li:before
       background-image: url(imagesFolder/bg_demo.png);
       content: "";
       top: 5px;
       left: -10px;
       bottom: 0;
       right: 0;
       position: absolute;
       z-index: -1;
       opacity: 0.5;

You can try this code. I think it will be worked. You can visit the demo

unable to start mongodb local server


sudo service mongod stop
sudo mongod

To stop current active mongodb service, allowing you to then start a new one

Oracle Date datatype, transformed to 'YYYY-MM-DD HH24:MI:SS TMZ' through SQL

to convert a TimestampTZ in oracle, you do

TO_TIMESTAMP_TZ('2012-10-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') 
  at time zone 'region'

see here:

and here for regions:


SQL> select a, sys_extract_utc(a), a at time zone '-05:00' from (select TO_TIMESTAMP_TZ('2013-04-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);

09-APR-13 CST
09-APR-13 -05:00

SQL> select a, sys_extract_utc(a), a at time zone '-05:00' from (select TO_TIMESTAMP_TZ('2013-03-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);

09-MAR-13 CST
09-MAR-13 -05:00

SQL> select a, sys_extract_utc(a), a at time zone 'America/Los_Angeles' from (select TO_TIMESTAMP_TZ('2013-04-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);

09-APR-13 CST

XML element with attribute and content using JAXB

The correct scheme should be:

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="" 

<complexType name="sportType">
        <extension base="string">
            <attribute name="type" type="string" />
            <attribute name="gender" type="string" />

<element name="sports">
            <element name="sport" minOccurs="0" maxOccurs="unbounded"
                type="tns:sportType" />

Code generated for SportType will be:


import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;

@XmlType(name = "sportType")
public class SportType {
    protected String value;
    protected String type;
    protected String gender;

    public String getValue() {
        return value;

    public void setValue(String value) {
        this.value = value;

    public String getType() {
    return type;

    public void setType(String value) {
        this.type = value;

    public String getGender() {
        return gender;

    public void setGender(String value) {
        this.gender = value;

keyCode values for numeric keypad?

You can use the key code page in order to find the:


to diference the number keyboard.

function getNumberFromKeyEvent(event) {
   if (event.code.indexOf('Numpad') === 0) {
      var number = parseInt(event.code.replace('Numpad', ''), 10);
      if (number >= 0 && number <= 9) {
           // numbers from numeric keyboard

How to cast or convert an unsigned int to int in C?

It depends on what you want the behaviour to be. An int cannot hold many of the values that an unsigned int can.

You can cast as usual:

int signedInt = (int) myUnsigned;

but this will cause problems if the unsigned value is past the max int can hold. This means half of the possible unsigned values will result in erroneous behaviour unless you specifically watch out for it.

You should probably reexamine how you store values in the first place if you're having to convert for no good reason.

EDIT: As mentioned by ProdigySim in the comments, the maximum value is platform dependent. But you can access it with INT_MAX and UINT_MAX.

For the usual 4-byte types:

4 bytes = (4*8) bits = 32 bits

If all 32 bits are used, as in unsigned, the maximum value will be 2^32 - 1, or 4,294,967,295.

A signed int effectively sacrifices one bit for the sign, so the maximum value will be 2^31 - 1, or 2,147,483,647. Note that this is half of the other value.

How to pass an object from one activity to another on Android

As mentioned in the comments, this answer breaks encapsulation and tightly couples components, which is very likely not what you want. The best solution is probably making your object Parcelable or Serializable, as other responses explain. Having said that, the solution solves the problem. So if you know what you are doing:

Use a class with static fields:

public class Globals {
    public static Customer customer = new Customer();

Inside the activities you can use:

Activity From:

Globals.customer = myCustomerFromActivity;

Activity Target:

myCustomerTo = Globals.customer;

It's an easy way to pass information for activities.

How to directly move camera to current location in Google Maps Android API v2?

make sure you have these permissions:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

Then make some activity and register a LocationListener

package com.example.location;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;

public class LocationActivity extends SherlockFragmentActivity implements LocationListener     {
private GoogleMap map;
private LocationManager locationManager;
private static final long MIN_TIME = 400;
private static final float MIN_DISTANCE = 1000;

protected void onCreate(Bundle savedInstanceState) {
    map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(;

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this); //You can also use LocationManager.GPS_PROVIDER and LocationManager.PASSIVE_PROVIDER        

public void onLocationChanged(Location location) {
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);

public void onStatusChanged(String provider, int status, Bundle extras) { }

public void onProviderEnabled(String provider) { }

public void onProviderDisabled(String provider) { }


<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android=""

PHP Multiple Checkbox Array

add [] in the name of the attributes in the input tag

 <form action="" name="frm" method="post">
<input type="checkbox" name="hobby[]" value="coding">  coding &nbsp
<input type="checkbox" name="hobby[]" value="database">  database &nbsp
<input type="checkbox" name="hobby[]" value="software engineer">  soft Engineering <br>
<input type="submit" name="submit" value="submit"> 

for PHP Code :

   $hobby = $_POST['hobby'];

   foreach ($hobby as $hobys=>$value) {
             echo "Hobby : ".$value."<br />";

.NET - How do I retrieve specific items out of a Dataset?

The DataSet object has a Tables array. If you know the table you want, it will have a Row array, each object of which has an ItemArray array. In your case the code would most likely be

int var1 = int.Parse(ds.Tables[0].Rows[0].ItemArray[4].ToString());

and so forth. This would give you the 4th item in the first row. You can also use Columns instead of ItemArray and specify the column name as a string instead of remembering it's index. That approach can be easier to keep up with if the table structure changes. So that would be

int var1 = int.Parse(ds.Tables[0].Rows[0]["MyColumnName"].ToString());

Convert float to double without losing precision

Use a BigDecimal instead of float/double. There are a lot of numbers which can't be represented as binary floating point (for example, 0.1). So you either must always round the result to a known precision or use BigDecimal.

See for more information.

How to make matrices in Python?

I got a simple fix to this by casting the lists into strings and performing string operations to get the proper print out of the matrix.

Creating the function

By creating a function, it saves you the trouble of writing the for loop every time you want to print out a matrix.

def print_matrix(matrix):
    for row in matrix:
        new_row = str(row)
        new_row = new_row.replace(',','')
        new_row = new_row.replace('[','')
        new_row = new_row.replace(']','')


Example of a 5x5 matrix with 0 as every entry:

>>> test_matrix = [[0] * 5 for i in range(5)]
>>> print_matrix(test_matrix)
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0 

Example of a 2x3 matrix with 0 as every entry:

>>> test_matrix = [[0] * 3 for i in range(2)]
>>> print_matrix(test_matrix)
0 0 0
0 0 0


If you want to make it print:

D D D D D 

I suggest you just change the way you enter your data into your lists within lists. In my method, each list within the larger list represents a line in the matrix, not columns.

ECONNREFUSED error when connecting to mongodb from node.js

I also got stucked with same problem so I fixed it like this :

If you are running mongo and nodejs in docker container or in docker compose

so replace localhost with mongo (which is container name in docker in my case) something like this below in your nodejs mongo connection file.

var mongoURI = "mongodb://mongo:27017/<nodejs_container_name>";

Style the first <td> column of a table differently

To select the first column of a table you can use this syntax

tr td:nth-child(1n + 2){
  padding-left: 10px;

Show spinner GIF during an $http request in AngularJS?

create directive with this code:

$scope.$watch($http.pendingRequests, toggleLoader);

function toggleLoader(status){
  } else {

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

A bit late to the party but still - I prefer using numpy where:

import numpy as np
df['First Season'] = np.where(df['First Season'] > 1990, 1, df['First Season'])

Unknown SSL protocol error in connection

I get the same problem. With the last version of git and no proxy.

I fixed it:

  • sign in the GitHub
  • enter the interface: "Personal settings", then click "SSH Keys" please confirm whether you have put the '' that generated by the command
  • 'ssh-keygen -t rsa ' on windows into github --> GIT BASH
  • 'Add SSH key' and put the '' into it.

More info: create the key

copy the key

Android: show/hide a view using an animation

Try this.

    .setListener(new AnimatorListenerAdapter() {
        public void onAnimationEnd(Animator animation) {

Warning as error - How to get rid of these

The top answer is outdated for Visual Studio 2015.


Configuration Properties -> C/C++ -> General -> Treat Warning As Errors


Konfigurationseigenschaften -> C/C++ -> Allgemein -> Warnungen als Fehler behandeln

Or use this image as reference, way easier to quickly mentally figure out the location:

enter image description here

How can I generate a self-signed certificate with SubjectAltName using OpenSSL?

Can someone help me with the exact syntax?

It's a three-step process, and it involves modifying the openssl.cnf file. You might be able to do it with only command line options, but I don't do it that way.

Find your openssl.cnf file. It is likely located in /usr/lib/ssl/openssl.cnf:

$ find /usr/lib -name openssl.cnf

On my Debian system, /usr/lib/ssl/openssl.cnf is used by the built-in openssl program. On recent Debian systems it is located at /etc/ssl/openssl.cnf

You can determine which openssl.cnf is being used by adding a spurious XXX to the file and see if openssl chokes.

First, modify the req parameters. Add an alternate_names section to openssl.cnf with the names you want to use. There are no existing alternate_names sections, so it does not matter where you add it.

[ alternate_names ]

DNS.1        =
DNS.2        =
DNS.3        =
DNS.4        =

Next, add the following to the existing [ v3_ca ] section. Search for the exact string [ v3_ca ]:

subjectAltName      = @alternate_names

You might change keyUsage to the following under [ v3_ca ]:

keyUsage = digitalSignature, keyEncipherment

digitalSignature and keyEncipherment are standard fare for a server certificate. Don't worry about nonRepudiation. It's a useless bit thought up by computer science guys/gals who wanted to be lawyers. It means nothing in the legal world.

In the end, the IETF (RFC 5280), browsers and CAs run fast and loose, so it probably does not matter what key usage you provide.

Second, modify the signing parameters. Find this line under the CA_default section:

# Extension copying option: use with caution.
# copy_extensions = copy

And change it to:

# Extension copying option: use with caution.
copy_extensions = copy

This ensures the SANs are copied into the certificate. The other ways to copy the DNS names are broken.

Third, generate your self-signed certificate:

$ openssl genrsa -out private.key 3072
$ openssl req -new -x509 -key private.key -sha256 -out certificate.pem -days 730
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.

Finally, examine the certificate:

$ openssl x509 -in certificate.pem -text -noout
        Version: 3 (0x2)
        Serial Number: 9647297427330319047 (0x85e215e5869042c7)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
            Not Before: Feb  1 05:23:05 2014 GMT
            Not After : Feb  1 05:23:05 2016 GMT
        Subject: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (3072 bit)
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
            X509v3 Authority Key Identifier:

            X509v3 Basic Constraints: critical
            X509v3 Key Usage:
                Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign
            X509v3 Subject Alternative Name:
    Signature Algorithm: sha256WithRSAEncryption

getDate with Jquery Datepicker

You can format the jquery date with this line:


Difference between clustered and nonclustered index

A comparison of a non-clustered index with a clustered index with an example

As an example of a non-clustered index, let’s say that we have a non-clustered index on the EmployeeID column. A non-clustered index will store both the value of the


AND a pointer to the row in the Employee table where that value is actually stored. But a clustered index, on the other hand, will actually store the row data for a particular EmployeeID – so if you are running a query that looks for an EmployeeID of 15, the data from other columns in the table like

EmployeeName, EmployeeAddress, etc

. will all actually be stored in the leaf node of the clustered index itself.

This means that with a non-clustered index extra work is required to follow that pointer to the row in the table to retrieve any other desired values, as opposed to a clustered index which can just access the row directly since it is being stored in the same order as the clustered index itself. So, reading from a clustered index is generally faster than reading from a non-clustered index.

How to reset settings in Visual Studio Code?

On Linux environment delete the folder "~/.config/Code" to reset Visual Studio Code Settings.

Replace specific text with a redacted version using Python

You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.

NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.


Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.


NER with spacy

Just be aware that this is not 100%!

Here are a little snippet for you to try out:

import spacy

phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
   doc = nlp(phrase)
   replaced = ""
   for token in doc:
      if token in doc.ents:
         replaced+="XXXX "
         replaced+=token.text+" "

Read more here:

You could, instead of replacing with XXXX, replace based on the entity type, like:

if ent.label_ == "PERSON":
   replaced += "<PERSON> "


import re, random

personames = ["Jack", "Mike", "Bob", "Dylan"]

phrase = re.replace("<PERSON>", random.choice(personames), phrase)

Including external HTML file to another HTML file

The iframe element.

<iframe src="name.html"></iframe>

But content that you way to have appear on multiple pages is better handled using templates.

Change onclick action with a Javascript function

I recommend this approach:

Instead of having two click handlers, have only one function with a if-else statement. Let the state of the BUTTON element determine which branch of the if-else statement gets executed:


<button id="a" onclick="toggleError(this)">Button A</button>


function toggleError(button) { 
    if ( button.className === 'visible' ) {
        // HIDE ERROR
        button.className = '';
    } else {
        // SHOW ERROR
        button.className = 'visible';

Live demo:

Serializing list to JSON

Yes, but then what do you do about the django objects? simple json tends to choke on them.

If the objects are individual model objects (not querysets, e.g.), I have occasionally stored the model object type and the pk, like so:

seralized_dict = simplejson.dumps(my_dict, 
                     default=lambda a: "[%s,%s]" % (str(type(a)),

to de-serialize, you can reconstruct the object referenced with model.objects.get(). This doesn't help if you are interested in the object details at the type the dict is stored, but it's effective if all you need to know is which object was involved.

How to know whether refresh button or browser back button is clicked in Firefox

For Back Button in jquery //

 jQuery(window).bind("unload", function() { //

and in html5 there is an event The event is called 'popstate'

window.onpopstate = function(event) {
alert("location: " + document.location + ", state: " + JSON.stringify(event.state));

and for refresh please check Check if page gets reloaded or refreshed in Javascript

In Mozilla Client-x and client-y is inside document area

Proper usage of Optional.ifPresent()

In addition to @JBNizet's answer, my general use case for ifPresent is to combine .isPresent() and .get():

Old way:

Optional opt = getIntOptional();
if(opt.isPresent()) {
    Integer value = opt.get();
    // do something with value

New way:

Optional opt = getIntOptional();
opt.ifPresent(value -> {
    // do something with value

This, to me, is more intuitive.

How to run Maven from another directory (without cd to project dir)?

You can use the parameter -f (or --file) and specify the path to your pom file, e.g. mvn -f /path/to/pom.xml

This runs maven "as if" it were in /path/to for the working directory.

Problems with jQuery getJSON using local files in Chrome

This is a known issue with Chrome.

Here's the link in the bug tracker:

Issue 40787: Local files doesn't load with Ajax

How to read multiple Integer values from a single line of input in Java?

Java 8

BufferedReader in = new BufferedReader(new InputStreamReader(;
int arr[] =" ")).mapToInt(Integer::parseInt).toArray();

splitting a string based on tab in the file

Split on tab, but then remove all blank matches.

text = "hi\tthere\t\t\tmy main man"
print [splits for splits in text.split("\t") if splits is not ""]


['hi', 'there', 'my main man']

How to add a search box with icon to the navbar in Bootstrap 3?

I tried @PhilNicholas 's code and got the same problem of @its_me said in the comments that search bar show up on the next line of navbar, and I found that form need to be added an attribute width.

<form role="search" style="width: 15em; margin: 0.3em 2em;">
    <div class="input-group">
        <input type="text" class="form-control" placeholder="Search">
        <div class="input-group-btn">
            <button type="submit" class="btn btn-default">
                <span class="glyphicon glyphicon-search"></span>