Programs & Examples On #Shorthand if

How do I use the ternary operator ( ? : ) in PHP as a shorthand for "if / else"?

Conditional Welcome Message

echo 'Welcome '.($user['is_logged_in'] ? $user['first_name'] : 'Guest').'!';

Nested PHP Shorthand

echo 'Your score is:  '.($score > 10 ? ($age > 10 ? 'Average' : 'Exceptional') : ($age > 10 ? 'Horrible' : 'Average') );

How to call one shell script from another shell script?

pathToShell="/home/praveen/"   
chmod a+x $pathToShell"myShell.sh"
sh $pathToShell"myShell.sh"

Using Gradle to build a jar with dependencies

Update: In newer Gradle versions (4+) the compile qualifier is deprecated in favour of the new api and implementation configurations. If you use these, the following should work for you:

// Include dependent libraries in archive.
mainClassName = "com.company.application.Main"

jar {
  manifest { 
    attributes "Main-Class": "$mainClassName"
  }  

  from {
    configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
  }
}

For older gradle versions, or if you still use the "compile" qualifier for your dependencies, this should work:

// Include dependent libraries in archive.
mainClassName = "com.company.application.Main"

jar {
  manifest { 
    attributes "Main-Class": "$mainClassName"
  }  

  from {
    configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
  }
}

Note that mainClassName must appear BEFORE jar {.

jQuery AutoComplete Trigger Change Event

$('#search').autocomplete( { source: items } );
$('#search:focus').autocomplete('search', $('#search').val() );

This seems to be the only one that worked for me.

How to get just the date part of getdate()?

If you are using SQL Server 2008 or later

select convert(date, getdate())

Otherwise

select convert(varchar(10), getdate(),120)

What is base 64 encoding used for?

Aside from what's already been said, two very common uses that have not been listed are

Hashes:

Hashes are one-way functions that transform a block of bytes into another block of bytes of a fixed size such as 128bit or 256bit (SHA/MD5). Converting the resulting bytes into Base64 makes it much easier to display the hash especially when you are comparing a checksum for integrity. Hashes are so often seen in Base64 that many people mistake Base64 itself as a hash.

Cryptography:

Since an encryption key does not have to be text but raw bytes it is sometimes necessary to store it in a file or database, which Base64 comes in handy for. Same with the resulting encrypted bytes.

Note that although Base64 is often used in cryptography is not a security mechanism. Anyone can convert the Base64 string back to its original bytes, so it should not be used as a means for protecting data, only as a format to display or store raw bytes more easily.

Certificates

x509 certificates in PEM format are base 64 encoded. http://how2ssl.com/articles/working_with_pem_files/

Pass a data.frame column name to a function

You can just use the column name directly:

df <- data.frame(A=1:10, B=2:11, C=3:12)
fun1 <- function(x, column){
  max(x[,column])
}
fun1(df, "B")
fun1(df, c("B","A"))

There's no need to use substitute, eval, etc.

You can even pass the desired function as a parameter:

fun1 <- function(x, column, fn) {
  fn(x[,column])
}
fun1(df, "B", max)

Alternatively, using [[ also works for selecting a single column at a time:

df <- data.frame(A=1:10, B=2:11, C=3:12)
fun1 <- function(x, column){
  max(x[[column]])
}
fun1(df, "B")

How to run Python script on terminal?

Let's say your script is called my_script.py and you have put it in your Downloads folder.

There are many ways of installing Python, but homebrew is the easiest.

0) Open Terminal.app

1) Install homebrew (by pasting the following text into Terminal.app and pressing the Enter key)

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

2) Install Python using homebrew

brew install python

3) cd into the directory that contains your Python script (as an example I'm using the Downloads (Downloads) folder in your home (~) folder):

cd ~/Downloads

4) Run the script using the python3 executable

python3 my_script.py

You can also skip step 3 and give python3 an absolute path instead

python3 ~/Downloads/my_script.py

Instead of typing out that whole thing (~/Downloads/my_script.py), you can find the .py file in Finder.app and just drag it into the Terminal.app window which should type out the path for you.

If you have spaces or certain other symbols somewhere in your filename you need to enclose the file name in quotes:

python3 "~/Downloads/some directory with spaces/and a filename with a | character.py"

Note that you need to install it as brew install python but later use the command python3 (with a 3 at the end).

Upload a file to Amazon S3 with NodeJS

Thanks to David as his solution helped me come up with my solution for uploading multi-part files from my Heroku hosted site to S3 bucket. I did it using formidable to handle incoming form and fs to get the file content. Hopefully, it may help you.

api.service.ts

public upload(files): Observable<any> {  
    const formData: FormData = new FormData(); 
    files.forEach(file => {
      // create a new multipart-form for every file 
      formData.append('file', file, file.name);           
    });   
    return this.http.post(uploadUrl, formData).pipe(
      map(this.extractData),
      catchError(this.handleError)); 
  }
}

server.js

app.post('/api/upload', upload);
app.use('/api/upload', router);

upload.js

const IncomingForm = require('formidable').IncomingForm;
const fs = require('fs');
const AWS = require('aws-sdk');

module.exports = function upload(req, res) {
    var form = new IncomingForm();

    const bucket = new AWS.S3(
      {
        signatureVersion: 'v4',
        accessKeyId: process.env.AWS_ACCESS_KEY_ID,
        secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
        region: 'us-east-1'       
      }
    ); 

    form.on('file', (field, file) => {

        const fileContent = fs.readFileSync(file.path);

        const s3Params = {
            Bucket: process.env.AWS_S3_BUCKET,
            Key: 'folder/' + file.name,
            Expires: 60,             
            Body: fileContent,
            ACL: 'public-read'
        };

        bucket.upload(s3Params, function(err, data) {
            if (err) {
                throw err;
            }            
            console.log('File uploaded to: ' + data.Location);
            fs.unlink(file.path, function (err) {
              if (err) {
                  console.error(err);
              }
              console.log('Temp File Delete');
          });
        });
    });              

    // The second callback is called when the form is completely parsed. 
    // In this case, we want to send back a success status code.
    form.on('end', () => {        
      res.status(200).json('upload ok');
    });

    form.parse(req);
}

upload-image.component.ts

import { Component, OnInit, ViewChild, Output, EventEmitter, Input } from '@angular/core';
import { ApiService } from '../api.service';
import { MatSnackBar } from '@angular/material/snack-bar';

@Component({
  selector: 'app-upload-image',
  templateUrl: './upload-image.component.html',
  styleUrls: ['./upload-image.component.css']
})

export class UploadImageComponent implements OnInit {
  public files: Set<File> = new Set();
  @ViewChild('file', { static: false }) file;
  public uploadedFiles: Array<string> = new Array<string>();
  public uploadedFileNames: Array<string> = new Array<string>();
  @Output() filesOutput = new EventEmitter<Array<string>>();
  @Input() CurrentImage: string;
  @Input() IsPublic: boolean;
  @Output() valueUpdate = new EventEmitter();
  strUploadedFiles:string = '';
  filesUploaded: boolean = false;     

  constructor(private api: ApiService, public snackBar: MatSnackBar,) { }

  ngOnInit() {    
  }

  updateValue(val) {  
    this.valueUpdate.emit(val);  
  }  

  reset()
  {
    this.files = new Set();
    this.uploadedFiles = new Array<string>();
    this.uploadedFileNames = new Array<string>();
    this.filesUploaded = false;
  }

  upload() { 

    this.api.upload(this.files).subscribe(res => {   
      this.filesOutput.emit(this.uploadedFiles); 
      if (res == 'upload ok')
      {
        this.reset(); 
      }     
    }, err => {
      console.log(err);
    });
  }

  onFilesAdded() {
    var txt = '';
    const files: { [key: string]: File } = this.file.nativeElement.files;

    for (let key in files) {
      if (!isNaN(parseInt(key))) {

        var currentFile = files[key];
        var sFileExtension = currentFile.name.split('.')[currentFile.name.split('.').length - 1].toLowerCase();
        var iFileSize = currentFile.size;

        if (!(sFileExtension === "jpg" 
              || sFileExtension === "png") 
              || iFileSize > 671329) {
            txt = "File type : " + sFileExtension + "\n\n";
            txt += "Size: " + iFileSize + "\n\n";
            txt += "Please make sure your file is in jpg or png format and less than 655 KB.\n\n";
            alert(txt);
            return false;
        }

        this.files.add(files[key]);
        this.uploadedFiles.push('https://gourmet-philatelist-assets.s3.amazonaws.com/folder/' + files[key].name);
        this.uploadedFileNames.push(files[key].name);
        if (this.IsPublic && this.uploadedFileNames.length == 1)
        {
          this.filesUploaded = true;
          this.updateValue(files[key].name);
          break;
        } 
        else if (!this.IsPublic && this.uploadedFileNames.length == 3)
        {
          this.strUploadedFiles += files[key].name;          
          this.updateValue(this.strUploadedFiles); 
          this.filesUploaded = true;
          break;
        }
        else
        {
          this.strUploadedFiles += files[key].name + ",";          
          this.updateValue(this.strUploadedFiles); 
        }      
      }
    }    
  }

  addFiles() {
    this.file.nativeElement.click();  
  }

  openSnackBar(message: string, action: string) {
    this.snackBar.open(message, action, {
      duration: 2000,
      verticalPosition: 'top'
    });
  }   

}

upload-image.component.html

<input type="file" #file style="display: none" (change)="onFilesAdded()" multiple />
&nbsp;<button mat-raised-button color="primary" 
         [disabled]="filesUploaded" (click)="$event.preventDefault(); addFiles()">
  Add Files
</button>
&nbsp;<button class="btn btn-success" [disabled]="uploadedFileNames.length == 0" (click)="$event.preventDefault(); upload()">
  Upload
</button>

Remove trailing zeros from decimal in SQL Server

Try this:

select Cast( Cast( (ROUND( 35.457514 , 2) *100) as Int) as float ) /100

How to dismiss keyboard iOS programmatically when pressing return

SWIFT 4:

self.view.endEditing(true)

or

Set text field's delegate to current viewcontroller and then:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    textField.resignFirstResponder()

    return true

}

Objective-C:

[self.view endEditing:YES];

or

Set text field's delegate to current viewcontroller and then:

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];

    return YES;
}

How to differentiate single click event and double click event?

let clickTimes = 0;
let timer = null;
roundBox.click = function (e) {
  clearTimeout(timer);
  timer = setTimeout(() => { // ????
    console.log("single click");
  }, 600);
  clickTimes++;

  if (clickTimes == 2) { // ??
    clearTimeout(timer);
    clickTimes = 0;
    console.log("double click");
    toggleExpanded(id);
  }
}

JQuery create a form and add elements to it programmatically

var form = $("<form/>", 
                 { action:'/myaction' }
            );
form.append( 
    $("<input>", 
         { type:'text', 
           placeholder:'Keywords', 
           name:'keyword', 
           style:'width:65%' }
     )
);

form.append( 
     $("<input>", 
          { type:'submit', 
            value:'Search', 
            style:'width:30%' }
       )
);

$("#someDivId").append(form);

Function in JavaScript that can be called only once

UnderscoreJs has a function that does that, underscorejs.org/#once

  // Returns a function that will be executed at most one time, no matter how
  // often you call it. Useful for lazy initialization.
  _.once = function(func) {
    var ran = false, memo;
    return function() {
      if (ran) return memo;
      ran = true;
      memo = func.apply(this, arguments);
      func = null;
      return memo;
    };
  };

What is external linkage and internal linkage?

Linkage determines whether identifiers that have identical names refer to the same object, function, or other entity, even if those identifiers appear in different translation units. The linkage of an identifier depends on how it was declared. There are three types of linkages:

  1. Internal linkage : identifiers can only be seen within a translation unit.
  2. External linkage : identifiers can be seen (and referred to) in other translation units.
  3. No linkage : identifiers can only be seen in the scope in which they are defined. Linkage does not affect scoping

C++ only : You can also have linkage between C++ and non-C++ code fragments, which is called language linkage.

Source :IBM Program Linkage

Clear form after submission with jQuery

You can reset your form with:

$("#myform")[0].reset();

Simple insecure two-way data "obfuscation"?

A variant of Marks (excellent) answer

  • Add "using"s
  • Make the class IDisposable
  • Remove the URL encoding code to make the example simpler.
  • Add a simple test fixture to demonstrate usage

Hope this helps

[TestFixture]
public class RijndaelHelperTests
{
    [Test]
    public void UseCase()
    {
        //These two values should not be hard coded in your code.
        byte[] key = {251, 9, 67, 117, 237, 158, 138, 150, 255, 97, 103, 128, 183, 65, 76, 161, 7, 79, 244, 225, 146, 180, 51, 123, 118, 167, 45, 10, 184, 181, 202, 190};
        byte[] vector = {214, 11, 221, 108, 210, 71, 14, 15, 151, 57, 241, 174, 177, 142, 115, 137};

        using (var rijndaelHelper = new RijndaelHelper(key, vector))
        {
            var encrypt = rijndaelHelper.Encrypt("StringToEncrypt");
            var decrypt = rijndaelHelper.Decrypt(encrypt);
            Assert.AreEqual("StringToEncrypt", decrypt);
        }
    }
}

public class RijndaelHelper : IDisposable
{
    Rijndael rijndael;
    UTF8Encoding encoding;

    public RijndaelHelper(byte[] key, byte[] vector)
    {
        encoding = new UTF8Encoding();
        rijndael = Rijndael.Create();
        rijndael.Key = key;
        rijndael.IV = vector;
    }

    public byte[] Encrypt(string valueToEncrypt)
    {
        var bytes = encoding.GetBytes(valueToEncrypt);
        using (var encryptor = rijndael.CreateEncryptor())
        using (var stream = new MemoryStream())
        using (var crypto = new CryptoStream(stream, encryptor, CryptoStreamMode.Write))
        {
            crypto.Write(bytes, 0, bytes.Length);
            crypto.FlushFinalBlock();
            stream.Position = 0;
            var encrypted = new byte[stream.Length];
            stream.Read(encrypted, 0, encrypted.Length);
            return encrypted;
        }
    }

    public string Decrypt(byte[] encryptedValue)
    {
        using (var decryptor = rijndael.CreateDecryptor())
        using (var stream = new MemoryStream())
        using (var crypto = new CryptoStream(stream, decryptor, CryptoStreamMode.Write))
        {
            crypto.Write(encryptedValue, 0, encryptedValue.Length);
            crypto.FlushFinalBlock();
            stream.Position = 0;
            var decryptedBytes = new Byte[stream.Length];
            stream.Read(decryptedBytes, 0, decryptedBytes.Length);
            return encoding.GetString(decryptedBytes);
        }
    }

    public void Dispose()
    {
        if (rijndael != null)
        {
            rijndael.Dispose();
        }
    }
}

How to use boost bind with a member function

Use the following instead:

boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );

This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.

Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.

Where is svn.exe in my machine?

TortoiseSVN doesn't use svn.exe it has SVN library compiled in. If you need to run your own tasks you would have to install stand alone subversion client. You either from Cygwin [http://cygwin.com ] or get a native version from http://subversion.apache.org/packages.html#windows

Using both Python 2.x and Python 3.x in IPython Notebook

From my Linux installation I did:

sudo ipython2 kernelspec install-self

And now my python 2 is back on the list.

Reference:

http://ipython.readthedocs.org/en/latest/install/kernel_install.html


UPDATE:

The method above is now deprecated and will be dropped in the future. The new method should be:

sudo ipython2 kernel install

Get key by value in dictionary

Heres a truly "Reversible Dictionary", Based upon Adam Acosta's solution, but enforcing val-to-key calls to be unique and easily return key from value:

from collections import UserDict


class ReversibleDict(UserDict):
    def __init__(self, enforce_unique=True, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.val_to_keys = {}
        self.check_val = self.check_unique if enforce_unique else lambda x: x

    def __setitem__(self, key, value):
        self.check_val(value)
        super().__setitem__(key, value)
        self.val_to_keys[value] = key

    def __call__(self, value):
        return self.val_to_keys[value]

    def check_unique(self, value):
        assert value not in self.val_to_keys, f"Non unique value '{value}'"
        return value

If you want to enforce uniqueness on dictionary values ensure to set enforce_unique=True. to get keys from values just do rev_dict(value), to call values from keys just do as usual dict['key'], here's an example of usage:

rev_dict = ReversibleDict(enforce_unique=True)
rev_dict["a"] = 1
rev_dict["b"] = 2
rev_dict["c"] = 3
print("full dictinoary is: ", rev_dict)
print("value for key 'b' is: ", rev_dict["b"])
print("key for value '2' is: ", rev_dict(2))
print("tring to set another key with the same value results in error: ")
rev_dict["d"] = 1

How to get the current user in ASP.NET MVC

If you are inside your login page, in LoginUser_LoggedIn event for instance, Current.User.Identity.Name will return an empty value, so you have to use yourLoginControlName.UserName property.

MembershipUser u = Membership.GetUser(LoginUser.UserName);

Insert text into textarea with jQuery

I use this function in my code:

_x000D_
_x000D_
$.fn.extend({_x000D_
  insertAtCaret: function(myValue) {_x000D_
    this.each(function() {_x000D_
      if (document.selection) {_x000D_
        this.focus();_x000D_
        var sel = document.selection.createRange();_x000D_
        sel.text = myValue;_x000D_
        this.focus();_x000D_
      } else if (this.selectionStart || this.selectionStart == '0') {_x000D_
        var startPos = this.selectionStart;_x000D_
        var endPos = this.selectionEnd;_x000D_
        var scrollTop = this.scrollTop;_x000D_
        this.value = this.value.substring(0, startPos) +_x000D_
          myValue + this.value.substring(endPos,this.value.length);_x000D_
        this.focus();_x000D_
        this.selectionStart = startPos + myValue.length;_x000D_
        this.selectionEnd = startPos + myValue.length;_x000D_
        this.scrollTop = scrollTop;_x000D_
      } else {_x000D_
        this.value += myValue;_x000D_
        this.focus();_x000D_
      }_x000D_
    });_x000D_
    return this;_x000D_
  }_x000D_
});
_x000D_
input{width:100px}_x000D_
label{display:block;margin:10px 0}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label>Copy text from: <input id="in2copy" type="text" value="x"></label>_x000D_
<label>Insert text in: <input id="in2ins" type="text" value="1,2,3" autofocus></label>_x000D_
<button onclick="$('#in2ins').insertAtCaret($('#in2copy').val())">Insert</button>
_x000D_
_x000D_
_x000D_

It's not 100% mine, I googled it somewhere and then tuned for mine app.

Usage: $('#element').insertAtCaret('text');

An invalid XML character (Unicode: 0xc) was found

There are a few characters that are dissallowed in XML documents, even when you encapsulate data in CDATA-blocks.

If you generated the document you will need to entity encode it or strip it out. If you have an errorneous document, you should strip away these characters before trying to parse it.

See dolmens answer in this thread: Invalid Characters in XML

Where he links to this article: http://www.w3.org/TR/xml/#charsets

Basically, all characters below 0x20 is disallowed, except 0x9 (TAB), 0xA (CR?), 0xD (LF?)

Removing viewcontrollers from navigation stack

Swift 5, Xcode 11.3

I found this approach simple by specifying which view controller(s) you want to remove from the navigation stack.

extension UINavigationController {

    func removeViewController(_ controller: UIViewController.Type) {
        if let viewController = viewControllers.first(where: { $0.isKind(of: controller.self) }) {
            viewController.removeFromParent()
        }
    }
}

Example use:

navigationController.removeViewController(YourViewController.self)

How do I create ColorStateList programmatically?

The first dimension is an array of state sets, the second ist the state set itself. The colors array lists the colors for each matching state set, therefore the length of the colors array has to match the first dimension of the states array (or it will crash when the state is "used"). Here and example:

ColorStateList myColorStateList = new ColorStateList(
                        new int[][]{
                                new int[]{android.R.attr.state_pressed}, //1
                                new int[]{android.R.attr.state_focused}, //2
                                new int[]{android.R.attr.state_focused, android.R.attr.state_pressed} //3
                        },
                        new int[] {
                            Color.RED, //1
                            Color.GREEN, //2
                            Color.BLUE //3
                        }
                    );

hope this helps.

EDIT example: a xml color state list like:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="@color/white"/>
    <item android:color="@color/black"/>
</selector>

would look like this

ColorStateList myColorStateList = new ColorStateList(
        new int[][]{
                new int[]{android.R.attr.state_pressed},
                new int[]{}
        },
        new int[] {
                context.getResources().getColor(R.color.white),
                context.getResources().getColor(R.color.black)
        }
);

How to set a cookie for another domain

You cannot set cookies for another domain. Allowing this would present an enormous security flaw.

You need to get b.com to set the cookie. If a.com redirect the user to b.com/setcookie.php?c=value

The setcookie script could contain the following to set the cookie and redirect to the correct page on b.com

<?php
    setcookie('a', $_GET['c']);
    header("Location: b.com/landingpage.php");
?>

Compress files while reading data from STDIN

Yes, gzip will let you do this. If you simply run gzip > foo.gz, it will compress STDIN to the file foo.gz. You can also pipe data into it, like some_command | gzip > foo.gz.

How do I get the old value of a changed cell in Excel VBA?

I have an alternative solution for you. You could create a hidden worksheet to maintain the old values for your range of interest.

Private Sub Workbook_Open()

Dim hiddenSheet As Worksheet

Set hiddenSheet = Me.Worksheets.Add
hiddenSheet.Visible = xlSheetVeryHidden
hiddenSheet.Name = "HiddenSheet"

'Change Sheet1 to whatever sheet you're working with
Sheet1.UsedRange.Copy ThisWorkbook.Worksheets("HiddenSheet").Range(Sheet1.UsedRange.Address)

End Sub

Delete it when the workbook is closed...

Private Sub Workbook_BeforeClose(Cancel As Boolean)

Application.DisplayAlerts = False
Me.Worksheets("HiddenSheet").Delete
Application.DisplayAlerts = True

End Sub

And modify your Worksheet_Change event like so...

For Each cell In Target

    If Not (Intersect(cell, Range("cell_of_interest")) Is Nothing) Then
        new_value = cell.Value
        ' here's your "old" value...
        old_value = ThisWorkbook.Worksheets("HiddenSheet").Range(cell.Address).Value
        Call DoFoo(old_value, new_value)
    End If

Next cell

' Update your "old" values...
ThisWorkbook.Worksheets("HiddenSheet").UsedRange.Clear
Me.UsedRange.Copy ThisWorkbook.Worksheets("HiddenSheet").Range(Me.UsedRange.Address)

Hidden TextArea

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

This sets the css display property to none, which prevents the browser from rendering the textarea.

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.

How can I generate a unique ID in Python?

here you can find an implementation :

def __uniqueid__():
    """
      generate unique id with length 17 to 21.
      ensure uniqueness even with daylight savings events (clocks adjusted one-hour backward).

      if you generate 1 million ids per second during 100 years, you will generate 
      2*25 (approx sec per year) * 10**6 (1 million id per sec) * 100 (years) = 5 * 10**9 unique ids.

      with 17 digits (radix 16) id, you can represent 16**17 = 295147905179352825856 ids (around 2.9 * 10**20).
      In fact, as we need far less than that, we agree that the format used to represent id (seed + timestamp reversed)
      do not cover all numbers that could be represented with 35 digits (radix 16).

      if you generate 1 million id per second with this algorithm, it will increase the seed by less than 2**12 per hour
      so if a DST occurs and backward one hour, we need to ensure to generate unique id for twice times for the same period.
      the seed must be at least 1 to 2**13 range. if we want to ensure uniqueness for two hours (100% contingency), we need 
      a seed for 1 to 2**14 range. that's what we have with this algorithm. You have to increment seed_range_bits if you
      move your machine by airplane to another time zone or if you have a glucky wallet and use a computer that can generate
      more than 1 million ids per second.

      one word about predictability : This algorithm is absolutely NOT designed to generate unpredictable unique id.
      you can add a sha-1 or sha-256 digest step at the end of this algorithm but you will loose uniqueness and enter to collision probability world.
      hash algorithms ensure that for same id generated here, you will have the same hash but for two differents id (a pair of ids), it is
      possible to have the same hash with a very little probability. You would certainly take an option on a bijective function that maps
      35 digits (or more) number to 35 digits (or more) number based on cipher block and secret key. read paper on breaking PRNG algorithms 
      in order to be convinced that problems could occur as soon as you use random library :)

      1 million id per second ?... on a Intel(R) Core(TM)2 CPU 6400 @ 2.13GHz, you get :

      >>> timeit.timeit(uniqueid,number=40000)
      1.0114529132843018

      an average of 40000 id/second
    """
    mynow=datetime.now
    sft=datetime.strftime
    # store old datetime each time in order to check if we generate during same microsecond (glucky wallet !)
    # or if daylight savings event occurs (when clocks are adjusted backward) [rarely detected at this level]
    old_time=mynow() # fake init - on very speed machine it could increase your seed to seed + 1... but we have our contingency :)
    # manage seed
    seed_range_bits=14 # max range for seed
    seed_max_value=2**seed_range_bits - 1 # seed could not exceed 2**nbbits - 1
    # get random seed
    seed=random.getrandbits(seed_range_bits)
    current_seed=str(seed)
    # producing new ids
    while True:
        # get current time 
        current_time=mynow()
        if current_time <= old_time:
            # previous id generated in the same microsecond or Daylight saving time event occurs (when clocks are adjusted backward)
            seed = max(1,(seed + 1) % seed_max_value)
            current_seed=str(seed)
        # generate new id (concatenate seed and timestamp as numbers)
        #newid=hex(int(''.join([sft(current_time,'%f%S%M%H%d%m%Y'),current_seed])))[2:-1]
        newid=int(''.join([sft(current_time,'%f%S%M%H%d%m%Y'),current_seed]))
        # save current time
        old_time=current_time
        # return a new id
        yield newid

""" you get a new id for each call of uniqueid() """
uniqueid=__uniqueid__().next

import unittest
class UniqueIdTest(unittest.TestCase):
    def testGen(self):
        for _ in range(3):
            m=[uniqueid() for _ in range(10)]
            self.assertEqual(len(m),len(set(m)),"duplicates found !")

hope it helps !

dynamically add and remove view to viewpager

To remove you can use this directly:

getSupportFragmentManager().beginTransaction().remove(fragment).
                            commitAllowingStateLoss();

fragment is the fragment you want to remove.

Return string without trailing slash

function someFunction(site) {
  if (site.indexOf('/') > 0)
    return site.substring(0, site.indexOf('/'));
  return site;
}

How to extract text from a PDF file?

A more robust way, supposing there are multiple PDF's or just one !

import os
from PyPDF2 import PdfFileWriter, PdfFileReader
from io import BytesIO

mydir = # specify path to your directory where PDF or PDF's are

for arch in os.listdir(mydir): 
    buffer = io.BytesIO()
    archpath = os.path.join(mydir, arch)
    with open(archpath) as f:
            pdfFileObj = open(archpath, 'rb')
            pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
            pdfReader.numPages
            pageObj = pdfReader.getPage(0) 
            ley = pageObj.extractText()
            file1 = open("myfile.txt","w")
            file1.writelines(ley)
            file1.close()
            

Simple timeout in java

What you are looking for can be found here. It may exist a more elegant way to accomplish that, but one possible approach is

Option 1 (preferred):

final Duration timeout = Duration.ofSeconds(30);
ExecutorService executor = Executors.newSingleThreadExecutor();

final Future<String> handler = executor.submit(new Callable() {
    @Override
    public String call() throws Exception {
        return requestDataFromModem();
    }
});

try {
    handler.get(timeout.toMillis(), TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
    handler.cancel(true);
}

executor.shutdownNow();

Option 2:

final Duration timeout = Duration.ofSeconds(30);
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

final Future<String> handler = executor.submit(new Callable() {
    @Override
    public String call() throws Exception {
        return requestDataFromModem();
    }
});

executor.schedule(new Runnable() {
    @Override
    public void run(){
        handler.cancel(true);
    }      
}, timeout.toMillis(), TimeUnit.MILLISECONDS);

executor.shutdownNow();

Those are only a draft so that you can get the main idea.

Where is the Query Analyzer in SQL Server Management Studio 2008 R2?

To analyze a query you already have entered into the Query editor, you need to choose "Include Actual Execution Plan" (7th toggle button to the right of the "! Execute" button). After executing the query, you need to click on the "Execution Plan" tab in the results pane at the bottom (above the results of the query).

XPath: How to select elements based on their value?

The condition below:

//Element[@attribute1="abc" and @attribute2="xyz" and Data]

checks for the existence of the element Data within Element and not for element value Data.

Instead you can use

//Element[@attribute1="abc" and @attribute2="xyz" and text()="Data"]

How to add buttons dynamically to my form?

Two problems- List is empty. You need to add some buttons to the list first. Second problem: You can't add buttons to "this". "This" is not referencing what you think, I think. Change this to reference a Panel for instance.

//Assume you have on your .aspx page:
<asp:Panel ID="Panel_Controls" runat="server"></asp:Panel>


private void button1_Click(object sender, EventArgs e)
    {
        List<Button> buttons = new List<Button>();


        for (int i = 0; i < buttons.Capacity; i++)
        {
            Panel_Controls.Controls.Add(buttons[i]);   
        }
    }

JavaScript object: access variable property by name as string

Since I was helped with my project by the answer above (I asked a duplicate question and was referred here), I am submitting an answer (my test code) for bracket notation when nesting within the var:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
  <script type="text/javascript">_x000D_
    function displayFile(whatOption, whatColor) {_x000D_
      var Test01 = {_x000D_
        rectangle: {_x000D_
          red: "RectangleRedFile",_x000D_
          blue: "RectangleBlueFile"_x000D_
        },_x000D_
        square: {_x000D_
          red: "SquareRedFile",_x000D_
          blue: "SquareBlueFile"_x000D_
        }_x000D_
      };_x000D_
      var filename = Test01[whatOption][whatColor];_x000D_
      alert(filename);_x000D_
    }_x000D_
  </script>_x000D_
</head>_x000D_
<body>_x000D_
  <p onclick="displayFile('rectangle', 'red')">[ Rec Red ]</p>_x000D_
  <br/>_x000D_
  <p onclick="displayFile('square', 'blue')">[ Sq Blue ]</p>_x000D_
  <br/>_x000D_
  <p onclick="displayFile('square', 'red')">[ Sq Red ]</p>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

A function to convert null to string

You can just use the null coalesce operator.

string result = value ?? "";

What does the Ellipsis object do?

__getitem__ minimal ... example in a custom class

When the magic syntax ... gets passed to [] in a custom class, __getitem__() receives a Ellipsis class object.

The class can then do whatever it wants with this Singleton object.

Example:

class C(object):
    def __getitem__(self, k):
        return k

# Single argument is passed directly.
assert C()[0] == 0

# Multiple indices generate a tuple.
assert C()[0, 1] == (0, 1)

# Slice notation generates a slice object.
assert C()[1:2:3] == slice(1, 2, 3)

# Ellipsis notation generates the Ellipsis class object.
# Ellipsis is a singleton, so we can compare with `is`.
assert C()[...] is Ellipsis

# Everything mixed up.
assert C()[1, 2:3:4, ..., 6] == (1, slice(2,3,4), Ellipsis, 6)

The Python built-in list class chooses to give it the semantic of a range, and any sane usage of it should too of course.

Personally, I'd just stay away from it in my APIs, and create a separate, more explicit method instead.

Tested in Python 3.5.2 and 2.7.12.

SQL LIKE condition to check for integer?

In PostreSQL you can use SIMILAR TO operator (more):

-- only digits
select * from books where title similar to '^[0-9]*$';
-- start with digit
select * from books where title similar to '^[0-9]%$';

Convert datetime value into string

Use DATE_FORMAT()

SELECT
  DATE_FORMAT(NOW(), '%d %m %Y') AS your_date;

Center Plot title in ggplot2

The ggeasy package has a function called easy_center_title() to do just that. I find it much more appealing than theme(plot.title = element_text(hjust = 0.5)) and it's so much easier to remember.

ggplot(data = dat, aes(time, total_bill, fill = time)) + 
  geom_bar(colour = "black", fill = "#DD8888", width = .8, stat = "identity") + 
  guides(fill = FALSE) +
  xlab("Time of day") +
  ylab("Total bill") +
  ggtitle("Average bill for 2 people") +
  ggeasy::easy_center_title()

enter image description here

Note that as of writing this answer you will need to install the development version of ggeasy from GitHub to use easy_center_title(). You can do so by running remotes::install_github("jonocarroll/ggeasy").

App crashing when trying to use RecyclerView on android 5.0

I had this problem when using Butterknife , I was using fragment

For Fragment, it should be ButterKnife.bind(this,view);

For Activity ButterKnife.bind(this);

Returning a boolean value in a JavaScript function

You could wrap your return value in the Boolean function

Boolean([return value])

That'll ensure all falsey values are false and truthy statements are true.

How to check if a double value has no decimal part

All Integers are modulo of 1. So below check must give you the answer.

if(d % 1 == 0)

ImportError: No Module named simplejson

@noskio is correct... it just means that simplejson isn't found on your system and you need to install it for Python older than 2.6. one way is to use the setuptools easy_install tool. with it, you can install it as easily as: easy_install simplejson

UPDATE (Feb 2014): this is probably old news to many of you, but pip is a more modern tool that works in a similar way (i.e., pip install simplejson), only it can also uninstall apps.

Simulation of CONNECT BY PRIOR of Oracle in SQL Server

The SQL standard way to implement recursive queries, as implemented e.g. by IBM DB2 and SQL Server, is the WITH clause. See this article for one example of translating a CONNECT BY into a WITH (technically a recursive CTE) -- the example is for DB2 but I believe it will work on SQL Server as well.

Edit: apparently the original querant requires a specific example, here's one from the IBM site whose URL I already gave. Given a table:

CREATE TABLE emp(empid  INTEGER NOT NULL PRIMARY KEY,
                 name   VARCHAR(10),
                 salary DECIMAL(9, 2),
                 mgrid  INTEGER);

where mgrid references an employee's manager's empid, the task is, get the names of everybody who reports directly or indirectly to Joan. In Oracle, that's a simple CONNECT:

SELECT name 
  FROM emp
  START WITH name = 'Joan'
  CONNECT BY PRIOR empid = mgrid

In SQL Server, IBM DB2, or PostgreSQL 8.4 (as well as in the SQL standard, for what that's worth;-), the perfectly equivalent solution is instead a recursive query (more complex syntax, but, actually, even more power and flexibility):

WITH n(empid, name) AS 
   (SELECT empid, name 
    FROM emp
    WHERE name = 'Joan'
        UNION ALL
    SELECT nplus1.empid, nplus1.name 
    FROM emp as nplus1, n
    WHERE n.empid = nplus1.mgrid)
SELECT name FROM n

Oracle's START WITH clause becomes the first nested SELECT, the base case of the recursion, to be UNIONed with the recursive part which is just another SELECT.

SQL Server's specific flavor of WITH is of course documented on MSDN, which also gives guidelines and limitations for using this keyword, as well as several examples.

How to sort a Ruby Hash by number value?

No idea how you got your results, since it would not sort by string value... You should reverse a1 and a2 in your example

Best way in any case (as per Mladen) is:

metrics = {"sitea.com" => 745, "siteb.com" => 9, "sitec.com" => 10 }
metrics.sort_by {|_key, value| value}
  # ==> [["siteb.com", 9], ["sitec.com", 10], ["sitea.com", 745]]

If you need a hash as a result, you can use to_h (in Ruby 2.0+)

metrics.sort_by {|_key, value| value}.to_h
  # ==> {"siteb.com" => 9, "sitec.com" => 10, "sitea.com", 745}

git recover deleted file where no commit was made after the delete

git checkout HEAD -- client/src/pp_web/index.cljs

How to create a hash or dictionary object in JavaScript

You want to create an Object, not an Array.

Like so,

var Map = {};

Map['key1'] = 'value1';
Map['key2'] = 'value2';

You can check if the key exists in multiple ways:

Map.hasOwnProperty(key);
Map[key] != undefined // For illustration // Edit, remove null check
if (key in Map) ...

How to temporarily disable a click handler in jQuery?

Try utilizing .one()

_x000D_
_x000D_
var button = $("#button"),_x000D_
  result = $("#result"),_x000D_
  buttonHandler = function buttonHandler(e) {_x000D_
    result.html("processing...");_x000D_
    $(this).fadeOut(1000, function() {_x000D_
      // do stuff_x000D_
      setTimeout(function() {_x000D_
        // reset `click` event at `button`_x000D_
        button.fadeIn({_x000D_
          duration: 500,_x000D_
          start: function() {_x000D_
            result.html("done at " + $.now());_x000D_
          }_x000D_
        }).one("click", buttonHandler);_x000D_
_x000D_
      }, 5000)_x000D_
    })_x000D_
  };_x000D_
_x000D_
button.one("click", buttonHandler);
_x000D_
#button {_x000D_
  width: 50px;_x000D_
  height: 50px;_x000D_
  background: olive;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">_x000D_
</script>_x000D_
<div id="result"></div>_x000D_
<div id="button">click</div>
_x000D_
_x000D_
_x000D_

Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file

  1. Find the path from error log and open the file in explorer 2)select the file and right-click -> properties
  2. Then check the 'unblock' option and click on apply enter image description here

How to fix "unable to open stdio.h in Turbo C" error?

Since you did not mention which version of Turbo C this method below will cover both v2 and v3.

  • Click on 'Options', 'Directories', enter the proper location for the Include and Lib directories.

Fatal error: Call to a member function bind_param() on boolean

Any time you get the...

"Fatal error: Call to a member function bind_param() on boolean"

...it is likely because there is an issue with your query. The prepare() might return FALSE (a Boolean), but this generic failure message doesn't leave you much in the way of clues. How do you find out what is wrong with your query? You ask!

First of all, make sure error reporting is turned on and visible: add these two lines to the top of your file(s) right after your opening <?php tag:

error_reporting(E_ALL);
ini_set('display_errors', 1);

If your error reporting has been set in the php.ini you won't have to worry about this. Just make sure you handle errors gracefully and never reveal the true cause of any issues to your users. Revealing the true cause to the public can be a gold engraved invitation for those wanting to harm your sites and servers. If you do not want to send errors to the browser you can always monitor your web server error logs. Log locations will vary from server to server e.g., on Ubuntu the error log is typically located at /var/log/apache2/error.log. If you're examining error logs in a Linux environment you can use tail -f /path/to/log in a console window to see errors as they occur in real-time....or as you make them.

Once you're squared away on standard error reporting adding error checking on your database connection and queries will give you much more detail about the problems going on. Have a look at this example where the column name is incorrect. First, the code which returns the generic fatal error message:

$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
$query = $mysqli->prepare($sql)); // assuming $mysqli is the connection
$query->bind_param('s', $definition);
$query->execute();

The error is generic and not very helpful to you in solving what is going on.

With a couple of more lines of code you can get very detailed information which you can use to solve the issue immediately. Check the prepare() statement for truthiness and if it is good you can proceed on to binding and executing.

$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
if($query = $mysqli->prepare($sql)) { // assuming $mysqli is the connection
    $query->bind_param('s', $definition);
    $query->execute();
    // any additional code you need would go here.
} else {
    $error = $mysqli->errno . ' ' . $mysqli->error;
    echo $error; // 1054 Unknown column 'foo' in 'field list'
}

If something is wrong you can spit out an error message which takes you directly to the issue. In this case there is no foo column in the table, solving the problem is trivial.

If you choose, you can include this checking in a function or class and extend it by handling the errors gracefully as mentioned previously.

Disable / Check for Mock Location (prevent gps spoofing)

This scrip is working for all version of android and i find it after many search

LocationManager locMan;
    String[] mockProviders = {LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER};

    try {
        locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        for (String p : mockProviders) {
            if (p.contentEquals(LocationManager.GPS_PROVIDER))
                locMan.addTestProvider(p, false, false, false, false, true, true, true, 1,
                        android.hardware.SensorManager.SENSOR_STATUS_ACCURACY_HIGH);
            else
                locMan.addTestProvider(p, false, false, false, false, true, true, true, 1,
                        android.hardware.SensorManager.SENSOR_STATUS_ACCURACY_LOW);

            locMan.setTestProviderEnabled(p, true);
            locMan.setTestProviderStatus(p, android.location.LocationProvider.AVAILABLE, Bundle.EMPTY,
                    java.lang.System.currentTimeMillis());
        }
    } catch (Exception ignored) {
        // here you should show dialog which is mean the mock location is not enable
    }

All shards failed

If you encounter this apparent index corruption in a running system, you can work around it by deleting all files called segments.gen. It is advisory only, and Lucene can recover correctly without it.

From ElasticSearch Blog

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

Unfortunately this error is not descriptive for a range of different problems related to the same issue - a binding error. It also does not specify where the error is, and so your problem is not necessarily in the execution, but the sql statement that was already 'prepared'.

These are the possible errors and their solutions:

  1. There is a parameter mismatch - the number of fields does not match the parameters that have been bound. Watch out for arrays in arrays. To double check - use var_dump($var). "print_r" doesn't necessarily show you if the index in an array is another array (if the array has one value in it), whereas var_dump will.

  2. You have tried to bind using the same binding value, for example: ":hash" and ":hash". Every index has to be unique, even if logically it makes sense to use the same for two different parts, even if it's the same value. (it's similar to a constant but more like a placeholder)

  3. If you're binding more than one value in a statement (as is often the case with an "INSERT"), you need to bindParam and then bindValue to the parameters. The process here is to bind the parameters to the fields, and then bind the values to the parameters.

    // Code snippet
    $column_names = array();
    $stmt->bindParam(':'.$i, $column_names[$i], $param_type);
    $stmt->bindValue(':'.$i, $values[$i], $param_type);
    $i++;
    //.....
    
  4. When binding values to column_names or table_names you can use `` but its not necessary, but make sure to be consistent.

  5. Any value in '' single quotes is always treated as a string and will not be read as a column/table name or placeholder to bind to.

What is the best method of handling currency/money?

You'll probably want to use a DECIMAL type in your database. In your migration, do something like this:

# precision is the total number of digits
# scale is the number of digits to the right of the decimal point
add_column :items, :price, :decimal, :precision => 8, :scale => 2

In Rails, the :decimal type is returned as BigDecimal, which is great for price calculation.

If you insist on using integers, you will have to manually convert to and from BigDecimals everywhere, which will probably just become a pain.

As pointed out by mcl, to print the price, use:

number_to_currency(price, :unit => "€")
#=> €1,234.01

Create Elasticsearch curl query for not null and not empty("")

You can do that with bool query and combination of must and must_not like this:

GET index/_search
{
    "query": {
        "bool": {
            "must": [
                {"exists": {"field": "field1"}}
            ],
            "must_not": [
                {"term": {"field1": ""}}
            ]
        }
    }
}

I tested this with Elasticsearch 5.6.5 in Kibana.

How to get an enum value from a string value in Java?

Enum is very useful, I have been using Enum a lot to add a description for some fields in different languages, as the following example:

public enum Status {

    ACT(new String[] { "Accepted", "?????" }),
    REJ(new String[] { "Rejected", "?????" }),
    PND(new String[] { "Pending", "?? ????????" }),
    ERR(new String[] { "Error", "???" }),
    SNT(new String[] { "Sent", "?????" });

    private String[] status;

    public String getDescription(String lang) {
        return lang.equals("en") ? status[0] : status[1];
    }

    Status(String[] status) {
        this.status = status;
    }
}

And then you can retrieve the description dynamically based in the language code passed to getDescription(String lang) method, for example:

String statusDescription = Status.valueOf("ACT").getDescription("en");

What is function overloading and overriding in php?

Method overloading occurs when two or more methods with same method name but different number of parameters in single class. PHP does not support method overloading. Method overriding means two methods with same method name and same number of parameters in two different classes means parent class and child class.

C-like structures in Python

You can subclass the C structure that is available in the standard library. The ctypes module provides a Structure class. The example from the docs:

>>> from ctypes import *
>>> class POINT(Structure):
...     _fields_ = [("x", c_int),
...                 ("y", c_int)]
...
>>> point = POINT(10, 20)
>>> print point.x, point.y
10 20
>>> point = POINT(y=5)
>>> print point.x, point.y
0 5
>>> POINT(1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: too many initializers
>>>
>>> class RECT(Structure):
...     _fields_ = [("upperleft", POINT),
...                 ("lowerright", POINT)]
...
>>> rc = RECT(point)
>>> print rc.upperleft.x, rc.upperleft.y
0 5
>>> print rc.lowerright.x, rc.lowerright.y
0 0
>>>

Android Studio Emulator and "Process finished with exit code 0"

I had this problem and it took me nearly 2 days to resolve...

I had moved my SDK location, due to the system drive being full, and it seems that someone, somewhere at Android Studio central has hard-coded the path to the HaxM driver installer. As my HamX driver was out of date, the emulator wouldn't start.

Solution: navigate to [your sdk location]\extras\intel\Hardware_Accelerated_Execution_Manager and run the intelhaxm-android.exe installer to update yourself to the latest driver.

How do you implement a circular buffer in C?

C style, simple ring buffer for integers. First use init than use put and get. If buffer does not contain any data it returns "0" zero.

//=====================================
// ring buffer address based
//=====================================
#define cRingBufCount   512
int     sRingBuf[cRingBufCount];    // Ring Buffer
int     sRingBufPut;                // Input index address
int     sRingBufGet;                // Output index address
Bool    sRingOverWrite;

void    GetRingBufCount(void)
{
int     r;
`       r= sRingBufPut - sRingBufGet;
        if ( r < cRingBufCount ) r+= cRingBufCount;
        return r; 
}

void    InitRingBuffer(void)
{
        sRingBufPut= 0;
        sRingBufGet= 0;
}       

void    PutRingBuffer(int d)
{
        sRingBuffer[sRingBufPut]= d;
        if (sRingBufPut==sRingBufGet)// both address are like ziro
        {
            sRingBufPut= IncRingBufferPointer(sRingBufPut);
            sRingBufGet= IncRingBufferPointer(sRingBufGet);
        }
        else //Put over write a data
        {
            sRingBufPut= IncRingBufferPointer(sRingBufPut);
            if (sRingBufPut==sRingBufGet)
            {
                sRingOverWrite= Ture;
                sRingBufGet= IncRingBufferPointer(sRingBufGet);
            }
        }
}

int     GetRingBuffer(void)
{
int     r;
        if (sRingBufGet==sRingBufPut) return 0;
        r= sRingBuf[sRingBufGet];
        sRingBufGet= IncRingBufferPointer(sRingBufGet);
        sRingOverWrite=False;
        return r;
}

int     IncRingBufferPointer(int a)
{
        a+= 1;
        if (a>= cRingBufCount) a= 0;
        return a;
}

ASP.NET jQuery Ajax Calling Code-Behind Method

This hasn't solved my problem too, so I changed the parameters slightly.
This code worked for me:

var dataValue = "{ name: 'person', isGoing: 'true', returnAddress: 'returnEmail' }";

$.ajax({
    type: "POST",
    url: "Default.aspx/OnSubmit",
    data: dataValue,
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
    },
    success: function (result) {
        alert("We returned: " + result.d);
    }
});

How to convert <font size="10"> to px?

According to The W3C:

This attribute sets the size of the font. Possible values:

  • An integer between 1 and 7. This sets the font to some fixed size, whose rendering depends on the user agent. Not all user agents may render all seven sizes.
  • A relative increase in font size. The value "+1" means one size larger. The value "-3" means three sizes smaller. All sizes belong to the scale of 1 to 7.

Hence, the conversion you're asking for is not possible. The browser is not required to use specific sizes with specific size attributes.

Also note that use of the font element is discouraged by W3 in favor of style sheets.

Find an object in array?

Another way to get access to array.index(of: Any) is by declaring your object

import Foundation
class Model: NSObject {  }

Post-increment and Pre-increment concept?

The pre increment is before increment value ++ e.g.:

(++v) or 1 + v

The post increment is after increment the value ++ e.g.:

(rmv++) or rmv + 1

Program:

int rmv = 10, vivek = 10;
cout << "rmv++ = " << rmv++ << endl; // the value is 10
cout << "++vivek = " << ++vivek; // the value is 11

Changing git commit message after push (given that no one pulled from remote)

Changing history

If it is the most recent commit, you can simply do this:

git commit --amend

This brings up the editor with the last commit message and lets you edit the message. (You can use -m if you want to wipe out the old message and use a new one.)

Pushing

And then when you push, do this:

git push --force-with-lease <repository> <branch>

Or you can use "+":

git push <repository> +<branch>

Or you can use --force:

git push --force <repository> <branch>

Be careful when using these commands.

  • If someone else pushed changes to the same branch, you probably want to avoid destroying those changes. The --force-with-lease option is the safest, because it will abort if there are any upstream changes (

  • If you don't specify the branch explicitly, Git will use the default push settings. If your default push setting is "matching", then you may destroy changes on several branches at the same time.

Pulling / fetching afterwards

Anyone who already pulled will now get an error message, and they will need to update (assuming they aren't making any changes themselves) by doing something like this:

git fetch origin
git reset --hard origin/master # Loses local commits

Be careful when using reset --hard. If you have changes to the branch, those changes will be destroyed.

A note about modifying history

The destroyed data is really just the old commit message, but --force doesn't know that, and will happily delete other data too. So think of --force as "I want to destroy data, and I know for sure what data is being destroyed." But when the destroyed data is committed, you can often recover old commits from the reflog—the data is actually orphaned instead of destroyed (although orphaned commits are periodically deleted).

If you don't think you're destroying data, then stay away from --force... bad things might happen.

This is why --force-with-lease is somewhat safer.

JPA Criteria API - How to add JOIN clause (as general sentence as possible)

Warning! There's a numbers of errors on the Sun JPA 2 example and the resulting pasted content in Pascal's answer. Please consult this post.

This post and the Sun Java EE 6 JPA 2 example really held back my comprehension of JPA 2. After plowing through the Hibernate and OpenJPA manuals and thinking that I had a good understanding of JPA 2, I still got confused afterwards when returning to this post.

yii2 hidden input value

You can do it with the options

echo   $form->field($model, 'hidden1', 
      ['options' => ['value'=> 'your value'] ])->hiddenInput()->label(false);

How to resolve ORA 00936 Missing Expression Error?

This happens every time you insert/ update and you don't use single quotes. When the variable is empty it will result in that error. Fix it by using ''

Assuming the first parameter is an empty variable here is a simple example:

Wrong

nvl( ,0)

Fix

nvl('' ,0)

Put your query into your database software and check it for that error. Generally this is an easy fix

Python - Get path of root project structure

A standard way to achieve this would be to use the pkg_resources module which is part of the setuptools package. setuptools is used to create an install-able python package.

You can use pkg_resources to return the contents of your desired file as a string and you can use pkg_resources to get the actual path of the desired file on your system.

Let's say that you have a package called stackoverflow.

stackoverflow/
|-- app
|   `-- __init__.py
`-- resources
    |-- bands
    |   |-- Dream\ Theater
    |   |-- __init__.py
    |   |-- King's\ X
    |   |-- Megadeth
    |   `-- Rush
    `-- __init__.py

3 directories, 7 files

Now let's say that you want to access the file Rush from a module app.run. Use pkg_resources.resouces_filename to get the path to Rush and pkg_resources.resource_string to get the contents of Rush; thusly:

import pkg_resources

if __name__ == "__main__":
    print pkg_resources.resource_filename('resources.bands', 'Rush')
    print pkg_resources.resource_string('resources.bands', 'Rush')

The output:

/home/sri/workspace/stackoverflow/resources/bands/Rush
Base: Geddy Lee
Vocals: Geddy Lee
Guitar: Alex Lifeson
Drums: Neil Peart

This works for all packages in your python path. So if you want to know where lxml.etree exists on your system:

import pkg_resources

if __name__ == "__main__":
    print pkg_resources.resource_filename('lxml', 'etree')

output:

/usr/lib64/python2.7/site-packages/lxml/etree

The point is that you can use this standard method to access files that are installed on your system (e.g pip install xxx or yum -y install python-xxx) and files that are within the module that you're currently working on.

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

I had a similar problem which I fixed by moving some fragment transaction code from onResume() into onStart().

To be more precise: My app is a launcher. After pressing the Android Home button, the user can choose a launcher until his/her decision is remembered. When going "back" at this point (e. g. by tapping in the greyish area) the app crashed.

Maybe this helps somebody.

Using an authorization header with Fetch in React Native

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

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

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

Here's how it looks on a high level:

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

I structured my object as such:

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

Creating and Naming Worksheet in Excel VBA

Are you committing the cell before pressing the button (pressing Enter)? The contents of the cell must be stored before it can be used to name a sheet.

A better way to do this is to pop up a dialog box and get the name you wish to use.

Specifying java version in maven - differences between properties and compiler plugin

None of the solutions above worked for me straight away. So I followed these steps:

  1. Add in pom.xml:
<properties>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
</properties>
  1. Go to Project Properties > Java Build Path, then remove the JRE System Library pointing to JRE1.5.

  2. Force updated the project.

ORA-01461: can bind a LONG value only for insert into a LONG column-Occurs when querying

Kiran's answer is definetely the answer for my case.

In code part I split string to 4000 char strings and try to put them in to db.

Explodes with this error.

The cause of the error is using utf chars, those counts 2 bytes each. Even I truncate to 4000 chars in code(sth. like String.Take(4000)), oracle considers 4001 when string contains 'ö' or any other non-eng(non ascii to be precise, which are represented with two or bytes in utf8) characters.

How do I convert two lists into a dictionary?

If you need to transform keys or values before creating a dictionary then a generator expression could be used. Example:

>>> adict = dict((str(k), v) for k, v in zip(['a', 1, 'b'], [2, 'c', 3])) 

Take a look Code Like a Pythonista: Idiomatic Python.

How to upgrade R in ubuntu?

Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here

  1. Open the sources.list file:

     sudo nano /etc/apt/sources.list    
    
  2. Add a line with the source from where the packages will be retrieved. For example:

     deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
    

    Replace https://cloud.r-project.org with whatever mirror you would like to use, and replace version/ with whatever version of Ubuntu you are using (eg, trusty/, xenial/, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/ and version/.

  3. Fetch the secure APT key:

     gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
    

or

    gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
  1. Add it to keyring:

     gpg -a --export E084DAB9 | sudo apt-key add -
    
  2. Update your sources and upgrade your installation:

     sudo apt-get update && sudo apt-get upgrade
    
  3. Install the new version

     sudo apt-get install r-base-dev
    
  4. Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:

-- copy the packages from R-oldversion/library to R-newversion/library, (do not overwrite a package if it already exists in the new version!).

-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE).

Need to get current timestamp in Java

Print a Timestamp in java, using the java.sql.Timestamp.

import java.sql.Timestamp;
import java.util.Date;

public class GetCurrentTimeStamp {
    public static void main( String[] args ){
        java.util.Date date= new java.util.Date();
        System.out.println(new Timestamp(date.getTime()));
    }
}

This prints:

2014-08-07 17:34:16.664

Print a Timestamp in Java using SimpleDateFormat on a one-liner.

import java.util.Date;
import java.text.SimpleDateFormat;

class Runner{
    public static void main(String[] args){

        System.out.println(
            new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new Date()));

    }

}

Prints:

08/14/2014 14:10:38

Java date format legend:

G Era designation      Text               AD
y Year                 Year               1996; 96
M Month in year        Month              July; Jul; 07
w Week in year         Number             27
W Week in month        Number             2
D Day in year          Number             189
d Day in month         Number             10
F Day of week in month Number             2
E Day in week          Text               Tuesday; Tue
a Am/pm marker         Text               PM
H Hour in day (0-23)   Number             0
k Hour in day (1-24)   Number             24
K Hour in am/pm (0-11) Number             0
h Hour in am/pm (1-12) Number             12
m Minute in hour       Number             30
s Second in minute     Number             55
S Millisecond          Number             978
z Time zone            General time zone  Pacific Standard Time; PST; GMT-08:00
Z Time zone            RFC 822 time zone  -0800

Server.UrlEncode vs. HttpUtility.UrlEncode

Server.UrlEncode() is there to provide backward compatibility with Classic ASP,

Server.UrlEncode(str);

Is equivalent to:

HttpUtility.UrlEncode(str, Response.ContentEncoding);

Python Key Error=0 - Can't find Dict error in code

It only comes when your list or dictionary not available in the local function.

How can I open a popup window with a fixed size using the HREF tag?

I can't comment on Esben Skov Pedersen's answer directly, but using the following notation for links:

<a href="javascript:window.open('http://www.websiteofyourchoice.com');">Click here</a>

In Internet Explorer, the new browser window appears, but the current window navigates to a page which says "[Object]". To avoid this, simple put a "void(0)" behind the JavaScript function.

Source: https://support.microsoft.com/en-us/kb/257321

Auto number column in SharePoint list

If you want to control the formatting of the unique identifier you can create your own <FieldType> in SharePoint. MSDN also has a visual How-To. This basically means that you're creating a custom column.

WSS defines the Counter field type (which is what the ID column above is using). I've never had the need to re-use this or extend it, but it should be possible.

A solution might exist without creating a custom <FieldType>. For example: if you wanted unique IDs like CUST1, CUST2, ... it might be possible to create a Calculated column and use the value of the ID column in you formula (="CUST" & [ID]). I haven't tried this, but this should work :)

Asynchronous vs synchronous execution, what does it really mean?

As a really simple example,

SYNCHRONOUS

Imagine 3 school students instructed to run a relay race on a road.

1st student runs her given distance, stops and passes the baton to the 2nd. No one else has started to run.

1------>
        2.
                3.

When the 2nd student retrieves the baton, she starts to run her given distance.

      1.
        2------>
                3.

The 2nd student got her shoelace untied. Now she has stopped and tying up again. Because of this, 2nd's end time has got extended and the 3rd's starting time has got delayed.

      1.
        --2.--->
                3.

This pattern continues on till the 3rd retrieves the baton from 2nd and finishes the race.

ASYNCHRONOUS

Just Imagine 10 random people walking on the same road. They're not on a queue of course, just randomly walking on different places on the road in different paces.

2nd person's shoelace got untied. She stopped to get it tied up again.

But nobody is waiting for her to get it tied up. Everyone else is still walking the same way they did before, in that same pace of theirs.

10-->    9-->
   8--> 7-->   6-->
 5-->     4-->
1-->   2.    3-->

how to create a Java Date object of midnight today and midnight tomorrow?

As of JodaTime 2.3, the toDateMidnight() is deprecated.

From Upgrade from 2.2 to 2.3

    Deprecations since 2.2
    ----------------------
    - DateMidnight [#41]
     This class is flawed in concept
     The time of midnight occasionally does not occur in some time-zones
     This is a result of a daylight savings time from 00:00 to 01:00
     DateMidnight is essentially a DateTime with a time locked to midnight
     Such a concept is more generally a poor one to use, given LocalDate
     Replace DateMidnight with LocalDate
     Or replace it with DateTime, perhaps using the withTimeAtStartOfDay() method

Here is a sample code without toDateMidnight() method.

Code

DateTime todayAtMidnight = new DateTime().withTimeAtStartOfDay();
System.out.println(todayAtMidnight.toString("yyyy-MM-dd HH:mm:ss"));

Output (may be different depending on your local time zone)

2013-09-28 00:00:00

Could not instantiate mail function. Why this error occurring

Make sure that you also include smtp class which comes with phpmailer:

// for mailing
require("phpmailer/class.phpmailer.php");
require("phpmailer/class.smtp.php");

Check if a string has a certain piece of text

Here you go: ES5

var test = 'Hello World';
if( test.indexOf('World') >= 0){
  // Found world
}

With ES6 best way would be to use includes function to test if the string contains the looking work.

const test = 'Hello World';
if (test.includes('World')) { 
  // Found world
}

Cross Browser Flash Detection in Javascript

Detecting and embedding Flash within a web document is a surprisingly difficult task.

I was very disappointed with the quality and non-standards compliant markup generated from both SWFObject and Adobe's solutions. Additionally, my testing found Adobe's auto updater to be inconsistent and unreliable.

The JavaScript Flash Detection Library (Flash Detect) and JavaScript Flash HTML Generator Library (Flash TML) are a legible, maintainable and standards compliant markup solution.

-"Luke read the source!"

Possible to iterate backwards through a foreach?

It is possible if you can change the collection code that implements IEnumerable or IEnumerable (e.g. your own implementation of IList).

Create an Iterator doing this job for you, for example like the following implementation through the IEnumerable interface (assuming 'items' is a List field in this sample):

public IEnumerator<TObject> GetEnumerator()
{
    for (var i = items.Count - 1; i >= 0; i--)
    { 
        yield return items[i];
    }
}

IEnumerator IEnumerable.GetEnumerator()
{
    return GetEnumerator();
}

Because of this your List will iterate in reverse order through your list.

Just a hint: You should clearly state this special behaviour of your list within the documentation (even better by choosing a self-explaining class name like Stack or Queue, too).

Best practice to validate null and empty collection in Java

We'll check a Collection object is empty, null or not. these all methods which are given below, are present in org.apache.commons.collections4.CollectionUtils package.

Check on List or set type of collection Objects.

CollectionUtils.isEmpty(listObject);
CollectionUtils.isNotEmpty(listObject);

Check on Map type of Objects.

MapUtils.isEmpty(mapObject);
MapUtils.isNotEmpty(mapObject);

The return type of all methods is boolean.

Force an SVN checkout command to overwrite current files

Pull from the repository to a new directory, then rename the old one to old_crufty, and the new one to my_real_webserver_directory, and you're good to go.

If your intention is that every single file is in SVN, then this is a good way to test your theory. If your intention is that some files are not in SVN, then use Brian's copy/paste technique.

Setting Margin Properties in code

Margin = new Thickness(0, 0, 0, 0);

How do I print a double value without scientific notation using Java?

The following code detects if the provided number is presented in scientific notation. If so it is represented in normal presentation with a maximum of '25' digits.

 static String convertFromScientificNotation(double number) {
    // Check if in scientific notation
    if (String.valueOf(number).toLowerCase().contains("e")) {
        System.out.println("The scientific notation number'"
                + number
                + "' detected, it will be converted to normal representation with 25 maximum fraction digits.");
        NumberFormat formatter = new DecimalFormat();
        formatter.setMaximumFractionDigits(25);
        return formatter.format(number);
    } else
        return String.valueOf(number);
}

Checking the equality of two slices

In case that you are interested in writing a test, then github.com/stretchr/testify/assert is your friend.

Import the library at the very beginning of the file:

import (
    "github.com/stretchr/testify/assert"
)

Then inside the test you do:


func TestEquality_SomeSlice (t * testing.T) {
    a := []int{1, 2}
    b := []int{2, 1}
    assert.Equal(t, a, b)
}

The error prompted will be:

                Diff:
                --- Expected
                +++ Actual
                @@ -1,4 +1,4 @@
                 ([]int) (len=2) {
                + (int) 1,
                  (int) 2,
                - (int) 2,
                  (int) 1,
Test:           TestEquality_SomeSlice

Where can I download IntelliJ IDEA Color Schemes?

Please note there are two very nice color schemes by default in IDEA 10.

The one that is included is named Railcasts. It is included with the Ruby plugin (free official plugin, install via plugin manager).

Railcasts IDEA 10 color scheme

How can I do DNS lookups in Python, including referring to /etc/hosts?

The normal name resolution in Python works fine. Why do you need DNSpython for that. Just use socket's getaddrinfo which follows the rules configured for your operating system (on Debian, it follows /etc/nsswitch.conf:

>>> print socket.getaddrinfo('google.com', 80)
[(10, 1, 6, '', ('2a00:1450:8006::63', 80, 0, 0)), (10, 2, 17, '', ('2a00:1450:8006::63', 80, 0, 0)), (10, 3, 0, '', ('2a00:1450:8006::63', 80, 0, 0)), (10, 1, 6, '', ('2a00:1450:8006::68', 80, 0, 0)), (10, 2, 17, '', ('2a00:1450:8006::68', 80, 0, 0)), (10, 3, 0, '', ('2a00:1450:8006::68', 80, 0, 0)), (10, 1, 6, '', ('2a00:1450:8006::93', 80, 0, 0)), (10, 2, 17, '', ('2a00:1450:8006::93', 80, 0, 0)), (10, 3, 0, '', ('2a00:1450:8006::93', 80, 0, 0)), (2, 1, 6, '', ('209.85.229.104', 80)), (2, 2, 17, '', ('209.85.229.104', 80)), (2, 3, 0, '', ('209.85.229.104', 80)), (2, 1, 6, '', ('209.85.229.99', 80)), (2, 2, 17, '', ('209.85.229.99', 80)), (2, 3, 0, '', ('209.85.229.99', 80)), (2, 1, 6, '', ('209.85.229.147', 80)), (2, 2, 17, '', ('209.85.229.147', 80)), (2, 3, 0, '', ('209.85.229.147', 80))]

Deleting multiple columns based on column names in Pandas

Simple and Easy. Remove all columns after the 22th.

df.drop(columns=df.columns[22:]) # love it

Cant get text of a DropDownList in code - can get value but not text

Have a look here, this has a proof-of-concept page and demo you can use to get anything from the drop-down: asp:DropDownList Control Tutorial Page

Getting the error "Java.lang.IllegalStateException Activity has been destroyed" when using tabs with ViewPager

Wanted to add that my problem was in an activity where I tried to make a FragmentTransaction in onCreate BEFORE I called super.onCreate(). I just moved super.onCreate() to top of function and was worked fine.

Command output redirect to file and terminal

It is worth mentioning that 2>&1 means that standard error will be redirected too, together with standard output. So

someCommand | tee someFile

gives you just the standard output in the file, but not the standard error: standard error will appear in console only. To get standard error in the file too, you can use

someCommand 2>&1 | tee someFile

(source: In the shell, what is " 2>&1 "? ). Finally, both the above commands will truncate the file and start clear. If you use a sequence of commands, you may want to get output&error of all of them, one after another. In this case you can use -a flag to "tee" command:

someCommand 2>&1 | tee -a someFile

How to add a second x-axis in matplotlib

You can use twiny to create 2 x-axis scales. For Example:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()

a = np.cos(2*np.pi*np.linspace(0, 1, 60.))

ax1.plot(range(60), a)
ax2.plot(range(100), np.ones(100)) # Create a dummy plot
ax2.cla()
plt.show()

Ref: http://matplotlib.sourceforge.net/faq/howto_faq.html#multiple-y-axis-scales

Output: enter image description here

SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable

Please follow below steps it work's for me:

  • Go to your react-native Project then go to android directory Create a file with following name:

local.properties

  • Open the file and paste your Android SDK path like below:

For windows users:

sdk.dir=C:\\Users\\UserName\\AppData\\Local\\Android\\sdk

Replace UserName with your pc user name . Also make sure the folder is sdk or Sdk. In my case my computer user name is Zahid so the path look like:

sdk.dir=C:\\Users\\Zahid\\AppData\\Local\\Android\\sdk

For Mac users:

sdk.dir = /Users/USERNAME/Library/Android/sdk

Where USERNAME is your OSX username.

For Linux (Ubuntu) users:

sdk.dir = /home/USERNAME/Android/Sdk

Where USERNAME is your linux username(Linux paths are case-sensitive: make sure the case of S in Sdk matches)

In case if this doesn't work, add ANDROID_HOME variable in "Environment Variables" as C:\Users\USER\AppData\Local\Android\Sdk

enter image description here

Python Threading String Arguments

You're trying to create a tuple, but you're just parenthesizing a string :)

Add an extra ',':

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=(dRecieved,))  # <- note extra ','
processThread.start()

Or use brackets to make a list:

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=[dRecieved])  # <- 1 element list
processThread.start()

If you notice, from the stack trace: self.__target(*self.__args, **self.__kwargs)

The *self.__args turns your string into a list of characters, passing them to the processLine function. If you pass it a one element list, it will pass that element as the first argument - in your case, the string.

How to convert List to Json in Java

For simplicity and well structured sake, use SpringMVC. It's just so simple.

@RequestMapping("/carlist.json")
public @ResponseBody List<String> getCarList() {
    return carService.getAllCars();
}

Reference and credit: https://github.com/xvitcoder/spring-mvc-angularjs

Get keys from HashMap in Java

This is doable, at least in theory, if you know the index:

System.out.println(team1.keySet().toArray()[0]);

keySet() returns a set, so you convert the set to an array.

The problem, of course, is that a set doesn't promise to keep your order. If you only have one item in your HashMap, you're good, but if you have more than that, it's best to loop over the map, as other answers have done.

Alternative to a goto statement in Java

You could use a labeled BREAK statement:

search:
    for (i = 0; i < arrayOfInts.length; i++) {
        for (j = 0; j < arrayOfInts[i].length; j++) {
            if (arrayOfInts[i][j] == searchfor) {
                foundIt = true;
                break search;
            }
        }
    }

However, in properly designed code, you shouldn't need GOTO functionality.

How can I inspect element in an Android browser?

If you want to inspect html, css or maybe you need js console in your mobile browser . You can use excelent tool eruda Using it you have the same Developer Tools on your mobile browser like in your desctop device. Dont forget to upvote :) Here is a link https://github.com/liriliri/eruda

Java 8 lambda Void argument

You can create a sub-interface for that special case:

interface Command extends Action<Void, Void> {
  default Void execute(Void v) {
    execute();
    return null;
  }
  void execute();
}

It uses a default method to override the inherited parameterized method Void execute(Void), delegating the call to the simpler method void execute().

The result is that it's much simpler to use:

Command c = () -> System.out.println("Do nothing!");

Nesting await in Parallel.ForEach

Wrap the Parallel.Foreach into a Task.Run() and instead of the await keyword use [yourasyncmethod].Result

(you need to do the Task.Run thing to not block the UI thread)

Something like this:

var yourForeachTask = Task.Run(() =>
        {
            Parallel.ForEach(ids, i =>
            {
                ICustomerRepo repo = new CustomerRepo();
                var cust = repo.GetCustomer(i).Result;
                customers.Add(cust);
            });
        });
await yourForeachTask;

Text vertical alignment in WPF TextBlock

In my case, I did this to make the TextBlock display nicer.

<Border BorderThickness="3" BorderBrush="Yellow" CornerRadius="10" Padding="2"
    HorizontalAlignment="Center" VerticalAlignment="Center" Height="30" Width="150">
        <TextBlock FontSize="20" Height="23" HorizontalAlignment="Left" Margin="0,0,0,-5" Text="" VerticalAlignment="Top" Width="141" Background="White" />
</Border>

The trick to make the text further from the bottom is to set

Margin="0,0,0,-5"

Regex (grep) for multi-line search needed

Your fundamental problem is that grep works one line at a time - so it cannot find a SELECT statement spread across lines.

Your second problem is that the regex you are using doesn't deal with the complexity of what can appear between SELECT and FROM - in particular, it omits commas, full stops (periods) and blanks, but also quotes and anything that can be inside a quoted string.

I would likely go with a Perl-based solution, having Perl read 'paragraphs' at a time and applying a regex to that. The downside is having to deal with the recursive search - there are modules to do that, of course, including the core module File::Find.

In outline, for a single file:

$/ = "\n\n";    # Paragraphs

while (<>)
{
     if ($_ =~ m/SELECT.*customerName.*FROM/mi)
     {
         printf file name
         go to next file
     }
}

That needs to be wrapped into a sub that is then invoked by the methods of File::Find.

How to create an installer for a .net Windows Service using Visual Studio

In the service project do the following:

  1. In the solution explorer double click your services .cs file. It should bring up a screen that is all gray and talks about dragging stuff from the toolbox.
  2. Then right click on the gray area and select add installer. This will add an installer project file to your project.
  3. Then you will have 2 components on the design view of the ProjectInstaller.cs (serviceProcessInstaller1 and serviceInstaller1). You should then setup the properties as you need such as service name and user that it should run as.

Now you need to make a setup project. The best thing to do is use the setup wizard.

  1. Right click on your solution and add a new project: Add > New Project > Setup and Deployment Projects > Setup Wizard

    a. This could vary slightly for different versions of Visual Studio. b. Visual Studio 2010 it is located in: Install Templates > Other Project Types > Setup and Deployment > Visual Studio Installer

  2. On the second step select "Create a Setup for a Windows Application."

  3. On the 3rd step, select "Primary output from..."

  4. Click through to Finish.

Next edit your installer to make sure the correct output is included.

  1. Right click on the setup project in your Solution Explorer.
  2. Select View > Custom Actions. (In VS2008 it might be View > Editor > Custom Actions)
  3. Right-click on the Install action in the Custom Actions tree and select 'Add Custom Action...'
  4. In the "Select Item in Project" dialog, select Application Folder and click OK.
  5. Click OK to select "Primary output from..." option. A new node should be created.
  6. Repeat steps 4 - 5 for commit, rollback and uninstall actions.

You can edit the installer output name by right clicking the Installer project in your solution and select Properties. Change the 'Output file name:' to whatever you want. By selecting the installer project as well and looking at the properties windows, you can edit the Product Name, Title, Manufacturer, etc...

Next build your installer and it will produce an MSI and a setup.exe. Choose whichever you want to use to deploy your service.

How to use random in BATCH script?

set /a number=%random% %% [maximum]-[minimum]

example "

set /a number=%random% %% 100-50

will give a random number between 100 and 50. Be sure to only use one percentage sign as the operand if you are not using the line in a batch script!

Convert floats to ints in Pandas?

Considering the following data frame:

>>> df = pd.DataFrame(10*np.random.rand(3, 4), columns=list("ABCD"))
>>> print(df)
...           A         B         C         D
... 0  8.362940  0.354027  1.916283  6.226750
... 1  1.988232  9.003545  9.277504  8.522808
... 2  1.141432  4.935593  2.700118  7.739108

Using a list of column names, change the type for multiple columns with applymap():

>>> cols = ['A', 'B']
>>> df[cols] = df[cols].applymap(np.int64)
>>> print(df)
...    A  B         C         D
... 0  8  0  1.916283  6.226750
... 1  1  9  9.277504  8.522808
... 2  1  4  2.700118  7.739108

Or for a single column with apply():

>>> df['C'] = df['C'].apply(np.int64)
>>> print(df)
...    A  B  C         D
... 0  8  0  1  6.226750
... 1  1  9  9  8.522808
... 2  1  4  2  7.739108

Why is Java's SimpleDateFormat not thread-safe?

SimpleDateFormat stores intermediate results in instance fields. So if one instance is used by two threads they can mess each other's results.

Looking at the source code reveals that there is a Calendar instance field, which is used by operations on DateFormat / SimpleDateFormat.

For example parse(..) calls calendar.clear() initially and then calendar.add(..). If another thread invokes parse(..) before the completion of the first invocation, it will clear the calendar, but the other invocation will expect it to be populated with intermediate results of the calculation.

One way to reuse date formats without trading thread-safety is to put them in a ThreadLocal - some libraries do that. That's if you need to use the same format multiple times within one thread. But in case you are using a servlet container (that has a thread pool), remember to clean the thread-local after you finish.

To be honest, I don't understand why they need the instance field, but that's the way it is. You can also use joda-time DateTimeFormat which is threadsafe.

How do I check if file exists in Makefile so I can delete it?

It may need a backslash on the end of the line for continuation (although perhaps that depends on the version of make):

if [ -a myApp ] ; \
then \
     rm myApp ; \
fi;

How do I tell matplotlib that I am done with a plot?

If you're using Matplotlib interactively, for example in a web application, (e.g. ipython) you maybe looking for

plt.show()

instead of plt.close() or plt.clf().

How to install pip in CentOS 7?

Update: The python34 bug mentioned below has finally been fixed. It is a perfectly fine choice now.

Rather than using broken EPEL python34 packages, you can enable the IUS repo and have it work properly.

  • pip inside virtual environments

The main python34u and python35u IUS packages include the pyvenv tool (/usr/bin/pyvenv-3.4 or /usr/bin/pyvenv-3.5) that includes bundled wheels of pip and setuptools for bootstrapping virtual environments.

  • global pip

The python34u-pip and python35u-pip IUS packages include /usr/bin/pip3.4 and /usr/bin/pip3.5 respectively. These work just fine to install packages to the system site-packages directory.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder"

I was facing same error. I have configured slf4j-api, slf4j-log4j12 and log4j, in my local development. All configuration was fine, but slf4j-log4j12 dependency which I copied from mvnrepository had test scope <scope>test</scope>. When I removed this every thing is fine.

Some times silly mistakes breaks our head ;)

How to Get Element By Class in JavaScript?

document.querySelectorAll(".your_class_name_here");

That will work in "modern" browsers that implement that method (IE8+).

function ReplaceContentInContainer(selector, content) {
  var nodeList = document.querySelectorAll(selector);
  for (var i = 0, length = nodeList.length; i < length; i++) {
     nodeList[i].innerHTML = content;
  }
}

ReplaceContentInContainer(".theclass", "HELLO WORLD");

If you want to provide support for older browsers, you could load a stand-alone selector engine like Sizzle (4KB mini+gzip) or Peppy (10K mini) and fall back to it if the native querySelector method is not found.

Is it overkill to load a selector engine just so you can get elements with a certain class? Probably. However, the scripts aren't all that big and you will may find the selector engine useful in many other places in your script.

How To Show And Hide Input Fields Based On Radio Button Selection

Using the visibility property only affects the visibility of the elements on the page; they will still be there in the page layout. To completely remove the elements from the page, use the display property.

display:none // for hiding
display:block // for showing

Make sure to change your css file to use display instead of visibility too.

As for the javascript (this is not jQuery), make sure you hide the options by default when the page loads:

<script type="text/javascript">
    window.onload = function() {
        document.getElementById('ifYes').style.display = 'none';
    }

    function yesnoCheck() {
        if (document.getElementById('yesCheck').checked) {
            document.getElementById('ifYes').style.display = 'block';
        } 
        else {
            document.getElementById('ifYes').style.display = 'none';
        }
    }

</script>

If you haven't done so already, I would recommend taking a look at jQuery. jQuery code is much clearer and easier to write and understand.

http://www.w3schools.com/jquery/default.asp

Getting content/message from HttpResponseMessage

Try this, you can create an extension method like this:

    public static string ContentToString(this HttpContent httpContent)
    {
        var readAsStringAsync = httpContent.ReadAsStringAsync();
        return readAsStringAsync.Result;
    }

and then, simple call the extension method:

txtBlock.Text = response.Content.ContentToString();

I hope this help you ;-)

How to implement WiX installer upgrade?

I used this site to help me understand the basics about WiX Upgrade:

http://wix.tramontana.co.hu/tutorial/upgrades-and-modularization

Afterwards I created a sample Installer, (installed a test file), then created the Upgrade installer (installed 2 sample test files). This will give you a basic understanding of how the mechanism works.

And as Mike said in the book from Apress, "The Definitive Guide to Windows Installer", it will help you out to understand, but it is not written using WiX.

Another site that was pretty helpful was this one:

http://www.wixwiki.com/index.php?title=Main_Page

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

In the web development world, the term "redirect" is the act of sending the client an empty HTTP response with just a Location header containing the new URL to which the client has to send a brand new GET request. So basically:

  • Client sends a HTTP request to some.jsp.
  • Server sends a HTTP response back with Location: other.jsp header
  • Client sends a HTTP request to other.jsp (this get reflected in browser address bar!)
  • Server sends a HTTP response back with content of other.jsp.

You can track it with the web browser's builtin/addon developer toolset. Press F12 in Chrome/IE9/Firebug and check the "Network" section to see it.

Exactly the above is achieved by sendRedirect("other.jsp"). The RequestDispatcher#forward() doesn't send a redirect. Instead, it uses the content of the target page as HTTP response.

  • Client sends a HTTP request to some.jsp.
  • Server sends a HTTP response back with content of other.jsp.

However, as the original HTTP request was to some.jsp, the URL in browser address bar remains unchanged. Also, any request attributes set in the controller behind some.jsp will be available in other.jsp. This does not happen during a redirect because you're basically forcing the client to create a new HTTP request on other.jsp, hereby throwing away the original request on some.jsp including all of its attribtues.


The RequestDispatcher is extremely useful in the MVC paradigm and/or when you want to hide JSP's from direct access. You can put JSP's in the /WEB-INF folder and use a Servlet which controls, preprocesses and postprocesses the requests. The JSPs in the /WEB-INF folder are not directly accessible by URL, but the Servlet can access them using RequestDispatcher#forward().

You can for example have a JSP file in /WEB-INF/login.jsp and a LoginServlet which is mapped on an url-pattern of /login. When you invoke http://example.com/context/login, then the servlet's doGet() will be invoked. You can do any preprocessing stuff in there and finally forward the request like:

request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);

When you submit a form, you normally want to use POST:

<form action="login" method="post">

This way the servlet's doPost() will be invoked and you can do any postprocessing stuff in there (e.g. validation, business logic, login the user, etc).

If there are any errors, then you normally want to forward the request back to the same page and display the errors there next to the input fields and so on. You can use the RequestDispatcher for this.

If a POST is successful, you normally want to redirect the request, so that the request won't be resubmitted when the user refreshes the request (e.g. pressing F5 or navigating back in history).

User user = userDAO.find(username, password);
if (user != null) {
    request.getSession().setAttribute("user", user); // Login user.
    response.sendRedirect("home"); // Redirects to http://example.com/context/home after succesful login.
} else {
    request.setAttribute("error", "Unknown login, please try again."); // Set error.
    request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response); // Forward to same page so that you can display error.
}

A redirect thus instructs the client to fire a new GET request on the given URL. Refreshing the request would then only refresh the redirected request and not the initial request. This will avoid "double submits" and confusion and bad user experiences. This is also called the POST-Redirect-GET pattern.

See also:

Do a "git export" (like "svn export")?

From the Git Manual:

Using git-checkout-index to "export an entire tree"

The prefix ability basically makes it trivial to use git-checkout-index as an "export as tree" function. Just read the desired tree into the index, and do:

$ git checkout-index --prefix=git-export-dir/ -a

How to merge two arrays in JavaScript and de-duplicate items

Array.prototype.union = function (other_array) {
/* you can include a test to check whether other_array really is an array */
  other_array.forEach(function(v) { if(this.indexOf(v) === -1) {this.push(v);}}, this);    
}

Is there a way to use shell_exec without waiting for the command to complete?

This will execute a command and disconnect from the running process. Of course, it can be any command you want. But for a test, you can create a php file with a sleep(20) command it.

exec("nohup /usr/bin/php -f sleep.php > /dev/null 2>&1 &");

How can I find and run the keytool

keytool is located in JDK bin directory ($JAVA_HOME/bin). JAVA_HOME is your JDK installation directory. To use that command line you should also include $JAVA_HOME/bin to your PATH environment variable.

matplotlib has no attribute 'pyplot'

pyplot is a sub-module of matplotlib which doesn't get imported with a simple import matplotlib.

>>> import matplotlib
>>> print matplotlib.pyplot
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
>>> import matplotlib.pyplot
>>> 

It seems customary to do: import matplotlib.pyplot as plt at which time you can use the various functions and classes it contains:

p = plt.plot(...)

How can I create a keystore?

Create keystore file from command line :

  1. Open Command line:

    Microsoft Windows [Version 6.1.7601]
    Copyright (c) 2009 Microsoft Corporation.  All rights reserved
    
    // (if you want to store keystore file at C:/ open command line with RUN AS ADMINISTRATOR)
    
    C:\Windows\system32> keytool -genkey -v -keystore [your keystore file path]{C:/index.keystore} -alias [your_alias_name]{index} -keyalg RSA -keysize 2048 -validity 10000[in days]
    
  2. Enter > It will prompt you for password > enter password (it will be invisible)

    Enter keystore password:
    Re-enter new password:
    
  3. Enter > It will ask your detail.

    What is your first and last name?
     [Unknown]:  {AB} // [Your Name / Name of Signer] 
    What is the name of your organizational unit?
     [Unknown]:  {Self} // [Your Unit Name] 
    What is the name of your organization?
     [Unknown]:  {Self} // [Your Organization Name] 
    What is the name of your City or Locality?
     [Unknown]:  {INDORE} // [Your City Name] 
    What is the name of your State or Province?
     [Unknown]:  {MP} //[Your State] 
    What is the two-letter country code for this unit?
     [Unknown]:  91
    
  4. Enter > Enter Y

    Is CN=AB, OU=Self, O=Self, L=INDORE, ST=MP, C=91 correct?
    [no]:  Y
    
  5. Enter > Enter password again.

    Generating 2,048 bit RSA key pair and self-signed certificate    (SHA256withRSA) with a validity of 10,000 days
        for: CN=AB, OU=Self, O=Self, L=INDORE, ST=MP, C=91
    Enter key password for <index> (RETURN if same as keystore password):
    Re-enter new password:
    

[ Storing C:/index.keystore ]

  1. And your are DONE!!!

Export In Eclipse :

Export your android package to .apk with your created keystore file

  1. Right click on Package you want to export and select export enter image description here

  2. Select Export Android Application > Next enter image description here

  3. Next
    enter image description here

  4. Select Use Existing Keystore > Browse .keystore file > enter password > Next enter image description here

  5. Select Alias > enter password > Next enter image description here

  6. Browse APK Destination > Finish enter image description here

In Android Studio:

Create keystore [.keystore/.jks] in studio...

  1. Click Build (ALT+B) > Generate Signed APK...
    enter image description here

  2. Click Create new..(ALT+C)
    enter image description here

  3. Browse Key store path (SHIFT+ENTER) > Select Path > Enter name > OK enter image description here

  4. Fill the detail about your .jks/keystore file enter image description here

  5. Next
    enter image description here

  6. Your file
    enter image description here

  7. Enter Studio Master Password (You can RESET if you don't know) > OK enter image description here

  8. Select *Destination Folder * > Build Type

    release : for publish on app store
    debug : for debugging your application
    

    Click Finish

    enter image description here

Done !!!

Html Agility Pack get all elements by class

You can use the following script:

var findclasses = _doc.DocumentNode.Descendants("div").Where(d => 
    d.Attributes.Contains("class") && d.Attributes["class"].Value.Contains("float")
);

Animate element to auto height with jQuery

you can always do this:

jQuery.fn.animateAuto = function(prop, speed, callback){
var elem, height, width;
return this.each(function(i, el){
    el = jQuery(el), elem = el.clone().css({"height":"auto","width":"auto"}).appendTo("body");
    height = elem.css("height"),
    width = elem.css("width"),
    elem.remove();

    if(prop === "height")
        el.animate({"height":height}, speed, callback);
    else if(prop === "width")
        el.animate({"width":width}, speed, callback);  
    else if(prop === "both")
        el.animate({"width":width,"height":height}, speed, callback);
});  
}

here is a fiddle: http://jsfiddle.net/Zuriel/faE9w/2/

How to delete a whole folder and content?

see android.os.FileUtils, it's hide on API 21

public static boolean deleteContents(File dir) {
    File[] files = dir.listFiles();
    boolean success = true;
    if (files != null) {
        for (File file : files) {
            if (file.isDirectory()) {
                success &= deleteContents(file);
            }
            if (!file.delete()) {
                Log.w("Failed to delete " + file);
                success = false;
            }
        }
    }
    return success;
}

Source: https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/os/FileUtils.java#414

Click a button programmatically

in c# this is working :D

protect void button1_Click(object sender, EventArgs e){
    button2_Click(button2, null);
}

protect void button2_Click(object sender, EventeArgs e){
    //some codes here
}

for vb.net

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)   Handles Button1.Click
    Button2_Click(Sender, e)
End Sub

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs)   Handles Button2.Click
    //some codes here
End Sub

Make the current Git branch a master branch

The following steps are performed in the Git browser powered by Atlassian (Bitbucket server)

Making {current-branch} as master

  1. Make a branch out of master and name it “master-duplicate”.
  2. Make a branch out of {current-branch} and name it “{current-branch}-copy”.
  3. In repository setting (Bitbucket) change “Default Branch” to point at “master-duplicate” (without this step, you will not be able to delete master - “In the Next step”).
  4. Delete “master” branch - I did this step from source tree (you can do it from the CLI or Git browser)
  5. Rename “{current-branch}” to “master” and push to repository (this will create a new “master” branch still “{current-branch}” will exist).
  6. In repository settings, change “Default Branch” to point at “master”.

jQuery Ajax calls and the Html.AntiForgeryToken()

The Solution i found is not for ASPX but for Razor, but quite comperable issue.

I resolved it by adding the AntiForgery to the request. The HTML Helper does not create a HTML id with the call

@Html.AntiForgeryToken()

In order to add the token to the postrequest i just added the AntiForgery id to the hidden field with jquery:

$("input[name*='__RequestVerificationToken']").attr('id', '__AjaxAntiForgeryForm');

This caused the controller to accept the request with the [ValidateAntiForgeryToken] attribute

How to write oracle insert script with one field as CLOB?

Keep in mind that SQL strings can not be larger than 4000 bytes, while Pl/SQL can have strings as large as 32767 bytes. see below for an example of inserting a large string via an anonymous block which I believe will do everything you need it to do.

note I changed the varchar2(32000) to CLOB

set serveroutput ON 
CREATE TABLE testclob 
  ( 
     id NUMBER, 
     c  CLOB, 
     d  VARCHAR2(4000) 
  ); 

DECLARE 
    reallybigtextstring CLOB := '123'; 
    i                   INT; 
BEGIN 
    WHILE Length(reallybigtextstring) <= 60000 LOOP 
        reallybigtextstring := reallybigtextstring 
                               || '000000000000000000000000000000000'; 
    END LOOP; 

    INSERT INTO testclob 
                (id, 
                 c, 
                 d) 
    VALUES     (0, 
                reallybigtextstring, 
                'done'); 

    dbms_output.Put_line('I have finished inputting your clob: ' 
                         || Length(reallybigtextstring)); 
END; 

/ 
SELECT * 
FROM   testclob; 


 "I have finished inputting your clob: 60030"

System.Data.SqlClient.SqlException: Login failed for user

You can also get this error if your SQL Server has not been configured to use Mixed mode authentication - it doesn't actually tell you that this is not enabled!

Split function equivalent in T-SQL?

DECLARE
    @InputString NVARCHAR(MAX) = 'token1,token2,token3,token4,token5'
    , @delimiter varchar(10) = ','

DECLARE @xml AS XML = CAST(('<X>'+REPLACE(@InputString,@delimiter ,'</X><X>')+'</X>') AS XML)
SELECT C.value('.', 'varchar(10)') AS value
FROM @xml.nodes('X') as X(C)

Source of this response: http://sqlhint.com/sqlserver/how-to/best-split-function-tsql-delimited

Can you have a <span> within a <span>?

HTML4 specification states that:

Inline elements may contain only data and other inline elements

Span is an inline element, therefore having span inside span is valid. There's a related question: Can <span> tags have any type of tags inside them? which makes it completely clear.

HTML5 specification (including the most current draft of HTML 5.3 dated November 16, 2017) changes terminology, but it's still perfectly valid to place span inside another span.

Why use the 'ref' keyword when passing an object?

This is like passing a pointer to a pointer in C. In .NET this will allow you to change what the original T refers to, personally though I think if you are doing that in .NET you have probably got a design issue!

Firebase TIMESTAMP to date and Time

First Of All Firebase.ServerValue.TIMESTAMP is not working anymore for me.

So for adding timestamp you have to use Firebase.database.ServerValue.TIMESTAMP

And the timestamp is in long millisecond format.To convert millisecond to simple dateformat .

Ex- dd/MM/yy HH:mm:ss

You can use the following code in java:

To get the timestamp value in string from the firebase database

String x = dataSnapshot.getValue (String.class);

The data is in string now. You can convert the string to long

long milliSeconds= Long.parseLong(x);

Then create SimpleDateFormat

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy HH:mm:ss");

Now convert your millisecond timestamp to ur sdf format

String dateAsString = sdf.format (milliSeconds);

After that you can parse it to ur Date variable

 date = sdf.parse (dateAsString);

What is the difference between WCF and WPF?

Windows Presentation Foundation (WPF)

Next-Generation User Experiences. The Windows Presentation Foundation, WPF, provides a unified framework for building applications and high-fidelity experiences in Windows Vista that blend application UI, documents, and media content. WPF offers developers 2D and 3D graphics support, hardware-accelerated effects, scalability to different form factors, interactive data visualization, and superior content readability.

Windows Communication Foundation (WCF)

Windows Communication Foundation (WCF) is Microsoft’s unified programming model for building service-oriented applications. It enables developers to build secure, reliable, transacted solutions that integrate across platforms and interoperate with existing investments.

What does "@" mean in Windows batch scripts

you can include @ in a 'scriptBlock' like this:

@(
  echo don't echoed
  hostname
)
echo echoed

and especially do not do that :)

for %%a in ("@") do %%~aecho %%~a

Inner join with 3 tables in mysql

The correct statement should be :

SELECT
  student.firstname,
  student.lastname,
  exam.name,
  exam.date,
  grade.grade
FROM grade
  INNER JOIN student
    ON student.studentId = grade.fk_studentId
  INNER JOIN exam
    ON exam.examId = grade.fk_examId
ORDER BY exam.date

A table is refered to other on the basis of the foreign key relationship defined. You should refer the ids properly if you wish the data to show as queried. So you should refer the id's to the proper foreign keys in the table rather than just on the id which doesn't define a proper relation

overlay two images in android to set an imageview

ok just so you know there is a program out there that's called DroidDraw. It can help you draw objects and try them one on top of the other. I tried your solution but I had animation under the smaller image so that didn't work. But then I tried to place one image in a relative layout that's suppose to be under first and then on top of that I drew the other image that is suppose to overlay and everything worked great. So RelativeLayout, DroidDraw and you are good to go :) Simple, no any kind of jiggery pockery :) and here is a bit of code for ya:

The logo is going to be on top of shazam background image.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/widget30"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<ImageView
android:id="@+id/widget39"
android:layout_width="219px"
android:layout_height="225px"
android:src="@drawable/shazam_bkgd"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
>
</ImageView>
<ImageView
android:id="@+id/widget37"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/shazam_logo"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
>
</ImageView>
</RelativeLayout>

libpthread.so.0: error adding symbols: DSO missing from command line

The same problem happened to me when I use distcc to make my c++ project; Finally I solved it with export CXX="distcc g++".

How do I make a transparent border with CSS?

Many of you must be landing here to find a solution for opaque border instead of a transparent one. In that case you can use rgba, where a stands for alpha.

.your_class {
    height: 100px;
    width: 100px;
    margin: 100px;
    border: 10px solid rgba(255,255,255,.5);
}

Demo

Here, you can change the opacity of the border from 0-1


If you simply want a complete transparent border, the best thing to use is transparent, like border: 1px solid transparent;

javax.servlet.ServletException cannot be resolved to a type in spring web app

import javax.servlet

STEP 1

Go to properties of your project ( with Alt+Enter or righ-click )

STEP 2

check on Apache Tomcat v7.0 under Targeted Runtime and it works.

source: https://stackoverflow.com/a/9287149

Very Simple Image Slider/Slideshow with left and right button. No autoplay

Why try to reinvent the wheel? There are more lightweight jQuery slideshow solutions out there then you could poke a stick at, and someone has already done the hard work for you and thought about issues that you might run into (cross-browser compatability etc).

jQuery Cycle is one of my favourite light weight libraries.

What you want to achieve could be done in just

    jQuery("#slideshow").cycle({
    timeout:0, // no autoplay
    fx: 'fade', //fade effect, although there are heaps
    next: '#next',
    prev: '#prev'
    });

JSFIDDLE TO SEE HOW EASY IT IS

Detect if a page has a vertical scrollbar?

I wrote an updated version of Kees C. Bakker's answer:

const hasVerticalScroll = (node) => {
  if (!node) {
    if (window.innerHeight) {
      return document.body.offsetHeight > window.innerHeight
    }
    return (document.documentElement.scrollHeight > document.documentElement.offsetHeight)
      || (document.body.scrollHeight > document.body.offsetHeight)
  }
  return node.scrollHeight > node.offsetHeight
}

if (hasVerticalScroll(document.querySelector('body'))) {
  this.props.handleDisableDownScrollerButton()
}

The function returns true or false depending whether the page has a vertical scrollbar or not.

For example:

const hasVScroll = hasVerticalScroll(document.querySelector('body'))

if (hasVScroll) {
  console.log('HAS SCROLL', hasVScroll)
}

How do I break a string across more than one line of code in JavaScript?

You can break a long string constant into logical chunks and assign them into an array. Then do a join with an empty string as a delimiter.

var stringArray = [
  '1. This is first part....',
  '2. This is second part.....',
  '3. Finishing here.'
];

var bigLongString = stringArray.join('');
console.log(bigLongString);

Output will be:

  1. This is first part....2. This is second part.....3. Finishing here.

There's a slight performance hit this way but you gain in code readability and maintainability.

Android Location Manager, Get GPS location ,if no GPS then get to Network Provider location

Main Class:

public class AndroidLocationActivity extends Activity {

Button btnGPSShowLocation;
Button btnNWShowLocation;

AppLocationService appLocationService;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    appLocationService = new AppLocationService(
            AndroidLocationActivity.this);

    btnGPSShowLocation = (Button) findViewById(R.id.btnGPSShowLocation);
    btnGPSShowLocation.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {

            Location gpsLocation = appLocationService
                    .getLocation(LocationManager.GPS_PROVIDER);

            if (gpsLocation != null) {
                double latitude = gpsLocation.getLatitude();
                double longitude = gpsLocation.getLongitude();
                Toast.makeText(
                        getApplicationContext(),
                        "Mobile Location (GPS): \nLatitude: " + latitude
                                + "\nLongitude: " + longitude,
                        Toast.LENGTH_LONG).show();
            } else {
                showSettingsAlert("GPS");
            }

        }
    });

    btnNWShowLocation = (Button) findViewById(R.id.btnNWShowLocation);
    btnNWShowLocation.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {

            Location nwLocation = appLocationService
                    .getLocation(LocationManager.NETWORK_PROVIDER);

            if (nwLocation != null) {
                double latitude = nwLocation.getLatitude();
                double longitude = nwLocation.getLongitude();
                Toast.makeText(
                        getApplicationContext(),
                        "Mobile Location (NW): \nLatitude: " + latitude
                                + "\nLongitude: " + longitude,
                        Toast.LENGTH_LONG).show();

            } else {
                showSettingsAlert("NETWORK");
            }

        }
    });

}

public void showSettingsAlert(String provider) {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(
            AndroidLocationActivity.this);

    alertDialog.setTitle(provider + " SETTINGS");

    alertDialog.setMessage(provider
            + " is not enabled! Want to go to settings menu?");

    alertDialog.setPositiveButton("Settings",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(
                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    AndroidLocationActivity.this.startActivity(intent);
                }
            });

    alertDialog.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

    alertDialog.show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;

}

}

Next Class:

public class AppLocationService extends Service implements LocationListener {

protected LocationManager locationManager;
Location location;

private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;

public AppLocationService(Context context) {
    locationManager = (LocationManager) context
            .getSystemService(LOCATION_SERVICE);
}

public Location getLocation(String provider) {
    if (locationManager.isProviderEnabled(provider)) {
        locationManager.requestLocationUpdates(provider,
                MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
        if (locationManager != null) {
            location = locationManager.getLastKnownLocation(provider);
            return location;
        }
    }
    return null;
}

@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

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

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

}

Don't forget to add in your manifest.

<!-- to get location using GPS -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<!-- to get location using NetworkProvider -->
<uses-permission android:name="android.permission.INTERNET" />

How can I move all the files from one folder to another using the command line?

move c:\sourcefolder c:\targetfolder

will work, but you will end up with a structure like this:

c:\targetfolder\sourcefolder\[all the subfolders & files]

If you want to move just the contents of one folder to another, then this should do it:

SET src_folder=c:\srcfold
SET tar_folder=c:\tarfold

for /f %%a IN ('dir "%src_folder%" /b') do move "%src_folder%\%%a" "%tar_folder%\"

pause

SimpleXml to string

You can use ->child to get a child element named child.

This element will contain the text of the child element.

But if you try var_dump() on that variable, you will see it is not actually a PHP string.

The easiest way around this is to perform a strval(xml->child); That will convert it to an actual PHP string.

This is useful when debugging when looping your XML and using var_dump() to check the result.

So $s = strval($xml->child);.

Select rows from a data frame based on values in a vector

Another option would be to use a keyed data.table:

library(data.table)
setDT(dt, key = 'fct')[J(vc)]  # or: setDT(dt, key = 'fct')[.(vc)]

which results in:

   fct X
1:   a 2
2:   a 7
3:   a 1
4:   c 3
5:   c 5
6:   c 9
7:   c 2
8:   c 4

What this does:

  • setDT(dt, key = 'fct') transforms the data.frame to a data.table (which is an enhanced form of a data.frame) with the fct column set as key.
  • Next you can just subset with the vc vector with [J(vc)].

NOTE: when the key is a factor/character variable, you can also use setDT(dt, key = 'fct')[vc] but that won't work when vc is a numeric vector. When vc is a numeric vector and is not wrapped in J() or .(), vc will work as a rowindex.

A more detailed explanation of the concept of keys and subsetting can be found in the vignette Keys and fast binary search based subset.

An alternative as suggested by @Frank in the comments:

setDT(dt)[J(vc), on=.(fct)]

When vc contains values that are not present in dt, you'll need to add nomatch = 0:

setDT(dt, key = 'fct')[J(vc), nomatch = 0]

or:

setDT(dt)[J(vc), on=.(fct), nomatch = 0]

Python: Adding element to list while iterating

well, according to http://docs.python.org/tutorial/controlflow.html

It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify the list you are iterating over (for example, to duplicate selected items) you must iterate over a copy.

How to efficiently change image attribute "src" from relative URL to absolute using jQuery?

The replace method in Javascript returns a value, and does not act upon the existing string object. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

In your example, you will have to do

$(this).attr("src", $(this).attr("src").replace(...))

How to deal with INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES without uninstall?

Just delete the old build from the device and reinstall the same. Because device.keystore is already exist in the device so just uninstall the build and reinstall the APK thats all..

Thanks

How to uninstall an older PHP version from centOS7

Subscribing to the IUS Community Project Repository

cd ~
curl 'https://setup.ius.io/' -o setup-ius.sh

Run the script:

sudo bash setup-ius.sh

Upgrading mod_php with Apache

This section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section.

Begin by removing existing PHP packages. Press y and hit Enter to continue when prompted.

sudo yum remove php-cli mod_php php-common

Install the new PHP 7 packages from IUS. Again, press y and Enter when prompted.

sudo yum install mod_php70u php70u-cli php70u-mysqlnd

Finally, restart Apache to load the new version of mod_php:

sudo apachectl restart

You can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl:

systemctl status httpd

Get the length of a String

If you are just trying to see if a string is empty or not (checking for length of 0), Swift offers a simple boolean test method on String

myString.isEmpty

The other side of this coin was people asking in ObjectiveC how to ask if a string was empty where the answer was to check for a length of 0:

NSString is empty

node: command not found

The problem is that your PATH does not include the location of the node executable.

You can likely run node as "/usr/local/bin/node".

You can add that location to your path by running the following command to add a single line to your bashrc file:

echo 'export PATH=$PATH:/usr/local/bin' >> $HOME/.bashrc

Convert bytes to a string

For Python 3, this is a much safer and Pythonic approach to convert from byte to string:

def byte_to_str(bytes_or_str):
    if isinstance(bytes_or_str, bytes): # Check if it's in bytes
        print(bytes_or_str.decode('utf-8'))
    else:
        print("Object not of byte type")

byte_to_str(b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2\n')

Output:

total 0
-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1
-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2

What is this CSS selector? [class*="span"]

It's an attribute wildcard selector. In the sample you've given, it looks for any child element under .show-grid that has a class that CONTAINS span.

So would select the <strong> element in this example:

<div class="show-grid">
    <strong class="span6">Blah blah</strong>
</div>

You can also do searches for 'begins with...'

div[class^="something"] { }

which would work on something like this:-

<div class="something-else-class"></div>

and 'ends with...'

div[class$="something"] { }

which would work on

<div class="you-are-something"></div>

Good references

Adding values to an array in java

You have not one, but many mistakes. It should be:

int[] tall = new int[28123];

for (int j=0;j<28123;j++){
    tall[j] = j+1;
}

Your code is putting a 0 in all the positions of the array.

Morover, it'll throw an exception, because the last index of the array is 28123-1 (arrays in Java start in 0!).

How can I check if a string contains ANY letters from the alphabet?

You can use regular expression like this:

import re

print re.search('[a-zA-Z]+',string)

Read a javascript cookie by name

document.cookie="MYBIGCOOKIE=1";

Your cookies would look like:

"MYBIGCOOKIE=1; PHPSESSID=d76f00dvgrtea8f917f50db8c31cce9"

first of all read all cookies:

var read_cookies = document.cookie;

then split all cookies with ";":

var split_read_cookie = read_cookies.split(";");

then use for loop to read each value. Into loop each value split again with "=":

for (i=0;i<split_read_cookie.length;i++){
    var value=split_read_cookie[i];
    value=value.split("=");
    if(value[0]=="MYBIGCOOKIE" && value[1]=="1"){
        alert('it is 1');
    }
}

How to express a One-To-Many relationship in Django

If the "many" model does not justify the creation of a model per-se (not the case here, but it might benefits other people), another alternative would be to rely on specific PostgreSQL data types, via the Django Contrib package

Postgres can deal with Array or JSON data types, and this may be a nice workaround to handle One-To-Many when the many-ies can only be tied to a single entity of the one.

Postgres allows you to access single elements of the array, which means that queries can be really fast, and avoid application-level overheads. And of course, Django implements a cool API to leverage this feature.

It obviously has the disadvantage of not being portable to others database backend, but I thougt it still worth mentionning.

Hope it may help some people looking for ideas.

What is username and password when starting Spring Boot with Tomcat?

When I started learning Spring Security, then I overrided the method userDetailsService() as in below code snippet:

@Configuration
@EnableWebSecurity
public class ApplicationSecurityConfiguration extends WebSecurityConfigurerAdapter{

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/", "/index").permitAll()
                .anyRequest().authenticated()
                .and()
                .httpBasic();
    }

    @Override
    @Bean
    public UserDetailsService userDetailsService() {
        List<UserDetails> users= new ArrayList<UserDetails>();
        users.add(User.withDefaultPasswordEncoder().username("admin").password("nimda").roles("USER","ADMIN").build());
        users.add(User.withDefaultPasswordEncoder().username("Spring").password("Security").roles("USER").build());
        return new InMemoryUserDetailsManager(users);
    }
}

So we can log in to the application using the above-mentioned creds. (e.g. admin/nimda)

Note: This we should not use in production.

How to draw a line in android

There are two main ways you can draw a line, by using a Canvas or by using a View.

Drawing a Line with Canvas

From the documentation we see that we need to use the following method:

drawLine (float startX, float startY, float stopX, float stopY, Paint paint)

Here is a picture:

canvas.drawLine

The Paint object just tells Canvas what color to paint the line, how wide it should be, and so on.

Here is some sample code:

private Paint paint = new Paint();
....

private void init() {
    paint.setColor(Color.BLACK);
    paint.setStrokeWidth(1f);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    startX = 20;
    startY = 100;
    stopX = 140;
    stopY = 30;

    canvas.drawLine(startX, startY, stopX, stopY, paint);
}

Drawing a Line with View

If you only need a straight horizontal or vertical line, then the easiest way may be to just use a View in your xml layout file. You would do something like this:

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@android:color/black" />

Here is a picture with two lines (one horizontal and one vertical) to show what it would look like:

drawing a line with a view in xml layout

And here is the complete xml layout for that:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:text="TextView1 in vertical linear layout" />

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@android:color/black" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:text="TextView2 in vertical linear layout" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:padding="10dp"
        android:text="TextView3 in horizontal linear layout" />

    <View
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:background="@android:color/black" />

    <TextView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:padding="10dp"
        android:text="TextView4 in horizontal linear layout" />
</LinearLayout>

</LinearLayout>

Convert list of ASCII codes to string (byte array) in Python

Shorter version of previous using map() function (works for python 2.7):

"".join(map(chr, myList))

delete all record from table in mysql

It’s because you tried to update a table without a WHERE that uses a KEY column.

The quick fix is to add SET SQL_SAFE_UPDATES=0; before your query :

SET SQL_SAFE_UPDATES=0; 

Or

close the safe update mode. Edit -> Preferences -> SQL Editor -> SQL Editor remove Forbid UPDATE and DELETE statements without a WHERE clause (safe updates) .

BTW you can use TRUNCATE TABLE tablename; to delete all the records .

how to set ul/li bullet point color?

http://www.w3schools.com/cssref/pr_list-style-type.asp

You need to use list-style-type: to change bullet type/style and the above link has all of the options listed. As others have stated the color is changed using the color property on the ul itself

To create 'black filled' bullets, use 'disc' instead of 'circle',i.e.:

list-style-type:disc

Clicking the back button twice to exit an activity

I think this what you need, I mean when we want to show this toast, when there is only one activity in the stack and user pressing back from this last activity of the stack.

var exitOpened=false // Declare it globaly

and in onBackPressed method change it like:

override fun onBackPressed() {
        if (isTaskRoot && !exitOpened)
        {
            exitOpened=true
            toast("Please press back again to exit")
            return
        }
        super.onBackPressed()
    }

Here, isTaskRoot will return true if the current activity is the root activity(first activity) of the stack and false if it is not.

You can check the official documentation here

Should I use SVN or Git?

Here is a copy of an answer I made of some duplicate question since then deleted about Git vs. SVN (September 2009).

Better? Aside from the usual link WhyGitIsBetterThanX, they are different:

one is a Central VCS based on cheap copy for branches and tags the other (Git) is a distributed VCS based on a graph of revisions. See also Core concepts of VCS.


That first part generated some mis-informed comments pretending that the fundamental purpose of the two programs (SVN and Git) is the same, but that they have been implemented quite differently.
To clarify the fundamental difference between SVN and Git, let me rephrase:

  • SVN is the third implementation of a revision control: RCS, then CVS and finally SVN manage directories of versioned data. SVN offers VCS features (labeling and merging), but its tag is just a directory copy (like a branch, except you are not "supposed" to touch anything in a tag directory), and its merge is still complicated, currently based on meta-data added to remember what has already been merged.

  • Git is a file content management (a tool made to merge files), evolved into a true Version Control System, based on a DAG (Directed Acyclic Graph) of commits, where branches are part of the history of datas (and not a data itself), and where tags are a true meta-data.

To say they are not "fundamentally" different because you can achieve the same thing, resolve the same problem, is... plain false on so many levels.

  • if you have many complex merges, doing them with SVN will be longer and more error prone. if you have to create many branches, you will need to manage them and merge them, again much more easily with Git than with SVN, especially if a high number of files are involved (the speed then becomes important)
  • if you have partial merges for a work in progress, you will take advantage of the Git staging area (index) to commit only what you need, stash the rest, and move on on another branch.
  • if you need offline development... well with Git you are always "online", with your own local repository, whatever the workflow you want to follow with other repositories.

Still the comments on that old (deleted) answer insisted:

VonC: You are confusing fundamental difference in implementation (the differences are very fundamental, we both clearly agree on this) with difference in purpose.
They are both tools used for the same purpose: this is why many teams who've formerly used SVN have quite successfully been able to dump it in favor of Git.
If they didn't solve the same problem, this substitutability wouldn't exist.

, to which I replied:

"substitutability"... interesting term (used in computer programming).
Off course, Git is hardly a subtype of SVN.

You may achieve the same technical features (tag, branch, merge) with both, but Git does not get in your way and allow you to focus on the content of the files, without thinking about the tool itself.

You certainly cannot (always) just replace SVN by Git "without altering any of the desirable properties of that program (correctness, task performed, ...)" (which is a reference to the aforementioned substitutability definition):

  • One is an extended revision tool, the other a true version control system.
  • One is suited small to medium monolithic project with simple merge workflow and (not too much) parallel versions. SVN is enough for that purpose, and you may not need all the Git features.
  • The other allows for medium to large projects based on multiple components (one repo per component), with large number of files to merges between multiple branches in a complex merge workflow, parallel versions in branches, retrofit merges, and so on. You could do it with SVN, but you are much better off with Git.
    SVN simply can not manage any project of any size with any merge workflow. Git can.

Again, their nature is fundamentally different (which then leads to different implementation but that is not the point).
One see revision control as directories and files, the other only see the content of the file (so much so that empty directories won't even register in Git!).

The general end-goal might be the same, but you cannot use them in the same way, nor can you solve the same class of problem (in scope or complexity).

Datanode process not running in Hadoop

Need to follow 3 steps.

(1) Need to go to the logs and check the most recent log (In hadoop- 2.6.0/logs/hadoop-user-datanode-ubuntu.log)

If the error is as

java.io.IOException: Incompatible clusterIDs in /home/kutty/work/hadoop2data/dfs/data: namenode clusterID = CID-c41df580-e197-4db6-a02a-a62b71463089; datanode clusterID = CID-a5f4ba24-3a56-4125-9137-fa77c5bb07b1

i.e. namenode cluster id and datanode cluster id's are not identical.

(2) Now copy the namenode clusterID which is CID-c41df580-e197-4db6-a02a-a62b71463089 in above error

(3) Replace the Datanode cluster ID with Namenode cluster ID in hadoopdata/dfs/data/current/version

clusterID=CID-c41df580-e197-4db6-a02a-a62b71463089

Restart Hadoop. Will run DataNode

Bootstrap: adding gaps between divs

An alternative way to accomplish what you are asking, without having problems on the mobile version of your website, (Remember that the margin attribute will brake your responsive layout on mobile version thus you have to add on your element a supplementary attribute like @media (min-width:768px){ 'your-class'{margin:0}} to override the previous margin)

is to nest your class in your preferred div and then add on your class the margin option you want

like the following example: HTML

<div class="container">
  <div class="col-md-3 col-xs-12">
   <div class="events">
     <img src="..."  class="img-responsive" alt="...."/>
     <div class="figcaption">
       <h2>Event Title</h2>
       <p>Event Description.</p>
     </div>
   </div>
  </div>
  <div class="col-md-3 col-xs-12">
   <div class="events">
    <img src="..."  class="img-responsive" alt="...."/>
    <div class="figcaption">
     <h2>Event Title</h2>
     <p>Event Description. </p>
    </div>
   </div>
  </div>
  <div class="col-md-3 col-xs-12">
   <div class="events">
    <img src="..."  class="img-responsive" alt="...."/>
    <div class="figcaption">
     <h2>Event Title</h2>
     <p>Event Description. </p>
    </div>
   </div>
  </div>
</div>

And on your CSS you just add the margin option on your class which in this example is "events" like:

.events{
margin: 20px 10px;
}

By this method you will have all the wanted space between your divs making sure you do not brake anything on your website's mobile and tablet versions.

Clearing UIWebview cache

You can disable the caching by doing the following:

NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
[sharedCache release];

ARC:

NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];

Virtual member call in a constructor

I think that ignoring the warning might be legitimate if you want to give the child class the ability to set or override a property that the parent constructor will use right away:

internal class Parent
{
    public Parent()
    {
        Console.WriteLine("Parent ctor");
        Console.WriteLine(Something);
    }

    protected virtual string Something { get; } = "Parent";
}

internal class Child : Parent
{
    public Child()
    {
        Console.WriteLine("Child ctor");
        Console.WriteLine(Something);
    }

    protected override string Something { get; } = "Child";
}

The risk here would be for the child class to set the property from its constructor in which case the change in the value would occur after the base class constructor has been called.

My use case is that I want the child class to provide a specific value or a utility class such as a converter and I don't want to have to call an initialization method on the base.

The output of the above when instantiating the child class is:

Parent ctor
Child
Child ctor
Child

HTML iframe - disable scroll

Unfortunately I do not believe it's possible in fully-conforming HTML5 with just HTML and CSS properties. Fortunately however, most browsers do still support the scrolling property (which was removed from the HTML5 specification).

overflow isn't a solution for HTML5 as the only modern browser which wrongly supports this is Firefox.

A current solution would be to combine the two:

<iframe src="" scrolling="no"></iframe>
iframe {
  overflow: hidden;
}

But this could be rendered obsolete as browsers update. You may want to check this for a JavaScript solution: http://www.christersvensson.com/html-tool/iframe.htm

Edit: I've checked and scrolling="no" will work in IE10, Chrome 25 and Opera 12.12.

How can I remove an element from a list?

Use - (Negative sign) along with position of element, example if 3rd element is to be removed use it as your_list[-3]

Input

my_list <- list(a = 3, b = 3, c = 4, d = "Hello", e = NA)
my_list
# $`a`
# [1] 3

# $b
# [1] 3

# $c
# [1] 4

# $d
# [1] "Hello"

# $e
# [1] NA

Remove single element from list

 my_list[-3]
 # $`a`
 # [1] 3

 # $b
 # [1] 3

 # $d
 # [1] "Hello"

 # $e
 [1] NA

Remove multiple elements from list

 my_list[c(-1,-3,-2)]
 # $`d`
 # [1] "Hello"

 # $e
 # [1] NA

 my_list[c(-3:-5)]
 # $`a`
 # [1] 3

 # $b
 # [1] 3

 my_list[-seq(1:2)]
 # $`c`
 # [1] 4

 # $d
 # [1] "Hello"

 # $e
 # [1] NA

test attribute in JSTL <c:if> tag

You can also use something like

<c:if test="${ testObject.testPropert == "testValue" }">...</c:if>

How to "fadeOut" & "remove" a div in jQuery?

.fadeOut('slow', this.remove);

How to handle an IF STATEMENT in a Mustache template?

In general, you use the # syntax:

{{#a_boolean}}
  I only show up if the boolean was true.
{{/a_boolean}}

The goal is to move as much logic as possible out of the template (which makes sense).

What are the differences between Abstract Factory and Factory design patterns?

The Difference Between The Two

The main difference between a "factory method" and an "abstract factory" is that the factory method is a method, and an abstract factory is an object. I think a lot of people get these two terms confused, and start using them interchangeably. I remember that I had a hard time finding exactly what the difference was when I learnt them.

Because the factory method is just a method, it can be overridden in a subclass, hence the second half of your quote:

... the Factory Method pattern uses inheritance and relies on a subclass to handle the desired object instantiation.

The quote assumes that an object is calling its own factory method here. Therefore the only thing that could change the return value would be a subclass.

The abstract factory is an object that has multiple factory methods on it. Looking at the first half of your quote:

... with the Abstract Factory pattern, a class delegates the responsibility of object instantiation to another object via composition ...

What they're saying is that there is an object A, who wants to make a Foo object. Instead of making the Foo object itself (e.g., with a factory method), it's going to get a different object (the abstract factory) to create the Foo object.

Code Examples

To show you the difference, here is a factory method in use:

class A {
    public void doSomething() {
        Foo f = makeFoo();
        f.whatever();   
    }

    protected Foo makeFoo() {
        return new RegularFoo();
    }
}

class B extends A {
    protected Foo makeFoo() {
        //subclass is overriding the factory method 
        //to return something different
        return new SpecialFoo();
    }
}

And here is an abstract factory in use:

class A {
    private Factory factory;

    public A(Factory factory) {
        this.factory = factory;
    }

    public void doSomething() {
        //The concrete class of "f" depends on the concrete class
        //of the factory passed into the constructor. If you provide a
        //different factory, you get a different Foo object.
        Foo f = factory.makeFoo();
        f.whatever();
    }
}

interface Factory {
    Foo makeFoo();
    Bar makeBar();
    Aycufcn makeAmbiguousYetCommonlyUsedFakeClassName();
}

//need to make concrete factories that implement the "Factory" interface here

CodeIgniter Active Record - Get number of returned rows

If you only need the number of rows in a query and don't need the actual row data, use count_all_results

echo $this->db
       ->where('active',1)
       ->count_all_results('table_name');

How to turn IDENTITY_INSERT on and off using SQL Server 2008?

You need to add the command 'go' after you set the identity insert. Example:

SET IDENTITY_INSERT sometableWithIdentity ON
go

INSERT sometableWithIdentity (IdentityColumn, col2, col3, ...)
VALUES (AnIdentityValue, col2value, col3value, ...)

SET IDENTITY_INSERT sometableWithIdentity OFF
go

JavaScript: How to get parent element by selector?

Using leech's answer with indexOf (to support IE)

This is using what leech talked about, but making it work for IE (IE doesn't support matches):

function closest(el, selector, stopSelector) {
  var retval = null;
  while (el) {
    if (el.className.indexOf(selector) > -1) {
      retval = el;
      break
    } else if (stopSelector && el.className.indexOf(stopSelector) > -1) {
      break
    }
    el = el.parentElement;
  }
  return retval;
}

It's not perfect, but it works if the selector is unique enough so it won't accidentally match the incorrect element.

Detect page change on DataTable

An alternative approach would be to register an event handler on the pagination link like so:

$("#dataTableID_paginate").on("click", "a", function() { alert("clicked") });

Replace "#dataTableID_" with the ID of your table, of course. And I'm using JQuery's ON method as that is the current best practice.

Regular expression for matching HH:MM time format

The below regex will help to validate hh:mm format

^([0-1][0-9]|2[0-3]):[0-5][0-9]$

How to split a string literal across multiple lines in C / Objective-C?

One more solution for the pile, change your .m file to .mm so that it becomes Objective-C++ and use C++ raw literals, like this:

const char *sql_query = R"(SELECT word_id
                           FROM table1, table2
                           WHERE table2.word_id = table1.word_id
                           ORDER BY table1.word ASC)";

Raw literals ignore everything until the termination sequence, which in the default case is parenthesis-quote.

If the parenthesis-quote sequence has to appear in the string somewhere, you can easily specify a custom delimiter too, like this:

const char *sql_query = R"T3RM!N8(
                                  SELECT word_id
                                  FROM table1, table2
                                  WHERE table2.word_id = table1.word_id
                                  ORDER BY table1.word ASC
                         )T3RM!N8";

How to compare two dates?

Use time

Let's say you have the initial dates as strings like these:
date1 = "31/12/2015"
date2 = "01/01/2016"

You can do the following:
newdate1 = time.strptime(date1, "%d/%m/%Y") and newdate2 = time.strptime(date2, "%d/%m/%Y") to convert them to python's date format. Then, the comparison is obvious:

newdate1 > newdate2 will return False
newdate1 < newdate2 will return True

Amazon Interview Question: Design an OO parking lot

Models don't exist in isolation. The structures you'd define for a simulation of cars entering a car park, an embedded system which guides you to a free space, a car parking billing system or for the automated gates/ticket machines usual in car parks are all different.

How to set a selected option of a dropdown list control using angular JS

It can be usefull. Bindings dose not always work.

<select id="product" class="form-control" name="product" required
        ng-model="issue.productId"
        ng-change="getProductVersions()"
        ng-options="p.id as p.shortName for p in products">
</select>

For example. You fill options list source model from rest-service. Selected value was known befor filling list and was set. After executing rest-request with $http list option be done. But selected option is not set. By unknown reasons AngularJS in shadow $digest executing not bind selected as it shuold be. I gotta use JQuery to set selected. It`s important! Angular in shadow add prefix to value of attr "value" for generated by ng-repeat optinos. For int it is "number:".

$scope.issue.productId = productId;
function activate() {
   $http.get('/product/list')
     .then(function (response) {
       $scope.products = response.data;

       if (productId) {
           console.log("" + $("#product option").length);//for clarity                       
           $timeout(function () {
               console.log("" + $("#product option").length);//for clarity
               $('#product').val('number:'+productId);
               //$scope.issue.productId = productId;//not work at all
           }, 200);
       }
   });
}